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