##// END OF EJS Templates
Turn quit/exit into magics instead of special-cased strings
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,2579 +1,2592 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 960 2005-12-28 06:51:01Z fperez $"""
4 $Id: Magic.py 962 2005-12-28 18:04:59Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 from cStringIO import StringIO
33 from cStringIO import StringIO
34 from getopt import getopt
34 from getopt import getopt
35 from pprint import pprint, pformat
35 from pprint import pprint, pformat
36
36
37 # profile isn't bundled by default in Debian for license reasons
37 # profile isn't bundled by default in Debian for license reasons
38 try:
38 try:
39 import profile,pstats
39 import profile,pstats
40 except ImportError:
40 except ImportError:
41 profile = pstats = None
41 profile = pstats = None
42
42
43 # Homebrewed
43 # Homebrewed
44 from IPython import Debugger, OInspect, wildcard
44 from IPython import Debugger, OInspect, wildcard
45 from IPython.FakeModule import FakeModule
45 from IPython.FakeModule import FakeModule
46 from IPython.Itpl import Itpl, itpl, printpl,itplns
46 from IPython.Itpl import Itpl, itpl, printpl,itplns
47 from IPython.PyColorize import Parser
47 from IPython.PyColorize import Parser
48 from IPython.Struct import Struct
48 from IPython.Struct import Struct
49 from IPython.genutils import *
49 from IPython.genutils import *
50
50
51 # Globals to be set later by Magic constructor
51 # Globals to be set later by Magic constructor
52 MAGIC_PREFIX = ''
52 MAGIC_PREFIX = ''
53 MAGIC_ESCAPE = ''
53 MAGIC_ESCAPE = ''
54
54
55 #***************************************************************************
55 #***************************************************************************
56 # Utility functions
56 # Utility functions
57 def magic2python(cmd):
57 def magic2python(cmd):
58 """Convert a command string of magic syntax to valid Python code."""
58 """Convert a command string of magic syntax to valid Python code."""
59
59
60 if cmd.startswith('#'+MAGIC_ESCAPE) or \
60 if cmd.startswith('#'+MAGIC_ESCAPE) or \
61 cmd.startswith(MAGIC_ESCAPE):
61 cmd.startswith(MAGIC_ESCAPE):
62 if cmd[0]=='#':
62 if cmd[0]=='#':
63 cmd = cmd[1:]
63 cmd = cmd[1:]
64 # we need to return the proper line end later
64 # we need to return the proper line end later
65 if cmd[-1] == '\n':
65 if cmd[-1] == '\n':
66 endl = '\n'
66 endl = '\n'
67 else:
67 else:
68 endl = ''
68 endl = ''
69 try:
69 try:
70 func,args = cmd[1:].split(' ',1)
70 func,args = cmd[1:].split(' ',1)
71 except:
71 except:
72 func,args = cmd[1:].rstrip(),''
72 func,args = cmd[1:].rstrip(),''
73 args = args.replace('"','\\"').replace("'","\\'").rstrip()
73 args = args.replace('"','\\"').replace("'","\\'").rstrip()
74 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
74 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
75 else:
75 else:
76 return cmd
76 return cmd
77
77
78 def on_off(tag):
78 def on_off(tag):
79 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
79 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
80 return ['OFF','ON'][tag]
80 return ['OFF','ON'][tag]
81
81
82
82
83 #****************************************************************************
83 #****************************************************************************
84 # Utility classes
84 # Utility classes
85 class Macro:
85 class Macro:
86 """Simple class to store the value of macros as strings.
86 """Simple class to store the value of macros as strings.
87
87
88 This allows us to later exec them by checking when something is an
88 This allows us to later exec them by checking when something is an
89 instance of this class."""
89 instance of this class."""
90
90
91 def __init__(self,cmds):
91 def __init__(self,cmds):
92 """Build a macro from a list of commands."""
92 """Build a macro from a list of commands."""
93
93
94 # Since the list may include multi-line entries, first make sure that
94 # Since the list may include multi-line entries, first make sure that
95 # they've been all broken up before passing it to magic2python
95 # they've been all broken up before passing it to magic2python
96 cmdlist = map(magic2python,''.join(cmds).split('\n'))
96 cmdlist = map(magic2python,''.join(cmds).split('\n'))
97 self.value = '\n'.join(cmdlist)
97 self.value = '\n'.join(cmdlist)
98
98
99 def __str__(self):
99 def __str__(self):
100 return self.value
100 return self.value
101
101
102 #***************************************************************************
102 #***************************************************************************
103 # Main class implementing Magic functionality
103 # Main class implementing Magic functionality
104 class Magic:
104 class Magic:
105 """Magic functions for InteractiveShell.
105 """Magic functions for InteractiveShell.
106
106
107 Shell functions which can be reached as %function_name. All magic
107 Shell functions which can be reached as %function_name. All magic
108 functions should accept a string, which they can parse for their own
108 functions should accept a string, which they can parse for their own
109 needs. This can make some functions easier to type, eg `%cd ../`
109 needs. This can make some functions easier to type, eg `%cd ../`
110 vs. `%cd("../")`
110 vs. `%cd("../")`
111
111
112 ALL definitions MUST begin with the prefix magic_. The user won't need it
112 ALL definitions MUST begin with the prefix magic_. The user won't need it
113 at the command line, but it is is needed in the definition. """
113 at the command line, but it is is needed in the definition. """
114
114
115 # class globals
115 # class globals
116 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
116 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
117 'Automagic is ON, % prefix NOT needed for magic functions.']
117 'Automagic is ON, % prefix NOT needed for magic functions.']
118
118
119 #......................................................................
119 #......................................................................
120 # some utility functions
120 # some utility functions
121
121
122 def __init__(self,shell):
122 def __init__(self,shell):
123 # XXX This is hackish, clean up later to avoid these messy globals
123 # XXX This is hackish, clean up later to avoid these messy globals
124 global MAGIC_PREFIX, MAGIC_ESCAPE
124 global MAGIC_PREFIX, MAGIC_ESCAPE
125
125
126 self.options_table = {}
126 self.options_table = {}
127 MAGIC_PREFIX = shell.name+'.magic_'
127 MAGIC_PREFIX = shell.name+'.magic_'
128 MAGIC_ESCAPE = shell.ESC_MAGIC
128 MAGIC_ESCAPE = shell.ESC_MAGIC
129 if profile is None:
129 if profile is None:
130 self.magic_prun = self.profile_missing_notice
130 self.magic_prun = self.profile_missing_notice
131
131
132 def profile_missing_notice(self, *args, **kwargs):
132 def profile_missing_notice(self, *args, **kwargs):
133 error("""\
133 error("""\
134 The profile module could not be found. If you are a Debian user,
134 The profile module could not be found. If you are a Debian user,
135 it has been removed from the standard Debian package because of its non-free
135 it has been removed from the standard Debian package because of its non-free
136 license. To use profiling, please install"python2.3-profiler" from non-free.""")
136 license. To use profiling, please install"python2.3-profiler" from non-free.""")
137
137
138 def default_option(self,fn,optstr):
138 def default_option(self,fn,optstr):
139 """Make an entry in the options_table for fn, with value optstr"""
139 """Make an entry in the options_table for fn, with value optstr"""
140
140
141 if fn not in self.lsmagic():
141 if fn not in self.lsmagic():
142 error("%s is not a magic function" % fn)
142 error("%s is not a magic function" % fn)
143 self.options_table[fn] = optstr
143 self.options_table[fn] = optstr
144
144
145 def lsmagic(self):
145 def lsmagic(self):
146 """Return a list of currently available magic functions.
146 """Return a list of currently available magic functions.
147
147
148 Gives a list of the bare names after mangling (['ls','cd', ...], not
148 Gives a list of the bare names after mangling (['ls','cd', ...], not
149 ['magic_ls','magic_cd',...]"""
149 ['magic_ls','magic_cd',...]"""
150
150
151 # FIXME. This needs a cleanup, in the way the magics list is built.
151 # FIXME. This needs a cleanup, in the way the magics list is built.
152
152
153 # magics in class definition
153 # magics in class definition
154 class_magic = lambda fn: fn.startswith('magic_') and \
154 class_magic = lambda fn: fn.startswith('magic_') and \
155 callable(Magic.__dict__[fn])
155 callable(Magic.__dict__[fn])
156 # in instance namespace (run-time user additions)
156 # in instance namespace (run-time user additions)
157 inst_magic = lambda fn: fn.startswith('magic_') and \
157 inst_magic = lambda fn: fn.startswith('magic_') and \
158 callable(self.__dict__[fn])
158 callable(self.__dict__[fn])
159 # and bound magics by user (so they can access self):
159 # and bound magics by user (so they can access self):
160 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
160 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
161 callable(self.__class__.__dict__[fn])
161 callable(self.__class__.__dict__[fn])
162 magics = filter(class_magic,Magic.__dict__.keys()) + \
162 magics = filter(class_magic,Magic.__dict__.keys()) + \
163 filter(inst_magic,self.__dict__.keys()) + \
163 filter(inst_magic,self.__dict__.keys()) + \
164 filter(inst_bound_magic,self.__class__.__dict__.keys())
164 filter(inst_bound_magic,self.__class__.__dict__.keys())
165 out = []
165 out = []
166 for fn in magics:
166 for fn in magics:
167 out.append(fn.replace('magic_','',1))
167 out.append(fn.replace('magic_','',1))
168 out.sort()
168 out.sort()
169 return out
169 return out
170
170
171 def set_shell(self,shell):
171 def set_shell(self,shell):
172 self.shell = shell
172 self.shell = shell
173 self.alias_table = shell.alias_table
173 self.alias_table = shell.alias_table
174
174
175 def extract_input_slices(self,slices):
175 def extract_input_slices(self,slices):
176 """Return as a string a set of input history slices.
176 """Return as a string a set of input history slices.
177
177
178 The set of slices is given as a list of strings (like ['1','4:8','9'],
178 The set of slices is given as a list of strings (like ['1','4:8','9'],
179 since this function is for use by magic functions which get their
179 since this function is for use by magic functions which get their
180 arguments as strings."""
180 arguments as strings."""
181
181
182 cmds = []
182 cmds = []
183 for chunk in slices:
183 for chunk in slices:
184 if ':' in chunk:
184 if ':' in chunk:
185 ini,fin = map(int,chunk.split(':'))
185 ini,fin = map(int,chunk.split(':'))
186 else:
186 else:
187 ini = int(chunk)
187 ini = int(chunk)
188 fin = ini+1
188 fin = ini+1
189 cmds.append(self.shell.input_hist[ini:fin])
189 cmds.append(self.shell.input_hist[ini:fin])
190 return cmds
190 return cmds
191
191
192 def _ofind(self,oname):
192 def _ofind(self,oname):
193 """Find an object in the available namespaces.
193 """Find an object in the available namespaces.
194
194
195 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
195 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
196
196
197 Has special code to detect magic functions.
197 Has special code to detect magic functions.
198 """
198 """
199
199
200 oname = oname.strip()
200 oname = oname.strip()
201
201
202 # Namespaces to search in:
202 # Namespaces to search in:
203 user_ns = self.shell.user_ns
203 user_ns = self.shell.user_ns
204 internal_ns = self.shell.internal_ns
204 internal_ns = self.shell.internal_ns
205 builtin_ns = __builtin__.__dict__
205 builtin_ns = __builtin__.__dict__
206 alias_ns = self.shell.alias_table
206 alias_ns = self.shell.alias_table
207
207
208 # Put them in a list. The order is important so that we find things in
208 # Put them in a list. The order is important so that we find things in
209 # the same order that Python finds them.
209 # the same order that Python finds them.
210 namespaces = [ ('Interactive',user_ns),
210 namespaces = [ ('Interactive',user_ns),
211 ('IPython internal',internal_ns),
211 ('IPython internal',internal_ns),
212 ('Python builtin',builtin_ns),
212 ('Python builtin',builtin_ns),
213 ('Alias',alias_ns),
213 ('Alias',alias_ns),
214 ]
214 ]
215
215
216 # initialize results to 'null'
216 # initialize results to 'null'
217 found = 0; obj = None; ospace = None; ds = None;
217 found = 0; obj = None; ospace = None; ds = None;
218 ismagic = 0; isalias = 0
218 ismagic = 0; isalias = 0
219
219
220 # Look for the given name by splitting it in parts. If the head is
220 # Look for the given name by splitting it in parts. If the head is
221 # found, then we look for all the remaining parts as members, and only
221 # found, then we look for all the remaining parts as members, and only
222 # declare success if we can find them all.
222 # declare success if we can find them all.
223 oname_parts = oname.split('.')
223 oname_parts = oname.split('.')
224 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
224 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
225 for nsname,ns in namespaces:
225 for nsname,ns in namespaces:
226 try:
226 try:
227 obj = ns[oname_head]
227 obj = ns[oname_head]
228 except KeyError:
228 except KeyError:
229 continue
229 continue
230 else:
230 else:
231 for part in oname_rest:
231 for part in oname_rest:
232 try:
232 try:
233 obj = getattr(obj,part)
233 obj = getattr(obj,part)
234 except:
234 except:
235 # Blanket except b/c some badly implemented objects
235 # Blanket except b/c some badly implemented objects
236 # allow __getattr__ to raise exceptions other than
236 # allow __getattr__ to raise exceptions other than
237 # AttributeError, which then crashes IPython.
237 # AttributeError, which then crashes IPython.
238 break
238 break
239 else:
239 else:
240 # If we finish the for loop (no break), we got all members
240 # If we finish the for loop (no break), we got all members
241 found = 1
241 found = 1
242 ospace = nsname
242 ospace = nsname
243 if ns == alias_ns:
243 if ns == alias_ns:
244 isalias = 1
244 isalias = 1
245 break # namespace loop
245 break # namespace loop
246
246
247 # Try to see if it's magic
247 # Try to see if it's magic
248 if not found:
248 if not found:
249 if oname.startswith(self.shell.ESC_MAGIC):
249 if oname.startswith(self.shell.ESC_MAGIC):
250 oname = oname[1:]
250 oname = oname[1:]
251 obj = getattr(self,'magic_'+oname,None)
251 obj = getattr(self,'magic_'+oname,None)
252 if obj is not None:
252 if obj is not None:
253 found = 1
253 found = 1
254 ospace = 'IPython internal'
254 ospace = 'IPython internal'
255 ismagic = 1
255 ismagic = 1
256
256
257 # Last try: special-case some literals like '', [], {}, etc:
257 # Last try: special-case some literals like '', [], {}, etc:
258 if not found and oname_head in ["''",'""','[]','{}','()']:
258 if not found and oname_head in ["''",'""','[]','{}','()']:
259 obj = eval(oname_head)
259 obj = eval(oname_head)
260 found = 1
260 found = 1
261 ospace = 'Interactive'
261 ospace = 'Interactive'
262
262
263 return {'found':found, 'obj':obj, 'namespace':ospace,
263 return {'found':found, 'obj':obj, 'namespace':ospace,
264 'ismagic':ismagic, 'isalias':isalias}
264 'ismagic':ismagic, 'isalias':isalias}
265
265
266 def arg_err(self,func):
266 def arg_err(self,func):
267 """Print docstring if incorrect arguments were passed"""
267 """Print docstring if incorrect arguments were passed"""
268 print 'Error in arguments:'
268 print 'Error in arguments:'
269 print OInspect.getdoc(func)
269 print OInspect.getdoc(func)
270
270
271
271
272 def format_latex(self,str):
272 def format_latex(self,str):
273 """Format a string for latex inclusion."""
273 """Format a string for latex inclusion."""
274
274
275 # Characters that need to be escaped for latex:
275 # Characters that need to be escaped for latex:
276 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
276 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
277 # Magic command names as headers:
277 # Magic command names as headers:
278 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
278 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
279 re.MULTILINE)
279 re.MULTILINE)
280 # Magic commands
280 # Magic commands
281 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
281 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
282 re.MULTILINE)
282 re.MULTILINE)
283 # Paragraph continue
283 # Paragraph continue
284 par_re = re.compile(r'\\$',re.MULTILINE)
284 par_re = re.compile(r'\\$',re.MULTILINE)
285
285
286 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
286 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
287 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
287 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
288 str = par_re.sub(r'\\\\',str)
288 str = par_re.sub(r'\\\\',str)
289 str = escape_re.sub(r'\\\1',str)
289 str = escape_re.sub(r'\\\1',str)
290 return str
290 return str
291
291
292 def format_screen(self,str):
292 def format_screen(self,str):
293 """Format a string for screen printing.
293 """Format a string for screen printing.
294
294
295 This removes some latex-type format codes."""
295 This removes some latex-type format codes."""
296 # Paragraph continue
296 # Paragraph continue
297 par_re = re.compile(r'\\$',re.MULTILINE)
297 par_re = re.compile(r'\\$',re.MULTILINE)
298 str = par_re.sub('',str)
298 str = par_re.sub('',str)
299 return str
299 return str
300
300
301 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
301 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
302 """Parse options passed to an argument string.
302 """Parse options passed to an argument string.
303
303
304 The interface is similar to that of getopt(), but it returns back a
304 The interface is similar to that of getopt(), but it returns back a
305 Struct with the options as keys and the stripped argument string still
305 Struct with the options as keys and the stripped argument string still
306 as a string.
306 as a string.
307
307
308 arg_str is quoted as a true sys.argv vector by using shlex.split.
308 arg_str is quoted as a true sys.argv vector by using shlex.split.
309 This allows us to easily expand variables, glob files, quote
309 This allows us to easily expand variables, glob files, quote
310 arguments, etc.
310 arguments, etc.
311
311
312 Options:
312 Options:
313 -mode: default 'string'. If given as 'list', the argument string is
313 -mode: default 'string'. If given as 'list', the argument string is
314 returned as a list (split on whitespace) instead of a string.
314 returned as a list (split on whitespace) instead of a string.
315
315
316 -list_all: put all option values in lists. Normally only options
316 -list_all: put all option values in lists. Normally only options
317 appearing more than once are put in a list."""
317 appearing more than once are put in a list."""
318
318
319 # inject default options at the beginning of the input line
319 # inject default options at the beginning of the input line
320 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
320 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
321 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
321 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
322
322
323 mode = kw.get('mode','string')
323 mode = kw.get('mode','string')
324 if mode not in ['string','list']:
324 if mode not in ['string','list']:
325 raise ValueError,'incorrect mode given: %s' % mode
325 raise ValueError,'incorrect mode given: %s' % mode
326 # Get options
326 # Get options
327 list_all = kw.get('list_all',0)
327 list_all = kw.get('list_all',0)
328
328
329 # Check if we have more than one argument to warrant extra processing:
329 # Check if we have more than one argument to warrant extra processing:
330 odict = {} # Dictionary with options
330 odict = {} # Dictionary with options
331 args = arg_str.split()
331 args = arg_str.split()
332 if len(args) >= 1:
332 if len(args) >= 1:
333 # If the list of inputs only has 0 or 1 thing in it, there's no
333 # If the list of inputs only has 0 or 1 thing in it, there's no
334 # need to look for options
334 # need to look for options
335 argv = shlex_split(arg_str)
335 argv = shlex_split(arg_str)
336 # Do regular option processing
336 # Do regular option processing
337 opts,args = getopt(argv,opt_str,*long_opts)
337 opts,args = getopt(argv,opt_str,*long_opts)
338 for o,a in opts:
338 for o,a in opts:
339 if o.startswith('--'):
339 if o.startswith('--'):
340 o = o[2:]
340 o = o[2:]
341 else:
341 else:
342 o = o[1:]
342 o = o[1:]
343 try:
343 try:
344 odict[o].append(a)
344 odict[o].append(a)
345 except AttributeError:
345 except AttributeError:
346 odict[o] = [odict[o],a]
346 odict[o] = [odict[o],a]
347 except KeyError:
347 except KeyError:
348 if list_all:
348 if list_all:
349 odict[o] = [a]
349 odict[o] = [a]
350 else:
350 else:
351 odict[o] = a
351 odict[o] = a
352
352
353 # Prepare opts,args for return
353 # Prepare opts,args for return
354 opts = Struct(odict)
354 opts = Struct(odict)
355 if mode == 'string':
355 if mode == 'string':
356 args = ' '.join(args)
356 args = ' '.join(args)
357
357
358 return opts,args
358 return opts,args
359
359
360 #......................................................................
360 #......................................................................
361 # And now the actual magic functions
361 # And now the actual magic functions
362
362
363 # Functions for IPython shell work (vars,funcs, config, etc)
363 # Functions for IPython shell work (vars,funcs, config, etc)
364 def magic_lsmagic(self, parameter_s = ''):
364 def magic_lsmagic(self, parameter_s = ''):
365 """List currently available magic functions."""
365 """List currently available magic functions."""
366 mesc = self.shell.ESC_MAGIC
366 mesc = self.shell.ESC_MAGIC
367 print 'Available magic functions:\n'+mesc+\
367 print 'Available magic functions:\n'+mesc+\
368 (' '+mesc).join(self.lsmagic())
368 (' '+mesc).join(self.lsmagic())
369 print '\n' + Magic.auto_status[self.shell.rc.automagic]
369 print '\n' + Magic.auto_status[self.shell.rc.automagic]
370 return None
370 return None
371
371
372 def magic_magic(self, parameter_s = ''):
372 def magic_magic(self, parameter_s = ''):
373 """Print information about the magic function system."""
373 """Print information about the magic function system."""
374
374
375 mode = ''
375 mode = ''
376 try:
376 try:
377 if parameter_s.split()[0] == '-latex':
377 if parameter_s.split()[0] == '-latex':
378 mode = 'latex'
378 mode = 'latex'
379 except:
379 except:
380 pass
380 pass
381
381
382 magic_docs = []
382 magic_docs = []
383 for fname in self.lsmagic():
383 for fname in self.lsmagic():
384 mname = 'magic_' + fname
384 mname = 'magic_' + fname
385 for space in (Magic,self,self.__class__):
385 for space in (Magic,self,self.__class__):
386 try:
386 try:
387 fn = space.__dict__[mname]
387 fn = space.__dict__[mname]
388 except KeyError:
388 except KeyError:
389 pass
389 pass
390 else:
390 else:
391 break
391 break
392 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
392 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
393 fname,fn.__doc__))
393 fname,fn.__doc__))
394 magic_docs = ''.join(magic_docs)
394 magic_docs = ''.join(magic_docs)
395
395
396 if mode == 'latex':
396 if mode == 'latex':
397 print self.format_latex(magic_docs)
397 print self.format_latex(magic_docs)
398 return
398 return
399 else:
399 else:
400 magic_docs = self.format_screen(magic_docs)
400 magic_docs = self.format_screen(magic_docs)
401
401
402 outmsg = """
402 outmsg = """
403 IPython's 'magic' functions
403 IPython's 'magic' functions
404 ===========================
404 ===========================
405
405
406 The magic function system provides a series of functions which allow you to
406 The magic function system provides a series of functions which allow you to
407 control the behavior of IPython itself, plus a lot of system-type
407 control the behavior of IPython itself, plus a lot of system-type
408 features. All these functions are prefixed with a % character, but parameters
408 features. All these functions are prefixed with a % character, but parameters
409 are given without parentheses or quotes.
409 are given without parentheses or quotes.
410
410
411 NOTE: If you have 'automagic' enabled (via the command line option or with the
411 NOTE: If you have 'automagic' enabled (via the command line option or with the
412 %automagic function), you don't need to type in the % explicitly. By default,
412 %automagic function), you don't need to type in the % explicitly. By default,
413 IPython ships with automagic on, so you should only rarely need the % escape.
413 IPython ships with automagic on, so you should only rarely need the % escape.
414
414
415 Example: typing '%cd mydir' (without the quotes) changes you working directory
415 Example: typing '%cd mydir' (without the quotes) changes you working directory
416 to 'mydir', if it exists.
416 to 'mydir', if it exists.
417
417
418 You can define your own magic functions to extend the system. See the supplied
418 You can define your own magic functions to extend the system. See the supplied
419 ipythonrc and example-magic.py files for details (in your ipython
419 ipythonrc and example-magic.py files for details (in your ipython
420 configuration directory, typically $HOME/.ipython/).
420 configuration directory, typically $HOME/.ipython/).
421
421
422 You can also define your own aliased names for magic functions. In your
422 You can also define your own aliased names for magic functions. In your
423 ipythonrc file, placing a line like:
423 ipythonrc file, placing a line like:
424
424
425 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
425 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
426
426
427 will define %pf as a new name for %profile.
427 will define %pf as a new name for %profile.
428
428
429 You can also call magics in code using the ipmagic() function, which IPython
429 You can also call magics in code using the ipmagic() function, which IPython
430 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
430 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
431
431
432 For a list of the available magic functions, use %lsmagic. For a description
432 For a list of the available magic functions, use %lsmagic. For a description
433 of any of them, type %magic_name?, e.g. '%cd?'.
433 of any of them, type %magic_name?, e.g. '%cd?'.
434
434
435 Currently the magic system has the following functions:\n"""
435 Currently the magic system has the following functions:\n"""
436
436
437 mesc = self.shell.ESC_MAGIC
437 mesc = self.shell.ESC_MAGIC
438 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
438 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
439 "\n\n%s%s\n\n%s" % (outmsg,
439 "\n\n%s%s\n\n%s" % (outmsg,
440 magic_docs,mesc,mesc,
440 magic_docs,mesc,mesc,
441 (' '+mesc).join(self.lsmagic()),
441 (' '+mesc).join(self.lsmagic()),
442 Magic.auto_status[self.shell.rc.automagic] ) )
442 Magic.auto_status[self.shell.rc.automagic] ) )
443
443
444 page(outmsg,screen_lines=self.shell.rc.screen_length)
444 page(outmsg,screen_lines=self.shell.rc.screen_length)
445
445
446 def magic_automagic(self, parameter_s = ''):
446 def magic_automagic(self, parameter_s = ''):
447 """Make magic functions callable without having to type the initial %.
447 """Make magic functions callable without having to type the initial %.
448
448
449 Toggles on/off (when off, you must call it as %automagic, of
449 Toggles on/off (when off, you must call it as %automagic, of
450 course). Note that magic functions have lowest priority, so if there's
450 course). Note that magic functions have lowest priority, so if there's
451 a variable whose name collides with that of a magic fn, automagic
451 a variable whose name collides with that of a magic fn, automagic
452 won't work for that function (you get the variable instead). However,
452 won't work for that function (you get the variable instead). However,
453 if you delete the variable (del var), the previously shadowed magic
453 if you delete the variable (del var), the previously shadowed magic
454 function becomes visible to automagic again."""
454 function becomes visible to automagic again."""
455
455
456 rc = self.shell.rc
456 rc = self.shell.rc
457 rc.automagic = not rc.automagic
457 rc.automagic = not rc.automagic
458 print '\n' + Magic.auto_status[rc.automagic]
458 print '\n' + Magic.auto_status[rc.automagic]
459
459
460 def magic_autocall(self, parameter_s = ''):
460 def magic_autocall(self, parameter_s = ''):
461 """Make functions callable without having to type parentheses.
461 """Make functions callable without having to type parentheses.
462
462
463 This toggles the autocall command line option on and off."""
463 This toggles the autocall command line option on and off."""
464
464
465 rc = self.shell.rc
465 rc = self.shell.rc
466 rc.autocall = not rc.autocall
466 rc.autocall = not rc.autocall
467 print "Automatic calling is:",['OFF','ON'][rc.autocall]
467 print "Automatic calling is:",['OFF','ON'][rc.autocall]
468
468
469 def magic_autoindent(self, parameter_s = ''):
469 def magic_autoindent(self, parameter_s = ''):
470 """Toggle autoindent on/off (if available)."""
470 """Toggle autoindent on/off (if available)."""
471
471
472 self.shell.set_autoindent()
472 self.shell.set_autoindent()
473 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
473 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
474
474
475 def magic_system_verbose(self, parameter_s = ''):
475 def magic_system_verbose(self, parameter_s = ''):
476 """Toggle verbose printing of system calls on/off."""
476 """Toggle verbose printing of system calls on/off."""
477
477
478 self.shell.rc_set_toggle('system_verbose')
478 self.shell.rc_set_toggle('system_verbose')
479 print "System verbose printing is:",\
479 print "System verbose printing is:",\
480 ['OFF','ON'][self.shell.rc.system_verbose]
480 ['OFF','ON'][self.shell.rc.system_verbose]
481
481
482 def magic_history(self, parameter_s = ''):
482 def magic_history(self, parameter_s = ''):
483 """Print input history (_i<n> variables), with most recent last.
483 """Print input history (_i<n> variables), with most recent last.
484
484
485 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
485 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
486 %history [-n] n -> print at most n inputs\\
486 %history [-n] n -> print at most n inputs\\
487 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
487 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
488
488
489 Each input's number <n> is shown, and is accessible as the
489 Each input's number <n> is shown, and is accessible as the
490 automatically generated variable _i<n>. Multi-line statements are
490 automatically generated variable _i<n>. Multi-line statements are
491 printed starting at a new line for easy copy/paste.
491 printed starting at a new line for easy copy/paste.
492
492
493 If option -n is used, input numbers are not printed. This is useful if
493 If option -n is used, input numbers are not printed. This is useful if
494 you want to get a printout of many lines which can be directly pasted
494 you want to get a printout of many lines which can be directly pasted
495 into a text editor.
495 into a text editor.
496
496
497 This feature is only available if numbered prompts are in use."""
497 This feature is only available if numbered prompts are in use."""
498
498
499 if not self.do_full_cache:
499 if not self.do_full_cache:
500 print 'This feature is only available if numbered prompts are in use.'
500 print 'This feature is only available if numbered prompts are in use.'
501 return
501 return
502 opts,args = self.parse_options(parameter_s,'n',mode='list')
502 opts,args = self.parse_options(parameter_s,'n',mode='list')
503
503
504 default_length = 40
504 default_length = 40
505 if len(args) == 0:
505 if len(args) == 0:
506 final = self.outputcache.prompt_count
506 final = self.outputcache.prompt_count
507 init = max(1,final-default_length)
507 init = max(1,final-default_length)
508 elif len(args) == 1:
508 elif len(args) == 1:
509 final = self.outputcache.prompt_count
509 final = self.outputcache.prompt_count
510 init = max(1,final-int(args[0]))
510 init = max(1,final-int(args[0]))
511 elif len(args) == 2:
511 elif len(args) == 2:
512 init,final = map(int,args)
512 init,final = map(int,args)
513 else:
513 else:
514 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
514 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
515 print self.magic_hist.__doc__
515 print self.magic_hist.__doc__
516 return
516 return
517 width = len(str(final))
517 width = len(str(final))
518 line_sep = ['','\n']
518 line_sep = ['','\n']
519 input_hist = self.shell.input_hist
519 input_hist = self.shell.input_hist
520 print_nums = not opts.has_key('n')
520 print_nums = not opts.has_key('n')
521 for in_num in range(init,final):
521 for in_num in range(init,final):
522 inline = input_hist[in_num]
522 inline = input_hist[in_num]
523 multiline = inline.count('\n') > 1
523 multiline = inline.count('\n') > 1
524 if print_nums:
524 if print_nums:
525 print str(in_num).ljust(width)+':'+ line_sep[multiline],
525 print str(in_num).ljust(width)+':'+ line_sep[multiline],
526 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
526 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
527 inline.startswith('#!'):
527 inline.startswith('#!'):
528 print inline[1:],
528 print inline[1:],
529 else:
529 else:
530 print inline,
530 print inline,
531
531
532 def magic_hist(self, parameter_s=''):
532 def magic_hist(self, parameter_s=''):
533 """Alternate name for %history."""
533 """Alternate name for %history."""
534 return self.magic_history(parameter_s)
534 return self.magic_history(parameter_s)
535
535
536 def magic_p(self, parameter_s=''):
536 def magic_p(self, parameter_s=''):
537 """Just a short alias for Python's 'print'."""
537 """Just a short alias for Python's 'print'."""
538 exec 'print ' + parameter_s in self.shell.user_ns
538 exec 'print ' + parameter_s in self.shell.user_ns
539
539
540 def magic_r(self, parameter_s=''):
540 def magic_r(self, parameter_s=''):
541 """Repeat previous input.
541 """Repeat previous input.
542
542
543 If given an argument, repeats the previous command which starts with
543 If given an argument, repeats the previous command which starts with
544 the same string, otherwise it just repeats the previous input.
544 the same string, otherwise it just repeats the previous input.
545
545
546 Shell escaped commands (with ! as first character) are not recognized
546 Shell escaped commands (with ! as first character) are not recognized
547 by this system, only pure python code and magic commands.
547 by this system, only pure python code and magic commands.
548 """
548 """
549
549
550 start = parameter_s.strip()
550 start = parameter_s.strip()
551 esc_magic = self.shell.ESC_MAGIC
551 esc_magic = self.shell.ESC_MAGIC
552 # Identify magic commands even if automagic is on (which means
552 # Identify magic commands even if automagic is on (which means
553 # the in-memory version is different from that typed by the user).
553 # the in-memory version is different from that typed by the user).
554 if self.shell.rc.automagic:
554 if self.shell.rc.automagic:
555 start_magic = esc_magic+start
555 start_magic = esc_magic+start
556 else:
556 else:
557 start_magic = start
557 start_magic = start
558 # Look through the input history in reverse
558 # Look through the input history in reverse
559 for n in range(len(self.shell.input_hist)-2,0,-1):
559 for n in range(len(self.shell.input_hist)-2,0,-1):
560 input = self.shell.input_hist[n]
560 input = self.shell.input_hist[n]
561 # skip plain 'r' lines so we don't recurse to infinity
561 # skip plain 'r' lines so we don't recurse to infinity
562 if input != 'ipmagic("r")\n' and \
562 if input != 'ipmagic("r")\n' and \
563 (input.startswith(start) or input.startswith(start_magic)):
563 (input.startswith(start) or input.startswith(start_magic)):
564 #print 'match',`input` # dbg
564 #print 'match',`input` # dbg
565 if input.startswith(esc_magic):
565 if input.startswith(esc_magic):
566 input = magic2python(input)
566 input = magic2python(input)
567 #print 'modified',`input` # dbg
567 #print 'modified',`input` # dbg
568 print 'Executing:',input,
568 print 'Executing:',input,
569 exec input in self.shell.user_ns
569 exec input in self.shell.user_ns
570 return
570 return
571 print 'No previous input matching `%s` found.' % start
571 print 'No previous input matching `%s` found.' % start
572
572
573 def magic_page(self, parameter_s=''):
573 def magic_page(self, parameter_s=''):
574 """Pretty print the object and display it through a pager.
574 """Pretty print the object and display it through a pager.
575
575
576 If no parameter is given, use _ (last output)."""
576 If no parameter is given, use _ (last output)."""
577 # After a function contributed by Olivier Aubert, slightly modified.
577 # After a function contributed by Olivier Aubert, slightly modified.
578
578
579 oname = parameter_s and parameter_s or '_'
579 oname = parameter_s and parameter_s or '_'
580 info = self._ofind(oname)
580 info = self._ofind(oname)
581 if info['found']:
581 if info['found']:
582 page(pformat(info['obj']))
582 page(pformat(info['obj']))
583 else:
583 else:
584 print 'Object `%s` not found' % oname
584 print 'Object `%s` not found' % oname
585
585
586 def magic_profile(self, parameter_s=''):
586 def magic_profile(self, parameter_s=''):
587 """Print your currently active IPyhton profile."""
587 """Print your currently active IPyhton profile."""
588 if self.shell.rc.profile:
588 if self.shell.rc.profile:
589 printpl('Current IPython profile: $self.shell.rc.profile.')
589 printpl('Current IPython profile: $self.shell.rc.profile.')
590 else:
590 else:
591 print 'No profile active.'
591 print 'No profile active.'
592
592
593 def _inspect(self,meth,oname,**kw):
593 def _inspect(self,meth,oname,**kw):
594 """Generic interface to the inspector system.
594 """Generic interface to the inspector system.
595
595
596 This function is meant to be called by pdef, pdoc & friends."""
596 This function is meant to be called by pdef, pdoc & friends."""
597
597
598 oname = oname.strip()
598 oname = oname.strip()
599 info = Struct(self._ofind(oname))
599 info = Struct(self._ofind(oname))
600 if info.found:
600 if info.found:
601 pmethod = getattr(self.shell.inspector,meth)
601 pmethod = getattr(self.shell.inspector,meth)
602 formatter = info.ismagic and self.format_screen or None
602 formatter = info.ismagic and self.format_screen or None
603 if meth == 'pdoc':
603 if meth == 'pdoc':
604 pmethod(info.obj,oname,formatter)
604 pmethod(info.obj,oname,formatter)
605 elif meth == 'pinfo':
605 elif meth == 'pinfo':
606 pmethod(info.obj,oname,formatter,info,**kw)
606 pmethod(info.obj,oname,formatter,info,**kw)
607 else:
607 else:
608 pmethod(info.obj,oname)
608 pmethod(info.obj,oname)
609 else:
609 else:
610 print 'Object `%s` not found.' % oname
610 print 'Object `%s` not found.' % oname
611 return 'not found' # so callers can take other action
611 return 'not found' # so callers can take other action
612
612
613 def magic_pdef(self, parameter_s=''):
613 def magic_pdef(self, parameter_s=''):
614 """Print the definition header for any callable object.
614 """Print the definition header for any callable object.
615
615
616 If the object is a class, print the constructor information."""
616 If the object is a class, print the constructor information."""
617 self._inspect('pdef',parameter_s)
617 self._inspect('pdef',parameter_s)
618
618
619 def magic_pdoc(self, parameter_s=''):
619 def magic_pdoc(self, parameter_s=''):
620 """Print the docstring for an object.
620 """Print the docstring for an object.
621
621
622 If the given object is a class, it will print both the class and the
622 If the given object is a class, it will print both the class and the
623 constructor docstrings."""
623 constructor docstrings."""
624 self._inspect('pdoc',parameter_s)
624 self._inspect('pdoc',parameter_s)
625
625
626 def magic_psource(self, parameter_s=''):
626 def magic_psource(self, parameter_s=''):
627 """Print (or run through pager) the source code for an object."""
627 """Print (or run through pager) the source code for an object."""
628 self._inspect('psource',parameter_s)
628 self._inspect('psource',parameter_s)
629
629
630 def magic_pfile(self, parameter_s=''):
630 def magic_pfile(self, parameter_s=''):
631 """Print (or run through pager) the file where an object is defined.
631 """Print (or run through pager) the file where an object is defined.
632
632
633 The file opens at the line where the object definition begins. IPython
633 The file opens at the line where the object definition begins. IPython
634 will honor the environment variable PAGER if set, and otherwise will
634 will honor the environment variable PAGER if set, and otherwise will
635 do its best to print the file in a convenient form.
635 do its best to print the file in a convenient form.
636
636
637 If the given argument is not an object currently defined, IPython will
637 If the given argument is not an object currently defined, IPython will
638 try to interpret it as a filename (automatically adding a .py extension
638 try to interpret it as a filename (automatically adding a .py extension
639 if needed). You can thus use %pfile as a syntax highlighting code
639 if needed). You can thus use %pfile as a syntax highlighting code
640 viewer."""
640 viewer."""
641
641
642 # first interpret argument as an object name
642 # first interpret argument as an object name
643 out = self._inspect('pfile',parameter_s)
643 out = self._inspect('pfile',parameter_s)
644 # if not, try the input as a filename
644 # if not, try the input as a filename
645 if out == 'not found':
645 if out == 'not found':
646 try:
646 try:
647 filename = get_py_filename(parameter_s)
647 filename = get_py_filename(parameter_s)
648 except IOError,msg:
648 except IOError,msg:
649 print msg
649 print msg
650 return
650 return
651 page(self.shell.inspector.format(file(filename).read()))
651 page(self.shell.inspector.format(file(filename).read()))
652
652
653 def magic_pinfo(self, parameter_s=''):
653 def magic_pinfo(self, parameter_s=''):
654 """Provide detailed information about an object.
654 """Provide detailed information about an object.
655
655
656 '%pinfo object' is just a synonym for object? or ?object."""
656 '%pinfo object' is just a synonym for object? or ?object."""
657
657
658 #print 'pinfo par: <%s>' % parameter_s # dbg
658 #print 'pinfo par: <%s>' % parameter_s # dbg
659
659
660 # detail_level: 0 -> obj? , 1 -> obj??
660 # detail_level: 0 -> obj? , 1 -> obj??
661 detail_level = 0
661 detail_level = 0
662 # We need to detect if we got called as 'pinfo pinfo foo', which can
662 # We need to detect if we got called as 'pinfo pinfo foo', which can
663 # happen if the user types 'pinfo foo?' at the cmd line.
663 # happen if the user types 'pinfo foo?' at the cmd line.
664 pinfo,qmark1,oname,qmark2 = \
664 pinfo,qmark1,oname,qmark2 = \
665 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
665 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
666 if pinfo or qmark1 or qmark2:
666 if pinfo or qmark1 or qmark2:
667 detail_level = 1
667 detail_level = 1
668 if "*" in oname:
668 if "*" in oname:
669 self.magic_psearch(oname)
669 self.magic_psearch(oname)
670 else:
670 else:
671 self._inspect('pinfo',oname,detail_level=detail_level)
671 self._inspect('pinfo',oname,detail_level=detail_level)
672
672
673 def magic_psearch(self, parameter_s=''):
673 def magic_psearch(self, parameter_s=''):
674 """Search for object in namespaces by wildcard.
674 """Search for object in namespaces by wildcard.
675
675
676 %psearch [options] PATTERN [OBJECT TYPE]
676 %psearch [options] PATTERN [OBJECT TYPE]
677
677
678 Note: ? can be used as a synonym for %psearch, at the beginning or at
678 Note: ? can be used as a synonym for %psearch, at the beginning or at
679 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
679 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
680 rest of the command line must be unchanged (options come first), so
680 rest of the command line must be unchanged (options come first), so
681 for example the following forms are equivalent
681 for example the following forms are equivalent
682
682
683 %psearch -i a* function
683 %psearch -i a* function
684 -i a* function?
684 -i a* function?
685 ?-i a* function
685 ?-i a* function
686
686
687 Arguments:
687 Arguments:
688
688
689 PATTERN
689 PATTERN
690
690
691 where PATTERN is a string containing * as a wildcard similar to its
691 where PATTERN is a string containing * as a wildcard similar to its
692 use in a shell. The pattern is matched in all namespaces on the
692 use in a shell. The pattern is matched in all namespaces on the
693 search path. By default objects starting with a single _ are not
693 search path. By default objects starting with a single _ are not
694 matched, many IPython generated objects have a single
694 matched, many IPython generated objects have a single
695 underscore. The default is case insensitive matching. Matching is
695 underscore. The default is case insensitive matching. Matching is
696 also done on the attributes of objects and not only on the objects
696 also done on the attributes of objects and not only on the objects
697 in a module.
697 in a module.
698
698
699 [OBJECT TYPE]
699 [OBJECT TYPE]
700
700
701 Is the name of a python type from the types module. The name is
701 Is the name of a python type from the types module. The name is
702 given in lowercase without the ending type, ex. StringType is
702 given in lowercase without the ending type, ex. StringType is
703 written string. By adding a type here only objects matching the
703 written string. By adding a type here only objects matching the
704 given type are matched. Using all here makes the pattern match all
704 given type are matched. Using all here makes the pattern match all
705 types (this is the default).
705 types (this is the default).
706
706
707 Options:
707 Options:
708
708
709 -a: makes the pattern match even objects whose names start with a
709 -a: makes the pattern match even objects whose names start with a
710 single underscore. These names are normally ommitted from the
710 single underscore. These names are normally ommitted from the
711 search.
711 search.
712
712
713 -i/-c: make the pattern case insensitive/sensitive. If neither of
713 -i/-c: make the pattern case insensitive/sensitive. If neither of
714 these options is given, the default is read from your ipythonrc
714 these options is given, the default is read from your ipythonrc
715 file. The option name which sets this value is
715 file. The option name which sets this value is
716 'wildcards_case_sensitive'. If this option is not specified in your
716 'wildcards_case_sensitive'. If this option is not specified in your
717 ipythonrc file, IPython's internal default is to do a case sensitive
717 ipythonrc file, IPython's internal default is to do a case sensitive
718 search.
718 search.
719
719
720 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
720 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
721 specifiy can be searched in any of the following namespaces:
721 specifiy can be searched in any of the following namespaces:
722 'builtin', 'user', 'user_global','internal', 'alias', where
722 'builtin', 'user', 'user_global','internal', 'alias', where
723 'builtin' and 'user' are the search defaults. Note that you should
723 'builtin' and 'user' are the search defaults. Note that you should
724 not use quotes when specifying namespaces.
724 not use quotes when specifying namespaces.
725
725
726 'Builtin' contains the python module builtin, 'user' contains all
726 'Builtin' contains the python module builtin, 'user' contains all
727 user data, 'alias' only contain the shell aliases and no python
727 user data, 'alias' only contain the shell aliases and no python
728 objects, 'internal' contains objects used by IPython. The
728 objects, 'internal' contains objects used by IPython. The
729 'user_global' namespace is only used by embedded IPython instances,
729 'user_global' namespace is only used by embedded IPython instances,
730 and it contains module-level globals. You can add namespaces to the
730 and it contains module-level globals. You can add namespaces to the
731 search with -s or exclude them with -e (these options can be given
731 search with -s or exclude them with -e (these options can be given
732 more than once).
732 more than once).
733
733
734 Examples:
734 Examples:
735
735
736 %psearch a* -> objects beginning with an a
736 %psearch a* -> objects beginning with an a
737 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
737 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
738 %psearch a* function -> all functions beginning with an a
738 %psearch a* function -> all functions beginning with an a
739 %psearch re.e* -> objects beginning with an e in module re
739 %psearch re.e* -> objects beginning with an e in module re
740 %psearch r*.e* -> objects that start with e in modules starting in r
740 %psearch r*.e* -> objects that start with e in modules starting in r
741 %psearch r*.* string -> all strings in modules beginning with r
741 %psearch r*.* string -> all strings in modules beginning with r
742
742
743 Case sensitve search:
743 Case sensitve search:
744
744
745 %psearch -c a* list all object beginning with lower case a
745 %psearch -c a* list all object beginning with lower case a
746
746
747 Show objects beginning with a single _:
747 Show objects beginning with a single _:
748
748
749 %psearch -a _* list objects beginning with a single underscore"""
749 %psearch -a _* list objects beginning with a single underscore"""
750
750
751 # default namespaces to be searched
751 # default namespaces to be searched
752 def_search = ['user','builtin']
752 def_search = ['user','builtin']
753
753
754 # Process options/args
754 # Process options/args
755 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
755 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
756 opt = opts.get
756 opt = opts.get
757 shell = self.shell
757 shell = self.shell
758 psearch = shell.inspector.psearch
758 psearch = shell.inspector.psearch
759
759
760 # select case options
760 # select case options
761 if opts.has_key('i'):
761 if opts.has_key('i'):
762 ignore_case = True
762 ignore_case = True
763 elif opts.has_key('c'):
763 elif opts.has_key('c'):
764 ignore_case = False
764 ignore_case = False
765 else:
765 else:
766 ignore_case = not shell.rc.wildcards_case_sensitive
766 ignore_case = not shell.rc.wildcards_case_sensitive
767
767
768 # Build list of namespaces to search from user options
768 # Build list of namespaces to search from user options
769 def_search.extend(opt('s',[]))
769 def_search.extend(opt('s',[]))
770 ns_exclude = ns_exclude=opt('e',[])
770 ns_exclude = ns_exclude=opt('e',[])
771 ns_search = [nm for nm in def_search if nm not in ns_exclude]
771 ns_search = [nm for nm in def_search if nm not in ns_exclude]
772
772
773 # Call the actual search
773 # Call the actual search
774 try:
774 try:
775 psearch(args,shell.ns_table,ns_search,
775 psearch(args,shell.ns_table,ns_search,
776 show_all=opt('a'),ignore_case=ignore_case)
776 show_all=opt('a'),ignore_case=ignore_case)
777 except:
777 except:
778 shell.showtraceback()
778 shell.showtraceback()
779
779
780 def magic_who_ls(self, parameter_s=''):
780 def magic_who_ls(self, parameter_s=''):
781 """Return a sorted list of all interactive variables.
781 """Return a sorted list of all interactive variables.
782
782
783 If arguments are given, only variables of types matching these
783 If arguments are given, only variables of types matching these
784 arguments are returned."""
784 arguments are returned."""
785
785
786 user_ns = self.shell.user_ns
786 user_ns = self.shell.user_ns
787 out = []
787 out = []
788 typelist = parameter_s.split()
788 typelist = parameter_s.split()
789 for i in self.shell.user_ns.keys():
789 for i in self.shell.user_ns.keys():
790 if not (i.startswith('_') or i.startswith('_i')) \
790 if not (i.startswith('_') or i.startswith('_i')) \
791 and not (self.internal_ns.has_key(i) or
791 and not (self.internal_ns.has_key(i) or
792 self.user_config_ns.has_key(i)):
792 self.user_config_ns.has_key(i)):
793 if typelist:
793 if typelist:
794 if type(user_ns[i]).__name__ in typelist:
794 if type(user_ns[i]).__name__ in typelist:
795 out.append(i)
795 out.append(i)
796 else:
796 else:
797 out.append(i)
797 out.append(i)
798 out.sort()
798 out.sort()
799 return out
799 return out
800
800
801 def magic_who(self, parameter_s=''):
801 def magic_who(self, parameter_s=''):
802 """Print all interactive variables, with some minimal formatting.
802 """Print all interactive variables, with some minimal formatting.
803
803
804 If any arguments are given, only variables whose type matches one of
804 If any arguments are given, only variables whose type matches one of
805 these are printed. For example:
805 these are printed. For example:
806
806
807 %who function str
807 %who function str
808
808
809 will only list functions and strings, excluding all other types of
809 will only list functions and strings, excluding all other types of
810 variables. To find the proper type names, simply use type(var) at a
810 variables. To find the proper type names, simply use type(var) at a
811 command line to see how python prints type names. For example:
811 command line to see how python prints type names. For example:
812
812
813 In [1]: type('hello')\\
813 In [1]: type('hello')\\
814 Out[1]: <type 'str'>
814 Out[1]: <type 'str'>
815
815
816 indicates that the type name for strings is 'str'.
816 indicates that the type name for strings is 'str'.
817
817
818 %who always excludes executed names loaded through your configuration
818 %who always excludes executed names loaded through your configuration
819 file and things which are internal to IPython.
819 file and things which are internal to IPython.
820
820
821 This is deliberate, as typically you may load many modules and the
821 This is deliberate, as typically you may load many modules and the
822 purpose of %who is to show you only what you've manually defined."""
822 purpose of %who is to show you only what you've manually defined."""
823
823
824 varlist = self.magic_who_ls(parameter_s)
824 varlist = self.magic_who_ls(parameter_s)
825 if not varlist:
825 if not varlist:
826 print 'Interactive namespace is empty.'
826 print 'Interactive namespace is empty.'
827 return
827 return
828
828
829 # if we have variables, move on...
829 # if we have variables, move on...
830
830
831 # stupid flushing problem: when prompts have no separators, stdout is
831 # stupid flushing problem: when prompts have no separators, stdout is
832 # getting lost. I'm starting to think this is a python bug. I'm having
832 # getting lost. I'm starting to think this is a python bug. I'm having
833 # to force a flush with a print because even a sys.stdout.flush
833 # to force a flush with a print because even a sys.stdout.flush
834 # doesn't seem to do anything!
834 # doesn't seem to do anything!
835
835
836 count = 0
836 count = 0
837 for i in varlist:
837 for i in varlist:
838 print i+'\t',
838 print i+'\t',
839 count += 1
839 count += 1
840 if count > 8:
840 if count > 8:
841 count = 0
841 count = 0
842 print
842 print
843 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
843 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
844
844
845 print # well, this does force a flush at the expense of an extra \n
845 print # well, this does force a flush at the expense of an extra \n
846
846
847 def magic_whos(self, parameter_s=''):
847 def magic_whos(self, parameter_s=''):
848 """Like %who, but gives some extra information about each variable.
848 """Like %who, but gives some extra information about each variable.
849
849
850 The same type filtering of %who can be applied here.
850 The same type filtering of %who can be applied here.
851
851
852 For all variables, the type is printed. Additionally it prints:
852 For all variables, the type is printed. Additionally it prints:
853
853
854 - For {},[],(): their length.
854 - For {},[],(): their length.
855
855
856 - For Numeric arrays, a summary with shape, number of elements,
856 - For Numeric arrays, a summary with shape, number of elements,
857 typecode and size in memory.
857 typecode and size in memory.
858
858
859 - Everything else: a string representation, snipping their middle if
859 - Everything else: a string representation, snipping their middle if
860 too long."""
860 too long."""
861
861
862 varnames = self.magic_who_ls(parameter_s)
862 varnames = self.magic_who_ls(parameter_s)
863 if not varnames:
863 if not varnames:
864 print 'Interactive namespace is empty.'
864 print 'Interactive namespace is empty.'
865 return
865 return
866
866
867 # if we have variables, move on...
867 # if we have variables, move on...
868
868
869 # for these types, show len() instead of data:
869 # for these types, show len() instead of data:
870 seq_types = [types.DictType,types.ListType,types.TupleType]
870 seq_types = [types.DictType,types.ListType,types.TupleType]
871
871
872 # for Numeric arrays, display summary info
872 # for Numeric arrays, display summary info
873 try:
873 try:
874 import Numeric
874 import Numeric
875 except ImportError:
875 except ImportError:
876 array_type = None
876 array_type = None
877 else:
877 else:
878 array_type = Numeric.ArrayType.__name__
878 array_type = Numeric.ArrayType.__name__
879
879
880 # Find all variable names and types so we can figure out column sizes
880 # Find all variable names and types so we can figure out column sizes
881 get_vars = lambda i: self.shell.user_ns[i]
881 get_vars = lambda i: self.shell.user_ns[i]
882 type_name = lambda v: type(v).__name__
882 type_name = lambda v: type(v).__name__
883 varlist = map(get_vars,varnames)
883 varlist = map(get_vars,varnames)
884 typelist = map(type_name,varlist)
884 typelist = map(type_name,varlist)
885 # column labels and # of spaces as separator
885 # column labels and # of spaces as separator
886 varlabel = 'Variable'
886 varlabel = 'Variable'
887 typelabel = 'Type'
887 typelabel = 'Type'
888 datalabel = 'Data/Info'
888 datalabel = 'Data/Info'
889 colsep = 3
889 colsep = 3
890 # variable format strings
890 # variable format strings
891 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
891 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
892 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
892 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
893 aformat = "%s: %s elems, type `%s`, %s bytes"
893 aformat = "%s: %s elems, type `%s`, %s bytes"
894 # find the size of the columns to format the output nicely
894 # find the size of the columns to format the output nicely
895 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
895 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
896 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
896 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
897 # table header
897 # table header
898 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
898 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
899 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
899 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
900 # and the table itself
900 # and the table itself
901 kb = 1024
901 kb = 1024
902 Mb = 1048576 # kb**2
902 Mb = 1048576 # kb**2
903 for vname,var,vtype in zip(varnames,varlist,typelist):
903 for vname,var,vtype in zip(varnames,varlist,typelist):
904 print itpl(vformat),
904 print itpl(vformat),
905 if vtype in seq_types:
905 if vtype in seq_types:
906 print len(var)
906 print len(var)
907 elif vtype==array_type:
907 elif vtype==array_type:
908 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
908 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
909 vsize = Numeric.size(var)
909 vsize = Numeric.size(var)
910 vbytes = vsize*var.itemsize()
910 vbytes = vsize*var.itemsize()
911 if vbytes < 100000:
911 if vbytes < 100000:
912 print aformat % (vshape,vsize,var.typecode(),vbytes)
912 print aformat % (vshape,vsize,var.typecode(),vbytes)
913 else:
913 else:
914 print aformat % (vshape,vsize,var.typecode(),vbytes),
914 print aformat % (vshape,vsize,var.typecode(),vbytes),
915 if vbytes < Mb:
915 if vbytes < Mb:
916 print '(%s kb)' % (vbytes/kb,)
916 print '(%s kb)' % (vbytes/kb,)
917 else:
917 else:
918 print '(%s Mb)' % (vbytes/Mb,)
918 print '(%s Mb)' % (vbytes/Mb,)
919 else:
919 else:
920 vstr = str(var)
920 vstr = str(var)
921 if len(vstr) < 50:
921 if len(vstr) < 50:
922 print vstr
922 print vstr
923 else:
923 else:
924 printpl(vfmt_short)
924 printpl(vfmt_short)
925
925
926 def magic_reset(self, parameter_s=''):
926 def magic_reset(self, parameter_s=''):
927 """Resets the namespace by removing all names defined by the user.
927 """Resets the namespace by removing all names defined by the user.
928
928
929 Input/Output history are left around in case you need them."""
929 Input/Output history are left around in case you need them."""
930
930
931 ans = raw_input(
931 ans = raw_input(
932 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
932 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
933 if not ans.lower() == 'y':
933 if not ans.lower() == 'y':
934 print 'Nothing done.'
934 print 'Nothing done.'
935 return
935 return
936 user_ns = self.shell.user_ns
936 user_ns = self.shell.user_ns
937 for i in self.magic_who_ls():
937 for i in self.magic_who_ls():
938 del(user_ns[i])
938 del(user_ns[i])
939
939
940 def magic_config(self,parameter_s=''):
940 def magic_config(self,parameter_s=''):
941 """Show IPython's internal configuration."""
941 """Show IPython's internal configuration."""
942
942
943 page('Current configuration structure:\n'+
943 page('Current configuration structure:\n'+
944 pformat(self.shell.rc.dict()))
944 pformat(self.shell.rc.dict()))
945
945
946 def magic_logstart(self,parameter_s=''):
946 def magic_logstart(self,parameter_s=''):
947 """Start logging anywhere in a session.
947 """Start logging anywhere in a session.
948
948
949 %logstart [log_name [log_mode]]
949 %logstart [log_name [log_mode]]
950
950
951 If no name is given, it defaults to a file named 'ipython.log' in your
951 If no name is given, it defaults to a file named 'ipython.log' in your
952 current directory, in 'rotate' mode (see below).
952 current directory, in 'rotate' mode (see below).
953
953
954 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
954 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
955 history up to that point and then continues logging.
955 history up to that point and then continues logging.
956
956
957 %logstart takes a second optional parameter: logging mode. This can be one
957 %logstart takes a second optional parameter: logging mode. This can be one
958 of (note that the modes are given unquoted):\\
958 of (note that the modes are given unquoted):\\
959 over: overwrite existing log.\\
959 over: overwrite existing log.\\
960 backup: rename (if exists) to name~ and start name.\\
960 backup: rename (if exists) to name~ and start name.\\
961 append: well, that says it.\\
961 append: well, that says it.\\
962 rotate: create rotating logs name.1~, name.2~, etc.
962 rotate: create rotating logs name.1~, name.2~, etc.
963 """
963 """
964
964
965 #FIXME. This function should all be moved to the Logger class.
965 #FIXME. This function should all be moved to the Logger class.
966
966
967 valid_modes = qw('over backup append rotate')
967 valid_modes = qw('over backup append rotate')
968 if self.LOG:
968 if self.LOG:
969 print 'Logging is already in place. Logfile:',self.LOG
969 print 'Logging is already in place. Logfile:',self.LOG
970 return
970 return
971
971
972 par = parameter_s.strip()
972 par = parameter_s.strip()
973 if not par:
973 if not par:
974 logname = self.LOGDEF
974 logname = self.LOGDEF
975 logmode = 'rotate' # use rotate for the auto-generated logs
975 logmode = 'rotate' # use rotate for the auto-generated logs
976 else:
976 else:
977 try:
977 try:
978 logname,logmode = par.split()
978 logname,logmode = par.split()
979 except:
979 except:
980 try:
980 try:
981 logname = par
981 logname = par
982 logmode = 'backup'
982 logmode = 'backup'
983 except:
983 except:
984 warn('Usage: %log [log_name [log_mode]]')
984 warn('Usage: %log [log_name [log_mode]]')
985 return
985 return
986 if not logmode in valid_modes:
986 if not logmode in valid_modes:
987 warn('Logging NOT activated.\n'
987 warn('Logging NOT activated.\n'
988 'Usage: %log [log_name [log_mode]]\n'
988 'Usage: %log [log_name [log_mode]]\n'
989 'Valid modes: '+str(valid_modes))
989 'Valid modes: '+str(valid_modes))
990 return
990 return
991
991
992 # If we made it this far, I think we're ok:
992 # If we made it this far, I think we're ok:
993 print 'Activating auto-logging.'
993 print 'Activating auto-logging.'
994 print 'Current session state plus future input saved to:',logname
994 print 'Current session state plus future input saved to:',logname
995 print 'Logging mode: ',logmode
995 print 'Logging mode: ',logmode
996 # put logname into rc struct as if it had been called on the command line,
996 # put logname into rc struct as if it had been called on the command line,
997 # so it ends up saved in the log header
997 # so it ends up saved in the log header
998 # Save it in case we need to restore it...
998 # Save it in case we need to restore it...
999 old_logfile = self.shell.rc.opts.get('logfile','')
999 old_logfile = self.shell.rc.opts.get('logfile','')
1000 logname = os.path.expanduser(logname)
1000 logname = os.path.expanduser(logname)
1001 self.shell.rc.opts.logfile = logname
1001 self.shell.rc.opts.logfile = logname
1002 self.LOGMODE = logmode # FIXME: this should be set through a function.
1002 self.LOGMODE = logmode # FIXME: this should be set through a function.
1003 try:
1003 try:
1004 header = str(self.LOGHEAD)
1004 header = str(self.LOGHEAD)
1005 self.create_log(header,logname)
1005 self.create_log(header,logname)
1006 self.logstart(header,logname)
1006 self.logstart(header,logname)
1007 except:
1007 except:
1008 self.LOG = '' # we are NOT logging, something went wrong
1008 self.LOG = '' # we are NOT logging, something went wrong
1009 self.shell.rc.opts.logfile = old_logfile
1009 self.shell.rc.opts.logfile = old_logfile
1010 warn("Couldn't start log: "+str(sys.exc_info()[1]))
1010 warn("Couldn't start log: "+str(sys.exc_info()[1]))
1011 else: # log input history up to this point
1011 else: # log input history up to this point
1012 self.logfile.write(self.shell.user_ns['_ih'][1:])
1012 self.logfile.write(self.shell.user_ns['_ih'][1:])
1013 self.logfile.flush()
1013 self.logfile.flush()
1014
1014
1015 def magic_logoff(self,parameter_s=''):
1015 def magic_logoff(self,parameter_s=''):
1016 """Temporarily stop logging.
1016 """Temporarily stop logging.
1017
1017
1018 You must have previously started logging."""
1018 You must have previously started logging."""
1019 self.switch_log(0)
1019 self.switch_log(0)
1020
1020
1021 def magic_logon(self,parameter_s=''):
1021 def magic_logon(self,parameter_s=''):
1022 """Restart logging.
1022 """Restart logging.
1023
1023
1024 This function is for restarting logging which you've temporarily
1024 This function is for restarting logging which you've temporarily
1025 stopped with %logoff. For starting logging for the first time, you
1025 stopped with %logoff. For starting logging for the first time, you
1026 must use the %logstart function, which allows you to specify an
1026 must use the %logstart function, which allows you to specify an
1027 optional log filename."""
1027 optional log filename."""
1028
1028
1029 self.switch_log(1)
1029 self.switch_log(1)
1030
1030
1031 def magic_logstate(self,parameter_s=''):
1031 def magic_logstate(self,parameter_s=''):
1032 """Print the status of the logging system."""
1032 """Print the status of the logging system."""
1033
1033
1034 self.logstate()
1034 self.logstate()
1035
1035
1036 def magic_pdb(self, parameter_s=''):
1036 def magic_pdb(self, parameter_s=''):
1037 """Control the calling of the pdb interactive debugger.
1037 """Control the calling of the pdb interactive debugger.
1038
1038
1039 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1039 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1040 argument it works as a toggle.
1040 argument it works as a toggle.
1041
1041
1042 When an exception is triggered, IPython can optionally call the
1042 When an exception is triggered, IPython can optionally call the
1043 interactive pdb debugger after the traceback printout. %pdb toggles
1043 interactive pdb debugger after the traceback printout. %pdb toggles
1044 this feature on and off."""
1044 this feature on and off."""
1045
1045
1046 par = parameter_s.strip().lower()
1046 par = parameter_s.strip().lower()
1047
1047
1048 if par:
1048 if par:
1049 try:
1049 try:
1050 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1050 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1051 except KeyError:
1051 except KeyError:
1052 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
1052 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
1053 return
1053 return
1054 else:
1054 else:
1055 self.shell.InteractiveTB.call_pdb = pdb
1055 self.shell.InteractiveTB.call_pdb = pdb
1056 else:
1056 else:
1057 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
1057 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
1058 print 'Automatic pdb calling has been turned',\
1058 print 'Automatic pdb calling has been turned',\
1059 on_off(self.shell.InteractiveTB.call_pdb)
1059 on_off(self.shell.InteractiveTB.call_pdb)
1060
1060
1061
1061
1062 def magic_prun(self, parameter_s ='',user_mode=1,
1062 def magic_prun(self, parameter_s ='',user_mode=1,
1063 opts=None,arg_lst=None,prog_ns=None):
1063 opts=None,arg_lst=None,prog_ns=None):
1064
1064
1065 """Run a statement through the python code profiler.
1065 """Run a statement through the python code profiler.
1066
1066
1067 Usage:\\
1067 Usage:\\
1068 %prun [options] statement
1068 %prun [options] statement
1069
1069
1070 The given statement (which doesn't require quote marks) is run via the
1070 The given statement (which doesn't require quote marks) is run via the
1071 python profiler in a manner similar to the profile.run() function.
1071 python profiler in a manner similar to the profile.run() function.
1072 Namespaces are internally managed to work correctly; profile.run
1072 Namespaces are internally managed to work correctly; profile.run
1073 cannot be used in IPython because it makes certain assumptions about
1073 cannot be used in IPython because it makes certain assumptions about
1074 namespaces which do not hold under IPython.
1074 namespaces which do not hold under IPython.
1075
1075
1076 Options:
1076 Options:
1077
1077
1078 -l <limit>: you can place restrictions on what or how much of the
1078 -l <limit>: you can place restrictions on what or how much of the
1079 profile gets printed. The limit value can be:
1079 profile gets printed. The limit value can be:
1080
1080
1081 * A string: only information for function names containing this string
1081 * A string: only information for function names containing this string
1082 is printed.
1082 is printed.
1083
1083
1084 * An integer: only these many lines are printed.
1084 * An integer: only these many lines are printed.
1085
1085
1086 * A float (between 0 and 1): this fraction of the report is printed
1086 * A float (between 0 and 1): this fraction of the report is printed
1087 (for example, use a limit of 0.4 to see the topmost 40% only).
1087 (for example, use a limit of 0.4 to see the topmost 40% only).
1088
1088
1089 You can combine several limits with repeated use of the option. For
1089 You can combine several limits with repeated use of the option. For
1090 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1090 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1091 information about class constructors.
1091 information about class constructors.
1092
1092
1093 -r: return the pstats.Stats object generated by the profiling. This
1093 -r: return the pstats.Stats object generated by the profiling. This
1094 object has all the information about the profile in it, and you can
1094 object has all the information about the profile in it, and you can
1095 later use it for further analysis or in other functions.
1095 later use it for further analysis or in other functions.
1096
1096
1097 Since magic functions have a particular form of calling which prevents
1097 Since magic functions have a particular form of calling which prevents
1098 you from writing something like:\\
1098 you from writing something like:\\
1099 In [1]: p = %prun -r print 4 # invalid!\\
1099 In [1]: p = %prun -r print 4 # invalid!\\
1100 you must instead use IPython's automatic variables to assign this:\\
1100 you must instead use IPython's automatic variables to assign this:\\
1101 In [1]: %prun -r print 4 \\
1101 In [1]: %prun -r print 4 \\
1102 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1102 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1103 In [2]: stats = _
1103 In [2]: stats = _
1104
1104
1105 If you really need to assign this value via an explicit function call,
1105 If you really need to assign this value via an explicit function call,
1106 you can always tap directly into the true name of the magic function
1106 you can always tap directly into the true name of the magic function
1107 by using the ipmagic function (which IPython automatically adds to the
1107 by using the ipmagic function (which IPython automatically adds to the
1108 builtins):\\
1108 builtins):\\
1109 In [3]: stats = ipmagic('prun','-r print 4')
1109 In [3]: stats = ipmagic('prun','-r print 4')
1110
1110
1111 You can type ipmagic? for more details on ipmagic.
1111 You can type ipmagic? for more details on ipmagic.
1112
1112
1113 -s <key>: sort profile by given key. You can provide more than one key
1113 -s <key>: sort profile by given key. You can provide more than one key
1114 by using the option several times: '-s key1 -s key2 -s key3...'. The
1114 by using the option several times: '-s key1 -s key2 -s key3...'. The
1115 default sorting key is 'time'.
1115 default sorting key is 'time'.
1116
1116
1117 The following is copied verbatim from the profile documentation
1117 The following is copied verbatim from the profile documentation
1118 referenced below:
1118 referenced below:
1119
1119
1120 When more than one key is provided, additional keys are used as
1120 When more than one key is provided, additional keys are used as
1121 secondary criteria when the there is equality in all keys selected
1121 secondary criteria when the there is equality in all keys selected
1122 before them.
1122 before them.
1123
1123
1124 Abbreviations can be used for any key names, as long as the
1124 Abbreviations can be used for any key names, as long as the
1125 abbreviation is unambiguous. The following are the keys currently
1125 abbreviation is unambiguous. The following are the keys currently
1126 defined:
1126 defined:
1127
1127
1128 Valid Arg Meaning\\
1128 Valid Arg Meaning\\
1129 "calls" call count\\
1129 "calls" call count\\
1130 "cumulative" cumulative time\\
1130 "cumulative" cumulative time\\
1131 "file" file name\\
1131 "file" file name\\
1132 "module" file name\\
1132 "module" file name\\
1133 "pcalls" primitive call count\\
1133 "pcalls" primitive call count\\
1134 "line" line number\\
1134 "line" line number\\
1135 "name" function name\\
1135 "name" function name\\
1136 "nfl" name/file/line\\
1136 "nfl" name/file/line\\
1137 "stdname" standard name\\
1137 "stdname" standard name\\
1138 "time" internal time
1138 "time" internal time
1139
1139
1140 Note that all sorts on statistics are in descending order (placing
1140 Note that all sorts on statistics are in descending order (placing
1141 most time consuming items first), where as name, file, and line number
1141 most time consuming items first), where as name, file, and line number
1142 searches are in ascending order (i.e., alphabetical). The subtle
1142 searches are in ascending order (i.e., alphabetical). The subtle
1143 distinction between "nfl" and "stdname" is that the standard name is a
1143 distinction between "nfl" and "stdname" is that the standard name is a
1144 sort of the name as printed, which means that the embedded line
1144 sort of the name as printed, which means that the embedded line
1145 numbers get compared in an odd way. For example, lines 3, 20, and 40
1145 numbers get compared in an odd way. For example, lines 3, 20, and 40
1146 would (if the file names were the same) appear in the string order
1146 would (if the file names were the same) appear in the string order
1147 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1147 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1148 line numbers. In fact, sort_stats("nfl") is the same as
1148 line numbers. In fact, sort_stats("nfl") is the same as
1149 sort_stats("name", "file", "line").
1149 sort_stats("name", "file", "line").
1150
1150
1151 -T <filename>: save profile results as shown on screen to a text
1151 -T <filename>: save profile results as shown on screen to a text
1152 file. The profile is still shown on screen.
1152 file. The profile is still shown on screen.
1153
1153
1154 -D <filename>: save (via dump_stats) profile statistics to given
1154 -D <filename>: save (via dump_stats) profile statistics to given
1155 filename. This data is in a format understod by the pstats module, and
1155 filename. This data is in a format understod by the pstats module, and
1156 is generated by a call to the dump_stats() method of profile
1156 is generated by a call to the dump_stats() method of profile
1157 objects. The profile is still shown on screen.
1157 objects. The profile is still shown on screen.
1158
1158
1159 If you want to run complete programs under the profiler's control, use
1159 If you want to run complete programs under the profiler's control, use
1160 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1160 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1161 contains profiler specific options as described here.
1161 contains profiler specific options as described here.
1162
1162
1163 You can read the complete documentation for the profile module with:\\
1163 You can read the complete documentation for the profile module with:\\
1164 In [1]: import profile; profile.help() """
1164 In [1]: import profile; profile.help() """
1165
1165
1166 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1166 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1167 # protect user quote marks
1167 # protect user quote marks
1168 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1168 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1169
1169
1170 if user_mode: # regular user call
1170 if user_mode: # regular user call
1171 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1171 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1172 list_all=1)
1172 list_all=1)
1173 namespace = self.shell.user_ns
1173 namespace = self.shell.user_ns
1174 else: # called to run a program by %run -p
1174 else: # called to run a program by %run -p
1175 try:
1175 try:
1176 filename = get_py_filename(arg_lst[0])
1176 filename = get_py_filename(arg_lst[0])
1177 except IOError,msg:
1177 except IOError,msg:
1178 error(msg)
1178 error(msg)
1179 return
1179 return
1180
1180
1181 arg_str = 'execfile(filename,prog_ns)'
1181 arg_str = 'execfile(filename,prog_ns)'
1182 namespace = locals()
1182 namespace = locals()
1183
1183
1184 opts.merge(opts_def)
1184 opts.merge(opts_def)
1185
1185
1186 prof = profile.Profile()
1186 prof = profile.Profile()
1187 try:
1187 try:
1188 prof = prof.runctx(arg_str,namespace,namespace)
1188 prof = prof.runctx(arg_str,namespace,namespace)
1189 sys_exit = ''
1189 sys_exit = ''
1190 except SystemExit:
1190 except SystemExit:
1191 sys_exit = """*** SystemExit exception caught in code being profiled."""
1191 sys_exit = """*** SystemExit exception caught in code being profiled."""
1192
1192
1193 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1193 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1194
1194
1195 lims = opts.l
1195 lims = opts.l
1196 if lims:
1196 if lims:
1197 lims = [] # rebuild lims with ints/floats/strings
1197 lims = [] # rebuild lims with ints/floats/strings
1198 for lim in opts.l:
1198 for lim in opts.l:
1199 try:
1199 try:
1200 lims.append(int(lim))
1200 lims.append(int(lim))
1201 except ValueError:
1201 except ValueError:
1202 try:
1202 try:
1203 lims.append(float(lim))
1203 lims.append(float(lim))
1204 except ValueError:
1204 except ValueError:
1205 lims.append(lim)
1205 lims.append(lim)
1206
1206
1207 # trap output
1207 # trap output
1208 sys_stdout = sys.stdout
1208 sys_stdout = sys.stdout
1209 stdout_trap = StringIO()
1209 stdout_trap = StringIO()
1210 try:
1210 try:
1211 sys.stdout = stdout_trap
1211 sys.stdout = stdout_trap
1212 stats.print_stats(*lims)
1212 stats.print_stats(*lims)
1213 finally:
1213 finally:
1214 sys.stdout = sys_stdout
1214 sys.stdout = sys_stdout
1215 output = stdout_trap.getvalue()
1215 output = stdout_trap.getvalue()
1216 output = output.rstrip()
1216 output = output.rstrip()
1217
1217
1218 page(output,screen_lines=self.shell.rc.screen_length)
1218 page(output,screen_lines=self.shell.rc.screen_length)
1219 print sys_exit,
1219 print sys_exit,
1220
1220
1221 dump_file = opts.D[0]
1221 dump_file = opts.D[0]
1222 text_file = opts.T[0]
1222 text_file = opts.T[0]
1223 if dump_file:
1223 if dump_file:
1224 prof.dump_stats(dump_file)
1224 prof.dump_stats(dump_file)
1225 print '\n*** Profile stats marshalled to file',\
1225 print '\n*** Profile stats marshalled to file',\
1226 `dump_file`+'.',sys_exit
1226 `dump_file`+'.',sys_exit
1227 if text_file:
1227 if text_file:
1228 file(text_file,'w').write(output)
1228 file(text_file,'w').write(output)
1229 print '\n*** Profile printout saved to text file',\
1229 print '\n*** Profile printout saved to text file',\
1230 `text_file`+'.',sys_exit
1230 `text_file`+'.',sys_exit
1231
1231
1232 if opts.has_key('r'):
1232 if opts.has_key('r'):
1233 return stats
1233 return stats
1234 else:
1234 else:
1235 return None
1235 return None
1236
1236
1237 def magic_run(self, parameter_s ='',runner=None):
1237 def magic_run(self, parameter_s ='',runner=None):
1238 """Run the named file inside IPython as a program.
1238 """Run the named file inside IPython as a program.
1239
1239
1240 Usage:\\
1240 Usage:\\
1241 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1241 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1242
1242
1243 Parameters after the filename are passed as command-line arguments to
1243 Parameters after the filename are passed as command-line arguments to
1244 the program (put in sys.argv). Then, control returns to IPython's
1244 the program (put in sys.argv). Then, control returns to IPython's
1245 prompt.
1245 prompt.
1246
1246
1247 This is similar to running at a system prompt:\\
1247 This is similar to running at a system prompt:\\
1248 $ python file args\\
1248 $ python file args\\
1249 but with the advantage of giving you IPython's tracebacks, and of
1249 but with the advantage of giving you IPython's tracebacks, and of
1250 loading all variables into your interactive namespace for further use
1250 loading all variables into your interactive namespace for further use
1251 (unless -p is used, see below).
1251 (unless -p is used, see below).
1252
1252
1253 The file is executed in a namespace initially consisting only of
1253 The file is executed in a namespace initially consisting only of
1254 __name__=='__main__' and sys.argv constructed as indicated. It thus
1254 __name__=='__main__' and sys.argv constructed as indicated. It thus
1255 sees its environment as if it were being run as a stand-alone
1255 sees its environment as if it were being run as a stand-alone
1256 program. But after execution, the IPython interactive namespace gets
1256 program. But after execution, the IPython interactive namespace gets
1257 updated with all variables defined in the program (except for __name__
1257 updated with all variables defined in the program (except for __name__
1258 and sys.argv). This allows for very convenient loading of code for
1258 and sys.argv). This allows for very convenient loading of code for
1259 interactive work, while giving each program a 'clean sheet' to run in.
1259 interactive work, while giving each program a 'clean sheet' to run in.
1260
1260
1261 Options:
1261 Options:
1262
1262
1263 -n: __name__ is NOT set to '__main__', but to the running file's name
1263 -n: __name__ is NOT set to '__main__', but to the running file's name
1264 without extension (as python does under import). This allows running
1264 without extension (as python does under import). This allows running
1265 scripts and reloading the definitions in them without calling code
1265 scripts and reloading the definitions in them without calling code
1266 protected by an ' if __name__ == "__main__" ' clause.
1266 protected by an ' if __name__ == "__main__" ' clause.
1267
1267
1268 -i: run the file in IPython's namespace instead of an empty one. This
1268 -i: run the file in IPython's namespace instead of an empty one. This
1269 is useful if you are experimenting with code written in a text editor
1269 is useful if you are experimenting with code written in a text editor
1270 which depends on variables defined interactively.
1270 which depends on variables defined interactively.
1271
1271
1272 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1272 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1273 being run. This is particularly useful if IPython is being used to
1273 being run. This is particularly useful if IPython is being used to
1274 run unittests, which always exit with a sys.exit() call. In such
1274 run unittests, which always exit with a sys.exit() call. In such
1275 cases you are interested in the output of the test results, not in
1275 cases you are interested in the output of the test results, not in
1276 seeing a traceback of the unittest module.
1276 seeing a traceback of the unittest module.
1277
1277
1278 -t: print timing information at the end of the run. IPython will give
1278 -t: print timing information at the end of the run. IPython will give
1279 you an estimated CPU time consumption for your script, which under
1279 you an estimated CPU time consumption for your script, which under
1280 Unix uses the resource module to avoid the wraparound problems of
1280 Unix uses the resource module to avoid the wraparound problems of
1281 time.clock(). Under Unix, an estimate of time spent on system tasks
1281 time.clock(). Under Unix, an estimate of time spent on system tasks
1282 is also given (for Windows platforms this is reported as 0.0).
1282 is also given (for Windows platforms this is reported as 0.0).
1283
1283
1284 If -t is given, an additional -N<N> option can be given, where <N>
1284 If -t is given, an additional -N<N> option can be given, where <N>
1285 must be an integer indicating how many times you want the script to
1285 must be an integer indicating how many times you want the script to
1286 run. The final timing report will include total and per run results.
1286 run. The final timing report will include total and per run results.
1287
1287
1288 For example (testing the script uniq_stable.py):
1288 For example (testing the script uniq_stable.py):
1289
1289
1290 In [1]: run -t uniq_stable
1290 In [1]: run -t uniq_stable
1291
1291
1292 IPython CPU timings (estimated):\\
1292 IPython CPU timings (estimated):\\
1293 User : 0.19597 s.\\
1293 User : 0.19597 s.\\
1294 System: 0.0 s.\\
1294 System: 0.0 s.\\
1295
1295
1296 In [2]: run -t -N5 uniq_stable
1296 In [2]: run -t -N5 uniq_stable
1297
1297
1298 IPython CPU timings (estimated):\\
1298 IPython CPU timings (estimated):\\
1299 Total runs performed: 5\\
1299 Total runs performed: 5\\
1300 Times : Total Per run\\
1300 Times : Total Per run\\
1301 User : 0.910862 s, 0.1821724 s.\\
1301 User : 0.910862 s, 0.1821724 s.\\
1302 System: 0.0 s, 0.0 s.
1302 System: 0.0 s, 0.0 s.
1303
1303
1304 -d: run your program under the control of pdb, the Python debugger.
1304 -d: run your program under the control of pdb, the Python debugger.
1305 This allows you to execute your program step by step, watch variables,
1305 This allows you to execute your program step by step, watch variables,
1306 etc. Internally, what IPython does is similar to calling:
1306 etc. Internally, what IPython does is similar to calling:
1307
1307
1308 pdb.run('execfile("YOURFILENAME")')
1308 pdb.run('execfile("YOURFILENAME")')
1309
1309
1310 with a breakpoint set on line 1 of your file. You can change the line
1310 with a breakpoint set on line 1 of your file. You can change the line
1311 number for this automatic breakpoint to be <N> by using the -bN option
1311 number for this automatic breakpoint to be <N> by using the -bN option
1312 (where N must be an integer). For example:
1312 (where N must be an integer). For example:
1313
1313
1314 %run -d -b40 myscript
1314 %run -d -b40 myscript
1315
1315
1316 will set the first breakpoint at line 40 in myscript.py. Note that
1316 will set the first breakpoint at line 40 in myscript.py. Note that
1317 the first breakpoint must be set on a line which actually does
1317 the first breakpoint must be set on a line which actually does
1318 something (not a comment or docstring) for it to stop execution.
1318 something (not a comment or docstring) for it to stop execution.
1319
1319
1320 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1320 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1321 first enter 'c' (without qoutes) to start execution up to the first
1321 first enter 'c' (without qoutes) to start execution up to the first
1322 breakpoint.
1322 breakpoint.
1323
1323
1324 Entering 'help' gives information about the use of the debugger. You
1324 Entering 'help' gives information about the use of the debugger. You
1325 can easily see pdb's full documentation with "import pdb;pdb.help()"
1325 can easily see pdb's full documentation with "import pdb;pdb.help()"
1326 at a prompt.
1326 at a prompt.
1327
1327
1328 -p: run program under the control of the Python profiler module (which
1328 -p: run program under the control of the Python profiler module (which
1329 prints a detailed report of execution times, function calls, etc).
1329 prints a detailed report of execution times, function calls, etc).
1330
1330
1331 You can pass other options after -p which affect the behavior of the
1331 You can pass other options after -p which affect the behavior of the
1332 profiler itself. See the docs for %prun for details.
1332 profiler itself. See the docs for %prun for details.
1333
1333
1334 In this mode, the program's variables do NOT propagate back to the
1334 In this mode, the program's variables do NOT propagate back to the
1335 IPython interactive namespace (because they remain in the namespace
1335 IPython interactive namespace (because they remain in the namespace
1336 where the profiler executes them).
1336 where the profiler executes them).
1337
1337
1338 Internally this triggers a call to %prun, see its documentation for
1338 Internally this triggers a call to %prun, see its documentation for
1339 details on the options available specifically for profiling."""
1339 details on the options available specifically for profiling."""
1340
1340
1341 # get arguments and set sys.argv for program to be run.
1341 # get arguments and set sys.argv for program to be run.
1342 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1342 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1343 mode='list',list_all=1)
1343 mode='list',list_all=1)
1344
1344
1345 try:
1345 try:
1346 filename = get_py_filename(arg_lst[0])
1346 filename = get_py_filename(arg_lst[0])
1347 except IndexError:
1347 except IndexError:
1348 warn('you must provide at least a filename.')
1348 warn('you must provide at least a filename.')
1349 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1349 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1350 return
1350 return
1351 except IOError,msg:
1351 except IOError,msg:
1352 error(msg)
1352 error(msg)
1353 return
1353 return
1354
1354
1355 # Control the response to exit() calls made by the script being run
1355 # Control the response to exit() calls made by the script being run
1356 exit_ignore = opts.has_key('e')
1356 exit_ignore = opts.has_key('e')
1357
1357
1358 # Make sure that the running script gets a proper sys.argv as if it
1358 # Make sure that the running script gets a proper sys.argv as if it
1359 # were run from a system shell.
1359 # were run from a system shell.
1360 save_argv = sys.argv # save it for later restoring
1360 save_argv = sys.argv # save it for later restoring
1361 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1361 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1362
1362
1363 if opts.has_key('i'):
1363 if opts.has_key('i'):
1364 prog_ns = self.shell.user_ns
1364 prog_ns = self.shell.user_ns
1365 __name__save = self.shell.user_ns['__name__']
1365 __name__save = self.shell.user_ns['__name__']
1366 prog_ns['__name__'] = '__main__'
1366 prog_ns['__name__'] = '__main__'
1367 else:
1367 else:
1368 if opts.has_key('n'):
1368 if opts.has_key('n'):
1369 name = os.path.splitext(os.path.basename(filename))[0]
1369 name = os.path.splitext(os.path.basename(filename))[0]
1370 else:
1370 else:
1371 name = '__main__'
1371 name = '__main__'
1372 prog_ns = {'__name__':name}
1372 prog_ns = {'__name__':name}
1373
1373
1374 # pickle fix. See iplib for an explanation
1374 # pickle fix. See iplib for an explanation
1375 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1375 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1376
1376
1377 stats = None
1377 stats = None
1378 try:
1378 try:
1379 if opts.has_key('p'):
1379 if opts.has_key('p'):
1380 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1380 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1381 else:
1381 else:
1382 if opts.has_key('d'):
1382 if opts.has_key('d'):
1383 deb = Debugger.Pdb(self.shell.rc.colors)
1383 deb = Debugger.Pdb(self.shell.rc.colors)
1384 # reset Breakpoint state, which is moronically kept
1384 # reset Breakpoint state, which is moronically kept
1385 # in a class
1385 # in a class
1386 bdb.Breakpoint.next = 1
1386 bdb.Breakpoint.next = 1
1387 bdb.Breakpoint.bplist = {}
1387 bdb.Breakpoint.bplist = {}
1388 bdb.Breakpoint.bpbynumber = [None]
1388 bdb.Breakpoint.bpbynumber = [None]
1389 # Set an initial breakpoint to stop execution
1389 # Set an initial breakpoint to stop execution
1390 maxtries = 10
1390 maxtries = 10
1391 bp = int(opts.get('b',[1])[0])
1391 bp = int(opts.get('b',[1])[0])
1392 checkline = deb.checkline(filename,bp)
1392 checkline = deb.checkline(filename,bp)
1393 if not checkline:
1393 if not checkline:
1394 for bp in range(bp+1,bp+maxtries+1):
1394 for bp in range(bp+1,bp+maxtries+1):
1395 if deb.checkline(filename,bp):
1395 if deb.checkline(filename,bp):
1396 break
1396 break
1397 else:
1397 else:
1398 msg = ("\nI failed to find a valid line to set "
1398 msg = ("\nI failed to find a valid line to set "
1399 "a breakpoint\n"
1399 "a breakpoint\n"
1400 "after trying up to line: %s.\n"
1400 "after trying up to line: %s.\n"
1401 "Please set a valid breakpoint manually "
1401 "Please set a valid breakpoint manually "
1402 "with the -b option." % bp)
1402 "with the -b option." % bp)
1403 error(msg)
1403 error(msg)
1404 return
1404 return
1405 # if we find a good linenumber, set the breakpoint
1405 # if we find a good linenumber, set the breakpoint
1406 deb.do_break('%s:%s' % (filename,bp))
1406 deb.do_break('%s:%s' % (filename,bp))
1407 # Start file run
1407 # Start file run
1408 print "NOTE: Enter 'c' at the",
1408 print "NOTE: Enter 'c' at the",
1409 print "ipdb> prompt to start your script."
1409 print "ipdb> prompt to start your script."
1410 try:
1410 try:
1411 deb.run('execfile("%s")' % filename,prog_ns)
1411 deb.run('execfile("%s")' % filename,prog_ns)
1412 except:
1412 except:
1413 etype, value, tb = sys.exc_info()
1413 etype, value, tb = sys.exc_info()
1414 # Skip three frames in the traceback: the %run one,
1414 # Skip three frames in the traceback: the %run one,
1415 # one inside bdb.py, and the command-line typed by the
1415 # one inside bdb.py, and the command-line typed by the
1416 # user (run by exec in pdb itself).
1416 # user (run by exec in pdb itself).
1417 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1417 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1418 else:
1418 else:
1419 if runner is None:
1419 if runner is None:
1420 runner = self.shell.safe_execfile
1420 runner = self.shell.safe_execfile
1421 if opts.has_key('t'):
1421 if opts.has_key('t'):
1422 try:
1422 try:
1423 nruns = int(opts['N'][0])
1423 nruns = int(opts['N'][0])
1424 if nruns < 1:
1424 if nruns < 1:
1425 error('Number of runs must be >=1')
1425 error('Number of runs must be >=1')
1426 return
1426 return
1427 except (KeyError):
1427 except (KeyError):
1428 nruns = 1
1428 nruns = 1
1429 if nruns == 1:
1429 if nruns == 1:
1430 t0 = clock2()
1430 t0 = clock2()
1431 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1431 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1432 t1 = clock2()
1432 t1 = clock2()
1433 t_usr = t1[0]-t0[0]
1433 t_usr = t1[0]-t0[0]
1434 t_sys = t1[1]-t1[1]
1434 t_sys = t1[1]-t1[1]
1435 print "\nIPython CPU timings (estimated):"
1435 print "\nIPython CPU timings (estimated):"
1436 print " User : %10s s." % t_usr
1436 print " User : %10s s." % t_usr
1437 print " System: %10s s." % t_sys
1437 print " System: %10s s." % t_sys
1438 else:
1438 else:
1439 runs = range(nruns)
1439 runs = range(nruns)
1440 t0 = clock2()
1440 t0 = clock2()
1441 for nr in runs:
1441 for nr in runs:
1442 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1442 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1443 t1 = clock2()
1443 t1 = clock2()
1444 t_usr = t1[0]-t0[0]
1444 t_usr = t1[0]-t0[0]
1445 t_sys = t1[1]-t1[1]
1445 t_sys = t1[1]-t1[1]
1446 print "\nIPython CPU timings (estimated):"
1446 print "\nIPython CPU timings (estimated):"
1447 print "Total runs performed:",nruns
1447 print "Total runs performed:",nruns
1448 print " Times : %10s %10s" % ('Total','Per run')
1448 print " Times : %10s %10s" % ('Total','Per run')
1449 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1449 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1450 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1450 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1451
1451
1452 else:
1452 else:
1453 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1453 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1454 if opts.has_key('i'):
1454 if opts.has_key('i'):
1455 self.shell.user_ns['__name__'] = __name__save
1455 self.shell.user_ns['__name__'] = __name__save
1456 else:
1456 else:
1457 # update IPython interactive namespace
1457 # update IPython interactive namespace
1458 del prog_ns['__name__']
1458 del prog_ns['__name__']
1459 self.shell.user_ns.update(prog_ns)
1459 self.shell.user_ns.update(prog_ns)
1460 finally:
1460 finally:
1461 sys.argv = save_argv
1461 sys.argv = save_argv
1462 return stats
1462 return stats
1463
1463
1464 def magic_runlog(self, parameter_s =''):
1464 def magic_runlog(self, parameter_s =''):
1465 """Run files as logs.
1465 """Run files as logs.
1466
1466
1467 Usage:\\
1467 Usage:\\
1468 %runlog file1 file2 ...
1468 %runlog file1 file2 ...
1469
1469
1470 Run the named files (treating them as log files) in sequence inside
1470 Run the named files (treating them as log files) in sequence inside
1471 the interpreter, and return to the prompt. This is much slower than
1471 the interpreter, and return to the prompt. This is much slower than
1472 %run because each line is executed in a try/except block, but it
1472 %run because each line is executed in a try/except block, but it
1473 allows running files with syntax errors in them.
1473 allows running files with syntax errors in them.
1474
1474
1475 Normally IPython will guess when a file is one of its own logfiles, so
1475 Normally IPython will guess when a file is one of its own logfiles, so
1476 you can typically use %run even for logs. This shorthand allows you to
1476 you can typically use %run even for logs. This shorthand allows you to
1477 force any file to be treated as a log file."""
1477 force any file to be treated as a log file."""
1478
1478
1479 for f in parameter_s.split():
1479 for f in parameter_s.split():
1480 self.shell.safe_execfile(f,self.shell.user_ns,
1480 self.shell.safe_execfile(f,self.shell.user_ns,
1481 self.shell.user_ns,islog=1)
1481 self.shell.user_ns,islog=1)
1482
1482
1483 def magic_time(self,parameter_s = ''):
1483 def magic_time(self,parameter_s = ''):
1484 """Time execution of a Python statement or expression.
1484 """Time execution of a Python statement or expression.
1485
1485
1486 The CPU and wall clock times are printed, and the value of the
1486 The CPU and wall clock times are printed, and the value of the
1487 expression (if any) is returned. Note that under Win32, system time
1487 expression (if any) is returned. Note that under Win32, system time
1488 is always reported as 0, since it can not be measured.
1488 is always reported as 0, since it can not be measured.
1489
1489
1490 This function provides very basic timing functionality. In Python
1490 This function provides very basic timing functionality. In Python
1491 2.3, the timeit module offers more control and sophistication, but for
1491 2.3, the timeit module offers more control and sophistication, but for
1492 now IPython supports Python 2.2, so we can not rely on timeit being
1492 now IPython supports Python 2.2, so we can not rely on timeit being
1493 present.
1493 present.
1494
1494
1495 Some examples:
1495 Some examples:
1496
1496
1497 In [1]: time 2**128
1497 In [1]: time 2**128
1498 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1498 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1499 Wall time: 0.00
1499 Wall time: 0.00
1500 Out[1]: 340282366920938463463374607431768211456L
1500 Out[1]: 340282366920938463463374607431768211456L
1501
1501
1502 In [2]: n = 1000000
1502 In [2]: n = 1000000
1503
1503
1504 In [3]: time sum(range(n))
1504 In [3]: time sum(range(n))
1505 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1505 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1506 Wall time: 1.37
1506 Wall time: 1.37
1507 Out[3]: 499999500000L
1507 Out[3]: 499999500000L
1508
1508
1509 In [4]: time print 'hello world'
1509 In [4]: time print 'hello world'
1510 hello world
1510 hello world
1511 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1511 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1512 Wall time: 0.00
1512 Wall time: 0.00
1513 """
1513 """
1514
1514
1515 # fail immediately if the given expression can't be compiled
1515 # fail immediately if the given expression can't be compiled
1516 try:
1516 try:
1517 mode = 'eval'
1517 mode = 'eval'
1518 code = compile(parameter_s,'<timed eval>',mode)
1518 code = compile(parameter_s,'<timed eval>',mode)
1519 except SyntaxError:
1519 except SyntaxError:
1520 mode = 'exec'
1520 mode = 'exec'
1521 code = compile(parameter_s,'<timed exec>',mode)
1521 code = compile(parameter_s,'<timed exec>',mode)
1522 # skew measurement as little as possible
1522 # skew measurement as little as possible
1523 glob = self.shell.user_ns
1523 glob = self.shell.user_ns
1524 clk = clock2
1524 clk = clock2
1525 wtime = time.time
1525 wtime = time.time
1526 # time execution
1526 # time execution
1527 wall_st = wtime()
1527 wall_st = wtime()
1528 if mode=='eval':
1528 if mode=='eval':
1529 st = clk()
1529 st = clk()
1530 out = eval(code,glob)
1530 out = eval(code,glob)
1531 end = clk()
1531 end = clk()
1532 else:
1532 else:
1533 st = clk()
1533 st = clk()
1534 exec code in glob
1534 exec code in glob
1535 end = clk()
1535 end = clk()
1536 out = None
1536 out = None
1537 wall_end = wtime()
1537 wall_end = wtime()
1538 # Compute actual times and report
1538 # Compute actual times and report
1539 wall_time = wall_end-wall_st
1539 wall_time = wall_end-wall_st
1540 cpu_user = end[0]-st[0]
1540 cpu_user = end[0]-st[0]
1541 cpu_sys = end[1]-st[1]
1541 cpu_sys = end[1]-st[1]
1542 cpu_tot = cpu_user+cpu_sys
1542 cpu_tot = cpu_user+cpu_sys
1543 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1543 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1544 (cpu_user,cpu_sys,cpu_tot)
1544 (cpu_user,cpu_sys,cpu_tot)
1545 print "Wall time: %.2f" % wall_time
1545 print "Wall time: %.2f" % wall_time
1546 return out
1546 return out
1547
1547
1548 def magic_macro(self,parameter_s = ''):
1548 def magic_macro(self,parameter_s = ''):
1549 """Define a set of input lines as a macro for future re-execution.
1549 """Define a set of input lines as a macro for future re-execution.
1550
1550
1551 Usage:\\
1551 Usage:\\
1552 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1552 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1553
1553
1554 This will define a global variable called `name` which is a string
1554 This will define a global variable called `name` which is a string
1555 made of joining the slices and lines you specify (n1,n2,... numbers
1555 made of joining the slices and lines you specify (n1,n2,... numbers
1556 above) from your input history into a single string. This variable
1556 above) from your input history into a single string. This variable
1557 acts like an automatic function which re-executes those lines as if
1557 acts like an automatic function which re-executes those lines as if
1558 you had typed them. You just type 'name' at the prompt and the code
1558 you had typed them. You just type 'name' at the prompt and the code
1559 executes.
1559 executes.
1560
1560
1561 Note that the slices use the standard Python slicing notation (5:8
1561 Note that the slices use the standard Python slicing notation (5:8
1562 means include lines numbered 5,6,7).
1562 means include lines numbered 5,6,7).
1563
1563
1564 For example, if your history contains (%hist prints it):
1564 For example, if your history contains (%hist prints it):
1565
1565
1566 44: x=1\\
1566 44: x=1\\
1567 45: y=3\\
1567 45: y=3\\
1568 46: z=x+y\\
1568 46: z=x+y\\
1569 47: print x\\
1569 47: print x\\
1570 48: a=5\\
1570 48: a=5\\
1571 49: print 'x',x,'y',y\\
1571 49: print 'x',x,'y',y\\
1572
1572
1573 you can create a macro with lines 44 through 47 (included) and line 49
1573 you can create a macro with lines 44 through 47 (included) and line 49
1574 called my_macro with:
1574 called my_macro with:
1575
1575
1576 In [51]: %macro my_macro 44:48 49
1576 In [51]: %macro my_macro 44:48 49
1577
1577
1578 Now, typing `my_macro` (without quotes) will re-execute all this code
1578 Now, typing `my_macro` (without quotes) will re-execute all this code
1579 in one pass.
1579 in one pass.
1580
1580
1581 You don't need to give the line-numbers in order, and any given line
1581 You don't need to give the line-numbers in order, and any given line
1582 number can appear multiple times. You can assemble macros with any
1582 number can appear multiple times. You can assemble macros with any
1583 lines from your input history in any order.
1583 lines from your input history in any order.
1584
1584
1585 The macro is a simple object which holds its value in an attribute,
1585 The macro is a simple object which holds its value in an attribute,
1586 but IPython's display system checks for macros and executes them as
1586 but IPython's display system checks for macros and executes them as
1587 code instead of printing them when you type their name.
1587 code instead of printing them when you type their name.
1588
1588
1589 You can view a macro's contents by explicitly printing it with:
1589 You can view a macro's contents by explicitly printing it with:
1590
1590
1591 'print macro_name'.
1591 'print macro_name'.
1592
1592
1593 For one-off cases which DON'T contain magic function calls in them you
1593 For one-off cases which DON'T contain magic function calls in them you
1594 can obtain similar results by explicitly executing slices from your
1594 can obtain similar results by explicitly executing slices from your
1595 input history with:
1595 input history with:
1596
1596
1597 In [60]: exec In[44:48]+In[49]"""
1597 In [60]: exec In[44:48]+In[49]"""
1598
1598
1599 args = parameter_s.split()
1599 args = parameter_s.split()
1600 name,ranges = args[0], args[1:]
1600 name,ranges = args[0], args[1:]
1601 #print 'rng',ranges # dbg
1601 #print 'rng',ranges # dbg
1602 cmds = self.extract_input_slices(ranges)
1602 cmds = self.extract_input_slices(ranges)
1603 macro = Macro(cmds)
1603 macro = Macro(cmds)
1604 self.shell.user_ns.update({name:macro})
1604 self.shell.user_ns.update({name:macro})
1605 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1605 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1606 print 'Macro contents:'
1606 print 'Macro contents:'
1607 print str(macro).rstrip(),
1607 print str(macro).rstrip(),
1608
1608
1609 def magic_save(self,parameter_s = ''):
1609 def magic_save(self,parameter_s = ''):
1610 """Save a set of lines to a given filename.
1610 """Save a set of lines to a given filename.
1611
1611
1612 Usage:\\
1612 Usage:\\
1613 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1613 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1614
1614
1615 This function uses the same syntax as %macro for line extraction, but
1615 This function uses the same syntax as %macro for line extraction, but
1616 instead of creating a macro it saves the resulting string to the
1616 instead of creating a macro it saves the resulting string to the
1617 filename you specify.
1617 filename you specify.
1618
1618
1619 It adds a '.py' extension to the file if you don't do so yourself, and
1619 It adds a '.py' extension to the file if you don't do so yourself, and
1620 it asks for confirmation before overwriting existing files."""
1620 it asks for confirmation before overwriting existing files."""
1621
1621
1622 args = parameter_s.split()
1622 args = parameter_s.split()
1623 fname,ranges = args[0], args[1:]
1623 fname,ranges = args[0], args[1:]
1624 if not fname.endswith('.py'):
1624 if not fname.endswith('.py'):
1625 fname += '.py'
1625 fname += '.py'
1626 if os.path.isfile(fname):
1626 if os.path.isfile(fname):
1627 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1627 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1628 if ans.lower() not in ['y','yes']:
1628 if ans.lower() not in ['y','yes']:
1629 print 'Operation cancelled.'
1629 print 'Operation cancelled.'
1630 return
1630 return
1631 cmds = ''.join(self.extract_input_slices(ranges))
1631 cmds = ''.join(self.extract_input_slices(ranges))
1632 f = file(fname,'w')
1632 f = file(fname,'w')
1633 f.write(cmds)
1633 f.write(cmds)
1634 f.close()
1634 f.close()
1635 print 'The following commands were written to file `%s`:' % fname
1635 print 'The following commands were written to file `%s`:' % fname
1636 print cmds
1636 print cmds
1637
1637
1638 def magic_ed(self,parameter_s = ''):
1638 def magic_ed(self,parameter_s = ''):
1639 """Alias to %edit."""
1639 """Alias to %edit."""
1640 return self.magic_edit(parameter_s)
1640 return self.magic_edit(parameter_s)
1641
1641
1642 def magic_edit(self,parameter_s = '',last_call=['','']):
1642 def magic_edit(self,parameter_s = '',last_call=['','']):
1643 """Bring up an editor and execute the resulting code.
1643 """Bring up an editor and execute the resulting code.
1644
1644
1645 Usage:
1645 Usage:
1646 %edit [options] [args]
1646 %edit [options] [args]
1647
1647
1648 %edit runs IPython's editor hook. The default version of this hook is
1648 %edit runs IPython's editor hook. The default version of this hook is
1649 set to call the __IPYTHON__.rc.editor command. This is read from your
1649 set to call the __IPYTHON__.rc.editor command. This is read from your
1650 environment variable $EDITOR. If this isn't found, it will default to
1650 environment variable $EDITOR. If this isn't found, it will default to
1651 vi under Linux/Unix and to notepad under Windows. See the end of this
1651 vi under Linux/Unix and to notepad under Windows. See the end of this
1652 docstring for how to change the editor hook.
1652 docstring for how to change the editor hook.
1653
1653
1654 You can also set the value of this editor via the command line option
1654 You can also set the value of this editor via the command line option
1655 '-editor' or in your ipythonrc file. This is useful if you wish to use
1655 '-editor' or in your ipythonrc file. This is useful if you wish to use
1656 specifically for IPython an editor different from your typical default
1656 specifically for IPython an editor different from your typical default
1657 (and for Windows users who typically don't set environment variables).
1657 (and for Windows users who typically don't set environment variables).
1658
1658
1659 This command allows you to conveniently edit multi-line code right in
1659 This command allows you to conveniently edit multi-line code right in
1660 your IPython session.
1660 your IPython session.
1661
1661
1662 If called without arguments, %edit opens up an empty editor with a
1662 If called without arguments, %edit opens up an empty editor with a
1663 temporary file and will execute the contents of this file when you
1663 temporary file and will execute the contents of this file when you
1664 close it (don't forget to save it!).
1664 close it (don't forget to save it!).
1665
1665
1666 Options:
1666 Options:
1667
1667
1668 -p: this will call the editor with the same data as the previous time
1668 -p: this will call the editor with the same data as the previous time
1669 it was used, regardless of how long ago (in your current session) it
1669 it was used, regardless of how long ago (in your current session) it
1670 was.
1670 was.
1671
1671
1672 -x: do not execute the edited code immediately upon exit. This is
1672 -x: do not execute the edited code immediately upon exit. This is
1673 mainly useful if you are editing programs which need to be called with
1673 mainly useful if you are editing programs which need to be called with
1674 command line arguments, which you can then do using %run.
1674 command line arguments, which you can then do using %run.
1675
1675
1676 Arguments:
1676 Arguments:
1677
1677
1678 If arguments are given, the following possibilites exist:
1678 If arguments are given, the following possibilites exist:
1679
1679
1680 - The arguments are numbers or pairs of colon-separated numbers (like
1680 - The arguments are numbers or pairs of colon-separated numbers (like
1681 1 4:8 9). These are interpreted as lines of previous input to be
1681 1 4:8 9). These are interpreted as lines of previous input to be
1682 loaded into the editor. The syntax is the same of the %macro command.
1682 loaded into the editor. The syntax is the same of the %macro command.
1683
1683
1684 - If the argument doesn't start with a number, it is evaluated as a
1684 - If the argument doesn't start with a number, it is evaluated as a
1685 variable and its contents loaded into the editor. You can thus edit
1685 variable and its contents loaded into the editor. You can thus edit
1686 any string which contains python code (including the result of
1686 any string which contains python code (including the result of
1687 previous edits).
1687 previous edits).
1688
1688
1689 - If the argument is the name of an object (other than a string),
1689 - If the argument is the name of an object (other than a string),
1690 IPython will try to locate the file where it was defined and open the
1690 IPython will try to locate the file where it was defined and open the
1691 editor at the point where it is defined. You can use `%edit function`
1691 editor at the point where it is defined. You can use `%edit function`
1692 to load an editor exactly at the point where 'function' is defined,
1692 to load an editor exactly at the point where 'function' is defined,
1693 edit it and have the file be executed automatically.
1693 edit it and have the file be executed automatically.
1694
1694
1695 Note: opening at an exact line is only supported under Unix, and some
1695 Note: opening at an exact line is only supported under Unix, and some
1696 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1696 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1697 '+NUMBER' parameter necessary for this feature. Good editors like
1697 '+NUMBER' parameter necessary for this feature. Good editors like
1698 (X)Emacs, vi, jed, pico and joe all do.
1698 (X)Emacs, vi, jed, pico and joe all do.
1699
1699
1700 - If the argument is not found as a variable, IPython will look for a
1700 - If the argument is not found as a variable, IPython will look for a
1701 file with that name (adding .py if necessary) and load it into the
1701 file with that name (adding .py if necessary) and load it into the
1702 editor. It will execute its contents with execfile() when you exit,
1702 editor. It will execute its contents with execfile() when you exit,
1703 loading any code in the file into your interactive namespace.
1703 loading any code in the file into your interactive namespace.
1704
1704
1705 After executing your code, %edit will return as output the code you
1705 After executing your code, %edit will return as output the code you
1706 typed in the editor (except when it was an existing file). This way
1706 typed in the editor (except when it was an existing file). This way
1707 you can reload the code in further invocations of %edit as a variable,
1707 you can reload the code in further invocations of %edit as a variable,
1708 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1708 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1709 the output.
1709 the output.
1710
1710
1711 Note that %edit is also available through the alias %ed.
1711 Note that %edit is also available through the alias %ed.
1712
1712
1713 This is an example of creating a simple function inside the editor and
1713 This is an example of creating a simple function inside the editor and
1714 then modifying it. First, start up the editor:
1714 then modifying it. First, start up the editor:
1715
1715
1716 In [1]: ed\\
1716 In [1]: ed\\
1717 Editing... done. Executing edited code...\\
1717 Editing... done. Executing edited code...\\
1718 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1718 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1719
1719
1720 We can then call the function foo():
1720 We can then call the function foo():
1721
1721
1722 In [2]: foo()\\
1722 In [2]: foo()\\
1723 foo() was defined in an editing session
1723 foo() was defined in an editing session
1724
1724
1725 Now we edit foo. IPython automatically loads the editor with the
1725 Now we edit foo. IPython automatically loads the editor with the
1726 (temporary) file where foo() was previously defined:
1726 (temporary) file where foo() was previously defined:
1727
1727
1728 In [3]: ed foo\\
1728 In [3]: ed foo\\
1729 Editing... done. Executing edited code...
1729 Editing... done. Executing edited code...
1730
1730
1731 And if we call foo() again we get the modified version:
1731 And if we call foo() again we get the modified version:
1732
1732
1733 In [4]: foo()\\
1733 In [4]: foo()\\
1734 foo() has now been changed!
1734 foo() has now been changed!
1735
1735
1736 Here is an example of how to edit a code snippet successive
1736 Here is an example of how to edit a code snippet successive
1737 times. First we call the editor:
1737 times. First we call the editor:
1738
1738
1739 In [8]: ed\\
1739 In [8]: ed\\
1740 Editing... done. Executing edited code...\\
1740 Editing... done. Executing edited code...\\
1741 hello\\
1741 hello\\
1742 Out[8]: "print 'hello'\\n"
1742 Out[8]: "print 'hello'\\n"
1743
1743
1744 Now we call it again with the previous output (stored in _):
1744 Now we call it again with the previous output (stored in _):
1745
1745
1746 In [9]: ed _\\
1746 In [9]: ed _\\
1747 Editing... done. Executing edited code...\\
1747 Editing... done. Executing edited code...\\
1748 hello world\\
1748 hello world\\
1749 Out[9]: "print 'hello world'\\n"
1749 Out[9]: "print 'hello world'\\n"
1750
1750
1751 Now we call it with the output #8 (stored in _8, also as Out[8]):
1751 Now we call it with the output #8 (stored in _8, also as Out[8]):
1752
1752
1753 In [10]: ed _8\\
1753 In [10]: ed _8\\
1754 Editing... done. Executing edited code...\\
1754 Editing... done. Executing edited code...\\
1755 hello again\\
1755 hello again\\
1756 Out[10]: "print 'hello again'\\n"
1756 Out[10]: "print 'hello again'\\n"
1757
1757
1758
1758
1759 Changing the default editor hook:
1759 Changing the default editor hook:
1760
1760
1761 If you wish to write your own editor hook, you can put it in a
1761 If you wish to write your own editor hook, you can put it in a
1762 configuration file which you load at startup time. The default hook
1762 configuration file which you load at startup time. The default hook
1763 is defined in the IPython.hooks module, and you can use that as a
1763 is defined in the IPython.hooks module, and you can use that as a
1764 starting example for further modifications. That file also has
1764 starting example for further modifications. That file also has
1765 general instructions on how to set a new hook for use once you've
1765 general instructions on how to set a new hook for use once you've
1766 defined it."""
1766 defined it."""
1767
1767
1768 # FIXME: This function has become a convoluted mess. It needs a
1768 # FIXME: This function has become a convoluted mess. It needs a
1769 # ground-up rewrite with clean, simple logic.
1769 # ground-up rewrite with clean, simple logic.
1770
1770
1771 def make_filename(arg):
1771 def make_filename(arg):
1772 "Make a filename from the given args"
1772 "Make a filename from the given args"
1773 try:
1773 try:
1774 filename = get_py_filename(arg)
1774 filename = get_py_filename(arg)
1775 except IOError:
1775 except IOError:
1776 if args.endswith('.py'):
1776 if args.endswith('.py'):
1777 filename = arg
1777 filename = arg
1778 else:
1778 else:
1779 filename = None
1779 filename = None
1780 return filename
1780 return filename
1781
1781
1782 # custom exceptions
1782 # custom exceptions
1783 class DataIsObject(Exception): pass
1783 class DataIsObject(Exception): pass
1784
1784
1785 opts,args = self.parse_options(parameter_s,'px')
1785 opts,args = self.parse_options(parameter_s,'px')
1786
1786
1787 # Default line number value
1787 # Default line number value
1788 lineno = None
1788 lineno = None
1789 if opts.has_key('p'):
1789 if opts.has_key('p'):
1790 args = '_%s' % last_call[0]
1790 args = '_%s' % last_call[0]
1791 if not self.shell.user_ns.has_key(args):
1791 if not self.shell.user_ns.has_key(args):
1792 args = last_call[1]
1792 args = last_call[1]
1793
1793
1794 # use last_call to remember the state of the previous call, but don't
1794 # use last_call to remember the state of the previous call, but don't
1795 # let it be clobbered by successive '-p' calls.
1795 # let it be clobbered by successive '-p' calls.
1796 try:
1796 try:
1797 last_call[0] = self.shell.outputcache.prompt_count
1797 last_call[0] = self.shell.outputcache.prompt_count
1798 if not opts.has_key('p'):
1798 if not opts.has_key('p'):
1799 last_call[1] = parameter_s
1799 last_call[1] = parameter_s
1800 except:
1800 except:
1801 pass
1801 pass
1802
1802
1803 # by default this is done with temp files, except when the given
1803 # by default this is done with temp files, except when the given
1804 # arg is a filename
1804 # arg is a filename
1805 use_temp = 1
1805 use_temp = 1
1806
1806
1807 if re.match(r'\d',args):
1807 if re.match(r'\d',args):
1808 # Mode where user specifies ranges of lines, like in %macro.
1808 # Mode where user specifies ranges of lines, like in %macro.
1809 # This means that you can't edit files whose names begin with
1809 # This means that you can't edit files whose names begin with
1810 # numbers this way. Tough.
1810 # numbers this way. Tough.
1811 ranges = args.split()
1811 ranges = args.split()
1812 data = ''.join(self.extract_input_slices(ranges))
1812 data = ''.join(self.extract_input_slices(ranges))
1813 elif args.endswith('.py'):
1813 elif args.endswith('.py'):
1814 filename = make_filename(args)
1814 filename = make_filename(args)
1815 data = ''
1815 data = ''
1816 use_temp = 0
1816 use_temp = 0
1817 elif args:
1817 elif args:
1818 try:
1818 try:
1819 # Load the parameter given as a variable. If not a string,
1819 # Load the parameter given as a variable. If not a string,
1820 # process it as an object instead (below)
1820 # process it as an object instead (below)
1821
1821
1822 #print '*** args',args,'type',type(args) # dbg
1822 #print '*** args',args,'type',type(args) # dbg
1823 data = eval(args,self.shell.user_ns)
1823 data = eval(args,self.shell.user_ns)
1824 if not type(data) in StringTypes:
1824 if not type(data) in StringTypes:
1825 raise DataIsObject
1825 raise DataIsObject
1826 except (NameError,SyntaxError):
1826 except (NameError,SyntaxError):
1827 # given argument is not a variable, try as a filename
1827 # given argument is not a variable, try as a filename
1828 filename = make_filename(args)
1828 filename = make_filename(args)
1829 if filename is None:
1829 if filename is None:
1830 warn("Argument given (%s) can't be found as a variable "
1830 warn("Argument given (%s) can't be found as a variable "
1831 "or as a filename." % args)
1831 "or as a filename." % args)
1832 return
1832 return
1833 data = ''
1833 data = ''
1834 use_temp = 0
1834 use_temp = 0
1835 except DataIsObject:
1835 except DataIsObject:
1836 # For objects, try to edit the file where they are defined
1836 # For objects, try to edit the file where they are defined
1837 try:
1837 try:
1838 filename = inspect.getabsfile(data)
1838 filename = inspect.getabsfile(data)
1839 datafile = 1
1839 datafile = 1
1840 except TypeError:
1840 except TypeError:
1841 filename = make_filename(args)
1841 filename = make_filename(args)
1842 datafile = 1
1842 datafile = 1
1843 warn('Could not find file where `%s` is defined.\n'
1843 warn('Could not find file where `%s` is defined.\n'
1844 'Opening a file named `%s`' % (args,filename))
1844 'Opening a file named `%s`' % (args,filename))
1845 # Now, make sure we can actually read the source (if it was in
1845 # Now, make sure we can actually read the source (if it was in
1846 # a temp file it's gone by now).
1846 # a temp file it's gone by now).
1847 if datafile:
1847 if datafile:
1848 try:
1848 try:
1849 lineno = inspect.getsourcelines(data)[1]
1849 lineno = inspect.getsourcelines(data)[1]
1850 except IOError:
1850 except IOError:
1851 filename = make_filename(args)
1851 filename = make_filename(args)
1852 if filename is None:
1852 if filename is None:
1853 warn('The file `%s` where `%s` was defined cannot '
1853 warn('The file `%s` where `%s` was defined cannot '
1854 'be read.' % (filename,data))
1854 'be read.' % (filename,data))
1855 return
1855 return
1856 use_temp = 0
1856 use_temp = 0
1857 else:
1857 else:
1858 data = ''
1858 data = ''
1859
1859
1860 if use_temp:
1860 if use_temp:
1861 filename = tempfile.mktemp('.py')
1861 filename = tempfile.mktemp('.py')
1862 self.shell.tempfiles.append(filename)
1862 self.shell.tempfiles.append(filename)
1863
1863
1864 if data and use_temp:
1864 if data and use_temp:
1865 tmp_file = open(filename,'w')
1865 tmp_file = open(filename,'w')
1866 tmp_file.write(data)
1866 tmp_file.write(data)
1867 tmp_file.close()
1867 tmp_file.close()
1868
1868
1869 # do actual editing here
1869 # do actual editing here
1870 print 'Editing...',
1870 print 'Editing...',
1871 sys.stdout.flush()
1871 sys.stdout.flush()
1872 self.shell.hooks.editor(filename,lineno)
1872 self.shell.hooks.editor(filename,lineno)
1873 if opts.has_key('x'): # -x prevents actual execution
1873 if opts.has_key('x'): # -x prevents actual execution
1874 print
1874 print
1875 else:
1875 else:
1876 print 'done. Executing edited code...'
1876 print 'done. Executing edited code...'
1877 try:
1877 try:
1878 self.shell.safe_execfile(filename,self.shell.user_ns)
1878 self.shell.safe_execfile(filename,self.shell.user_ns)
1879 except IOError,msg:
1879 except IOError,msg:
1880 if msg.filename == filename:
1880 if msg.filename == filename:
1881 warn('File not found. Did you forget to save?')
1881 warn('File not found. Did you forget to save?')
1882 return
1882 return
1883 else:
1883 else:
1884 self.shell.showtraceback()
1884 self.shell.showtraceback()
1885 except:
1885 except:
1886 self.shell.showtraceback()
1886 self.shell.showtraceback()
1887 if use_temp:
1887 if use_temp:
1888 contents = open(filename).read()
1888 contents = open(filename).read()
1889 return contents
1889 return contents
1890
1890
1891 def magic_xmode(self,parameter_s = ''):
1891 def magic_xmode(self,parameter_s = ''):
1892 """Switch modes for the exception handlers.
1892 """Switch modes for the exception handlers.
1893
1893
1894 Valid modes: Plain, Context and Verbose.
1894 Valid modes: Plain, Context and Verbose.
1895
1895
1896 If called without arguments, acts as a toggle."""
1896 If called without arguments, acts as a toggle."""
1897
1897
1898 new_mode = parameter_s.strip().capitalize()
1898 new_mode = parameter_s.strip().capitalize()
1899 try:
1899 try:
1900 self.InteractiveTB.set_mode(mode = new_mode)
1900 self.InteractiveTB.set_mode(mode = new_mode)
1901 print 'Exception reporting mode:',self.InteractiveTB.mode
1901 print 'Exception reporting mode:',self.InteractiveTB.mode
1902 except:
1902 except:
1903 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1903 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1904
1904
1905 def magic_colors(self,parameter_s = ''):
1905 def magic_colors(self,parameter_s = ''):
1906 """Switch color scheme for prompts, info system and exception handlers.
1906 """Switch color scheme for prompts, info system and exception handlers.
1907
1907
1908 Currently implemented schemes: NoColor, Linux, LightBG.
1908 Currently implemented schemes: NoColor, Linux, LightBG.
1909
1909
1910 Color scheme names are not case-sensitive."""
1910 Color scheme names are not case-sensitive."""
1911
1911
1912 new_scheme = parameter_s.strip()
1912 new_scheme = parameter_s.strip()
1913 if not new_scheme:
1913 if not new_scheme:
1914 print 'You must specify a color scheme.'
1914 print 'You must specify a color scheme.'
1915 return
1915 return
1916 # Under Windows, check for Gary Bishop's readline, which is necessary
1916 # Under Windows, check for Gary Bishop's readline, which is necessary
1917 # for ANSI coloring
1917 # for ANSI coloring
1918 if os.name in ['nt','dos']:
1918 if os.name in ['nt','dos']:
1919 try:
1919 try:
1920 import readline
1920 import readline
1921 except ImportError:
1921 except ImportError:
1922 has_readline = 0
1922 has_readline = 0
1923 else:
1923 else:
1924 try:
1924 try:
1925 readline.GetOutputFile()
1925 readline.GetOutputFile()
1926 except AttributeError:
1926 except AttributeError:
1927 has_readline = 0
1927 has_readline = 0
1928 else:
1928 else:
1929 has_readline = 1
1929 has_readline = 1
1930 if not has_readline:
1930 if not has_readline:
1931 msg = """\
1931 msg = """\
1932 Proper color support under MS Windows requires Gary Bishop's readline library.
1932 Proper color support under MS Windows requires Gary Bishop's readline library.
1933 You can find it at:
1933 You can find it at:
1934 http://sourceforge.net/projects/uncpythontools
1934 http://sourceforge.net/projects/uncpythontools
1935 Gary's readline needs the ctypes module, from:
1935 Gary's readline needs the ctypes module, from:
1936 http://starship.python.net/crew/theller/ctypes
1936 http://starship.python.net/crew/theller/ctypes
1937
1937
1938 Defaulting color scheme to 'NoColor'"""
1938 Defaulting color scheme to 'NoColor'"""
1939 new_scheme = 'NoColor'
1939 new_scheme = 'NoColor'
1940 warn(msg)
1940 warn(msg)
1941
1941
1942 # Set prompt colors
1942 # Set prompt colors
1943 try:
1943 try:
1944 self.shell.outputcache.set_colors(new_scheme)
1944 self.shell.outputcache.set_colors(new_scheme)
1945 except:
1945 except:
1946 warn('Error changing prompt color schemes.\n'
1946 warn('Error changing prompt color schemes.\n'
1947 + str(sys.exc_info()[1]))
1947 + str(sys.exc_info()[1]))
1948 else:
1948 else:
1949 self.shell.rc.colors = \
1949 self.shell.rc.colors = \
1950 self.shell.outputcache.color_table.active_scheme_name
1950 self.shell.outputcache.color_table.active_scheme_name
1951 # Set exception colors
1951 # Set exception colors
1952 try:
1952 try:
1953 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1953 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1954 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1954 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1955 except:
1955 except:
1956 warn('Error changing exception color schemes.\n'
1956 warn('Error changing exception color schemes.\n'
1957 + str(sys.exc_info()[1]))
1957 + str(sys.exc_info()[1]))
1958 # Set info (for 'object?') colors
1958 # Set info (for 'object?') colors
1959 if self.shell.rc.color_info:
1959 if self.shell.rc.color_info:
1960 try:
1960 try:
1961 self.shell.inspector.set_active_scheme(new_scheme)
1961 self.shell.inspector.set_active_scheme(new_scheme)
1962 except:
1962 except:
1963 warn('Error changing object inspector color schemes.\n'
1963 warn('Error changing object inspector color schemes.\n'
1964 + str(sys.exc_info()[1]))
1964 + str(sys.exc_info()[1]))
1965 else:
1965 else:
1966 self.shell.inspector.set_active_scheme('NoColor')
1966 self.shell.inspector.set_active_scheme('NoColor')
1967
1967
1968 def magic_color_info(self,parameter_s = ''):
1968 def magic_color_info(self,parameter_s = ''):
1969 """Toggle color_info.
1969 """Toggle color_info.
1970
1970
1971 The color_info configuration parameter controls whether colors are
1971 The color_info configuration parameter controls whether colors are
1972 used for displaying object details (by things like %psource, %pfile or
1972 used for displaying object details (by things like %psource, %pfile or
1973 the '?' system). This function toggles this value with each call.
1973 the '?' system). This function toggles this value with each call.
1974
1974
1975 Note that unless you have a fairly recent pager (less works better
1975 Note that unless you have a fairly recent pager (less works better
1976 than more) in your system, using colored object information displays
1976 than more) in your system, using colored object information displays
1977 will not work properly. Test it and see."""
1977 will not work properly. Test it and see."""
1978
1978
1979 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1979 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1980 self.magic_colors(self.shell.rc.colors)
1980 self.magic_colors(self.shell.rc.colors)
1981 print 'Object introspection functions have now coloring:',
1981 print 'Object introspection functions have now coloring:',
1982 print ['OFF','ON'][self.shell.rc.color_info]
1982 print ['OFF','ON'][self.shell.rc.color_info]
1983
1983
1984 def magic_Pprint(self, parameter_s=''):
1984 def magic_Pprint(self, parameter_s=''):
1985 """Toggle pretty printing on/off."""
1985 """Toggle pretty printing on/off."""
1986
1986
1987 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1987 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1988 print 'Pretty printing has been turned', \
1988 print 'Pretty printing has been turned', \
1989 ['OFF','ON'][self.shell.outputcache.Pprint]
1989 ['OFF','ON'][self.shell.outputcache.Pprint]
1990
1990
1991 def magic_exit(self, parameter_s=''):
1992 """Exit IPython, confirming if configured to do so.
1993
1994 You can configure whether IPython asks for confirmation upon exit by
1995 setting the confirm_exit flag in the ipythonrc file."""
1996
1997 self.shell.exit()
1998
1999 def magic_quit(self, parameter_s=''):
2000 """Exit IPython, confirming if configured to do so (like %exit)"""
2001
2002 self.shell.exit()
2003
1991 def magic_Exit(self, parameter_s=''):
2004 def magic_Exit(self, parameter_s=''):
1992 """Exit IPython without confirmation."""
2005 """Exit IPython without confirmation."""
1993
2006
1994 self.shell.exit_now = True
2007 self.shell.exit_now = True
1995
2008
1996 def magic_Quit(self, parameter_s=''):
2009 def magic_Quit(self, parameter_s=''):
1997 """Exit IPython without confirmation (like %Exit)."""
2010 """Exit IPython without confirmation (like %Exit)."""
1998
2011
1999 self.shell.exit_now = True
2012 self.shell.exit_now = True
2000
2013
2001 #......................................................................
2014 #......................................................................
2002 # Functions to implement unix shell-type things
2015 # Functions to implement unix shell-type things
2003
2016
2004 def magic_alias(self, parameter_s = ''):
2017 def magic_alias(self, parameter_s = ''):
2005 """Define an alias for a system command.
2018 """Define an alias for a system command.
2006
2019
2007 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2020 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2008
2021
2009 Then, typing 'alias_name params' will execute the system command 'cmd
2022 Then, typing 'alias_name params' will execute the system command 'cmd
2010 params' (from your underlying operating system).
2023 params' (from your underlying operating system).
2011
2024
2012 Aliases have lower precedence than magic functions and Python normal
2025 Aliases have lower precedence than magic functions and Python normal
2013 variables, so if 'foo' is both a Python variable and an alias, the
2026 variables, so if 'foo' is both a Python variable and an alias, the
2014 alias can not be executed until 'del foo' removes the Python variable.
2027 alias can not be executed until 'del foo' removes the Python variable.
2015
2028
2016 You can use the %l specifier in an alias definition to represent the
2029 You can use the %l specifier in an alias definition to represent the
2017 whole line when the alias is called. For example:
2030 whole line when the alias is called. For example:
2018
2031
2019 In [2]: alias all echo "Input in brackets: <%l>"\\
2032 In [2]: alias all echo "Input in brackets: <%l>"\\
2020 In [3]: all hello world\\
2033 In [3]: all hello world\\
2021 Input in brackets: <hello world>
2034 Input in brackets: <hello world>
2022
2035
2023 You can also define aliases with parameters using %s specifiers (one
2036 You can also define aliases with parameters using %s specifiers (one
2024 per parameter):
2037 per parameter):
2025
2038
2026 In [1]: alias parts echo first %s second %s\\
2039 In [1]: alias parts echo first %s second %s\\
2027 In [2]: %parts A B\\
2040 In [2]: %parts A B\\
2028 first A second B\\
2041 first A second B\\
2029 In [3]: %parts A\\
2042 In [3]: %parts A\\
2030 Incorrect number of arguments: 2 expected.\\
2043 Incorrect number of arguments: 2 expected.\\
2031 parts is an alias to: 'echo first %s second %s'
2044 parts is an alias to: 'echo first %s second %s'
2032
2045
2033 Note that %l and %s are mutually exclusive. You can only use one or
2046 Note that %l and %s are mutually exclusive. You can only use one or
2034 the other in your aliases.
2047 the other in your aliases.
2035
2048
2036 Aliases expand Python variables just like system calls using ! or !!
2049 Aliases expand Python variables just like system calls using ! or !!
2037 do: all expressions prefixed with '$' get expanded. For details of
2050 do: all expressions prefixed with '$' get expanded. For details of
2038 the semantic rules, see PEP-215:
2051 the semantic rules, see PEP-215:
2039 http://www.python.org/peps/pep-0215.html. This is the library used by
2052 http://www.python.org/peps/pep-0215.html. This is the library used by
2040 IPython for variable expansion. If you want to access a true shell
2053 IPython for variable expansion. If you want to access a true shell
2041 variable, an extra $ is necessary to prevent its expansion by IPython:
2054 variable, an extra $ is necessary to prevent its expansion by IPython:
2042
2055
2043 In [6]: alias show echo\\
2056 In [6]: alias show echo\\
2044 In [7]: PATH='A Python string'\\
2057 In [7]: PATH='A Python string'\\
2045 In [8]: show $PATH\\
2058 In [8]: show $PATH\\
2046 A Python string\\
2059 A Python string\\
2047 In [9]: show $$PATH\\
2060 In [9]: show $$PATH\\
2048 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2061 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2049
2062
2050 You can use the alias facility to acess all of $PATH. See the %rehash
2063 You can use the alias facility to acess all of $PATH. See the %rehash
2051 and %rehashx functions, which automatically create aliases for the
2064 and %rehashx functions, which automatically create aliases for the
2052 contents of your $PATH.
2065 contents of your $PATH.
2053
2066
2054 If called with no parameters, %alias prints the current alias table."""
2067 If called with no parameters, %alias prints the current alias table."""
2055
2068
2056 par = parameter_s.strip()
2069 par = parameter_s.strip()
2057 if not par:
2070 if not par:
2058 if self.shell.rc.automagic:
2071 if self.shell.rc.automagic:
2059 prechar = ''
2072 prechar = ''
2060 else:
2073 else:
2061 prechar = self.shell.ESC_MAGIC
2074 prechar = self.shell.ESC_MAGIC
2062 print 'Alias\t\tSystem Command\n'+'-'*30
2075 print 'Alias\t\tSystem Command\n'+'-'*30
2063 atab = self.shell.alias_table
2076 atab = self.shell.alias_table
2064 aliases = atab.keys()
2077 aliases = atab.keys()
2065 aliases.sort()
2078 aliases.sort()
2066 for alias in aliases:
2079 for alias in aliases:
2067 print prechar+alias+'\t\t'+atab[alias][1]
2080 print prechar+alias+'\t\t'+atab[alias][1]
2068 print '-'*30+'\nTotal number of aliases:',len(aliases)
2081 print '-'*30+'\nTotal number of aliases:',len(aliases)
2069 return
2082 return
2070 try:
2083 try:
2071 alias,cmd = par.split(None,1)
2084 alias,cmd = par.split(None,1)
2072 except:
2085 except:
2073 print OInspect.getdoc(self.magic_alias)
2086 print OInspect.getdoc(self.magic_alias)
2074 else:
2087 else:
2075 nargs = cmd.count('%s')
2088 nargs = cmd.count('%s')
2076 if nargs>0 and cmd.find('%l')>=0:
2089 if nargs>0 and cmd.find('%l')>=0:
2077 error('The %s and %l specifiers are mutually exclusive '
2090 error('The %s and %l specifiers are mutually exclusive '
2078 'in alias definitions.')
2091 'in alias definitions.')
2079 else: # all looks OK
2092 else: # all looks OK
2080 self.shell.alias_table[alias] = (nargs,cmd)
2093 self.shell.alias_table[alias] = (nargs,cmd)
2081 self.shell.alias_table_validate(verbose=1)
2094 self.shell.alias_table_validate(verbose=1)
2082 # end magic_alias
2095 # end magic_alias
2083
2096
2084 def magic_unalias(self, parameter_s = ''):
2097 def magic_unalias(self, parameter_s = ''):
2085 """Remove an alias"""
2098 """Remove an alias"""
2086
2099
2087 aname = parameter_s.strip()
2100 aname = parameter_s.strip()
2088 if aname in self.shell.alias_table:
2101 if aname in self.shell.alias_table:
2089 del self.shell.alias_table[aname]
2102 del self.shell.alias_table[aname]
2090
2103
2091 def magic_rehash(self, parameter_s = ''):
2104 def magic_rehash(self, parameter_s = ''):
2092 """Update the alias table with all entries in $PATH.
2105 """Update the alias table with all entries in $PATH.
2093
2106
2094 This version does no checks on execute permissions or whether the
2107 This version does no checks on execute permissions or whether the
2095 contents of $PATH are truly files (instead of directories or something
2108 contents of $PATH are truly files (instead of directories or something
2096 else). For such a safer (but slower) version, use %rehashx."""
2109 else). For such a safer (but slower) version, use %rehashx."""
2097
2110
2098 # This function (and rehashx) manipulate the alias_table directly
2111 # This function (and rehashx) manipulate the alias_table directly
2099 # rather than calling magic_alias, for speed reasons. A rehash on a
2112 # rather than calling magic_alias, for speed reasons. A rehash on a
2100 # typical Linux box involves several thousand entries, so efficiency
2113 # typical Linux box involves several thousand entries, so efficiency
2101 # here is a top concern.
2114 # here is a top concern.
2102
2115
2103 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2116 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2104 alias_table = self.shell.alias_table
2117 alias_table = self.shell.alias_table
2105 for pdir in path:
2118 for pdir in path:
2106 for ff in os.listdir(pdir):
2119 for ff in os.listdir(pdir):
2107 # each entry in the alias table must be (N,name), where
2120 # each entry in the alias table must be (N,name), where
2108 # N is the number of positional arguments of the alias.
2121 # N is the number of positional arguments of the alias.
2109 alias_table[ff] = (0,ff)
2122 alias_table[ff] = (0,ff)
2110 # Make sure the alias table doesn't contain keywords or builtins
2123 # Make sure the alias table doesn't contain keywords or builtins
2111 self.shell.alias_table_validate()
2124 self.shell.alias_table_validate()
2112 # Call again init_auto_alias() so we get 'rm -i' and other modified
2125 # Call again init_auto_alias() so we get 'rm -i' and other modified
2113 # aliases since %rehash will probably clobber them
2126 # aliases since %rehash will probably clobber them
2114 self.shell.init_auto_alias()
2127 self.shell.init_auto_alias()
2115
2128
2116 def magic_rehashx(self, parameter_s = ''):
2129 def magic_rehashx(self, parameter_s = ''):
2117 """Update the alias table with all executable files in $PATH.
2130 """Update the alias table with all executable files in $PATH.
2118
2131
2119 This version explicitly checks that every entry in $PATH is a file
2132 This version explicitly checks that every entry in $PATH is a file
2120 with execute access (os.X_OK), so it is much slower than %rehash.
2133 with execute access (os.X_OK), so it is much slower than %rehash.
2121
2134
2122 Under Windows, it checks executability as a match agains a
2135 Under Windows, it checks executability as a match agains a
2123 '|'-separated string of extensions, stored in the IPython config
2136 '|'-separated string of extensions, stored in the IPython config
2124 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2137 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2125
2138
2126 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2139 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2127 alias_table = self.shell.alias_table
2140 alias_table = self.shell.alias_table
2128
2141
2129 if os.name == 'posix':
2142 if os.name == 'posix':
2130 isexec = lambda fname:os.path.isfile(fname) and \
2143 isexec = lambda fname:os.path.isfile(fname) and \
2131 os.access(fname,os.X_OK)
2144 os.access(fname,os.X_OK)
2132 else:
2145 else:
2133
2146
2134 try:
2147 try:
2135 winext = os.environ['pathext'].replace(';','|').replace('.','')
2148 winext = os.environ['pathext'].replace(';','|').replace('.','')
2136 except KeyError:
2149 except KeyError:
2137 winext = 'exe|com|bat'
2150 winext = 'exe|com|bat'
2138
2151
2139 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2152 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2140 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2153 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2141 savedir = os.getcwd()
2154 savedir = os.getcwd()
2142 try:
2155 try:
2143 # write the whole loop for posix/Windows so we don't have an if in
2156 # write the whole loop for posix/Windows so we don't have an if in
2144 # the innermost part
2157 # the innermost part
2145 if os.name == 'posix':
2158 if os.name == 'posix':
2146 for pdir in path:
2159 for pdir in path:
2147 os.chdir(pdir)
2160 os.chdir(pdir)
2148 for ff in os.listdir(pdir):
2161 for ff in os.listdir(pdir):
2149 if isexec(ff):
2162 if isexec(ff):
2150 # each entry in the alias table must be (N,name),
2163 # each entry in the alias table must be (N,name),
2151 # where N is the number of positional arguments of the
2164 # where N is the number of positional arguments of the
2152 # alias.
2165 # alias.
2153 alias_table[ff] = (0,ff)
2166 alias_table[ff] = (0,ff)
2154 else:
2167 else:
2155 for pdir in path:
2168 for pdir in path:
2156 os.chdir(pdir)
2169 os.chdir(pdir)
2157 for ff in os.listdir(pdir):
2170 for ff in os.listdir(pdir):
2158 if isexec(ff):
2171 if isexec(ff):
2159 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2172 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2160 # Make sure the alias table doesn't contain keywords or builtins
2173 # Make sure the alias table doesn't contain keywords or builtins
2161 self.shell.alias_table_validate()
2174 self.shell.alias_table_validate()
2162 # Call again init_auto_alias() so we get 'rm -i' and other
2175 # Call again init_auto_alias() so we get 'rm -i' and other
2163 # modified aliases since %rehashx will probably clobber them
2176 # modified aliases since %rehashx will probably clobber them
2164 self.shell.init_auto_alias()
2177 self.shell.init_auto_alias()
2165 finally:
2178 finally:
2166 os.chdir(savedir)
2179 os.chdir(savedir)
2167
2180
2168 def magic_pwd(self, parameter_s = ''):
2181 def magic_pwd(self, parameter_s = ''):
2169 """Return the current working directory path."""
2182 """Return the current working directory path."""
2170 return os.getcwd()
2183 return os.getcwd()
2171
2184
2172 def magic_cd(self, parameter_s=''):
2185 def magic_cd(self, parameter_s=''):
2173 """Change the current working directory.
2186 """Change the current working directory.
2174
2187
2175 This command automatically maintains an internal list of directories
2188 This command automatically maintains an internal list of directories
2176 you visit during your IPython session, in the variable _dh. The
2189 you visit during your IPython session, in the variable _dh. The
2177 command %dhist shows this history nicely formatted.
2190 command %dhist shows this history nicely formatted.
2178
2191
2179 Usage:
2192 Usage:
2180
2193
2181 cd 'dir': changes to directory 'dir'.
2194 cd 'dir': changes to directory 'dir'.
2182
2195
2183 cd -: changes to the last visited directory.
2196 cd -: changes to the last visited directory.
2184
2197
2185 cd -<n>: changes to the n-th directory in the directory history.
2198 cd -<n>: changes to the n-th directory in the directory history.
2186
2199
2187 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2200 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2188 (note: cd <bookmark_name> is enough if there is no
2201 (note: cd <bookmark_name> is enough if there is no
2189 directory <bookmark_name>, but a bookmark with the name exists.)
2202 directory <bookmark_name>, but a bookmark with the name exists.)
2190
2203
2191 Options:
2204 Options:
2192
2205
2193 -q: quiet. Do not print the working directory after the cd command is
2206 -q: quiet. Do not print the working directory after the cd command is
2194 executed. By default IPython's cd command does print this directory,
2207 executed. By default IPython's cd command does print this directory,
2195 since the default prompts do not display path information.
2208 since the default prompts do not display path information.
2196
2209
2197 Note that !cd doesn't work for this purpose because the shell where
2210 Note that !cd doesn't work for this purpose because the shell where
2198 !command runs is immediately discarded after executing 'command'."""
2211 !command runs is immediately discarded after executing 'command'."""
2199
2212
2200 parameter_s = parameter_s.strip()
2213 parameter_s = parameter_s.strip()
2201 bkms = self.shell.persist.get("bookmarks",{})
2214 bkms = self.shell.persist.get("bookmarks",{})
2202
2215
2203 numcd = re.match(r'(-)(\d+)$',parameter_s)
2216 numcd = re.match(r'(-)(\d+)$',parameter_s)
2204 # jump in directory history by number
2217 # jump in directory history by number
2205 if numcd:
2218 if numcd:
2206 nn = int(numcd.group(2))
2219 nn = int(numcd.group(2))
2207 try:
2220 try:
2208 ps = self.shell.user_ns['_dh'][nn]
2221 ps = self.shell.user_ns['_dh'][nn]
2209 except IndexError:
2222 except IndexError:
2210 print 'The requested directory does not exist in history.'
2223 print 'The requested directory does not exist in history.'
2211 return
2224 return
2212 else:
2225 else:
2213 opts = {}
2226 opts = {}
2214 else:
2227 else:
2215 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2228 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2216 # jump to previous
2229 # jump to previous
2217 if ps == '-':
2230 if ps == '-':
2218 try:
2231 try:
2219 ps = self.shell.user_ns['_dh'][-2]
2232 ps = self.shell.user_ns['_dh'][-2]
2220 except IndexError:
2233 except IndexError:
2221 print 'No previous directory to change to.'
2234 print 'No previous directory to change to.'
2222 return
2235 return
2223 # jump to bookmark
2236 # jump to bookmark
2224 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2237 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2225 if bkms.has_key(ps):
2238 if bkms.has_key(ps):
2226 target = bkms[ps]
2239 target = bkms[ps]
2227 print '(bookmark:%s) -> %s' % (ps,target)
2240 print '(bookmark:%s) -> %s' % (ps,target)
2228 ps = target
2241 ps = target
2229 else:
2242 else:
2230 if bkms:
2243 if bkms:
2231 error("Bookmark '%s' not found. "
2244 error("Bookmark '%s' not found. "
2232 "Use '%bookmark -l' to see your bookmarks." % ps)
2245 "Use '%bookmark -l' to see your bookmarks." % ps)
2233 else:
2246 else:
2234 print "Bookmarks not set - use %bookmark <bookmarkname>"
2247 print "Bookmarks not set - use %bookmark <bookmarkname>"
2235 return
2248 return
2236
2249
2237 # at this point ps should point to the target dir
2250 # at this point ps should point to the target dir
2238 if ps:
2251 if ps:
2239 try:
2252 try:
2240 os.chdir(os.path.expanduser(ps))
2253 os.chdir(os.path.expanduser(ps))
2241 except OSError:
2254 except OSError:
2242 print sys.exc_info()[1]
2255 print sys.exc_info()[1]
2243 else:
2256 else:
2244 self.shell.user_ns['_dh'].append(os.getcwd())
2257 self.shell.user_ns['_dh'].append(os.getcwd())
2245 else:
2258 else:
2246 os.chdir(self.home_dir)
2259 os.chdir(self.home_dir)
2247 self.shell.user_ns['_dh'].append(os.getcwd())
2260 self.shell.user_ns['_dh'].append(os.getcwd())
2248 if not 'q' in opts:
2261 if not 'q' in opts:
2249 print self.shell.user_ns['_dh'][-1]
2262 print self.shell.user_ns['_dh'][-1]
2250
2263
2251 def magic_dhist(self, parameter_s=''):
2264 def magic_dhist(self, parameter_s=''):
2252 """Print your history of visited directories.
2265 """Print your history of visited directories.
2253
2266
2254 %dhist -> print full history\\
2267 %dhist -> print full history\\
2255 %dhist n -> print last n entries only\\
2268 %dhist n -> print last n entries only\\
2256 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2269 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2257
2270
2258 This history is automatically maintained by the %cd command, and
2271 This history is automatically maintained by the %cd command, and
2259 always available as the global list variable _dh. You can use %cd -<n>
2272 always available as the global list variable _dh. You can use %cd -<n>
2260 to go to directory number <n>."""
2273 to go to directory number <n>."""
2261
2274
2262 dh = self.shell.user_ns['_dh']
2275 dh = self.shell.user_ns['_dh']
2263 if parameter_s:
2276 if parameter_s:
2264 try:
2277 try:
2265 args = map(int,parameter_s.split())
2278 args = map(int,parameter_s.split())
2266 except:
2279 except:
2267 self.arg_err(Magic.magic_dhist)
2280 self.arg_err(Magic.magic_dhist)
2268 return
2281 return
2269 if len(args) == 1:
2282 if len(args) == 1:
2270 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2283 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2271 elif len(args) == 2:
2284 elif len(args) == 2:
2272 ini,fin = args
2285 ini,fin = args
2273 else:
2286 else:
2274 self.arg_err(Magic.magic_dhist)
2287 self.arg_err(Magic.magic_dhist)
2275 return
2288 return
2276 else:
2289 else:
2277 ini,fin = 0,len(dh)
2290 ini,fin = 0,len(dh)
2278 nlprint(dh,
2291 nlprint(dh,
2279 header = 'Directory history (kept in _dh)',
2292 header = 'Directory history (kept in _dh)',
2280 start=ini,stop=fin)
2293 start=ini,stop=fin)
2281
2294
2282 def magic_env(self, parameter_s=''):
2295 def magic_env(self, parameter_s=''):
2283 """List environment variables."""
2296 """List environment variables."""
2284
2297
2285 # environ is an instance of UserDict
2298 # environ is an instance of UserDict
2286 return os.environ.data
2299 return os.environ.data
2287
2300
2288 def magic_pushd(self, parameter_s=''):
2301 def magic_pushd(self, parameter_s=''):
2289 """Place the current dir on stack and change directory.
2302 """Place the current dir on stack and change directory.
2290
2303
2291 Usage:\\
2304 Usage:\\
2292 %pushd ['dirname']
2305 %pushd ['dirname']
2293
2306
2294 %pushd with no arguments does a %pushd to your home directory.
2307 %pushd with no arguments does a %pushd to your home directory.
2295 """
2308 """
2296 if parameter_s == '': parameter_s = '~'
2309 if parameter_s == '': parameter_s = '~'
2297 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2310 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2298 os.path.expanduser(self.dir_stack[0]):
2311 os.path.expanduser(self.dir_stack[0]):
2299 try:
2312 try:
2300 self.magic_cd(parameter_s)
2313 self.magic_cd(parameter_s)
2301 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2314 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2302 self.magic_dirs()
2315 self.magic_dirs()
2303 except:
2316 except:
2304 print 'Invalid directory'
2317 print 'Invalid directory'
2305 else:
2318 else:
2306 print 'You are already there!'
2319 print 'You are already there!'
2307
2320
2308 def magic_popd(self, parameter_s=''):
2321 def magic_popd(self, parameter_s=''):
2309 """Change to directory popped off the top of the stack.
2322 """Change to directory popped off the top of the stack.
2310 """
2323 """
2311 if len (self.dir_stack) > 1:
2324 if len (self.dir_stack) > 1:
2312 self.dir_stack.pop(0)
2325 self.dir_stack.pop(0)
2313 self.magic_cd(self.dir_stack[0])
2326 self.magic_cd(self.dir_stack[0])
2314 print self.dir_stack[0]
2327 print self.dir_stack[0]
2315 else:
2328 else:
2316 print "You can't remove the starting directory from the stack:",\
2329 print "You can't remove the starting directory from the stack:",\
2317 self.dir_stack
2330 self.dir_stack
2318
2331
2319 def magic_dirs(self, parameter_s=''):
2332 def magic_dirs(self, parameter_s=''):
2320 """Return the current directory stack."""
2333 """Return the current directory stack."""
2321
2334
2322 return self.dir_stack[:]
2335 return self.dir_stack[:]
2323
2336
2324 def magic_sc(self, parameter_s=''):
2337 def magic_sc(self, parameter_s=''):
2325 """Shell capture - execute a shell command and capture its output.
2338 """Shell capture - execute a shell command and capture its output.
2326
2339
2327 %sc [options] varname=command
2340 %sc [options] varname=command
2328
2341
2329 IPython will run the given command using commands.getoutput(), and
2342 IPython will run the given command using commands.getoutput(), and
2330 will then update the user's interactive namespace with a variable
2343 will then update the user's interactive namespace with a variable
2331 called varname, containing the value of the call. Your command can
2344 called varname, containing the value of the call. Your command can
2332 contain shell wildcards, pipes, etc.
2345 contain shell wildcards, pipes, etc.
2333
2346
2334 The '=' sign in the syntax is mandatory, and the variable name you
2347 The '=' sign in the syntax is mandatory, and the variable name you
2335 supply must follow Python's standard conventions for valid names.
2348 supply must follow Python's standard conventions for valid names.
2336
2349
2337 Options:
2350 Options:
2338
2351
2339 -l: list output. Split the output on newlines into a list before
2352 -l: list output. Split the output on newlines into a list before
2340 assigning it to the given variable. By default the output is stored
2353 assigning it to the given variable. By default the output is stored
2341 as a single string.
2354 as a single string.
2342
2355
2343 -v: verbose. Print the contents of the variable.
2356 -v: verbose. Print the contents of the variable.
2344
2357
2345 In most cases you should not need to split as a list, because the
2358 In most cases you should not need to split as a list, because the
2346 returned value is a special type of string which can automatically
2359 returned value is a special type of string which can automatically
2347 provide its contents either as a list (split on newlines) or as a
2360 provide its contents either as a list (split on newlines) or as a
2348 space-separated string. These are convenient, respectively, either
2361 space-separated string. These are convenient, respectively, either
2349 for sequential processing or to be passed to a shell command.
2362 for sequential processing or to be passed to a shell command.
2350
2363
2351 For example:
2364 For example:
2352
2365
2353 # Capture into variable a
2366 # Capture into variable a
2354 In [9]: sc a=ls *py
2367 In [9]: sc a=ls *py
2355
2368
2356 # a is a string with embedded newlines
2369 # a is a string with embedded newlines
2357 In [10]: a
2370 In [10]: a
2358 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2371 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2359
2372
2360 # which can be seen as a list:
2373 # which can be seen as a list:
2361 In [11]: a.l
2374 In [11]: a.l
2362 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2375 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2363
2376
2364 # or as a whitespace-separated string:
2377 # or as a whitespace-separated string:
2365 In [12]: a.s
2378 In [12]: a.s
2366 Out[12]: 'setup.py win32_manual_post_install.py'
2379 Out[12]: 'setup.py win32_manual_post_install.py'
2367
2380
2368 # a.s is useful to pass as a single command line:
2381 # a.s is useful to pass as a single command line:
2369 In [13]: !wc -l $a.s
2382 In [13]: !wc -l $a.s
2370 146 setup.py
2383 146 setup.py
2371 130 win32_manual_post_install.py
2384 130 win32_manual_post_install.py
2372 276 total
2385 276 total
2373
2386
2374 # while the list form is useful to loop over:
2387 # while the list form is useful to loop over:
2375 In [14]: for f in a.l:
2388 In [14]: for f in a.l:
2376 ....: !wc -l $f
2389 ....: !wc -l $f
2377 ....:
2390 ....:
2378 146 setup.py
2391 146 setup.py
2379 130 win32_manual_post_install.py
2392 130 win32_manual_post_install.py
2380
2393
2381 Similiarly, the lists returned by the -l option are also special, in
2394 Similiarly, the lists returned by the -l option are also special, in
2382 the sense that you can equally invoke the .s attribute on them to
2395 the sense that you can equally invoke the .s attribute on them to
2383 automatically get a whitespace-separated string from their contents:
2396 automatically get a whitespace-separated string from their contents:
2384
2397
2385 In [1]: sc -l b=ls *py
2398 In [1]: sc -l b=ls *py
2386
2399
2387 In [2]: b
2400 In [2]: b
2388 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2401 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2389
2402
2390 In [3]: b.s
2403 In [3]: b.s
2391 Out[3]: 'setup.py win32_manual_post_install.py'
2404 Out[3]: 'setup.py win32_manual_post_install.py'
2392
2405
2393 In summary, both the lists and strings used for ouptut capture have
2406 In summary, both the lists and strings used for ouptut capture have
2394 the following special attributes:
2407 the following special attributes:
2395
2408
2396 .l (or .list) : value as list.
2409 .l (or .list) : value as list.
2397 .n (or .nlstr): value as newline-separated string.
2410 .n (or .nlstr): value as newline-separated string.
2398 .s (or .spstr): value as space-separated string.
2411 .s (or .spstr): value as space-separated string.
2399 """
2412 """
2400
2413
2401 opts,args = self.parse_options(parameter_s,'lv')
2414 opts,args = self.parse_options(parameter_s,'lv')
2402 # Try to get a variable name and command to run
2415 # Try to get a variable name and command to run
2403 try:
2416 try:
2404 # the variable name must be obtained from the parse_options
2417 # the variable name must be obtained from the parse_options
2405 # output, which uses shlex.split to strip options out.
2418 # output, which uses shlex.split to strip options out.
2406 var,_ = args.split('=',1)
2419 var,_ = args.split('=',1)
2407 var = var.strip()
2420 var = var.strip()
2408 # But the the command has to be extracted from the original input
2421 # But the the command has to be extracted from the original input
2409 # parameter_s, not on what parse_options returns, to avoid the
2422 # parameter_s, not on what parse_options returns, to avoid the
2410 # quote stripping which shlex.split performs on it.
2423 # quote stripping which shlex.split performs on it.
2411 _,cmd = parameter_s.split('=',1)
2424 _,cmd = parameter_s.split('=',1)
2412 except ValueError:
2425 except ValueError:
2413 var,cmd = '',''
2426 var,cmd = '',''
2414 if not var:
2427 if not var:
2415 error('you must specify a variable to assign the command to.')
2428 error('you must specify a variable to assign the command to.')
2416 return
2429 return
2417 # If all looks ok, proceed
2430 # If all looks ok, proceed
2418 out,err = self.shell.getoutputerror(cmd)
2431 out,err = self.shell.getoutputerror(cmd)
2419 if err:
2432 if err:
2420 print >> Term.cerr,err
2433 print >> Term.cerr,err
2421 if opts.has_key('l'):
2434 if opts.has_key('l'):
2422 out = SList(out.split('\n'))
2435 out = SList(out.split('\n'))
2423 else:
2436 else:
2424 out = LSString(out)
2437 out = LSString(out)
2425 if opts.has_key('v'):
2438 if opts.has_key('v'):
2426 print '%s ==\n%s' % (var,pformat(out))
2439 print '%s ==\n%s' % (var,pformat(out))
2427 self.shell.user_ns.update({var:out})
2440 self.shell.user_ns.update({var:out})
2428
2441
2429 def magic_sx(self, parameter_s=''):
2442 def magic_sx(self, parameter_s=''):
2430 """Shell execute - run a shell command and capture its output.
2443 """Shell execute - run a shell command and capture its output.
2431
2444
2432 %sx command
2445 %sx command
2433
2446
2434 IPython will run the given command using commands.getoutput(), and
2447 IPython will run the given command using commands.getoutput(), and
2435 return the result formatted as a list (split on '\\n'). Since the
2448 return the result formatted as a list (split on '\\n'). Since the
2436 output is _returned_, it will be stored in ipython's regular output
2449 output is _returned_, it will be stored in ipython's regular output
2437 cache Out[N] and in the '_N' automatic variables.
2450 cache Out[N] and in the '_N' automatic variables.
2438
2451
2439 Notes:
2452 Notes:
2440
2453
2441 1) If an input line begins with '!!', then %sx is automatically
2454 1) If an input line begins with '!!', then %sx is automatically
2442 invoked. That is, while:
2455 invoked. That is, while:
2443 !ls
2456 !ls
2444 causes ipython to simply issue system('ls'), typing
2457 causes ipython to simply issue system('ls'), typing
2445 !!ls
2458 !!ls
2446 is a shorthand equivalent to:
2459 is a shorthand equivalent to:
2447 %sx ls
2460 %sx ls
2448
2461
2449 2) %sx differs from %sc in that %sx automatically splits into a list,
2462 2) %sx differs from %sc in that %sx automatically splits into a list,
2450 like '%sc -l'. The reason for this is to make it as easy as possible
2463 like '%sc -l'. The reason for this is to make it as easy as possible
2451 to process line-oriented shell output via further python commands.
2464 to process line-oriented shell output via further python commands.
2452 %sc is meant to provide much finer control, but requires more
2465 %sc is meant to provide much finer control, but requires more
2453 typing.
2466 typing.
2454
2467
2455 3) Just like %sc -l, this is a list with special attributes:
2468 3) Just like %sc -l, this is a list with special attributes:
2456
2469
2457 .l (or .list) : value as list.
2470 .l (or .list) : value as list.
2458 .n (or .nlstr): value as newline-separated string.
2471 .n (or .nlstr): value as newline-separated string.
2459 .s (or .spstr): value as whitespace-separated string.
2472 .s (or .spstr): value as whitespace-separated string.
2460
2473
2461 This is very useful when trying to use such lists as arguments to
2474 This is very useful when trying to use such lists as arguments to
2462 system commands."""
2475 system commands."""
2463
2476
2464 if parameter_s:
2477 if parameter_s:
2465 out,err = self.shell.getoutputerror(parameter_s)
2478 out,err = self.shell.getoutputerror(parameter_s)
2466 if err:
2479 if err:
2467 print >> Term.cerr,err
2480 print >> Term.cerr,err
2468 return SList(out.split('\n'))
2481 return SList(out.split('\n'))
2469
2482
2470 def magic_bg(self, parameter_s=''):
2483 def magic_bg(self, parameter_s=''):
2471 """Run a job in the background, in a separate thread.
2484 """Run a job in the background, in a separate thread.
2472
2485
2473 For example,
2486 For example,
2474
2487
2475 %bg myfunc(x,y,z=1)
2488 %bg myfunc(x,y,z=1)
2476
2489
2477 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2490 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2478 execution starts, a message will be printed indicating the job
2491 execution starts, a message will be printed indicating the job
2479 number. If your job number is 5, you can use
2492 number. If your job number is 5, you can use
2480
2493
2481 myvar = jobs.result(5) or myvar = jobs[5].result
2494 myvar = jobs.result(5) or myvar = jobs[5].result
2482
2495
2483 to assign this result to variable 'myvar'.
2496 to assign this result to variable 'myvar'.
2484
2497
2485 IPython has a job manager, accessible via the 'jobs' object. You can
2498 IPython has a job manager, accessible via the 'jobs' object. You can
2486 type jobs? to get more information about it, and use jobs.<TAB> to see
2499 type jobs? to get more information about it, and use jobs.<TAB> to see
2487 its attributes. All attributes not starting with an underscore are
2500 its attributes. All attributes not starting with an underscore are
2488 meant for public use.
2501 meant for public use.
2489
2502
2490 In particular, look at the jobs.new() method, which is used to create
2503 In particular, look at the jobs.new() method, which is used to create
2491 new jobs. This magic %bg function is just a convenience wrapper
2504 new jobs. This magic %bg function is just a convenience wrapper
2492 around jobs.new(), for expression-based jobs. If you want to create a
2505 around jobs.new(), for expression-based jobs. If you want to create a
2493 new job with an explicit function object and arguments, you must call
2506 new job with an explicit function object and arguments, you must call
2494 jobs.new() directly.
2507 jobs.new() directly.
2495
2508
2496 The jobs.new docstring also describes in detail several important
2509 The jobs.new docstring also describes in detail several important
2497 caveats associated with a thread-based model for background job
2510 caveats associated with a thread-based model for background job
2498 execution. Type jobs.new? for details.
2511 execution. Type jobs.new? for details.
2499
2512
2500 You can check the status of all jobs with jobs.status().
2513 You can check the status of all jobs with jobs.status().
2501
2514
2502 The jobs variable is set by IPython into the Python builtin namespace.
2515 The jobs variable is set by IPython into the Python builtin namespace.
2503 If you ever declare a variable named 'jobs', you will shadow this
2516 If you ever declare a variable named 'jobs', you will shadow this
2504 name. You can either delete your global jobs variable to regain
2517 name. You can either delete your global jobs variable to regain
2505 access to the job manager, or make a new name and assign it manually
2518 access to the job manager, or make a new name and assign it manually
2506 to the manager (stored in IPython's namespace). For example, to
2519 to the manager (stored in IPython's namespace). For example, to
2507 assign the job manager to the Jobs name, use:
2520 assign the job manager to the Jobs name, use:
2508
2521
2509 Jobs = __builtins__.jobs"""
2522 Jobs = __builtins__.jobs"""
2510
2523
2511 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2524 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2512
2525
2513 def magic_bookmark(self, parameter_s=''):
2526 def magic_bookmark(self, parameter_s=''):
2514 """Manage IPython's bookmark system.
2527 """Manage IPython's bookmark system.
2515
2528
2516 %bookmark <name> - set bookmark to current dir
2529 %bookmark <name> - set bookmark to current dir
2517 %bookmark <name> <dir> - set bookmark to <dir>
2530 %bookmark <name> <dir> - set bookmark to <dir>
2518 %bookmark -l - list all bookmarks
2531 %bookmark -l - list all bookmarks
2519 %bookmark -d <name> - remove bookmark
2532 %bookmark -d <name> - remove bookmark
2520 %bookmark -r - remove all bookmarks
2533 %bookmark -r - remove all bookmarks
2521
2534
2522 You can later on access a bookmarked folder with:
2535 You can later on access a bookmarked folder with:
2523 %cd -b <name>
2536 %cd -b <name>
2524 or simply '%cd <name>' if there is no directory called <name> AND
2537 or simply '%cd <name>' if there is no directory called <name> AND
2525 there is such a bookmark defined.
2538 there is such a bookmark defined.
2526
2539
2527 Your bookmarks persist through IPython sessions, but they are
2540 Your bookmarks persist through IPython sessions, but they are
2528 associated with each profile."""
2541 associated with each profile."""
2529
2542
2530 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2543 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2531 if len(args) > 2:
2544 if len(args) > 2:
2532 error('You can only give at most two arguments')
2545 error('You can only give at most two arguments')
2533 return
2546 return
2534
2547
2535 bkms = self.shell.persist.get('bookmarks',{})
2548 bkms = self.shell.persist.get('bookmarks',{})
2536
2549
2537 if opts.has_key('d'):
2550 if opts.has_key('d'):
2538 try:
2551 try:
2539 todel = args[0]
2552 todel = args[0]
2540 except IndexError:
2553 except IndexError:
2541 error('You must provide a bookmark to delete')
2554 error('You must provide a bookmark to delete')
2542 else:
2555 else:
2543 try:
2556 try:
2544 del bkms[todel]
2557 del bkms[todel]
2545 except:
2558 except:
2546 error("Can't delete bookmark '%s'" % todel)
2559 error("Can't delete bookmark '%s'" % todel)
2547 elif opts.has_key('r'):
2560 elif opts.has_key('r'):
2548 bkms = {}
2561 bkms = {}
2549 elif opts.has_key('l'):
2562 elif opts.has_key('l'):
2550 bks = bkms.keys()
2563 bks = bkms.keys()
2551 bks.sort()
2564 bks.sort()
2552 if bks:
2565 if bks:
2553 size = max(map(len,bks))
2566 size = max(map(len,bks))
2554 else:
2567 else:
2555 size = 0
2568 size = 0
2556 fmt = '%-'+str(size)+'s -> %s'
2569 fmt = '%-'+str(size)+'s -> %s'
2557 print 'Current bookmarks:'
2570 print 'Current bookmarks:'
2558 for bk in bks:
2571 for bk in bks:
2559 print fmt % (bk,bkms[bk])
2572 print fmt % (bk,bkms[bk])
2560 else:
2573 else:
2561 if not args:
2574 if not args:
2562 error("You must specify the bookmark name")
2575 error("You must specify the bookmark name")
2563 elif len(args)==1:
2576 elif len(args)==1:
2564 bkms[args[0]] = os.getcwd()
2577 bkms[args[0]] = os.getcwd()
2565 elif len(args)==2:
2578 elif len(args)==2:
2566 bkms[args[0]] = args[1]
2579 bkms[args[0]] = args[1]
2567 self.persist['bookmarks'] = bkms
2580 self.persist['bookmarks'] = bkms
2568
2581
2569 def magic_pycat(self, parameter_s=''):
2582 def magic_pycat(self, parameter_s=''):
2570 """Show a syntax-highlighted file through a pager.
2583 """Show a syntax-highlighted file through a pager.
2571
2584
2572 This magic is similar to the cat utility, but it will assume the file
2585 This magic is similar to the cat utility, but it will assume the file
2573 to be Python source and will show it with syntax highlighting. """
2586 to be Python source and will show it with syntax highlighting. """
2574
2587
2575 filename = get_py_filename(parameter_s)
2588 filename = get_py_filename(parameter_s)
2576 page(self.shell.colorize(file_read(filename)),
2589 page(self.shell.colorize(file_read(filename)),
2577 screen_lines=self.shell.rc.screen_length)
2590 screen_lines=self.shell.rc.screen_length)
2578
2591
2579 # end Magic
2592 # end Magic
@@ -1,1964 +1,1958 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or newer.
5 Requires Python 2.1 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 960 2005-12-28 06:51:01Z fperez $
9 $Id: iplib.py 962 2005-12-28 18:04:59Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import traceback
58 import traceback
59 import types
59 import types
60
60
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic,magic2python
70 from IPython.Magic import Magic,magic2python
71 from IPython.Struct import Struct
71 from IPython.Struct import Struct
72 from IPython.background_jobs import BackgroundJobManager
72 from IPython.background_jobs import BackgroundJobManager
73 from IPython.usage import cmd_line_usage,interactive_usage
73 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.genutils import *
74 from IPython.genutils import *
75
75
76 # store the builtin raw_input globally, and use this always, in case user code
76 # store the builtin raw_input globally, and use this always, in case user code
77 # overwrites it (like wx.py.PyShell does)
77 # overwrites it (like wx.py.PyShell does)
78 raw_input_original = raw_input
78 raw_input_original = raw_input
79
79
80 #****************************************************************************
80 #****************************************************************************
81 # Some utility function definitions
81 # Some utility function definitions
82
82
83 # This can be replaced with an isspace() call once we drop 2.2 compatibility
83 # This can be replaced with an isspace() call once we drop 2.2 compatibility
84 _isspace_match = re.compile(r'^\s+$').match
84 _isspace_match = re.compile(r'^\s+$').match
85 def isspace(s):
85 def isspace(s):
86 return bool(_isspace_match(s))
86 return bool(_isspace_match(s))
87
87
88 def esc_quotes(strng):
88 def esc_quotes(strng):
89 """Return the input string with single and double quotes escaped out"""
89 """Return the input string with single and double quotes escaped out"""
90
90
91 return strng.replace('"','\\"').replace("'","\\'")
91 return strng.replace('"','\\"').replace("'","\\'")
92
92
93 def import_fail_info(mod_name,fns=None):
93 def import_fail_info(mod_name,fns=None):
94 """Inform load failure for a module."""
94 """Inform load failure for a module."""
95
95
96 if fns == None:
96 if fns == None:
97 warn("Loading of %s failed.\n" % (mod_name,))
97 warn("Loading of %s failed.\n" % (mod_name,))
98 else:
98 else:
99 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
99 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
100
100
101 def qw_lol(indata):
101 def qw_lol(indata):
102 """qw_lol('a b') -> [['a','b']],
102 """qw_lol('a b') -> [['a','b']],
103 otherwise it's just a call to qw().
103 otherwise it's just a call to qw().
104
104
105 We need this to make sure the modules_some keys *always* end up as a
105 We need this to make sure the modules_some keys *always* end up as a
106 list of lists."""
106 list of lists."""
107
107
108 if type(indata) in StringTypes:
108 if type(indata) in StringTypes:
109 return [qw(indata)]
109 return [qw(indata)]
110 else:
110 else:
111 return qw(indata)
111 return qw(indata)
112
112
113 def ipmagic(arg_s):
113 def ipmagic(arg_s):
114 """Call a magic function by name.
114 """Call a magic function by name.
115
115
116 Input: a string containing the name of the magic function to call and any
116 Input: a string containing the name of the magic function to call and any
117 additional arguments to be passed to the magic.
117 additional arguments to be passed to the magic.
118
118
119 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
119 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
120 prompt:
120 prompt:
121
121
122 In[1]: %name -opt foo bar
122 In[1]: %name -opt foo bar
123
123
124 To call a magic without arguments, simply use ipmagic('name').
124 To call a magic without arguments, simply use ipmagic('name').
125
125
126 This provides a proper Python function to call IPython's magics in any
126 This provides a proper Python function to call IPython's magics in any
127 valid Python code you can type at the interpreter, including loops and
127 valid Python code you can type at the interpreter, including loops and
128 compound statements. It is added by IPython to the Python builtin
128 compound statements. It is added by IPython to the Python builtin
129 namespace upon initialization."""
129 namespace upon initialization."""
130
130
131 args = arg_s.split(' ',1)
131 args = arg_s.split(' ',1)
132 magic_name = args[0]
132 magic_name = args[0]
133 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
133 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
134 magic_name = magic_name[1:]
134 magic_name = magic_name[1:]
135 try:
135 try:
136 magic_args = args[1]
136 magic_args = args[1]
137 except IndexError:
137 except IndexError:
138 magic_args = ''
138 magic_args = ''
139 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
139 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
140 if fn is None:
140 if fn is None:
141 error("Magic function `%s` not found." % magic_name)
141 error("Magic function `%s` not found." % magic_name)
142 else:
142 else:
143 magic_args = __IPYTHON__.var_expand(magic_args)
143 magic_args = __IPYTHON__.var_expand(magic_args)
144 return fn(magic_args)
144 return fn(magic_args)
145
145
146 def ipalias(arg_s):
146 def ipalias(arg_s):
147 """Call an alias by name.
147 """Call an alias by name.
148
148
149 Input: a string containing the name of the alias to call and any
149 Input: a string containing the name of the alias to call and any
150 additional arguments to be passed to the magic.
150 additional arguments to be passed to the magic.
151
151
152 ipalias('name -opt foo bar') is equivalent to typing at the ipython
152 ipalias('name -opt foo bar') is equivalent to typing at the ipython
153 prompt:
153 prompt:
154
154
155 In[1]: name -opt foo bar
155 In[1]: name -opt foo bar
156
156
157 To call an alias without arguments, simply use ipalias('name').
157 To call an alias without arguments, simply use ipalias('name').
158
158
159 This provides a proper Python function to call IPython's aliases in any
159 This provides a proper Python function to call IPython's aliases in any
160 valid Python code you can type at the interpreter, including loops and
160 valid Python code you can type at the interpreter, including loops and
161 compound statements. It is added by IPython to the Python builtin
161 compound statements. It is added by IPython to the Python builtin
162 namespace upon initialization."""
162 namespace upon initialization."""
163
163
164 args = arg_s.split(' ',1)
164 args = arg_s.split(' ',1)
165 alias_name = args[0]
165 alias_name = args[0]
166 try:
166 try:
167 alias_args = args[1]
167 alias_args = args[1]
168 except IndexError:
168 except IndexError:
169 alias_args = ''
169 alias_args = ''
170 if alias_name in __IPYTHON__.alias_table:
170 if alias_name in __IPYTHON__.alias_table:
171 __IPYTHON__.call_alias(alias_name,alias_args)
171 __IPYTHON__.call_alias(alias_name,alias_args)
172 else:
172 else:
173 error("Alias `%s` not found." % alias_name)
173 error("Alias `%s` not found." % alias_name)
174
174
175 def softspace(file, newvalue):
175 def softspace(file, newvalue):
176 """Copied from code.py, to remove the dependency"""
176 """Copied from code.py, to remove the dependency"""
177 oldvalue = 0
177 oldvalue = 0
178 try:
178 try:
179 oldvalue = file.softspace
179 oldvalue = file.softspace
180 except AttributeError:
180 except AttributeError:
181 pass
181 pass
182 try:
182 try:
183 file.softspace = newvalue
183 file.softspace = newvalue
184 except (AttributeError, TypeError):
184 except (AttributeError, TypeError):
185 # "attribute-less object" or "read-only attributes"
185 # "attribute-less object" or "read-only attributes"
186 pass
186 pass
187 return oldvalue
187 return oldvalue
188
188
189
189
190 #****************************************************************************
190 #****************************************************************************
191 # Local use exceptions
191 # Local use exceptions
192 class SpaceInInput(exceptions.Exception): pass
192 class SpaceInInput(exceptions.Exception): pass
193
193
194 class IPythonExit(exceptions.Exception): pass
195
196 #****************************************************************************
194 #****************************************************************************
197 # Local use classes
195 # Local use classes
198 class Bunch: pass
196 class Bunch: pass
199
197
200 class InputList(list):
198 class InputList(list):
201 """Class to store user input.
199 """Class to store user input.
202
200
203 It's basically a list, but slices return a string instead of a list, thus
201 It's basically a list, but slices return a string instead of a list, thus
204 allowing things like (assuming 'In' is an instance):
202 allowing things like (assuming 'In' is an instance):
205
203
206 exec In[4:7]
204 exec In[4:7]
207
205
208 or
206 or
209
207
210 exec In[5:9] + In[14] + In[21:25]"""
208 exec In[5:9] + In[14] + In[21:25]"""
211
209
212 def __getslice__(self,i,j):
210 def __getslice__(self,i,j):
213 return ''.join(list.__getslice__(self,i,j))
211 return ''.join(list.__getslice__(self,i,j))
214
212
215 class SyntaxTB(ultraTB.ListTB):
213 class SyntaxTB(ultraTB.ListTB):
216 """Extension which holds some state: the last exception value"""
214 """Extension which holds some state: the last exception value"""
217
215
218 def __init__(self,color_scheme = 'NoColor'):
216 def __init__(self,color_scheme = 'NoColor'):
219 ultraTB.ListTB.__init__(self,color_scheme)
217 ultraTB.ListTB.__init__(self,color_scheme)
220 self.last_syntax_error = None
218 self.last_syntax_error = None
221
219
222 def __call__(self, etype, value, elist):
220 def __call__(self, etype, value, elist):
223 self.last_syntax_error = value
221 self.last_syntax_error = value
224 ultraTB.ListTB.__call__(self,etype,value,elist)
222 ultraTB.ListTB.__call__(self,etype,value,elist)
225
223
226 def clear_err_state(self):
224 def clear_err_state(self):
227 """Return the current error state and clear it"""
225 """Return the current error state and clear it"""
228 e = self.last_syntax_error
226 e = self.last_syntax_error
229 self.last_syntax_error = None
227 self.last_syntax_error = None
230 return e
228 return e
231
229
232 #****************************************************************************
230 #****************************************************************************
233 # Main IPython class
231 # Main IPython class
234 class InteractiveShell(Logger, Magic):
232 class InteractiveShell(Logger, Magic):
235 """An enhanced console for Python."""
233 """An enhanced console for Python."""
236
234
237 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
235 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
238 user_ns = None,user_global_ns=None,banner2='',
236 user_ns = None,user_global_ns=None,banner2='',
239 custom_exceptions=((),None),embedded=False):
237 custom_exceptions=((),None),embedded=False):
240
238
241 # Put a reference to self in builtins so that any form of embedded or
239 # Put a reference to self in builtins so that any form of embedded or
242 # imported code can test for being inside IPython.
240 # imported code can test for being inside IPython.
243 __builtin__.__IPYTHON__ = self
241 __builtin__.__IPYTHON__ = self
244
242
245 # And load into builtins ipmagic/ipalias as well
243 # And load into builtins ipmagic/ipalias as well
246 __builtin__.ipmagic = ipmagic
244 __builtin__.ipmagic = ipmagic
247 __builtin__.ipalias = ipalias
245 __builtin__.ipalias = ipalias
248
246
249 # Add to __builtin__ other parts of IPython's public API
247 # Add to __builtin__ other parts of IPython's public API
250 __builtin__.ip_set_hook = self.set_hook
248 __builtin__.ip_set_hook = self.set_hook
251
249
252 # Keep in the builtins a flag for when IPython is active. We set it
250 # Keep in the builtins a flag for when IPython is active. We set it
253 # with setdefault so that multiple nested IPythons don't clobber one
251 # with setdefault so that multiple nested IPythons don't clobber one
254 # another. Each will increase its value by one upon being activated,
252 # another. Each will increase its value by one upon being activated,
255 # which also gives us a way to determine the nesting level.
253 # which also gives us a way to determine the nesting level.
256 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
254 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
257
255
258 # Do the intuitively correct thing for quit/exit: we remove the
256 # Do the intuitively correct thing for quit/exit: we remove the
259 # builtins if they exist, and our own prefilter routine will handle
257 # builtins if they exist, and our own prefilter routine will handle
260 # these special cases
258 # these special cases
261 try:
259 try:
262 del __builtin__.exit, __builtin__.quit
260 del __builtin__.exit, __builtin__.quit
263 except AttributeError:
261 except AttributeError:
264 pass
262 pass
265
263
266 # We need to know whether the instance is meant for embedding, since
264 # We need to know whether the instance is meant for embedding, since
267 # global/local namespaces need to be handled differently in that case
265 # global/local namespaces need to be handled differently in that case
268 self.embedded = embedded
266 self.embedded = embedded
269
267
270 # command compiler
268 # command compiler
271 self.compile = codeop.CommandCompiler()
269 self.compile = codeop.CommandCompiler()
272
270
273 # User input buffer
271 # User input buffer
274 self.buffer = []
272 self.buffer = []
275
273
276 # Default name given in compilation of code
274 # Default name given in compilation of code
277 self.filename = '<ipython console>'
275 self.filename = '<ipython console>'
278
276
279 # Create the namespace where the user will operate. user_ns is
277 # Create the namespace where the user will operate. user_ns is
280 # normally the only one used, and it is passed to the exec calls as
278 # normally the only one used, and it is passed to the exec calls as
281 # the locals argument. But we do carry a user_global_ns namespace
279 # the locals argument. But we do carry a user_global_ns namespace
282 # given as the exec 'globals' argument, This is useful in embedding
280 # given as the exec 'globals' argument, This is useful in embedding
283 # situations where the ipython shell opens in a context where the
281 # situations where the ipython shell opens in a context where the
284 # distinction between locals and globals is meaningful.
282 # distinction between locals and globals is meaningful.
285
283
286 # FIXME. For some strange reason, __builtins__ is showing up at user
284 # FIXME. For some strange reason, __builtins__ is showing up at user
287 # level as a dict instead of a module. This is a manual fix, but I
285 # level as a dict instead of a module. This is a manual fix, but I
288 # should really track down where the problem is coming from. Alex
286 # should really track down where the problem is coming from. Alex
289 # Schmolck reported this problem first.
287 # Schmolck reported this problem first.
290
288
291 # A useful post by Alex Martelli on this topic:
289 # A useful post by Alex Martelli on this topic:
292 # Re: inconsistent value from __builtins__
290 # Re: inconsistent value from __builtins__
293 # Von: Alex Martelli <aleaxit@yahoo.com>
291 # Von: Alex Martelli <aleaxit@yahoo.com>
294 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
292 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
295 # Gruppen: comp.lang.python
293 # Gruppen: comp.lang.python
296 # Referenzen: 1
294 # Referenzen: 1
297
295
298 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
296 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
299 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
297 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
300 # > <type 'dict'>
298 # > <type 'dict'>
301 # > >>> print type(__builtins__)
299 # > >>> print type(__builtins__)
302 # > <type 'module'>
300 # > <type 'module'>
303 # > Is this difference in return value intentional?
301 # > Is this difference in return value intentional?
304
302
305 # Well, it's documented that '__builtins__' can be either a dictionary
303 # Well, it's documented that '__builtins__' can be either a dictionary
306 # or a module, and it's been that way for a long time. Whether it's
304 # or a module, and it's been that way for a long time. Whether it's
307 # intentional (or sensible), I don't know. In any case, the idea is
305 # intentional (or sensible), I don't know. In any case, the idea is
308 # that if you need to access the built-in namespace directly, you
306 # that if you need to access the built-in namespace directly, you
309 # should start with "import __builtin__" (note, no 's') which will
307 # should start with "import __builtin__" (note, no 's') which will
310 # definitely give you a module. Yeah, it's somewhat confusing:-(.
308 # definitely give you a module. Yeah, it's somewhat confusing:-(.
311
309
312 if user_ns is None:
310 if user_ns is None:
313 # Set __name__ to __main__ to better match the behavior of the
311 # Set __name__ to __main__ to better match the behavior of the
314 # normal interpreter.
312 # normal interpreter.
315 user_ns = {'__name__' :'__main__',
313 user_ns = {'__name__' :'__main__',
316 '__builtins__' : __builtin__,
314 '__builtins__' : __builtin__,
317 }
315 }
318
316
319 if user_global_ns is None:
317 if user_global_ns is None:
320 user_global_ns = {}
318 user_global_ns = {}
321
319
322 # Assign namespaces
320 # Assign namespaces
323 # This is the namespace where all normal user variables live
321 # This is the namespace where all normal user variables live
324 self.user_ns = user_ns
322 self.user_ns = user_ns
325 # Embedded instances require a separate namespace for globals.
323 # Embedded instances require a separate namespace for globals.
326 # Normally this one is unused by non-embedded instances.
324 # Normally this one is unused by non-embedded instances.
327 self.user_global_ns = user_global_ns
325 self.user_global_ns = user_global_ns
328 # A namespace to keep track of internal data structures to prevent
326 # A namespace to keep track of internal data structures to prevent
329 # them from cluttering user-visible stuff. Will be updated later
327 # them from cluttering user-visible stuff. Will be updated later
330 self.internal_ns = {}
328 self.internal_ns = {}
331
329
332 # Namespace of system aliases. Each entry in the alias
330 # Namespace of system aliases. Each entry in the alias
333 # table must be a 2-tuple of the form (N,name), where N is the number
331 # table must be a 2-tuple of the form (N,name), where N is the number
334 # of positional arguments of the alias.
332 # of positional arguments of the alias.
335 self.alias_table = {}
333 self.alias_table = {}
336
334
337 # A table holding all the namespaces IPython deals with, so that
335 # A table holding all the namespaces IPython deals with, so that
338 # introspection facilities can search easily.
336 # introspection facilities can search easily.
339 self.ns_table = {'user':user_ns,
337 self.ns_table = {'user':user_ns,
340 'user_global':user_global_ns,
338 'user_global':user_global_ns,
341 'alias':self.alias_table,
339 'alias':self.alias_table,
342 'internal':self.internal_ns,
340 'internal':self.internal_ns,
343 'builtin':__builtin__.__dict__
341 'builtin':__builtin__.__dict__
344 }
342 }
345
343
346 # The user namespace MUST have a pointer to the shell itself.
344 # The user namespace MUST have a pointer to the shell itself.
347 self.user_ns[name] = self
345 self.user_ns[name] = self
348
346
349 # We need to insert into sys.modules something that looks like a
347 # We need to insert into sys.modules something that looks like a
350 # module but which accesses the IPython namespace, for shelve and
348 # module but which accesses the IPython namespace, for shelve and
351 # pickle to work interactively. Normally they rely on getting
349 # pickle to work interactively. Normally they rely on getting
352 # everything out of __main__, but for embedding purposes each IPython
350 # everything out of __main__, but for embedding purposes each IPython
353 # instance has its own private namespace, so we can't go shoving
351 # instance has its own private namespace, so we can't go shoving
354 # everything into __main__.
352 # everything into __main__.
355
353
356 # note, however, that we should only do this for non-embedded
354 # note, however, that we should only do this for non-embedded
357 # ipythons, which really mimic the __main__.__dict__ with their own
355 # ipythons, which really mimic the __main__.__dict__ with their own
358 # namespace. Embedded instances, on the other hand, should not do
356 # namespace. Embedded instances, on the other hand, should not do
359 # this because they need to manage the user local/global namespaces
357 # this because they need to manage the user local/global namespaces
360 # only, but they live within a 'normal' __main__ (meaning, they
358 # only, but they live within a 'normal' __main__ (meaning, they
361 # shouldn't overtake the execution environment of the script they're
359 # shouldn't overtake the execution environment of the script they're
362 # embedded in).
360 # embedded in).
363
361
364 if not embedded:
362 if not embedded:
365 try:
363 try:
366 main_name = self.user_ns['__name__']
364 main_name = self.user_ns['__name__']
367 except KeyError:
365 except KeyError:
368 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
366 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
369 else:
367 else:
370 #print "pickle hack in place" # dbg
368 #print "pickle hack in place" # dbg
371 sys.modules[main_name] = FakeModule(self.user_ns)
369 sys.modules[main_name] = FakeModule(self.user_ns)
372
370
373 # List of input with multi-line handling.
371 # List of input with multi-line handling.
374 # Fill its zero entry, user counter starts at 1
372 # Fill its zero entry, user counter starts at 1
375 self.input_hist = InputList(['\n'])
373 self.input_hist = InputList(['\n'])
376
374
377 # list of visited directories
375 # list of visited directories
378 try:
376 try:
379 self.dir_hist = [os.getcwd()]
377 self.dir_hist = [os.getcwd()]
380 except IOError, e:
378 except IOError, e:
381 self.dir_hist = []
379 self.dir_hist = []
382
380
383 # dict of output history
381 # dict of output history
384 self.output_hist = {}
382 self.output_hist = {}
385
383
386 # dict of things NOT to alias (keywords, builtins and some magics)
384 # dict of things NOT to alias (keywords, builtins and some magics)
387 no_alias = {}
385 no_alias = {}
388 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
386 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
389 for key in keyword.kwlist + no_alias_magics:
387 for key in keyword.kwlist + no_alias_magics:
390 no_alias[key] = 1
388 no_alias[key] = 1
391 no_alias.update(__builtin__.__dict__)
389 no_alias.update(__builtin__.__dict__)
392 self.no_alias = no_alias
390 self.no_alias = no_alias
393
391
394 # make global variables for user access to these
392 # make global variables for user access to these
395 self.user_ns['_ih'] = self.input_hist
393 self.user_ns['_ih'] = self.input_hist
396 self.user_ns['_oh'] = self.output_hist
394 self.user_ns['_oh'] = self.output_hist
397 self.user_ns['_dh'] = self.dir_hist
395 self.user_ns['_dh'] = self.dir_hist
398
396
399 # user aliases to input and output histories
397 # user aliases to input and output histories
400 self.user_ns['In'] = self.input_hist
398 self.user_ns['In'] = self.input_hist
401 self.user_ns['Out'] = self.output_hist
399 self.user_ns['Out'] = self.output_hist
402
400
403 # Store the actual shell's name
401 # Store the actual shell's name
404 self.name = name
402 self.name = name
405
403
406 # Object variable to store code object waiting execution. This is
404 # Object variable to store code object waiting execution. This is
407 # used mainly by the multithreaded shells, but it can come in handy in
405 # used mainly by the multithreaded shells, but it can come in handy in
408 # other situations. No need to use a Queue here, since it's a single
406 # other situations. No need to use a Queue here, since it's a single
409 # item which gets cleared once run.
407 # item which gets cleared once run.
410 self.code_to_run = None
408 self.code_to_run = None
411
409
412 # Job manager (for jobs run as background threads)
410 # Job manager (for jobs run as background threads)
413 self.jobs = BackgroundJobManager()
411 self.jobs = BackgroundJobManager()
414 # Put the job manager into builtins so it's always there.
412 # Put the job manager into builtins so it's always there.
415 __builtin__.jobs = self.jobs
413 __builtin__.jobs = self.jobs
416
414
417 # escapes for automatic behavior on the command line
415 # escapes for automatic behavior on the command line
418 self.ESC_SHELL = '!'
416 self.ESC_SHELL = '!'
419 self.ESC_HELP = '?'
417 self.ESC_HELP = '?'
420 self.ESC_MAGIC = '%'
418 self.ESC_MAGIC = '%'
421 self.ESC_QUOTE = ','
419 self.ESC_QUOTE = ','
422 self.ESC_QUOTE2 = ';'
420 self.ESC_QUOTE2 = ';'
423 self.ESC_PAREN = '/'
421 self.ESC_PAREN = '/'
424
422
425 # And their associated handlers
423 # And their associated handlers
426 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
424 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
427 self.ESC_QUOTE:self.handle_auto,
425 self.ESC_QUOTE:self.handle_auto,
428 self.ESC_QUOTE2:self.handle_auto,
426 self.ESC_QUOTE2:self.handle_auto,
429 self.ESC_MAGIC:self.handle_magic,
427 self.ESC_MAGIC:self.handle_magic,
430 self.ESC_HELP:self.handle_help,
428 self.ESC_HELP:self.handle_help,
431 self.ESC_SHELL:self.handle_shell_escape,
429 self.ESC_SHELL:self.handle_shell_escape,
432 }
430 }
433
431
434 # class initializations
432 # class initializations
435 Logger.__init__(self,log_ns = self.user_ns)
433 Logger.__init__(self,log_ns = self.user_ns)
436 Magic.__init__(self,self)
434 Magic.__init__(self,self)
437
435
438 # an ugly hack to get a pointer to the shell, so I can start writing
436 # an ugly hack to get a pointer to the shell, so I can start writing
439 # magic code via this pointer instead of the current mixin salad.
437 # magic code via this pointer instead of the current mixin salad.
440 Magic.set_shell(self,self)
438 Magic.set_shell(self,self)
441
439
442 # Python source parser/formatter for syntax highlighting
440 # Python source parser/formatter for syntax highlighting
443 pyformat = PyColorize.Parser().format
441 pyformat = PyColorize.Parser().format
444 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
442 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
445
443
446 # hooks holds pointers used for user-side customizations
444 # hooks holds pointers used for user-side customizations
447 self.hooks = Struct()
445 self.hooks = Struct()
448
446
449 # Set all default hooks, defined in the IPython.hooks module.
447 # Set all default hooks, defined in the IPython.hooks module.
450 hooks = IPython.hooks
448 hooks = IPython.hooks
451 for hook_name in hooks.__all__:
449 for hook_name in hooks.__all__:
452 self.set_hook(hook_name,getattr(hooks,hook_name))
450 self.set_hook(hook_name,getattr(hooks,hook_name))
453
451
454 # Flag to mark unconditional exit
452 # Flag to mark unconditional exit
455 self.exit_now = False
453 self.exit_now = False
456
454
457 self.usage_min = """\
455 self.usage_min = """\
458 An enhanced console for Python.
456 An enhanced console for Python.
459 Some of its features are:
457 Some of its features are:
460 - Readline support if the readline library is present.
458 - Readline support if the readline library is present.
461 - Tab completion in the local namespace.
459 - Tab completion in the local namespace.
462 - Logging of input, see command-line options.
460 - Logging of input, see command-line options.
463 - System shell escape via ! , eg !ls.
461 - System shell escape via ! , eg !ls.
464 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
462 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
465 - Keeps track of locally defined variables via %who, %whos.
463 - Keeps track of locally defined variables via %who, %whos.
466 - Show object information with a ? eg ?x or x? (use ?? for more info).
464 - Show object information with a ? eg ?x or x? (use ?? for more info).
467 """
465 """
468 if usage: self.usage = usage
466 if usage: self.usage = usage
469 else: self.usage = self.usage_min
467 else: self.usage = self.usage_min
470
468
471 # Storage
469 # Storage
472 self.rc = rc # This will hold all configuration information
470 self.rc = rc # This will hold all configuration information
473 self.inputcache = []
471 self.inputcache = []
474 self._boundcache = []
472 self._boundcache = []
475 self.pager = 'less'
473 self.pager = 'less'
476 # temporary files used for various purposes. Deleted at exit.
474 # temporary files used for various purposes. Deleted at exit.
477 self.tempfiles = []
475 self.tempfiles = []
478
476
479 # Keep track of readline usage (later set by init_readline)
477 # Keep track of readline usage (later set by init_readline)
480 self.has_readline = False
478 self.has_readline = False
481
479
482 # for pushd/popd management
480 # for pushd/popd management
483 try:
481 try:
484 self.home_dir = get_home_dir()
482 self.home_dir = get_home_dir()
485 except HomeDirError,msg:
483 except HomeDirError,msg:
486 fatal(msg)
484 fatal(msg)
487
485
488 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
486 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
489
487
490 # Functions to call the underlying shell.
488 # Functions to call the underlying shell.
491
489
492 # utility to expand user variables via Itpl
490 # utility to expand user variables via Itpl
493 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
491 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
494 self.user_ns))
492 self.user_ns))
495 # The first is similar to os.system, but it doesn't return a value,
493 # The first is similar to os.system, but it doesn't return a value,
496 # and it allows interpolation of variables in the user's namespace.
494 # and it allows interpolation of variables in the user's namespace.
497 self.system = lambda cmd: shell(self.var_expand(cmd),
495 self.system = lambda cmd: shell(self.var_expand(cmd),
498 header='IPython system call: ',
496 header='IPython system call: ',
499 verbose=self.rc.system_verbose)
497 verbose=self.rc.system_verbose)
500 # These are for getoutput and getoutputerror:
498 # These are for getoutput and getoutputerror:
501 self.getoutput = lambda cmd: \
499 self.getoutput = lambda cmd: \
502 getoutput(self.var_expand(cmd),
500 getoutput(self.var_expand(cmd),
503 header='IPython system call: ',
501 header='IPython system call: ',
504 verbose=self.rc.system_verbose)
502 verbose=self.rc.system_verbose)
505 self.getoutputerror = lambda cmd: \
503 self.getoutputerror = lambda cmd: \
506 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
504 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
507 self.user_ns)),
505 self.user_ns)),
508 header='IPython system call: ',
506 header='IPython system call: ',
509 verbose=self.rc.system_verbose)
507 verbose=self.rc.system_verbose)
510
508
511 # RegExp for splitting line contents into pre-char//first
509 # RegExp for splitting line contents into pre-char//first
512 # word-method//rest. For clarity, each group in on one line.
510 # word-method//rest. For clarity, each group in on one line.
513
511
514 # WARNING: update the regexp if the above escapes are changed, as they
512 # WARNING: update the regexp if the above escapes are changed, as they
515 # are hardwired in.
513 # are hardwired in.
516
514
517 # Don't get carried away with trying to make the autocalling catch too
515 # Don't get carried away with trying to make the autocalling catch too
518 # much: it's better to be conservative rather than to trigger hidden
516 # much: it's better to be conservative rather than to trigger hidden
519 # evals() somewhere and end up causing side effects.
517 # evals() somewhere and end up causing side effects.
520
518
521 self.line_split = re.compile(r'^([\s*,;/])'
519 self.line_split = re.compile(r'^([\s*,;/])'
522 r'([\?\w\.]+\w*\s*)'
520 r'([\?\w\.]+\w*\s*)'
523 r'(\(?.*$)')
521 r'(\(?.*$)')
524
522
525 # Original re, keep around for a while in case changes break something
523 # Original re, keep around for a while in case changes break something
526 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
524 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
527 # r'(\s*[\?\w\.]+\w*\s*)'
525 # r'(\s*[\?\w\.]+\w*\s*)'
528 # r'(\(?.*$)')
526 # r'(\(?.*$)')
529
527
530 # RegExp to identify potential function names
528 # RegExp to identify potential function names
531 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
529 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
532 # RegExp to exclude strings with this start from autocalling
530 # RegExp to exclude strings with this start from autocalling
533 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
531 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
534
532
535 # try to catch also methods for stuff in lists/tuples/dicts: off
533 # try to catch also methods for stuff in lists/tuples/dicts: off
536 # (experimental). For this to work, the line_split regexp would need
534 # (experimental). For this to work, the line_split regexp would need
537 # to be modified so it wouldn't break things at '['. That line is
535 # to be modified so it wouldn't break things at '['. That line is
538 # nasty enough that I shouldn't change it until I can test it _well_.
536 # nasty enough that I shouldn't change it until I can test it _well_.
539 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
537 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
540
538
541 # keep track of where we started running (mainly for crash post-mortem)
539 # keep track of where we started running (mainly for crash post-mortem)
542 self.starting_dir = os.getcwd()
540 self.starting_dir = os.getcwd()
543
541
544 # Attributes for Logger mixin class, make defaults here
542 # Attributes for Logger mixin class, make defaults here
545 self._dolog = False
543 self._dolog = False
546 self.LOG = ''
544 self.LOG = ''
547 self.LOGDEF = '.InteractiveShell.log'
545 self.LOGDEF = '.InteractiveShell.log'
548 self.LOGMODE = 'over'
546 self.LOGMODE = 'over'
549 self.LOGHEAD = Itpl(
547 self.LOGHEAD = Itpl(
550 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
548 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
551 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
549 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
552 #log# opts = $self.rc.opts
550 #log# opts = $self.rc.opts
553 #log# args = $self.rc.args
551 #log# args = $self.rc.args
554 #log# It is safe to make manual edits below here.
552 #log# It is safe to make manual edits below here.
555 #log#-----------------------------------------------------------------------
553 #log#-----------------------------------------------------------------------
556 """)
554 """)
557 # Various switches which can be set
555 # Various switches which can be set
558 self.CACHELENGTH = 5000 # this is cheap, it's just text
556 self.CACHELENGTH = 5000 # this is cheap, it's just text
559 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
557 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
560 self.banner2 = banner2
558 self.banner2 = banner2
561
559
562 # TraceBack handlers:
560 # TraceBack handlers:
563 # Need two, one for syntax errors and one for other exceptions.
561 # Need two, one for syntax errors and one for other exceptions.
564 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
562 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
565 # The interactive one is initialized with an offset, meaning we always
563 # 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
564 # want to remove the topmost item in the traceback, which is our own
567 # internal code. Valid modes: ['Plain','Context','Verbose']
565 # internal code. Valid modes: ['Plain','Context','Verbose']
568 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
566 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
569 color_scheme='NoColor',
567 color_scheme='NoColor',
570 tb_offset = 1)
568 tb_offset = 1)
571 # and add any custom exception handlers the user may have specified
569 # and add any custom exception handlers the user may have specified
572 self.set_custom_exc(*custom_exceptions)
570 self.set_custom_exc(*custom_exceptions)
573
571
574 # Object inspector
572 # Object inspector
575 self.inspector = OInspect.Inspector(OInspect.InspectColors,
573 self.inspector = OInspect.Inspector(OInspect.InspectColors,
576 PyColorize.ANSICodeColors,
574 PyColorize.ANSICodeColors,
577 'NoColor')
575 'NoColor')
578 # indentation management
576 # indentation management
579 self.autoindent = False
577 self.autoindent = False
580 self.indent_current_nsp = 0
578 self.indent_current_nsp = 0
581 self.indent_current = '' # actual indent string
579 self.indent_current = '' # actual indent string
582
580
583 # Make some aliases automatically
581 # Make some aliases automatically
584 # Prepare list of shell aliases to auto-define
582 # Prepare list of shell aliases to auto-define
585 if os.name == 'posix':
583 if os.name == 'posix':
586 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
584 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
587 'mv mv -i','rm rm -i','cp cp -i',
585 'mv mv -i','rm rm -i','cp cp -i',
588 'cat cat','less less','clear clear',
586 'cat cat','less less','clear clear',
589 # a better ls
587 # a better ls
590 'ls ls -F',
588 'ls ls -F',
591 # long ls
589 # long ls
592 'll ls -lF',
590 'll ls -lF',
593 # color ls
591 # color ls
594 'lc ls -F -o --color',
592 'lc ls -F -o --color',
595 # ls normal files only
593 # ls normal files only
596 'lf ls -F -o --color %l | grep ^-',
594 'lf ls -F -o --color %l | grep ^-',
597 # ls symbolic links
595 # ls symbolic links
598 'lk ls -F -o --color %l | grep ^l',
596 'lk ls -F -o --color %l | grep ^l',
599 # directories or links to directories,
597 # directories or links to directories,
600 'ldir ls -F -o --color %l | grep /$',
598 'ldir ls -F -o --color %l | grep /$',
601 # things which are executable
599 # things which are executable
602 'lx ls -F -o --color %l | grep ^-..x',
600 'lx ls -F -o --color %l | grep ^-..x',
603 )
601 )
604 elif os.name in ['nt','dos']:
602 elif os.name in ['nt','dos']:
605 auto_alias = ('dir dir /on', 'ls dir /on',
603 auto_alias = ('dir dir /on', 'ls dir /on',
606 'ddir dir /ad /on', 'ldir dir /ad /on',
604 'ddir dir /ad /on', 'ldir dir /ad /on',
607 'mkdir mkdir','rmdir rmdir','echo echo',
605 'mkdir mkdir','rmdir rmdir','echo echo',
608 'ren ren','cls cls','copy copy')
606 'ren ren','cls cls','copy copy')
609 else:
607 else:
610 auto_alias = ()
608 auto_alias = ()
611 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
609 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
612 # Call the actual (public) initializer
610 # Call the actual (public) initializer
613 self.init_auto_alias()
611 self.init_auto_alias()
614 # end __init__
612 # end __init__
615
613
616 def set_hook(self,name,hook):
614 def set_hook(self,name,hook):
617 """set_hook(name,hook) -> sets an internal IPython hook.
615 """set_hook(name,hook) -> sets an internal IPython hook.
618
616
619 IPython exposes some of its internal API as user-modifiable hooks. By
617 IPython exposes some of its internal API as user-modifiable hooks. By
620 resetting one of these hooks, you can modify IPython's behavior to
618 resetting one of these hooks, you can modify IPython's behavior to
621 call at runtime your own routines."""
619 call at runtime your own routines."""
622
620
623 # At some point in the future, this should validate the hook before it
621 # At some point in the future, this should validate the hook before it
624 # accepts it. Probably at least check that the hook takes the number
622 # accepts it. Probably at least check that the hook takes the number
625 # of args it's supposed to.
623 # of args it's supposed to.
626 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
624 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
627
625
628 def set_custom_exc(self,exc_tuple,handler):
626 def set_custom_exc(self,exc_tuple,handler):
629 """set_custom_exc(exc_tuple,handler)
627 """set_custom_exc(exc_tuple,handler)
630
628
631 Set a custom exception handler, which will be called if any of the
629 Set a custom exception handler, which will be called if any of the
632 exceptions in exc_tuple occur in the mainloop (specifically, in the
630 exceptions in exc_tuple occur in the mainloop (specifically, in the
633 runcode() method.
631 runcode() method.
634
632
635 Inputs:
633 Inputs:
636
634
637 - exc_tuple: a *tuple* of valid exceptions to call the defined
635 - exc_tuple: a *tuple* of valid exceptions to call the defined
638 handler for. It is very important that you use a tuple, and NOT A
636 handler for. It is very important that you use a tuple, and NOT A
639 LIST here, because of the way Python's except statement works. If
637 LIST here, because of the way Python's except statement works. If
640 you only want to trap a single exception, use a singleton tuple:
638 you only want to trap a single exception, use a singleton tuple:
641
639
642 exc_tuple == (MyCustomException,)
640 exc_tuple == (MyCustomException,)
643
641
644 - handler: this must be defined as a function with the following
642 - handler: this must be defined as a function with the following
645 basic interface: def my_handler(self,etype,value,tb).
643 basic interface: def my_handler(self,etype,value,tb).
646
644
647 This will be made into an instance method (via new.instancemethod)
645 This will be made into an instance method (via new.instancemethod)
648 of IPython itself, and it will be called if any of the exceptions
646 of IPython itself, and it will be called if any of the exceptions
649 listed in the exc_tuple are caught. If the handler is None, an
647 listed in the exc_tuple are caught. If the handler is None, an
650 internal basic one is used, which just prints basic info.
648 internal basic one is used, which just prints basic info.
651
649
652 WARNING: by putting in your own exception handler into IPython's main
650 WARNING: by putting in your own exception handler into IPython's main
653 execution loop, you run a very good chance of nasty crashes. This
651 execution loop, you run a very good chance of nasty crashes. This
654 facility should only be used if you really know what you are doing."""
652 facility should only be used if you really know what you are doing."""
655
653
656 assert type(exc_tuple)==type(()) , \
654 assert type(exc_tuple)==type(()) , \
657 "The custom exceptions must be given AS A TUPLE."
655 "The custom exceptions must be given AS A TUPLE."
658
656
659 def dummy_handler(self,etype,value,tb):
657 def dummy_handler(self,etype,value,tb):
660 print '*** Simple custom exception handler ***'
658 print '*** Simple custom exception handler ***'
661 print 'Exception type :',etype
659 print 'Exception type :',etype
662 print 'Exception value:',value
660 print 'Exception value:',value
663 print 'Traceback :',tb
661 print 'Traceback :',tb
664 print 'Source code :','\n'.join(self.buffer)
662 print 'Source code :','\n'.join(self.buffer)
665
663
666 if handler is None: handler = dummy_handler
664 if handler is None: handler = dummy_handler
667
665
668 self.CustomTB = new.instancemethod(handler,self,self.__class__)
666 self.CustomTB = new.instancemethod(handler,self,self.__class__)
669 self.custom_exceptions = exc_tuple
667 self.custom_exceptions = exc_tuple
670
668
671 def set_custom_completer(self,completer,pos=0):
669 def set_custom_completer(self,completer,pos=0):
672 """set_custom_completer(completer,pos=0)
670 """set_custom_completer(completer,pos=0)
673
671
674 Adds a new custom completer function.
672 Adds a new custom completer function.
675
673
676 The position argument (defaults to 0) is the index in the completers
674 The position argument (defaults to 0) is the index in the completers
677 list where you want the completer to be inserted."""
675 list where you want the completer to be inserted."""
678
676
679 newcomp = new.instancemethod(completer,self.Completer,
677 newcomp = new.instancemethod(completer,self.Completer,
680 self.Completer.__class__)
678 self.Completer.__class__)
681 self.Completer.matchers.insert(pos,newcomp)
679 self.Completer.matchers.insert(pos,newcomp)
682
680
683 def complete(self,text):
681 def complete(self,text):
684 """Return a sorted list of all possible completions on text.
682 """Return a sorted list of all possible completions on text.
685
683
686 Inputs:
684 Inputs:
687
685
688 - text: a string of text to be completed on.
686 - text: a string of text to be completed on.
689
687
690 This is a wrapper around the completion mechanism, similar to what
688 This is a wrapper around the completion mechanism, similar to what
691 readline does at the command line when the TAB key is hit. By
689 readline does at the command line when the TAB key is hit. By
692 exposing it as a method, it can be used by other non-readline
690 exposing it as a method, it can be used by other non-readline
693 environments (such as GUIs) for text completion.
691 environments (such as GUIs) for text completion.
694
692
695 Simple usage example:
693 Simple usage example:
696
694
697 In [1]: x = 'hello'
695 In [1]: x = 'hello'
698
696
699 In [2]: __IP.complete('x.l')
697 In [2]: __IP.complete('x.l')
700 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
698 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
701
699
702 complete = self.Completer.complete
700 complete = self.Completer.complete
703 state = 0
701 state = 0
704 # use a dict so we get unique keys, since ipyhton's multiple
702 # use a dict so we get unique keys, since ipyhton's multiple
705 # completers can return duplicates.
703 # completers can return duplicates.
706 comps = {}
704 comps = {}
707 while True:
705 while True:
708 newcomp = complete(text,state)
706 newcomp = complete(text,state)
709 if newcomp is None:
707 if newcomp is None:
710 break
708 break
711 comps[newcomp] = 1
709 comps[newcomp] = 1
712 state += 1
710 state += 1
713 outcomps = comps.keys()
711 outcomps = comps.keys()
714 outcomps.sort()
712 outcomps.sort()
715 return outcomps
713 return outcomps
716
714
717 def set_completer_frame(self, frame):
715 def set_completer_frame(self, frame):
718 if frame:
716 if frame:
719 self.Completer.namespace = frame.f_locals
717 self.Completer.namespace = frame.f_locals
720 self.Completer.global_namespace = frame.f_globals
718 self.Completer.global_namespace = frame.f_globals
721 else:
719 else:
722 self.Completer.namespace = self.user_ns
720 self.Completer.namespace = self.user_ns
723 self.Completer.global_namespace = self.user_global_ns
721 self.Completer.global_namespace = self.user_global_ns
724
722
725 def post_config_initialization(self):
723 def post_config_initialization(self):
726 """Post configuration init method
724 """Post configuration init method
727
725
728 This is called after the configuration files have been processed to
726 This is called after the configuration files have been processed to
729 'finalize' the initialization."""
727 'finalize' the initialization."""
730
728
731 rc = self.rc
729 rc = self.rc
732
730
733 # Load readline proper
731 # Load readline proper
734 if rc.readline:
732 if rc.readline:
735 self.init_readline()
733 self.init_readline()
736
734
737 # Set user colors (don't do it in the constructor above so that it
735 # Set user colors (don't do it in the constructor above so that it
738 # doesn't crash if colors option is invalid)
736 # doesn't crash if colors option is invalid)
739 self.magic_colors(rc.colors)
737 self.magic_colors(rc.colors)
740
738
741 # Load user aliases
739 # Load user aliases
742 for alias in rc.alias:
740 for alias in rc.alias:
743 self.magic_alias(alias)
741 self.magic_alias(alias)
744
742
745 # dynamic data that survives through sessions
743 # dynamic data that survives through sessions
746 # XXX make the filename a config option?
744 # XXX make the filename a config option?
747 persist_base = 'persist'
745 persist_base = 'persist'
748 if rc.profile:
746 if rc.profile:
749 persist_base += '_%s' % rc.profile
747 persist_base += '_%s' % rc.profile
750 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
748 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
751
749
752 try:
750 try:
753 self.persist = pickle.load(file(self.persist_fname))
751 self.persist = pickle.load(file(self.persist_fname))
754 except:
752 except:
755 self.persist = {}
753 self.persist = {}
756
754
757 def init_auto_alias(self):
755 def init_auto_alias(self):
758 """Define some aliases automatically.
756 """Define some aliases automatically.
759
757
760 These are ALL parameter-less aliases"""
758 These are ALL parameter-less aliases"""
761 for alias,cmd in self.auto_alias:
759 for alias,cmd in self.auto_alias:
762 self.alias_table[alias] = (0,cmd)
760 self.alias_table[alias] = (0,cmd)
763
761
764 def alias_table_validate(self,verbose=0):
762 def alias_table_validate(self,verbose=0):
765 """Update information about the alias table.
763 """Update information about the alias table.
766
764
767 In particular, make sure no Python keywords/builtins are in it."""
765 In particular, make sure no Python keywords/builtins are in it."""
768
766
769 no_alias = self.no_alias
767 no_alias = self.no_alias
770 for k in self.alias_table.keys():
768 for k in self.alias_table.keys():
771 if k in no_alias:
769 if k in no_alias:
772 del self.alias_table[k]
770 del self.alias_table[k]
773 if verbose:
771 if verbose:
774 print ("Deleting alias <%s>, it's a Python "
772 print ("Deleting alias <%s>, it's a Python "
775 "keyword or builtin." % k)
773 "keyword or builtin." % k)
776
774
777 def set_autoindent(self,value=None):
775 def set_autoindent(self,value=None):
778 """Set the autoindent flag, checking for readline support.
776 """Set the autoindent flag, checking for readline support.
779
777
780 If called with no arguments, it acts as a toggle."""
778 If called with no arguments, it acts as a toggle."""
781
779
782 if not self.has_readline:
780 if not self.has_readline:
783 if os.name == 'posix':
781 if os.name == 'posix':
784 warn("The auto-indent feature requires the readline library")
782 warn("The auto-indent feature requires the readline library")
785 self.autoindent = 0
783 self.autoindent = 0
786 return
784 return
787 if value is None:
785 if value is None:
788 self.autoindent = not self.autoindent
786 self.autoindent = not self.autoindent
789 else:
787 else:
790 self.autoindent = value
788 self.autoindent = value
791
789
792 def rc_set_toggle(self,rc_field,value=None):
790 def rc_set_toggle(self,rc_field,value=None):
793 """Set or toggle a field in IPython's rc config. structure.
791 """Set or toggle a field in IPython's rc config. structure.
794
792
795 If called with no arguments, it acts as a toggle.
793 If called with no arguments, it acts as a toggle.
796
794
797 If called with a non-existent field, the resulting AttributeError
795 If called with a non-existent field, the resulting AttributeError
798 exception will propagate out."""
796 exception will propagate out."""
799
797
800 rc_val = getattr(self.rc,rc_field)
798 rc_val = getattr(self.rc,rc_field)
801 if value is None:
799 if value is None:
802 value = not rc_val
800 value = not rc_val
803 setattr(self.rc,rc_field,value)
801 setattr(self.rc,rc_field,value)
804
802
805 def user_setup(self,ipythondir,rc_suffix,mode='install'):
803 def user_setup(self,ipythondir,rc_suffix,mode='install'):
806 """Install the user configuration directory.
804 """Install the user configuration directory.
807
805
808 Can be called when running for the first time or to upgrade the user's
806 Can be called when running for the first time or to upgrade the user's
809 .ipython/ directory with the mode parameter. Valid modes are 'install'
807 .ipython/ directory with the mode parameter. Valid modes are 'install'
810 and 'upgrade'."""
808 and 'upgrade'."""
811
809
812 def wait():
810 def wait():
813 try:
811 try:
814 raw_input("Please press <RETURN> to start IPython.")
812 raw_input("Please press <RETURN> to start IPython.")
815 except EOFError:
813 except EOFError:
816 print >> Term.cout
814 print >> Term.cout
817 print '*'*70
815 print '*'*70
818
816
819 cwd = os.getcwd() # remember where we started
817 cwd = os.getcwd() # remember where we started
820 glb = glob.glob
818 glb = glob.glob
821 print '*'*70
819 print '*'*70
822 if mode == 'install':
820 if mode == 'install':
823 print \
821 print \
824 """Welcome to IPython. I will try to create a personal configuration directory
822 """Welcome to IPython. I will try to create a personal configuration directory
825 where you can customize many aspects of IPython's functionality in:\n"""
823 where you can customize many aspects of IPython's functionality in:\n"""
826 else:
824 else:
827 print 'I am going to upgrade your configuration in:'
825 print 'I am going to upgrade your configuration in:'
828
826
829 print ipythondir
827 print ipythondir
830
828
831 rcdirend = os.path.join('IPython','UserConfig')
829 rcdirend = os.path.join('IPython','UserConfig')
832 cfg = lambda d: os.path.join(d,rcdirend)
830 cfg = lambda d: os.path.join(d,rcdirend)
833 try:
831 try:
834 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
832 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
835 except IOError:
833 except IOError:
836 warning = """
834 warning = """
837 Installation error. IPython's directory was not found.
835 Installation error. IPython's directory was not found.
838
836
839 Check the following:
837 Check the following:
840
838
841 The ipython/IPython directory should be in a directory belonging to your
839 The ipython/IPython directory should be in a directory belonging to your
842 PYTHONPATH environment variable (that is, it should be in a directory
840 PYTHONPATH environment variable (that is, it should be in a directory
843 belonging to sys.path). You can copy it explicitly there or just link to it.
841 belonging to sys.path). You can copy it explicitly there or just link to it.
844
842
845 IPython will proceed with builtin defaults.
843 IPython will proceed with builtin defaults.
846 """
844 """
847 warn(warning)
845 warn(warning)
848 wait()
846 wait()
849 return
847 return
850
848
851 if mode == 'install':
849 if mode == 'install':
852 try:
850 try:
853 shutil.copytree(rcdir,ipythondir)
851 shutil.copytree(rcdir,ipythondir)
854 os.chdir(ipythondir)
852 os.chdir(ipythondir)
855 rc_files = glb("ipythonrc*")
853 rc_files = glb("ipythonrc*")
856 for rc_file in rc_files:
854 for rc_file in rc_files:
857 os.rename(rc_file,rc_file+rc_suffix)
855 os.rename(rc_file,rc_file+rc_suffix)
858 except:
856 except:
859 warning = """
857 warning = """
860
858
861 There was a problem with the installation:
859 There was a problem with the installation:
862 %s
860 %s
863 Try to correct it or contact the developers if you think it's a bug.
861 Try to correct it or contact the developers if you think it's a bug.
864 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
862 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
865 warn(warning)
863 warn(warning)
866 wait()
864 wait()
867 return
865 return
868
866
869 elif mode == 'upgrade':
867 elif mode == 'upgrade':
870 try:
868 try:
871 os.chdir(ipythondir)
869 os.chdir(ipythondir)
872 except:
870 except:
873 print """
871 print """
874 Can not upgrade: changing to directory %s failed. Details:
872 Can not upgrade: changing to directory %s failed. Details:
875 %s
873 %s
876 """ % (ipythondir,sys.exc_info()[1])
874 """ % (ipythondir,sys.exc_info()[1])
877 wait()
875 wait()
878 return
876 return
879 else:
877 else:
880 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
878 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
881 for new_full_path in sources:
879 for new_full_path in sources:
882 new_filename = os.path.basename(new_full_path)
880 new_filename = os.path.basename(new_full_path)
883 if new_filename.startswith('ipythonrc'):
881 if new_filename.startswith('ipythonrc'):
884 new_filename = new_filename + rc_suffix
882 new_filename = new_filename + rc_suffix
885 # The config directory should only contain files, skip any
883 # The config directory should only contain files, skip any
886 # directories which may be there (like CVS)
884 # directories which may be there (like CVS)
887 if os.path.isdir(new_full_path):
885 if os.path.isdir(new_full_path):
888 continue
886 continue
889 if os.path.exists(new_filename):
887 if os.path.exists(new_filename):
890 old_file = new_filename+'.old'
888 old_file = new_filename+'.old'
891 if os.path.exists(old_file):
889 if os.path.exists(old_file):
892 os.remove(old_file)
890 os.remove(old_file)
893 os.rename(new_filename,old_file)
891 os.rename(new_filename,old_file)
894 shutil.copy(new_full_path,new_filename)
892 shutil.copy(new_full_path,new_filename)
895 else:
893 else:
896 raise ValueError,'unrecognized mode for install:',`mode`
894 raise ValueError,'unrecognized mode for install:',`mode`
897
895
898 # Fix line-endings to those native to each platform in the config
896 # Fix line-endings to those native to each platform in the config
899 # directory.
897 # directory.
900 try:
898 try:
901 os.chdir(ipythondir)
899 os.chdir(ipythondir)
902 except:
900 except:
903 print """
901 print """
904 Problem: changing to directory %s failed.
902 Problem: changing to directory %s failed.
905 Details:
903 Details:
906 %s
904 %s
907
905
908 Some configuration files may have incorrect line endings. This should not
906 Some configuration files may have incorrect line endings. This should not
909 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
907 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
910 wait()
908 wait()
911 else:
909 else:
912 for fname in glb('ipythonrc*'):
910 for fname in glb('ipythonrc*'):
913 try:
911 try:
914 native_line_ends(fname,backup=0)
912 native_line_ends(fname,backup=0)
915 except IOError:
913 except IOError:
916 pass
914 pass
917
915
918 if mode == 'install':
916 if mode == 'install':
919 print """
917 print """
920 Successful installation!
918 Successful installation!
921
919
922 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
920 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
923 IPython manual (there are both HTML and PDF versions supplied with the
921 IPython manual (there are both HTML and PDF versions supplied with the
924 distribution) to make sure that your system environment is properly configured
922 distribution) to make sure that your system environment is properly configured
925 to take advantage of IPython's features."""
923 to take advantage of IPython's features."""
926 else:
924 else:
927 print """
925 print """
928 Successful upgrade!
926 Successful upgrade!
929
927
930 All files in your directory:
928 All files in your directory:
931 %(ipythondir)s
929 %(ipythondir)s
932 which would have been overwritten by the upgrade were backed up with a .old
930 which would have been overwritten by the upgrade were backed up with a .old
933 extension. If you had made particular customizations in those files you may
931 extension. If you had made particular customizations in those files you may
934 want to merge them back into the new files.""" % locals()
932 want to merge them back into the new files.""" % locals()
935 wait()
933 wait()
936 os.chdir(cwd)
934 os.chdir(cwd)
937 # end user_setup()
935 # end user_setup()
938
936
939 def atexit_operations(self):
937 def atexit_operations(self):
940 """This will be executed at the time of exit.
938 """This will be executed at the time of exit.
941
939
942 Saving of persistent data should be performed here. """
940 Saving of persistent data should be performed here. """
943
941
944 # input history
942 # input history
945 self.savehist()
943 self.savehist()
946
944
947 # Cleanup all tempfiles left around
945 # Cleanup all tempfiles left around
948 for tfile in self.tempfiles:
946 for tfile in self.tempfiles:
949 try:
947 try:
950 os.unlink(tfile)
948 os.unlink(tfile)
951 except OSError:
949 except OSError:
952 pass
950 pass
953
951
954 # save the "persistent data" catch-all dictionary
952 # save the "persistent data" catch-all dictionary
955 try:
953 try:
956 pickle.dump(self.persist, open(self.persist_fname,"w"))
954 pickle.dump(self.persist, open(self.persist_fname,"w"))
957 except:
955 except:
958 print "*** ERROR *** persistent data saving failed."
956 print "*** ERROR *** persistent data saving failed."
959
957
960 def savehist(self):
958 def savehist(self):
961 """Save input history to a file (via readline library)."""
959 """Save input history to a file (via readline library)."""
962 try:
960 try:
963 self.readline.write_history_file(self.histfile)
961 self.readline.write_history_file(self.histfile)
964 except:
962 except:
965 print 'Unable to save IPython command history to file: ' + \
963 print 'Unable to save IPython command history to file: ' + \
966 `self.histfile`
964 `self.histfile`
967
965
968 def pre_readline(self):
966 def pre_readline(self):
969 """readline hook to be used at the start of each line.
967 """readline hook to be used at the start of each line.
970
968
971 Currently it handles auto-indent only."""
969 Currently it handles auto-indent only."""
972
970
973 self.readline.insert_text(self.indent_current)
971 self.readline.insert_text(self.indent_current)
974
972
975 def init_readline(self):
973 def init_readline(self):
976 """Command history completion/saving/reloading."""
974 """Command history completion/saving/reloading."""
977 try:
975 try:
978 import readline
976 import readline
979 except ImportError:
977 except ImportError:
980 self.has_readline = 0
978 self.has_readline = 0
981 self.readline = None
979 self.readline = None
982 # no point in bugging windows users with this every time:
980 # no point in bugging windows users with this every time:
983 if os.name == 'posix':
981 if os.name == 'posix':
984 warn('Readline services not available on this platform.')
982 warn('Readline services not available on this platform.')
985 else:
983 else:
986 import atexit
984 import atexit
987 from IPython.completer import IPCompleter
985 from IPython.completer import IPCompleter
988 self.Completer = IPCompleter(self,
986 self.Completer = IPCompleter(self,
989 self.user_ns,
987 self.user_ns,
990 self.user_global_ns,
988 self.user_global_ns,
991 self.rc.readline_omit__names,
989 self.rc.readline_omit__names,
992 self.alias_table)
990 self.alias_table)
993
991
994 # Platform-specific configuration
992 # Platform-specific configuration
995 if os.name == 'nt':
993 if os.name == 'nt':
996 self.readline_startup_hook = readline.set_pre_input_hook
994 self.readline_startup_hook = readline.set_pre_input_hook
997 else:
995 else:
998 self.readline_startup_hook = readline.set_startup_hook
996 self.readline_startup_hook = readline.set_startup_hook
999
997
1000 # Load user's initrc file (readline config)
998 # Load user's initrc file (readline config)
1001 inputrc_name = os.environ.get('INPUTRC')
999 inputrc_name = os.environ.get('INPUTRC')
1002 if inputrc_name is None:
1000 if inputrc_name is None:
1003 home_dir = get_home_dir()
1001 home_dir = get_home_dir()
1004 if home_dir is not None:
1002 if home_dir is not None:
1005 inputrc_name = os.path.join(home_dir,'.inputrc')
1003 inputrc_name = os.path.join(home_dir,'.inputrc')
1006 if os.path.isfile(inputrc_name):
1004 if os.path.isfile(inputrc_name):
1007 try:
1005 try:
1008 readline.read_init_file(inputrc_name)
1006 readline.read_init_file(inputrc_name)
1009 except:
1007 except:
1010 warn('Problems reading readline initialization file <%s>'
1008 warn('Problems reading readline initialization file <%s>'
1011 % inputrc_name)
1009 % inputrc_name)
1012
1010
1013 self.has_readline = 1
1011 self.has_readline = 1
1014 self.readline = readline
1012 self.readline = readline
1015 # save this in sys so embedded copies can restore it properly
1013 # save this in sys so embedded copies can restore it properly
1016 sys.ipcompleter = self.Completer.complete
1014 sys.ipcompleter = self.Completer.complete
1017 readline.set_completer(self.Completer.complete)
1015 readline.set_completer(self.Completer.complete)
1018
1016
1019 # Configure readline according to user's prefs
1017 # Configure readline according to user's prefs
1020 for rlcommand in self.rc.readline_parse_and_bind:
1018 for rlcommand in self.rc.readline_parse_and_bind:
1021 readline.parse_and_bind(rlcommand)
1019 readline.parse_and_bind(rlcommand)
1022
1020
1023 # remove some chars from the delimiters list
1021 # remove some chars from the delimiters list
1024 delims = readline.get_completer_delims()
1022 delims = readline.get_completer_delims()
1025 delims = delims.translate(string._idmap,
1023 delims = delims.translate(string._idmap,
1026 self.rc.readline_remove_delims)
1024 self.rc.readline_remove_delims)
1027 readline.set_completer_delims(delims)
1025 readline.set_completer_delims(delims)
1028 # otherwise we end up with a monster history after a while:
1026 # otherwise we end up with a monster history after a while:
1029 readline.set_history_length(1000)
1027 readline.set_history_length(1000)
1030 try:
1028 try:
1031 #print '*** Reading readline history' # dbg
1029 #print '*** Reading readline history' # dbg
1032 readline.read_history_file(self.histfile)
1030 readline.read_history_file(self.histfile)
1033 except IOError:
1031 except IOError:
1034 pass # It doesn't exist yet.
1032 pass # It doesn't exist yet.
1035
1033
1036 atexit.register(self.atexit_operations)
1034 atexit.register(self.atexit_operations)
1037 del atexit
1035 del atexit
1038
1036
1039 # Configure auto-indent for all platforms
1037 # Configure auto-indent for all platforms
1040 self.set_autoindent(self.rc.autoindent)
1038 self.set_autoindent(self.rc.autoindent)
1041
1039
1042 def _should_recompile(self,e):
1040 def _should_recompile(self,e):
1043 """Utility routine for edit_syntax_error"""
1041 """Utility routine for edit_syntax_error"""
1044
1042
1045 if e.filename in ('<ipython console>','<input>','<string>',
1043 if e.filename in ('<ipython console>','<input>','<string>',
1046 '<console>'):
1044 '<console>'):
1047 return False
1045 return False
1048 try:
1046 try:
1049 if not ask_yes_no('Return to editor to correct syntax error? '
1047 if not ask_yes_no('Return to editor to correct syntax error? '
1050 '[Y/n] ','y'):
1048 '[Y/n] ','y'):
1051 return False
1049 return False
1052 except EOFError:
1050 except EOFError:
1053 return False
1051 return False
1054 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1052 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1055 return True
1053 return True
1056
1054
1057 def edit_syntax_error(self):
1055 def edit_syntax_error(self):
1058 """The bottom half of the syntax error handler called in the main loop.
1056 """The bottom half of the syntax error handler called in the main loop.
1059
1057
1060 Loop until syntax error is fixed or user cancels.
1058 Loop until syntax error is fixed or user cancels.
1061 """
1059 """
1062
1060
1063 while self.SyntaxTB.last_syntax_error:
1061 while self.SyntaxTB.last_syntax_error:
1064 # copy and clear last_syntax_error
1062 # copy and clear last_syntax_error
1065 err = self.SyntaxTB.clear_err_state()
1063 err = self.SyntaxTB.clear_err_state()
1066 if not self._should_recompile(err):
1064 if not self._should_recompile(err):
1067 return
1065 return
1068 try:
1066 try:
1069 # may set last_syntax_error again if a SyntaxError is raised
1067 # may set last_syntax_error again if a SyntaxError is raised
1070 self.safe_execfile(err.filename,self.shell.user_ns)
1068 self.safe_execfile(err.filename,self.shell.user_ns)
1071 except:
1069 except:
1072 self.showtraceback()
1070 self.showtraceback()
1073 else:
1071 else:
1074 f = file(err.filename)
1072 f = file(err.filename)
1075 try:
1073 try:
1076 sys.displayhook(f.read())
1074 sys.displayhook(f.read())
1077 finally:
1075 finally:
1078 f.close()
1076 f.close()
1079
1077
1080 def showsyntaxerror(self, filename=None):
1078 def showsyntaxerror(self, filename=None):
1081 """Display the syntax error that just occurred.
1079 """Display the syntax error that just occurred.
1082
1080
1083 This doesn't display a stack trace because there isn't one.
1081 This doesn't display a stack trace because there isn't one.
1084
1082
1085 If a filename is given, it is stuffed in the exception instead
1083 If a filename is given, it is stuffed in the exception instead
1086 of what was there before (because Python's parser always uses
1084 of what was there before (because Python's parser always uses
1087 "<string>" when reading from a string).
1085 "<string>" when reading from a string).
1088 """
1086 """
1089 type, value, sys.last_traceback = sys.exc_info()
1087 type, value, sys.last_traceback = sys.exc_info()
1090 sys.last_type = type
1088 sys.last_type = type
1091 sys.last_value = value
1089 sys.last_value = value
1092 if filename and type is SyntaxError:
1090 if filename and type is SyntaxError:
1093 # Work hard to stuff the correct filename in the exception
1091 # Work hard to stuff the correct filename in the exception
1094 try:
1092 try:
1095 msg, (dummy_filename, lineno, offset, line) = value
1093 msg, (dummy_filename, lineno, offset, line) = value
1096 except:
1094 except:
1097 # Not the format we expect; leave it alone
1095 # Not the format we expect; leave it alone
1098 pass
1096 pass
1099 else:
1097 else:
1100 # Stuff in the right filename
1098 # Stuff in the right filename
1101 try:
1099 try:
1102 # Assume SyntaxError is a class exception
1100 # Assume SyntaxError is a class exception
1103 value = SyntaxError(msg, (filename, lineno, offset, line))
1101 value = SyntaxError(msg, (filename, lineno, offset, line))
1104 except:
1102 except:
1105 # If that failed, assume SyntaxError is a string
1103 # If that failed, assume SyntaxError is a string
1106 value = msg, (filename, lineno, offset, line)
1104 value = msg, (filename, lineno, offset, line)
1107 self.SyntaxTB(type,value,[])
1105 self.SyntaxTB(type,value,[])
1108
1106
1109 def debugger(self):
1107 def debugger(self):
1110 """Call the pdb debugger."""
1108 """Call the pdb debugger."""
1111
1109
1112 if not self.rc.pdb:
1110 if not self.rc.pdb:
1113 return
1111 return
1114 pdb.pm()
1112 pdb.pm()
1115
1113
1116 def showtraceback(self,exc_tuple = None,filename=None):
1114 def showtraceback(self,exc_tuple = None,filename=None):
1117 """Display the exception that just occurred."""
1115 """Display the exception that just occurred."""
1118
1116
1119 # Though this won't be called by syntax errors in the input line,
1117 # Though this won't be called by syntax errors in the input line,
1120 # there may be SyntaxError cases whith imported code.
1118 # there may be SyntaxError cases whith imported code.
1121 if exc_tuple is None:
1119 if exc_tuple is None:
1122 type, value, tb = sys.exc_info()
1120 type, value, tb = sys.exc_info()
1123 else:
1121 else:
1124 type, value, tb = exc_tuple
1122 type, value, tb = exc_tuple
1125 if type is SyntaxError:
1123 if type is SyntaxError:
1126 self.showsyntaxerror(filename)
1124 self.showsyntaxerror(filename)
1127 else:
1125 else:
1128 sys.last_type = type
1126 sys.last_type = type
1129 sys.last_value = value
1127 sys.last_value = value
1130 sys.last_traceback = tb
1128 sys.last_traceback = tb
1131 self.InteractiveTB()
1129 self.InteractiveTB()
1132 if self.InteractiveTB.call_pdb and self.has_readline:
1130 if self.InteractiveTB.call_pdb and self.has_readline:
1133 # pdb mucks up readline, fix it back
1131 # pdb mucks up readline, fix it back
1134 self.readline.set_completer(self.Completer.complete)
1132 self.readline.set_completer(self.Completer.complete)
1135
1133
1136 def update_cache(self, line):
1134 def update_cache(self, line):
1137 """puts line into cache"""
1135 """puts line into cache"""
1138 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1136 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1139 if len(self.inputcache) >= self.CACHELENGTH:
1137 if len(self.inputcache) >= self.CACHELENGTH:
1140 self.inputcache.pop() # This doesn't :-)
1138 self.inputcache.pop() # This doesn't :-)
1141
1139
1142 def mainloop(self,banner=None):
1140 def mainloop(self,banner=None):
1143 """Creates the local namespace and starts the mainloop.
1141 """Creates the local namespace and starts the mainloop.
1144
1142
1145 If an optional banner argument is given, it will override the
1143 If an optional banner argument is given, it will override the
1146 internally created default banner."""
1144 internally created default banner."""
1147
1145
1148 if self.rc.c: # Emulate Python's -c option
1146 if self.rc.c: # Emulate Python's -c option
1149 self.exec_init_cmd()
1147 self.exec_init_cmd()
1150 if banner is None:
1148 if banner is None:
1151 if self.rc.banner:
1149 if self.rc.banner:
1152 banner = self.BANNER+self.banner2
1150 banner = self.BANNER+self.banner2
1153 else:
1151 else:
1154 banner = ''
1152 banner = ''
1155 self.interact(banner)
1153 self.interact(banner)
1156
1154
1157 def exec_init_cmd(self):
1155 def exec_init_cmd(self):
1158 """Execute a command given at the command line.
1156 """Execute a command given at the command line.
1159
1157
1160 This emulates Python's -c option."""
1158 This emulates Python's -c option."""
1161
1159
1162 sys.argv = ['-c']
1160 sys.argv = ['-c']
1163 self.push(self.rc.c)
1161 self.push(self.rc.c)
1164
1162
1165 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1163 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1166 """Embeds IPython into a running python program.
1164 """Embeds IPython into a running python program.
1167
1165
1168 Input:
1166 Input:
1169
1167
1170 - header: An optional header message can be specified.
1168 - header: An optional header message can be specified.
1171
1169
1172 - local_ns, global_ns: working namespaces. If given as None, the
1170 - local_ns, global_ns: working namespaces. If given as None, the
1173 IPython-initialized one is updated with __main__.__dict__, so that
1171 IPython-initialized one is updated with __main__.__dict__, so that
1174 program variables become visible but user-specific configuration
1172 program variables become visible but user-specific configuration
1175 remains possible.
1173 remains possible.
1176
1174
1177 - stack_depth: specifies how many levels in the stack to go to
1175 - stack_depth: specifies how many levels in the stack to go to
1178 looking for namespaces (when local_ns and global_ns are None). This
1176 looking for namespaces (when local_ns and global_ns are None). This
1179 allows an intermediate caller to make sure that this function gets
1177 allows an intermediate caller to make sure that this function gets
1180 the namespace from the intended level in the stack. By default (0)
1178 the namespace from the intended level in the stack. By default (0)
1181 it will get its locals and globals from the immediate caller.
1179 it will get its locals and globals from the immediate caller.
1182
1180
1183 Warning: it's possible to use this in a program which is being run by
1181 Warning: it's possible to use this in a program which is being run by
1184 IPython itself (via %run), but some funny things will happen (a few
1182 IPython itself (via %run), but some funny things will happen (a few
1185 globals get overwritten). In the future this will be cleaned up, as
1183 globals get overwritten). In the future this will be cleaned up, as
1186 there is no fundamental reason why it can't work perfectly."""
1184 there is no fundamental reason why it can't work perfectly."""
1187
1185
1188 # Get locals and globals from caller
1186 # Get locals and globals from caller
1189 if local_ns is None or global_ns is None:
1187 if local_ns is None or global_ns is None:
1190 call_frame = sys._getframe(stack_depth).f_back
1188 call_frame = sys._getframe(stack_depth).f_back
1191
1189
1192 if local_ns is None:
1190 if local_ns is None:
1193 local_ns = call_frame.f_locals
1191 local_ns = call_frame.f_locals
1194 if global_ns is None:
1192 if global_ns is None:
1195 global_ns = call_frame.f_globals
1193 global_ns = call_frame.f_globals
1196
1194
1197 # Update namespaces and fire up interpreter
1195 # Update namespaces and fire up interpreter
1198 self.user_ns = local_ns
1196 self.user_ns = local_ns
1199 self.user_global_ns = global_ns
1197 self.user_global_ns = global_ns
1200
1198
1201 # Patch for global embedding to make sure that things don't overwrite
1199 # Patch for global embedding to make sure that things don't overwrite
1202 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1200 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1203 # FIXME. Test this a bit more carefully (the if.. is new)
1201 # FIXME. Test this a bit more carefully (the if.. is new)
1204 if local_ns is None and global_ns is None:
1202 if local_ns is None and global_ns is None:
1205 self.user_global_ns.update(__main__.__dict__)
1203 self.user_global_ns.update(__main__.__dict__)
1206
1204
1207 # make sure the tab-completer has the correct frame information, so it
1205 # make sure the tab-completer has the correct frame information, so it
1208 # actually completes using the frame's locals/globals
1206 # actually completes using the frame's locals/globals
1209 self.set_completer_frame(call_frame)
1207 self.set_completer_frame(call_frame)
1210
1208
1211 self.interact(header)
1209 self.interact(header)
1212
1210
1213 def interact(self, banner=None):
1211 def interact(self, banner=None):
1214 """Closely emulate the interactive Python console.
1212 """Closely emulate the interactive Python console.
1215
1213
1216 The optional banner argument specify the banner to print
1214 The optional banner argument specify the banner to print
1217 before the first interaction; by default it prints a banner
1215 before the first interaction; by default it prints a banner
1218 similar to the one printed by the real Python interpreter,
1216 similar to the one printed by the real Python interpreter,
1219 followed by the current class name in parentheses (so as not
1217 followed by the current class name in parentheses (so as not
1220 to confuse this with the real interpreter -- since it's so
1218 to confuse this with the real interpreter -- since it's so
1221 close!).
1219 close!).
1222
1220
1223 """
1221 """
1224 cprt = 'Type "copyright", "credits" or "license" for more information.'
1222 cprt = 'Type "copyright", "credits" or "license" for more information.'
1225 if banner is None:
1223 if banner is None:
1226 self.write("Python %s on %s\n%s\n(%s)\n" %
1224 self.write("Python %s on %s\n%s\n(%s)\n" %
1227 (sys.version, sys.platform, cprt,
1225 (sys.version, sys.platform, cprt,
1228 self.__class__.__name__))
1226 self.__class__.__name__))
1229 else:
1227 else:
1230 self.write(banner)
1228 self.write(banner)
1231
1229
1232 more = 0
1230 more = 0
1233
1231
1234 # Mark activity in the builtins
1232 # Mark activity in the builtins
1235 __builtin__.__dict__['__IPYTHON__active'] += 1
1233 __builtin__.__dict__['__IPYTHON__active'] += 1
1236
1234
1237 # compiled regexps for autoindent management
1235 # compiled regexps for autoindent management
1238 ini_spaces_re = re.compile(r'^(\s+)')
1236 ini_spaces_re = re.compile(r'^(\s+)')
1239 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1237 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1240
1238
1241 # exit_now is set by a call to %Exit or %Quit
1239 # exit_now is set by a call to %Exit or %Quit
1242 while not self.exit_now:
1240 while not self.exit_now:
1243 try:
1241 try:
1244 if more:
1242 if more:
1245 prompt = self.outputcache.prompt2
1243 prompt = self.outputcache.prompt2
1246 if self.autoindent:
1244 if self.autoindent:
1247 self.readline_startup_hook(self.pre_readline)
1245 self.readline_startup_hook(self.pre_readline)
1248 else:
1246 else:
1249 prompt = self.outputcache.prompt1
1247 prompt = self.outputcache.prompt1
1250 try:
1248 try:
1251 line = self.raw_input(prompt,more)
1249 line = self.raw_input(prompt,more)
1252 if self.autoindent:
1250 if self.autoindent:
1253 self.readline_startup_hook(None)
1251 self.readline_startup_hook(None)
1254 except EOFError:
1252 except EOFError:
1255 if self.autoindent:
1253 if self.autoindent:
1256 self.readline_startup_hook(None)
1254 self.readline_startup_hook(None)
1257 self.write("\n")
1255 self.write("\n")
1258 self.exit()
1256 self.exit()
1259 except IPythonExit:
1260 self.exit()
1261 else:
1257 else:
1262 more = self.push(line)
1258 more = self.push(line)
1263 # Auto-indent management
1259 # Auto-indent management
1264 if self.autoindent:
1260 if self.autoindent:
1265 if line:
1261 if line:
1266 ini_spaces = ini_spaces_re.match(line)
1262 ini_spaces = ini_spaces_re.match(line)
1267 if ini_spaces:
1263 if ini_spaces:
1268 nspaces = ini_spaces.end()
1264 nspaces = ini_spaces.end()
1269 else:
1265 else:
1270 nspaces = 0
1266 nspaces = 0
1271 self.indent_current_nsp = nspaces
1267 self.indent_current_nsp = nspaces
1272
1268
1273 if line[-1] == ':':
1269 if line[-1] == ':':
1274 self.indent_current_nsp += 4
1270 self.indent_current_nsp += 4
1275 elif dedent_re.match(line):
1271 elif dedent_re.match(line):
1276 self.indent_current_nsp -= 4
1272 self.indent_current_nsp -= 4
1277 else:
1273 else:
1278 self.indent_current_nsp = 0
1274 self.indent_current_nsp = 0
1279
1275
1280 # indent_current is the actual string to be inserted
1276 # indent_current is the actual string to be inserted
1281 # by the readline hooks for indentation
1277 # by the readline hooks for indentation
1282 self.indent_current = ' '* self.indent_current_nsp
1278 self.indent_current = ' '* self.indent_current_nsp
1283
1279
1284 if (self.SyntaxTB.last_syntax_error and
1280 if (self.SyntaxTB.last_syntax_error and
1285 self.rc.autoedit_syntax):
1281 self.rc.autoedit_syntax):
1286 self.edit_syntax_error()
1282 self.edit_syntax_error()
1287
1283
1288 except KeyboardInterrupt:
1284 except KeyboardInterrupt:
1289 self.write("\nKeyboardInterrupt\n")
1285 self.write("\nKeyboardInterrupt\n")
1290 self.resetbuffer()
1286 self.resetbuffer()
1291 more = 0
1287 more = 0
1292 # keep cache in sync with the prompt counter:
1288 # keep cache in sync with the prompt counter:
1293 self.outputcache.prompt_count -= 1
1289 self.outputcache.prompt_count -= 1
1294
1290
1295 if self.autoindent:
1291 if self.autoindent:
1296 self.indent_current_nsp = 0
1292 self.indent_current_nsp = 0
1297 self.indent_current = ' '* self.indent_current_nsp
1293 self.indent_current = ' '* self.indent_current_nsp
1298
1294
1299 except bdb.BdbQuit:
1295 except bdb.BdbQuit:
1300 warn("The Python debugger has exited with a BdbQuit exception.\n"
1296 warn("The Python debugger has exited with a BdbQuit exception.\n"
1301 "Because of how pdb handles the stack, it is impossible\n"
1297 "Because of how pdb handles the stack, it is impossible\n"
1302 "for IPython to properly format this particular exception.\n"
1298 "for IPython to properly format this particular exception.\n"
1303 "IPython will resume normal operation.")
1299 "IPython will resume normal operation.")
1304
1300
1305 # We are off again...
1301 # We are off again...
1306 __builtin__.__dict__['__IPYTHON__active'] -= 1
1302 __builtin__.__dict__['__IPYTHON__active'] -= 1
1307
1303
1308 def excepthook(self, type, value, tb):
1304 def excepthook(self, type, value, tb):
1309 """One more defense for GUI apps that call sys.excepthook.
1305 """One more defense for GUI apps that call sys.excepthook.
1310
1306
1311 GUI frameworks like wxPython trap exceptions and call
1307 GUI frameworks like wxPython trap exceptions and call
1312 sys.excepthook themselves. I guess this is a feature that
1308 sys.excepthook themselves. I guess this is a feature that
1313 enables them to keep running after exceptions that would
1309 enables them to keep running after exceptions that would
1314 otherwise kill their mainloop. This is a bother for IPython
1310 otherwise kill their mainloop. This is a bother for IPython
1315 which excepts to catch all of the program exceptions with a try:
1311 which excepts to catch all of the program exceptions with a try:
1316 except: statement.
1312 except: statement.
1317
1313
1318 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1314 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1319 any app directly invokes sys.excepthook, it will look to the user like
1315 any app directly invokes sys.excepthook, it will look to the user like
1320 IPython crashed. In order to work around this, we can disable the
1316 IPython crashed. In order to work around this, we can disable the
1321 CrashHandler and replace it with this excepthook instead, which prints a
1317 CrashHandler and replace it with this excepthook instead, which prints a
1322 regular traceback using our InteractiveTB. In this fashion, apps which
1318 regular traceback using our InteractiveTB. In this fashion, apps which
1323 call sys.excepthook will generate a regular-looking exception from
1319 call sys.excepthook will generate a regular-looking exception from
1324 IPython, and the CrashHandler will only be triggered by real IPython
1320 IPython, and the CrashHandler will only be triggered by real IPython
1325 crashes.
1321 crashes.
1326
1322
1327 This hook should be used sparingly, only in places which are not likely
1323 This hook should be used sparingly, only in places which are not likely
1328 to be true IPython errors.
1324 to be true IPython errors.
1329 """
1325 """
1330
1326
1331 self.InteractiveTB(type, value, tb, tb_offset=0)
1327 self.InteractiveTB(type, value, tb, tb_offset=0)
1332 if self.InteractiveTB.call_pdb and self.has_readline:
1328 if self.InteractiveTB.call_pdb and self.has_readline:
1333 self.readline.set_completer(self.Completer.complete)
1329 self.readline.set_completer(self.Completer.complete)
1334
1330
1335 def call_alias(self,alias,rest=''):
1331 def call_alias(self,alias,rest=''):
1336 """Call an alias given its name and the rest of the line.
1332 """Call an alias given its name and the rest of the line.
1337
1333
1338 This function MUST be given a proper alias, because it doesn't make
1334 This function MUST be given a proper alias, because it doesn't make
1339 any checks when looking up into the alias table. The caller is
1335 any checks when looking up into the alias table. The caller is
1340 responsible for invoking it only with a valid alias."""
1336 responsible for invoking it only with a valid alias."""
1341
1337
1342 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1338 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1343 nargs,cmd = self.alias_table[alias]
1339 nargs,cmd = self.alias_table[alias]
1344 # Expand the %l special to be the user's input line
1340 # Expand the %l special to be the user's input line
1345 if cmd.find('%l') >= 0:
1341 if cmd.find('%l') >= 0:
1346 cmd = cmd.replace('%l',rest)
1342 cmd = cmd.replace('%l',rest)
1347 rest = ''
1343 rest = ''
1348 if nargs==0:
1344 if nargs==0:
1349 # Simple, argument-less aliases
1345 # Simple, argument-less aliases
1350 cmd = '%s %s' % (cmd,rest)
1346 cmd = '%s %s' % (cmd,rest)
1351 else:
1347 else:
1352 # Handle aliases with positional arguments
1348 # Handle aliases with positional arguments
1353 args = rest.split(None,nargs)
1349 args = rest.split(None,nargs)
1354 if len(args)< nargs:
1350 if len(args)< nargs:
1355 error('Alias <%s> requires %s arguments, %s given.' %
1351 error('Alias <%s> requires %s arguments, %s given.' %
1356 (alias,nargs,len(args)))
1352 (alias,nargs,len(args)))
1357 return
1353 return
1358 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1354 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1359 # Now call the macro, evaluating in the user's namespace
1355 # Now call the macro, evaluating in the user's namespace
1360 try:
1356 try:
1361 self.system(cmd)
1357 self.system(cmd)
1362 except:
1358 except:
1363 self.showtraceback()
1359 self.showtraceback()
1364
1360
1365 def runlines(self,lines):
1361 def runlines(self,lines):
1366 """Run a string of one or more lines of source.
1362 """Run a string of one or more lines of source.
1367
1363
1368 This method is capable of running a string containing multiple source
1364 This method is capable of running a string containing multiple source
1369 lines, as if they had been entered at the IPython prompt. Since it
1365 lines, as if they had been entered at the IPython prompt. Since it
1370 exposes IPython's processing machinery, the given strings can contain
1366 exposes IPython's processing machinery, the given strings can contain
1371 magic calls (%magic), special shell access (!cmd), etc."""
1367 magic calls (%magic), special shell access (!cmd), etc."""
1372
1368
1373 # We must start with a clean buffer, in case this is run from an
1369 # We must start with a clean buffer, in case this is run from an
1374 # interactive IPython session (via a magic, for example).
1370 # interactive IPython session (via a magic, for example).
1375 self.resetbuffer()
1371 self.resetbuffer()
1376 lines = lines.split('\n')
1372 lines = lines.split('\n')
1377 more = 0
1373 more = 0
1378 for line in lines:
1374 for line in lines:
1379 # skip blank lines so we don't mess up the prompt counter, but do
1375 # skip blank lines so we don't mess up the prompt counter, but do
1380 # NOT skip even a blank line if we are in a code block (more is
1376 # NOT skip even a blank line if we are in a code block (more is
1381 # true)
1377 # true)
1382 if line or more:
1378 if line or more:
1383 more = self.push((self.prefilter(line,more)))
1379 more = self.push((self.prefilter(line,more)))
1384 # IPython's runsource returns None if there was an error
1380 # IPython's runsource returns None if there was an error
1385 # compiling the code. This allows us to stop processing right
1381 # compiling the code. This allows us to stop processing right
1386 # away, so the user gets the error message at the right place.
1382 # away, so the user gets the error message at the right place.
1387 if more is None:
1383 if more is None:
1388 break
1384 break
1389 # final newline in case the input didn't have it, so that the code
1385 # final newline in case the input didn't have it, so that the code
1390 # actually does get executed
1386 # actually does get executed
1391 if more:
1387 if more:
1392 self.push('\n')
1388 self.push('\n')
1393
1389
1394 def runsource(self, source, filename='<input>', symbol='single'):
1390 def runsource(self, source, filename='<input>', symbol='single'):
1395 """Compile and run some source in the interpreter.
1391 """Compile and run some source in the interpreter.
1396
1392
1397 Arguments are as for compile_command().
1393 Arguments are as for compile_command().
1398
1394
1399 One several things can happen:
1395 One several things can happen:
1400
1396
1401 1) The input is incorrect; compile_command() raised an
1397 1) The input is incorrect; compile_command() raised an
1402 exception (SyntaxError or OverflowError). A syntax traceback
1398 exception (SyntaxError or OverflowError). A syntax traceback
1403 will be printed by calling the showsyntaxerror() method.
1399 will be printed by calling the showsyntaxerror() method.
1404
1400
1405 2) The input is incomplete, and more input is required;
1401 2) The input is incomplete, and more input is required;
1406 compile_command() returned None. Nothing happens.
1402 compile_command() returned None. Nothing happens.
1407
1403
1408 3) The input is complete; compile_command() returned a code
1404 3) The input is complete; compile_command() returned a code
1409 object. The code is executed by calling self.runcode() (which
1405 object. The code is executed by calling self.runcode() (which
1410 also handles run-time exceptions, except for SystemExit).
1406 also handles run-time exceptions, except for SystemExit).
1411
1407
1412 The return value is:
1408 The return value is:
1413
1409
1414 - True in case 2
1410 - True in case 2
1415
1411
1416 - False in the other cases, unless an exception is raised, where
1412 - False in the other cases, unless an exception is raised, where
1417 None is returned instead. This can be used by external callers to
1413 None is returned instead. This can be used by external callers to
1418 know whether to continue feeding input or not.
1414 know whether to continue feeding input or not.
1419
1415
1420 The return value can be used to decide whether to use sys.ps1 or
1416 The return value can be used to decide whether to use sys.ps1 or
1421 sys.ps2 to prompt the next line."""
1417 sys.ps2 to prompt the next line."""
1422
1418
1423 try:
1419 try:
1424 code = self.compile(source,filename,symbol)
1420 code = self.compile(source,filename,symbol)
1425 except (OverflowError, SyntaxError, ValueError):
1421 except (OverflowError, SyntaxError, ValueError):
1426 # Case 1
1422 # Case 1
1427 self.showsyntaxerror(filename)
1423 self.showsyntaxerror(filename)
1428 return None
1424 return None
1429
1425
1430 if code is None:
1426 if code is None:
1431 # Case 2
1427 # Case 2
1432 return True
1428 return True
1433
1429
1434 # Case 3
1430 # Case 3
1435 # We store the code object so that threaded shells and
1431 # We store the code object so that threaded shells and
1436 # custom exception handlers can access all this info if needed.
1432 # custom exception handlers can access all this info if needed.
1437 # The source corresponding to this can be obtained from the
1433 # The source corresponding to this can be obtained from the
1438 # buffer attribute as '\n'.join(self.buffer).
1434 # buffer attribute as '\n'.join(self.buffer).
1439 self.code_to_run = code
1435 self.code_to_run = code
1440 # now actually execute the code object
1436 # now actually execute the code object
1441 if self.runcode(code) == 0:
1437 if self.runcode(code) == 0:
1442 return False
1438 return False
1443 else:
1439 else:
1444 return None
1440 return None
1445
1441
1446 def runcode(self,code_obj):
1442 def runcode(self,code_obj):
1447 """Execute a code object.
1443 """Execute a code object.
1448
1444
1449 When an exception occurs, self.showtraceback() is called to display a
1445 When an exception occurs, self.showtraceback() is called to display a
1450 traceback.
1446 traceback.
1451
1447
1452 Return value: a flag indicating whether the code to be run completed
1448 Return value: a flag indicating whether the code to be run completed
1453 successfully:
1449 successfully:
1454
1450
1455 - 0: successful execution.
1451 - 0: successful execution.
1456 - 1: an error occurred.
1452 - 1: an error occurred.
1457 """
1453 """
1458
1454
1459 # Set our own excepthook in case the user code tries to call it
1455 # Set our own excepthook in case the user code tries to call it
1460 # directly, so that the IPython crash handler doesn't get triggered
1456 # directly, so that the IPython crash handler doesn't get triggered
1461 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1457 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1462 outflag = 1 # happens in more places, so it's easier as default
1458 outflag = 1 # happens in more places, so it's easier as default
1463 try:
1459 try:
1464 try:
1460 try:
1465 # Embedded instances require separate global/local namespaces
1461 # Embedded instances require separate global/local namespaces
1466 # so they can see both the surrounding (local) namespace and
1462 # so they can see both the surrounding (local) namespace and
1467 # the module-level globals when called inside another function.
1463 # the module-level globals when called inside another function.
1468 if self.embedded:
1464 if self.embedded:
1469 exec code_obj in self.user_global_ns, self.user_ns
1465 exec code_obj in self.user_global_ns, self.user_ns
1470 # Normal (non-embedded) instances should only have a single
1466 # Normal (non-embedded) instances should only have a single
1471 # namespace for user code execution, otherwise functions won't
1467 # namespace for user code execution, otherwise functions won't
1472 # see interactive top-level globals.
1468 # see interactive top-level globals.
1473 else:
1469 else:
1474 exec code_obj in self.user_ns
1470 exec code_obj in self.user_ns
1475 finally:
1471 finally:
1476 # Reset our crash handler in place
1472 # Reset our crash handler in place
1477 sys.excepthook = old_excepthook
1473 sys.excepthook = old_excepthook
1478 except SystemExit:
1474 except SystemExit:
1479 self.resetbuffer()
1475 self.resetbuffer()
1480 self.showtraceback()
1476 self.showtraceback()
1481 warn("Type exit or quit to exit IPython "
1477 warn("Type exit or quit to exit IPython "
1482 "(%Exit or %Quit do so unconditionally).",level=1)
1478 "(%Exit or %Quit do so unconditionally).",level=1)
1483 except self.custom_exceptions:
1479 except self.custom_exceptions:
1484 etype,value,tb = sys.exc_info()
1480 etype,value,tb = sys.exc_info()
1485 self.CustomTB(etype,value,tb)
1481 self.CustomTB(etype,value,tb)
1486 except:
1482 except:
1487 self.showtraceback()
1483 self.showtraceback()
1488 else:
1484 else:
1489 outflag = 0
1485 outflag = 0
1490 if softspace(sys.stdout, 0):
1486 if softspace(sys.stdout, 0):
1491 print
1487 print
1492 # Flush out code object which has been run (and source)
1488 # Flush out code object which has been run (and source)
1493 self.code_to_run = None
1489 self.code_to_run = None
1494 return outflag
1490 return outflag
1495
1491
1496 def push(self, line):
1492 def push(self, line):
1497 """Push a line to the interpreter.
1493 """Push a line to the interpreter.
1498
1494
1499 The line should not have a trailing newline; it may have
1495 The line should not have a trailing newline; it may have
1500 internal newlines. The line is appended to a buffer and the
1496 internal newlines. The line is appended to a buffer and the
1501 interpreter's runsource() method is called with the
1497 interpreter's runsource() method is called with the
1502 concatenated contents of the buffer as source. If this
1498 concatenated contents of the buffer as source. If this
1503 indicates that the command was executed or invalid, the buffer
1499 indicates that the command was executed or invalid, the buffer
1504 is reset; otherwise, the command is incomplete, and the buffer
1500 is reset; otherwise, the command is incomplete, and the buffer
1505 is left as it was after the line was appended. The return
1501 is left as it was after the line was appended. The return
1506 value is 1 if more input is required, 0 if the line was dealt
1502 value is 1 if more input is required, 0 if the line was dealt
1507 with in some way (this is the same as runsource()).
1503 with in some way (this is the same as runsource()).
1508
1504
1509 """
1505 """
1510 self.buffer.append(line)
1506 self.buffer.append(line)
1511 more = self.runsource('\n'.join(self.buffer), self.filename)
1507 more = self.runsource('\n'.join(self.buffer), self.filename)
1512 if not more:
1508 if not more:
1513 self.resetbuffer()
1509 self.resetbuffer()
1514 return more
1510 return more
1515
1511
1516 def resetbuffer(self):
1512 def resetbuffer(self):
1517 """Reset the input buffer."""
1513 """Reset the input buffer."""
1518 self.buffer[:] = []
1514 self.buffer[:] = []
1519
1515
1520 def raw_input(self,prompt='',continue_prompt=False):
1516 def raw_input(self,prompt='',continue_prompt=False):
1521 """Write a prompt and read a line.
1517 """Write a prompt and read a line.
1522
1518
1523 The returned line does not include the trailing newline.
1519 The returned line does not include the trailing newline.
1524 When the user enters the EOF key sequence, EOFError is raised.
1520 When the user enters the EOF key sequence, EOFError is raised.
1525
1521
1526 Optional inputs:
1522 Optional inputs:
1527
1523
1528 - prompt(''): a string to be printed to prompt the user.
1524 - prompt(''): a string to be printed to prompt the user.
1529
1525
1530 - continue_prompt(False): whether this line is the first one or a
1526 - continue_prompt(False): whether this line is the first one or a
1531 continuation in a sequence of inputs.
1527 continuation in a sequence of inputs.
1532 """
1528 """
1533
1529
1534 line = raw_input_original(prompt)
1530 line = raw_input_original(prompt)
1535 # Try to be reasonably smart about not re-indenting pasted input more
1531 # Try to be reasonably smart about not re-indenting pasted input more
1536 # than necessary. We do this by trimming out the auto-indent initial
1532 # than necessary. We do this by trimming out the auto-indent initial
1537 # spaces, if the user's actual input started itself with whitespace.
1533 # spaces, if the user's actual input started itself with whitespace.
1538 if self.autoindent:
1534 if self.autoindent:
1539 line2 = line[self.indent_current_nsp:]
1535 line2 = line[self.indent_current_nsp:]
1540 if line2[0:1] in (' ','\t'):
1536 if line2[0:1] in (' ','\t'):
1541 line = line2
1537 line = line2
1542 return self.prefilter(line,continue_prompt)
1538 return self.prefilter(line,continue_prompt)
1543
1539
1544 def split_user_input(self,line):
1540 def split_user_input(self,line):
1545 """Split user input into pre-char, function part and rest."""
1541 """Split user input into pre-char, function part and rest."""
1546
1542
1547 lsplit = self.line_split.match(line)
1543 lsplit = self.line_split.match(line)
1548 if lsplit is None: # no regexp match returns None
1544 if lsplit is None: # no regexp match returns None
1549 try:
1545 try:
1550 iFun,theRest = line.split(None,1)
1546 iFun,theRest = line.split(None,1)
1551 except ValueError:
1547 except ValueError:
1552 iFun,theRest = line,''
1548 iFun,theRest = line,''
1553 pre = re.match('^(\s*)(.*)',line).groups()[0]
1549 pre = re.match('^(\s*)(.*)',line).groups()[0]
1554 else:
1550 else:
1555 pre,iFun,theRest = lsplit.groups()
1551 pre,iFun,theRest = lsplit.groups()
1556
1552
1557 #print 'line:<%s>' % line # dbg
1553 #print 'line:<%s>' % line # dbg
1558 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1554 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1559 return pre,iFun.strip(),theRest
1555 return pre,iFun.strip(),theRest
1560
1556
1561 def _prefilter(self, line, continue_prompt):
1557 def _prefilter(self, line, continue_prompt):
1562 """Calls different preprocessors, depending on the form of line."""
1558 """Calls different preprocessors, depending on the form of line."""
1563
1559
1564 # All handlers *must* return a value, even if it's blank ('').
1560 # All handlers *must* return a value, even if it's blank ('').
1565
1561
1566 # Lines are NOT logged here. Handlers should process the line as
1562 # Lines are NOT logged here. Handlers should process the line as
1567 # needed, update the cache AND log it (so that the input cache array
1563 # needed, update the cache AND log it (so that the input cache array
1568 # stays synced).
1564 # stays synced).
1569
1565
1570 # This function is _very_ delicate, and since it's also the one which
1566 # This function is _very_ delicate, and since it's also the one which
1571 # determines IPython's response to user input, it must be as efficient
1567 # determines IPython's response to user input, it must be as efficient
1572 # as possible. For this reason it has _many_ returns in it, trying
1568 # as possible. For this reason it has _many_ returns in it, trying
1573 # always to exit as quickly as it can figure out what it needs to do.
1569 # always to exit as quickly as it can figure out what it needs to do.
1574
1570
1575 # This function is the main responsible for maintaining IPython's
1571 # This function is the main responsible for maintaining IPython's
1576 # behavior respectful of Python's semantics. So be _very_ careful if
1572 # behavior respectful of Python's semantics. So be _very_ careful if
1577 # making changes to anything here.
1573 # making changes to anything here.
1578
1574
1579 #.....................................................................
1575 #.....................................................................
1580 # Code begins
1576 # Code begins
1581
1577
1582 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1578 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1583
1579
1584 # save the line away in case we crash, so the post-mortem handler can
1580 # save the line away in case we crash, so the post-mortem handler can
1585 # record it
1581 # record it
1586 self._last_input_line = line
1582 self._last_input_line = line
1587
1583
1588 #print '***line: <%s>' % line # dbg
1584 #print '***line: <%s>' % line # dbg
1589
1585
1590 # the input history needs to track even empty lines
1586 # the input history needs to track even empty lines
1591 if not line.strip():
1587 if not line.strip():
1592 if not continue_prompt:
1588 if not continue_prompt:
1593 self.outputcache.prompt_count -= 1
1589 self.outputcache.prompt_count -= 1
1594 return self.handle_normal(line,continue_prompt)
1590 return self.handle_normal(line,continue_prompt)
1595 #return self.handle_normal('',continue_prompt)
1591 #return self.handle_normal('',continue_prompt)
1596
1592
1597 # print '***cont',continue_prompt # dbg
1593 # print '***cont',continue_prompt # dbg
1598 # special handlers are only allowed for single line statements
1594 # special handlers are only allowed for single line statements
1599 if continue_prompt and not self.rc.multi_line_specials:
1595 if continue_prompt and not self.rc.multi_line_specials:
1600 return self.handle_normal(line,continue_prompt)
1596 return self.handle_normal(line,continue_prompt)
1601
1597
1602 # For the rest, we need the structure of the input
1598 # For the rest, we need the structure of the input
1603 pre,iFun,theRest = self.split_user_input(line)
1599 pre,iFun,theRest = self.split_user_input(line)
1604 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1600 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1605
1601
1606 # First check for explicit escapes in the last/first character
1602 # First check for explicit escapes in the last/first character
1607 handler = None
1603 handler = None
1608 if line[-1] == self.ESC_HELP:
1604 if line[-1] == self.ESC_HELP:
1609 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1605 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1610 if handler is None:
1606 if handler is None:
1611 # look at the first character of iFun, NOT of line, so we skip
1607 # look at the first character of iFun, NOT of line, so we skip
1612 # leading whitespace in multiline input
1608 # leading whitespace in multiline input
1613 handler = self.esc_handlers.get(iFun[0:1])
1609 handler = self.esc_handlers.get(iFun[0:1])
1614 if handler is not None:
1610 if handler is not None:
1615 return handler(line,continue_prompt,pre,iFun,theRest)
1611 return handler(line,continue_prompt,pre,iFun,theRest)
1616 # Emacs ipython-mode tags certain input lines
1612 # Emacs ipython-mode tags certain input lines
1617 if line.endswith('# PYTHON-MODE'):
1613 if line.endswith('# PYTHON-MODE'):
1618 return self.handle_emacs(line,continue_prompt)
1614 return self.handle_emacs(line,continue_prompt)
1619
1615
1620 # Next, check if we can automatically execute this thing
1616 # Next, check if we can automatically execute this thing
1621
1617
1622 # Allow ! in multi-line statements if multi_line_specials is on:
1618 # Allow ! in multi-line statements if multi_line_specials is on:
1623 if continue_prompt and self.rc.multi_line_specials and \
1619 if continue_prompt and self.rc.multi_line_specials and \
1624 iFun.startswith(self.ESC_SHELL):
1620 iFun.startswith(self.ESC_SHELL):
1625 return self.handle_shell_escape(line,continue_prompt,
1621 return self.handle_shell_escape(line,continue_prompt,
1626 pre=pre,iFun=iFun,
1622 pre=pre,iFun=iFun,
1627 theRest=theRest)
1623 theRest=theRest)
1628
1624
1629 # Let's try to find if the input line is a magic fn
1625 # Let's try to find if the input line is a magic fn
1630 oinfo = None
1626 oinfo = None
1631 if hasattr(self,'magic_'+iFun):
1627 if hasattr(self,'magic_'+iFun):
1632 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1628 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1633 if oinfo['ismagic']:
1629 if oinfo['ismagic']:
1634 # Be careful not to call magics when a variable assignment is
1630 # Be careful not to call magics when a variable assignment is
1635 # being made (ls='hi', for example)
1631 # being made (ls='hi', for example)
1636 if self.rc.automagic and \
1632 if self.rc.automagic and \
1637 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1633 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1638 (self.rc.multi_line_specials or not continue_prompt):
1634 (self.rc.multi_line_specials or not continue_prompt):
1639 return self.handle_magic(line,continue_prompt,
1635 return self.handle_magic(line,continue_prompt,
1640 pre,iFun,theRest)
1636 pre,iFun,theRest)
1641 else:
1637 else:
1642 return self.handle_normal(line,continue_prompt)
1638 return self.handle_normal(line,continue_prompt)
1643
1639
1644 # If the rest of the line begins with an (in)equality, assginment or
1640 # If the rest of the line begins with an (in)equality, assginment or
1645 # function call, we should not call _ofind but simply execute it.
1641 # function call, we should not call _ofind but simply execute it.
1646 # This avoids spurious geattr() accesses on objects upon assignment.
1642 # This avoids spurious geattr() accesses on objects upon assignment.
1647 #
1643 #
1648 # It also allows users to assign to either alias or magic names true
1644 # It also allows users to assign to either alias or magic names true
1649 # python variables (the magic/alias systems always take second seat to
1645 # python variables (the magic/alias systems always take second seat to
1650 # true python code).
1646 # true python code).
1651 if theRest and theRest[0] in '!=()':
1647 if theRest and theRest[0] in '!=()':
1652 return self.handle_normal(line,continue_prompt)
1648 return self.handle_normal(line,continue_prompt)
1653
1649
1654 if oinfo is None:
1650 if oinfo is None:
1655 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1651 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1656
1652
1657 if not oinfo['found']:
1653 if not oinfo['found']:
1658 if iFun in ('quit','exit'):
1659 raise IPythonExit
1660 return self.handle_normal(line,continue_prompt)
1654 return self.handle_normal(line,continue_prompt)
1661 else:
1655 else:
1662 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1656 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1663 if oinfo['isalias']:
1657 if oinfo['isalias']:
1664 return self.handle_alias(line,continue_prompt,
1658 return self.handle_alias(line,continue_prompt,
1665 pre,iFun,theRest)
1659 pre,iFun,theRest)
1666
1660
1667 if self.rc.autocall and \
1661 if self.rc.autocall and \
1668 not self.re_exclude_auto.match(theRest) and \
1662 not self.re_exclude_auto.match(theRest) and \
1669 self.re_fun_name.match(iFun) and \
1663 self.re_fun_name.match(iFun) and \
1670 callable(oinfo['obj']) :
1664 callable(oinfo['obj']) :
1671 #print 'going auto' # dbg
1665 #print 'going auto' # dbg
1672 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1666 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1673 else:
1667 else:
1674 #print 'was callable?', callable(oinfo['obj']) # dbg
1668 #print 'was callable?', callable(oinfo['obj']) # dbg
1675 return self.handle_normal(line,continue_prompt)
1669 return self.handle_normal(line,continue_prompt)
1676
1670
1677 # If we get here, we have a normal Python line. Log and return.
1671 # If we get here, we have a normal Python line. Log and return.
1678 return self.handle_normal(line,continue_prompt)
1672 return self.handle_normal(line,continue_prompt)
1679
1673
1680 def _prefilter_dumb(self, line, continue_prompt):
1674 def _prefilter_dumb(self, line, continue_prompt):
1681 """simple prefilter function, for debugging"""
1675 """simple prefilter function, for debugging"""
1682 return self.handle_normal(line,continue_prompt)
1676 return self.handle_normal(line,continue_prompt)
1683
1677
1684 # Set the default prefilter() function (this can be user-overridden)
1678 # Set the default prefilter() function (this can be user-overridden)
1685 prefilter = _prefilter
1679 prefilter = _prefilter
1686
1680
1687 def handle_normal(self,line,continue_prompt=None,
1681 def handle_normal(self,line,continue_prompt=None,
1688 pre=None,iFun=None,theRest=None):
1682 pre=None,iFun=None,theRest=None):
1689 """Handle normal input lines. Use as a template for handlers."""
1683 """Handle normal input lines. Use as a template for handlers."""
1690
1684
1691 # With autoindent on, we need some way to exit the input loop, and I
1685 # With autoindent on, we need some way to exit the input loop, and I
1692 # don't want to force the user to have to backspace all the way to
1686 # don't want to force the user to have to backspace all the way to
1693 # clear the line. The rule will be in this case, that either two
1687 # clear the line. The rule will be in this case, that either two
1694 # lines of pure whitespace in a row, or a line of pure whitespace but
1688 # lines of pure whitespace in a row, or a line of pure whitespace but
1695 # of a size different to the indent level, will exit the input loop.
1689 # of a size different to the indent level, will exit the input loop.
1696 if (continue_prompt and self.autoindent and isspace(line) and
1690 if (continue_prompt and self.autoindent and isspace(line) and
1697 (line != self.indent_current or isspace(self.buffer[-1]))):
1691 (line != self.indent_current or isspace(self.buffer[-1]))):
1698 line = ''
1692 line = ''
1699
1693
1700 self.log(line,continue_prompt)
1694 self.log(line,continue_prompt)
1701 self.update_cache(line)
1695 self.update_cache(line)
1702 return line
1696 return line
1703
1697
1704 def handle_alias(self,line,continue_prompt=None,
1698 def handle_alias(self,line,continue_prompt=None,
1705 pre=None,iFun=None,theRest=None):
1699 pre=None,iFun=None,theRest=None):
1706 """Handle alias input lines. """
1700 """Handle alias input lines. """
1707
1701
1708 theRest = esc_quotes(theRest)
1702 theRest = esc_quotes(theRest)
1709 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1703 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1710 self.log(line_out,continue_prompt)
1704 self.log(line_out,continue_prompt)
1711 self.update_cache(line_out)
1705 self.update_cache(line_out)
1712 return line_out
1706 return line_out
1713
1707
1714 def handle_shell_escape(self, line, continue_prompt=None,
1708 def handle_shell_escape(self, line, continue_prompt=None,
1715 pre=None,iFun=None,theRest=None):
1709 pre=None,iFun=None,theRest=None):
1716 """Execute the line in a shell, empty return value"""
1710 """Execute the line in a shell, empty return value"""
1717
1711
1718 #print 'line in :', `line` # dbg
1712 #print 'line in :', `line` # dbg
1719 # Example of a special handler. Others follow a similar pattern.
1713 # Example of a special handler. Others follow a similar pattern.
1720 if continue_prompt: # multi-line statements
1714 if continue_prompt: # multi-line statements
1721 if iFun.startswith('!!'):
1715 if iFun.startswith('!!'):
1722 print 'SyntaxError: !! is not allowed in multiline statements'
1716 print 'SyntaxError: !! is not allowed in multiline statements'
1723 return pre
1717 return pre
1724 else:
1718 else:
1725 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1719 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1726 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1720 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1727 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1721 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1728 else: # single-line input
1722 else: # single-line input
1729 if line.startswith('!!'):
1723 if line.startswith('!!'):
1730 # rewrite iFun/theRest to properly hold the call to %sx and
1724 # rewrite iFun/theRest to properly hold the call to %sx and
1731 # the actual command to be executed, so handle_magic can work
1725 # the actual command to be executed, so handle_magic can work
1732 # correctly
1726 # correctly
1733 theRest = '%s %s' % (iFun[2:],theRest)
1727 theRest = '%s %s' % (iFun[2:],theRest)
1734 iFun = 'sx'
1728 iFun = 'sx'
1735 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1729 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1736 continue_prompt,pre,iFun,theRest)
1730 continue_prompt,pre,iFun,theRest)
1737 else:
1731 else:
1738 cmd = esc_quotes(line[1:])
1732 cmd = esc_quotes(line[1:])
1739 line_out = '%s.system("%s")' % (self.name,cmd)
1733 line_out = '%s.system("%s")' % (self.name,cmd)
1740 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1734 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1741 # update cache/log and return
1735 # update cache/log and return
1742 self.log(line_out,continue_prompt)
1736 self.log(line_out,continue_prompt)
1743 self.update_cache(line_out) # readline cache gets normal line
1737 self.update_cache(line_out) # readline cache gets normal line
1744 #print 'line out r:', `line_out` # dbg
1738 #print 'line out r:', `line_out` # dbg
1745 #print 'line out s:', line_out # dbg
1739 #print 'line out s:', line_out # dbg
1746 return line_out
1740 return line_out
1747
1741
1748 def handle_magic(self, line, continue_prompt=None,
1742 def handle_magic(self, line, continue_prompt=None,
1749 pre=None,iFun=None,theRest=None):
1743 pre=None,iFun=None,theRest=None):
1750 """Execute magic functions.
1744 """Execute magic functions.
1751
1745
1752 Also log them with a prepended # so the log is clean Python."""
1746 Also log them with a prepended # so the log is clean Python."""
1753
1747
1754 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1748 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1755 self.log(cmd,continue_prompt)
1749 self.log(cmd,continue_prompt)
1756 self.update_cache(line)
1750 self.update_cache(line)
1757 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1751 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1758 return cmd
1752 return cmd
1759
1753
1760 def handle_auto(self, line, continue_prompt=None,
1754 def handle_auto(self, line, continue_prompt=None,
1761 pre=None,iFun=None,theRest=None):
1755 pre=None,iFun=None,theRest=None):
1762 """Hande lines which can be auto-executed, quoting if requested."""
1756 """Hande lines which can be auto-executed, quoting if requested."""
1763
1757
1764 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1758 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1765
1759
1766 # This should only be active for single-line input!
1760 # This should only be active for single-line input!
1767 if continue_prompt:
1761 if continue_prompt:
1768 return line
1762 return line
1769
1763
1770 if pre == self.ESC_QUOTE:
1764 if pre == self.ESC_QUOTE:
1771 # Auto-quote splitting on whitespace
1765 # Auto-quote splitting on whitespace
1772 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1766 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1773 elif pre == self.ESC_QUOTE2:
1767 elif pre == self.ESC_QUOTE2:
1774 # Auto-quote whole string
1768 # Auto-quote whole string
1775 newcmd = '%s("%s")' % (iFun,theRest)
1769 newcmd = '%s("%s")' % (iFun,theRest)
1776 else:
1770 else:
1777 # Auto-paren
1771 # Auto-paren
1778 if theRest[0:1] in ('=','['):
1772 if theRest[0:1] in ('=','['):
1779 # Don't autocall in these cases. They can be either
1773 # Don't autocall in these cases. They can be either
1780 # rebindings of an existing callable's name, or item access
1774 # rebindings of an existing callable's name, or item access
1781 # for an object which is BOTH callable and implements
1775 # for an object which is BOTH callable and implements
1782 # __getitem__.
1776 # __getitem__.
1783 return '%s %s' % (iFun,theRest)
1777 return '%s %s' % (iFun,theRest)
1784 if theRest.endswith(';'):
1778 if theRest.endswith(';'):
1785 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1779 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1786 else:
1780 else:
1787 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1781 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1788
1782
1789 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1783 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1790 # log what is now valid Python, not the actual user input (without the
1784 # log what is now valid Python, not the actual user input (without the
1791 # final newline)
1785 # final newline)
1792 self.log(newcmd,continue_prompt)
1786 self.log(newcmd,continue_prompt)
1793 return newcmd
1787 return newcmd
1794
1788
1795 def handle_help(self, line, continue_prompt=None,
1789 def handle_help(self, line, continue_prompt=None,
1796 pre=None,iFun=None,theRest=None):
1790 pre=None,iFun=None,theRest=None):
1797 """Try to get some help for the object.
1791 """Try to get some help for the object.
1798
1792
1799 obj? or ?obj -> basic information.
1793 obj? or ?obj -> basic information.
1800 obj?? or ??obj -> more details.
1794 obj?? or ??obj -> more details.
1801 """
1795 """
1802
1796
1803 # We need to make sure that we don't process lines which would be
1797 # We need to make sure that we don't process lines which would be
1804 # otherwise valid python, such as "x=1 # what?"
1798 # otherwise valid python, such as "x=1 # what?"
1805 try:
1799 try:
1806 codeop.compile_command(line)
1800 codeop.compile_command(line)
1807 except SyntaxError:
1801 except SyntaxError:
1808 # We should only handle as help stuff which is NOT valid syntax
1802 # We should only handle as help stuff which is NOT valid syntax
1809 if line[0]==self.ESC_HELP:
1803 if line[0]==self.ESC_HELP:
1810 line = line[1:]
1804 line = line[1:]
1811 elif line[-1]==self.ESC_HELP:
1805 elif line[-1]==self.ESC_HELP:
1812 line = line[:-1]
1806 line = line[:-1]
1813 self.log('#?'+line)
1807 self.log('#?'+line)
1814 self.update_cache(line)
1808 self.update_cache(line)
1815 if line:
1809 if line:
1816 self.magic_pinfo(line)
1810 self.magic_pinfo(line)
1817 else:
1811 else:
1818 page(self.usage,screen_lines=self.rc.screen_length)
1812 page(self.usage,screen_lines=self.rc.screen_length)
1819 return '' # Empty string is needed here!
1813 return '' # Empty string is needed here!
1820 except:
1814 except:
1821 # Pass any other exceptions through to the normal handler
1815 # Pass any other exceptions through to the normal handler
1822 return self.handle_normal(line,continue_prompt)
1816 return self.handle_normal(line,continue_prompt)
1823 else:
1817 else:
1824 # If the code compiles ok, we should handle it normally
1818 # If the code compiles ok, we should handle it normally
1825 return self.handle_normal(line,continue_prompt)
1819 return self.handle_normal(line,continue_prompt)
1826
1820
1827 def handle_emacs(self,line,continue_prompt=None,
1821 def handle_emacs(self,line,continue_prompt=None,
1828 pre=None,iFun=None,theRest=None):
1822 pre=None,iFun=None,theRest=None):
1829 """Handle input lines marked by python-mode."""
1823 """Handle input lines marked by python-mode."""
1830
1824
1831 # Currently, nothing is done. Later more functionality can be added
1825 # Currently, nothing is done. Later more functionality can be added
1832 # here if needed.
1826 # here if needed.
1833
1827
1834 # The input cache shouldn't be updated
1828 # The input cache shouldn't be updated
1835
1829
1836 return line
1830 return line
1837
1831
1838 def write(self,data):
1832 def write(self,data):
1839 """Write a string to the default output"""
1833 """Write a string to the default output"""
1840 Term.cout.write(data)
1834 Term.cout.write(data)
1841
1835
1842 def write_err(self,data):
1836 def write_err(self,data):
1843 """Write a string to the default error output"""
1837 """Write a string to the default error output"""
1844 Term.cerr.write(data)
1838 Term.cerr.write(data)
1845
1839
1846 def exit(self):
1840 def exit(self):
1847 """Handle interactive exit.
1841 """Handle interactive exit.
1848
1842
1849 This method sets the exit_now attribute."""
1843 This method sets the exit_now attribute."""
1850
1844
1851 if self.rc.confirm_exit:
1845 if self.rc.confirm_exit:
1852 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1846 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1853 self.exit_now = True
1847 self.exit_now = True
1854 else:
1848 else:
1855 self.exit_now = True
1849 self.exit_now = True
1856 return self.exit_now
1850 return self.exit_now
1857
1851
1858 def safe_execfile(self,fname,*where,**kw):
1852 def safe_execfile(self,fname,*where,**kw):
1859 fname = os.path.expanduser(fname)
1853 fname = os.path.expanduser(fname)
1860
1854
1861 # find things also in current directory
1855 # find things also in current directory
1862 dname = os.path.dirname(fname)
1856 dname = os.path.dirname(fname)
1863 if not sys.path.count(dname):
1857 if not sys.path.count(dname):
1864 sys.path.append(dname)
1858 sys.path.append(dname)
1865
1859
1866 try:
1860 try:
1867 xfile = open(fname)
1861 xfile = open(fname)
1868 except:
1862 except:
1869 print >> Term.cerr, \
1863 print >> Term.cerr, \
1870 'Could not open file <%s> for safe execution.' % fname
1864 'Could not open file <%s> for safe execution.' % fname
1871 return None
1865 return None
1872
1866
1873 kw.setdefault('islog',0)
1867 kw.setdefault('islog',0)
1874 kw.setdefault('quiet',1)
1868 kw.setdefault('quiet',1)
1875 kw.setdefault('exit_ignore',0)
1869 kw.setdefault('exit_ignore',0)
1876 first = xfile.readline()
1870 first = xfile.readline()
1877 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1871 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1878 xfile.close()
1872 xfile.close()
1879 # line by line execution
1873 # line by line execution
1880 if first.startswith(_LOGHEAD) or kw['islog']:
1874 if first.startswith(_LOGHEAD) or kw['islog']:
1881 print 'Loading log file <%s> one line at a time...' % fname
1875 print 'Loading log file <%s> one line at a time...' % fname
1882 if kw['quiet']:
1876 if kw['quiet']:
1883 stdout_save = sys.stdout
1877 stdout_save = sys.stdout
1884 sys.stdout = StringIO.StringIO()
1878 sys.stdout = StringIO.StringIO()
1885 try:
1879 try:
1886 globs,locs = where[0:2]
1880 globs,locs = where[0:2]
1887 except:
1881 except:
1888 try:
1882 try:
1889 globs = locs = where[0]
1883 globs = locs = where[0]
1890 except:
1884 except:
1891 globs = locs = globals()
1885 globs = locs = globals()
1892 badblocks = []
1886 badblocks = []
1893
1887
1894 # we also need to identify indented blocks of code when replaying
1888 # we also need to identify indented blocks of code when replaying
1895 # logs and put them together before passing them to an exec
1889 # logs and put them together before passing them to an exec
1896 # statement. This takes a bit of regexp and look-ahead work in the
1890 # statement. This takes a bit of regexp and look-ahead work in the
1897 # file. It's easiest if we swallow the whole thing in memory
1891 # file. It's easiest if we swallow the whole thing in memory
1898 # first, and manually walk through the lines list moving the
1892 # first, and manually walk through the lines list moving the
1899 # counter ourselves.
1893 # counter ourselves.
1900 indent_re = re.compile('\s+\S')
1894 indent_re = re.compile('\s+\S')
1901 xfile = open(fname)
1895 xfile = open(fname)
1902 filelines = xfile.readlines()
1896 filelines = xfile.readlines()
1903 xfile.close()
1897 xfile.close()
1904 nlines = len(filelines)
1898 nlines = len(filelines)
1905 lnum = 0
1899 lnum = 0
1906 while lnum < nlines:
1900 while lnum < nlines:
1907 line = filelines[lnum]
1901 line = filelines[lnum]
1908 lnum += 1
1902 lnum += 1
1909 # don't re-insert logger status info into cache
1903 # don't re-insert logger status info into cache
1910 if line.startswith('#log#'):
1904 if line.startswith('#log#'):
1911 continue
1905 continue
1912 elif line.startswith('#%s'% self.ESC_MAGIC):
1906 elif line.startswith('#%s'% self.ESC_MAGIC):
1913 self.update_cache(line[1:])
1907 self.update_cache(line[1:])
1914 line = magic2python(line)
1908 line = magic2python(line)
1915 elif line.startswith('#!'):
1909 elif line.startswith('#!'):
1916 self.update_cache(line[1:])
1910 self.update_cache(line[1:])
1917 else:
1911 else:
1918 # build a block of code (maybe a single line) for execution
1912 # build a block of code (maybe a single line) for execution
1919 block = line
1913 block = line
1920 try:
1914 try:
1921 next = filelines[lnum] # lnum has already incremented
1915 next = filelines[lnum] # lnum has already incremented
1922 except:
1916 except:
1923 next = None
1917 next = None
1924 while next and indent_re.match(next):
1918 while next and indent_re.match(next):
1925 block += next
1919 block += next
1926 lnum += 1
1920 lnum += 1
1927 try:
1921 try:
1928 next = filelines[lnum]
1922 next = filelines[lnum]
1929 except:
1923 except:
1930 next = None
1924 next = None
1931 # now execute the block of one or more lines
1925 # now execute the block of one or more lines
1932 try:
1926 try:
1933 exec block in globs,locs
1927 exec block in globs,locs
1934 self.update_cache(block.rstrip())
1928 self.update_cache(block.rstrip())
1935 except SystemExit:
1929 except SystemExit:
1936 pass
1930 pass
1937 except:
1931 except:
1938 badblocks.append(block.rstrip())
1932 badblocks.append(block.rstrip())
1939 if kw['quiet']: # restore stdout
1933 if kw['quiet']: # restore stdout
1940 sys.stdout.close()
1934 sys.stdout.close()
1941 sys.stdout = stdout_save
1935 sys.stdout = stdout_save
1942 print 'Finished replaying log file <%s>' % fname
1936 print 'Finished replaying log file <%s>' % fname
1943 if badblocks:
1937 if badblocks:
1944 print >> sys.stderr, ('\nThe following lines/blocks in file '
1938 print >> sys.stderr, ('\nThe following lines/blocks in file '
1945 '<%s> reported errors:' % fname)
1939 '<%s> reported errors:' % fname)
1946
1940
1947 for badline in badblocks:
1941 for badline in badblocks:
1948 print >> sys.stderr, badline
1942 print >> sys.stderr, badline
1949 else: # regular file execution
1943 else: # regular file execution
1950 try:
1944 try:
1951 execfile(fname,*where)
1945 execfile(fname,*where)
1952 except SyntaxError:
1946 except SyntaxError:
1953 etype, evalue = sys.exc_info()[0:2]
1947 etype, evalue = sys.exc_info()[0:2]
1954 self.SyntaxTB(etype,evalue,[])
1948 self.SyntaxTB(etype,evalue,[])
1955 warn('Failure executing file: <%s>' % fname)
1949 warn('Failure executing file: <%s>' % fname)
1956 except SystemExit,status:
1950 except SystemExit,status:
1957 if not kw['exit_ignore']:
1951 if not kw['exit_ignore']:
1958 self.InteractiveTB()
1952 self.InteractiveTB()
1959 warn('Failure executing file: <%s>' % fname)
1953 warn('Failure executing file: <%s>' % fname)
1960 except:
1954 except:
1961 self.InteractiveTB()
1955 self.InteractiveTB()
1962 warn('Failure executing file: <%s>' % fname)
1956 warn('Failure executing file: <%s>' % fname)
1963
1957
1964 #************************* end of file <iplib.py> *****************************
1958 #************************* end of file <iplib.py> *****************************
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now