##// END OF EJS Templates
Fernando Perez -
Show More
@@ -1,3415 +1,3418 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #*****************************************************************************
5 #*****************************************************************************
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 #****************************************************************************
13 #****************************************************************************
14 # Modules and globals
14 # Modules and globals
15
15
16 from IPython import Release
17 __author__ = '%s <%s>\n%s <%s>' % \
18 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 __license__ = Release.license
20
21 # Python standard modules
16 # Python standard modules
22 import __builtin__
17 import __builtin__
23 import bdb
18 import bdb
24 import inspect
19 import inspect
25 import os
20 import os
26 import pdb
21 import pdb
27 import pydoc
22 import pydoc
28 import sys
23 import sys
29 import re
24 import re
30 import tempfile
25 import tempfile
31 import time
26 import time
32 import cPickle as pickle
27 import cPickle as pickle
33 import textwrap
28 import textwrap
34 from cStringIO import StringIO
29 from cStringIO import StringIO
35 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
36 from pprint import pprint, pformat
31 from pprint import pprint, pformat
37 from sets import Set
32 from sets import Set
38
33
39 # cProfile was added in Python2.5
34 # cProfile was added in Python2.5
40 try:
35 try:
41 import cProfile as profile
36 import cProfile as profile
42 import pstats
37 import pstats
43 except ImportError:
38 except ImportError:
44 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
45 try:
40 try:
46 import profile,pstats
41 import profile,pstats
47 except ImportError:
42 except ImportError:
48 profile = pstats = None
43 profile = pstats = None
49
44
50 # Homebrewed
45 # Homebrewed
51 import IPython
46 import IPython
52 from IPython import Debugger, OInspect, wildcard
47 from IPython import Debugger, OInspect, wildcard
53 from IPython.FakeModule import FakeModule
48 from IPython.FakeModule import FakeModule
54 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.Itpl import Itpl, itpl, printpl,itplns
55 from IPython.PyColorize import Parser
50 from IPython.PyColorize import Parser
56 from IPython.ipstruct import Struct
51 from IPython.ipstruct import Struct
57 from IPython.macro import Macro
52 from IPython.macro import Macro
58 from IPython.genutils import *
53 from IPython.genutils import *
59 from IPython import platutils
54 from IPython import platutils
60 import IPython.generics
55 import IPython.generics
61 import IPython.ipapi
56 import IPython.ipapi
62 from IPython.ipapi import UsageError
57 from IPython.ipapi import UsageError
63 from IPython.testing import decorators as testdec
58 from IPython.testing import decorators as testdec
64
59
65 #***************************************************************************
60 #***************************************************************************
66 # Utility functions
61 # Utility functions
67 def on_off(tag):
62 def on_off(tag):
68 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
63 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
69 return ['OFF','ON'][tag]
64 return ['OFF','ON'][tag]
70
65
71 class Bunch: pass
66 class Bunch: pass
72
67
73 def compress_dhist(dh):
68 def compress_dhist(dh):
74 head, tail = dh[:-10], dh[-10:]
69 head, tail = dh[:-10], dh[-10:]
75
70
76 newhead = []
71 newhead = []
77 done = Set()
72 done = Set()
78 for h in head:
73 for h in head:
79 if h in done:
74 if h in done:
80 continue
75 continue
81 newhead.append(h)
76 newhead.append(h)
82 done.add(h)
77 done.add(h)
83
78
84 return newhead + tail
79 return newhead + tail
85
80
86
81
87 #***************************************************************************
82 #***************************************************************************
88 # Main class implementing Magic functionality
83 # Main class implementing Magic functionality
89 class Magic:
84 class Magic:
90 """Magic functions for InteractiveShell.
85 """Magic functions for InteractiveShell.
91
86
92 Shell functions which can be reached as %function_name. All magic
87 Shell functions which can be reached as %function_name. All magic
93 functions should accept a string, which they can parse for their own
88 functions should accept a string, which they can parse for their own
94 needs. This can make some functions easier to type, eg `%cd ../`
89 needs. This can make some functions easier to type, eg `%cd ../`
95 vs. `%cd("../")`
90 vs. `%cd("../")`
96
91
97 ALL definitions MUST begin with the prefix magic_. The user won't need it
92 ALL definitions MUST begin with the prefix magic_. The user won't need it
98 at the command line, but it is is needed in the definition. """
93 at the command line, but it is is needed in the definition. """
99
94
100 # class globals
95 # class globals
101 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
96 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
102 'Automagic is ON, % prefix NOT needed for magic functions.']
97 'Automagic is ON, % prefix NOT needed for magic functions.']
103
98
104 #......................................................................
99 #......................................................................
105 # some utility functions
100 # some utility functions
106
101
107 def __init__(self,shell):
102 def __init__(self,shell):
108
103
109 self.options_table = {}
104 self.options_table = {}
110 if profile is None:
105 if profile is None:
111 self.magic_prun = self.profile_missing_notice
106 self.magic_prun = self.profile_missing_notice
112 self.shell = shell
107 self.shell = shell
113
108
114 # namespace for holding state we may need
109 # namespace for holding state we may need
115 self._magic_state = Bunch()
110 self._magic_state = Bunch()
116
111
117 def profile_missing_notice(self, *args, **kwargs):
112 def profile_missing_notice(self, *args, **kwargs):
118 error("""\
113 error("""\
119 The profile module could not be found. It has been removed from the standard
114 The profile module could not be found. It has been removed from the standard
120 python packages because of its non-free license. To use profiling, install the
115 python packages because of its non-free license. To use profiling, install the
121 python-profiler package from non-free.""")
116 python-profiler package from non-free.""")
122
117
123 def default_option(self,fn,optstr):
118 def default_option(self,fn,optstr):
124 """Make an entry in the options_table for fn, with value optstr"""
119 """Make an entry in the options_table for fn, with value optstr"""
125
120
126 if fn not in self.lsmagic():
121 if fn not in self.lsmagic():
127 error("%s is not a magic function" % fn)
122 error("%s is not a magic function" % fn)
128 self.options_table[fn] = optstr
123 self.options_table[fn] = optstr
129
124
130 def lsmagic(self):
125 def lsmagic(self):
131 """Return a list of currently available magic functions.
126 """Return a list of currently available magic functions.
132
127
133 Gives a list of the bare names after mangling (['ls','cd', ...], not
128 Gives a list of the bare names after mangling (['ls','cd', ...], not
134 ['magic_ls','magic_cd',...]"""
129 ['magic_ls','magic_cd',...]"""
135
130
136 # FIXME. This needs a cleanup, in the way the magics list is built.
131 # FIXME. This needs a cleanup, in the way the magics list is built.
137
132
138 # magics in class definition
133 # magics in class definition
139 class_magic = lambda fn: fn.startswith('magic_') and \
134 class_magic = lambda fn: fn.startswith('magic_') and \
140 callable(Magic.__dict__[fn])
135 callable(Magic.__dict__[fn])
141 # in instance namespace (run-time user additions)
136 # in instance namespace (run-time user additions)
142 inst_magic = lambda fn: fn.startswith('magic_') and \
137 inst_magic = lambda fn: fn.startswith('magic_') and \
143 callable(self.__dict__[fn])
138 callable(self.__dict__[fn])
144 # and bound magics by user (so they can access self):
139 # and bound magics by user (so they can access self):
145 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
140 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
146 callable(self.__class__.__dict__[fn])
141 callable(self.__class__.__dict__[fn])
147 magics = filter(class_magic,Magic.__dict__.keys()) + \
142 magics = filter(class_magic,Magic.__dict__.keys()) + \
148 filter(inst_magic,self.__dict__.keys()) + \
143 filter(inst_magic,self.__dict__.keys()) + \
149 filter(inst_bound_magic,self.__class__.__dict__.keys())
144 filter(inst_bound_magic,self.__class__.__dict__.keys())
150 out = []
145 out = []
151 for fn in Set(magics):
146 for fn in Set(magics):
152 out.append(fn.replace('magic_','',1))
147 out.append(fn.replace('magic_','',1))
153 out.sort()
148 out.sort()
154 return out
149 return out
155
150
156 def extract_input_slices(self,slices,raw=False):
151 def extract_input_slices(self,slices,raw=False):
157 """Return as a string a set of input history slices.
152 """Return as a string a set of input history slices.
158
153
159 Inputs:
154 Inputs:
160
155
161 - slices: the set of slices is given as a list of strings (like
156 - slices: the set of slices is given as a list of strings (like
162 ['1','4:8','9'], since this function is for use by magic functions
157 ['1','4:8','9'], since this function is for use by magic functions
163 which get their arguments as strings.
158 which get their arguments as strings.
164
159
165 Optional inputs:
160 Optional inputs:
166
161
167 - raw(False): by default, the processed input is used. If this is
162 - raw(False): by default, the processed input is used. If this is
168 true, the raw input history is used instead.
163 true, the raw input history is used instead.
169
164
170 Note that slices can be called with two notations:
165 Note that slices can be called with two notations:
171
166
172 N:M -> standard python form, means including items N...(M-1).
167 N:M -> standard python form, means including items N...(M-1).
173
168
174 N-M -> include items N..M (closed endpoint)."""
169 N-M -> include items N..M (closed endpoint)."""
175
170
176 if raw:
171 if raw:
177 hist = self.shell.input_hist_raw
172 hist = self.shell.input_hist_raw
178 else:
173 else:
179 hist = self.shell.input_hist
174 hist = self.shell.input_hist
180
175
181 cmds = []
176 cmds = []
182 for chunk in slices:
177 for chunk in slices:
183 if ':' in chunk:
178 if ':' in chunk:
184 ini,fin = map(int,chunk.split(':'))
179 ini,fin = map(int,chunk.split(':'))
185 elif '-' in chunk:
180 elif '-' in chunk:
186 ini,fin = map(int,chunk.split('-'))
181 ini,fin = map(int,chunk.split('-'))
187 fin += 1
182 fin += 1
188 else:
183 else:
189 ini = int(chunk)
184 ini = int(chunk)
190 fin = ini+1
185 fin = ini+1
191 cmds.append(hist[ini:fin])
186 cmds.append(hist[ini:fin])
192 return cmds
187 return cmds
193
188
194 def _ofind(self, oname, namespaces=None):
189 def _ofind(self, oname, namespaces=None):
195 """Find an object in the available namespaces.
190 """Find an object in the available namespaces.
196
191
197 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
192 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
198
193
199 Has special code to detect magic functions.
194 Has special code to detect magic functions.
200 """
195 """
201
196
202 oname = oname.strip()
197 oname = oname.strip()
203
198
204 alias_ns = None
199 alias_ns = None
205 if namespaces is None:
200 if namespaces is None:
206 # Namespaces to search in:
201 # Namespaces to search in:
207 # Put them in a list. The order is important so that we
202 # Put them in a list. The order is important so that we
208 # find things in the same order that Python finds them.
203 # find things in the same order that Python finds them.
209 namespaces = [ ('Interactive', self.shell.user_ns),
204 namespaces = [ ('Interactive', self.shell.user_ns),
210 ('IPython internal', self.shell.internal_ns),
205 ('IPython internal', self.shell.internal_ns),
211 ('Python builtin', __builtin__.__dict__),
206 ('Python builtin', __builtin__.__dict__),
212 ('Alias', self.shell.alias_table),
207 ('Alias', self.shell.alias_table),
213 ]
208 ]
214 alias_ns = self.shell.alias_table
209 alias_ns = self.shell.alias_table
215
210
216 # initialize results to 'null'
211 # initialize results to 'null'
217 found = 0; obj = None; ospace = None; ds = None;
212 found = 0; obj = None; ospace = None; ds = None;
218 ismagic = 0; isalias = 0; parent = None
213 ismagic = 0; isalias = 0; parent = None
219
214
220 # Look for the given name by splitting it in parts. If the head is
215 # Look for the given name by splitting it in parts. If the head is
221 # found, then we look for all the remaining parts as members, and only
216 # found, then we look for all the remaining parts as members, and only
222 # declare success if we can find them all.
217 # declare success if we can find them all.
223 oname_parts = oname.split('.')
218 oname_parts = oname.split('.')
224 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
219 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
225 for nsname,ns in namespaces:
220 for nsname,ns in namespaces:
226 try:
221 try:
227 obj = ns[oname_head]
222 obj = ns[oname_head]
228 except KeyError:
223 except KeyError:
229 continue
224 continue
230 else:
225 else:
231 #print 'oname_rest:', oname_rest # dbg
226 #print 'oname_rest:', oname_rest # dbg
232 for part in oname_rest:
227 for part in oname_rest:
233 try:
228 try:
234 parent = obj
229 parent = obj
235 obj = getattr(obj,part)
230 obj = getattr(obj,part)
236 except:
231 except:
237 # Blanket except b/c some badly implemented objects
232 # Blanket except b/c some badly implemented objects
238 # allow __getattr__ to raise exceptions other than
233 # allow __getattr__ to raise exceptions other than
239 # AttributeError, which then crashes IPython.
234 # AttributeError, which then crashes IPython.
240 break
235 break
241 else:
236 else:
242 # If we finish the for loop (no break), we got all members
237 # If we finish the for loop (no break), we got all members
243 found = 1
238 found = 1
244 ospace = nsname
239 ospace = nsname
245 if ns == alias_ns:
240 if ns == alias_ns:
246 isalias = 1
241 isalias = 1
247 break # namespace loop
242 break # namespace loop
248
243
249 # Try to see if it's magic
244 # Try to see if it's magic
250 if not found:
245 if not found:
251 if oname.startswith(self.shell.ESC_MAGIC):
246 if oname.startswith(self.shell.ESC_MAGIC):
252 oname = oname[1:]
247 oname = oname[1:]
253 obj = getattr(self,'magic_'+oname,None)
248 obj = getattr(self,'magic_'+oname,None)
254 if obj is not None:
249 if obj is not None:
255 found = 1
250 found = 1
256 ospace = 'IPython internal'
251 ospace = 'IPython internal'
257 ismagic = 1
252 ismagic = 1
258
253
259 # Last try: special-case some literals like '', [], {}, etc:
254 # Last try: special-case some literals like '', [], {}, etc:
260 if not found and oname_head in ["''",'""','[]','{}','()']:
255 if not found and oname_head in ["''",'""','[]','{}','()']:
261 obj = eval(oname_head)
256 obj = eval(oname_head)
262 found = 1
257 found = 1
263 ospace = 'Interactive'
258 ospace = 'Interactive'
264
259
265 return {'found':found, 'obj':obj, 'namespace':ospace,
260 return {'found':found, 'obj':obj, 'namespace':ospace,
266 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
261 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
267
262
268 def arg_err(self,func):
263 def arg_err(self,func):
269 """Print docstring if incorrect arguments were passed"""
264 """Print docstring if incorrect arguments were passed"""
270 print 'Error in arguments:'
265 print 'Error in arguments:'
271 print OInspect.getdoc(func)
266 print OInspect.getdoc(func)
272
267
273 def format_latex(self,strng):
268 def format_latex(self,strng):
274 """Format a string for latex inclusion."""
269 """Format a string for latex inclusion."""
275
270
276 # Characters that need to be escaped for latex:
271 # Characters that need to be escaped for latex:
277 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
272 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
278 # Magic command names as headers:
273 # Magic command names as headers:
279 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
274 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
280 re.MULTILINE)
275 re.MULTILINE)
281 # Magic commands
276 # Magic commands
282 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
277 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
283 re.MULTILINE)
278 re.MULTILINE)
284 # Paragraph continue
279 # Paragraph continue
285 par_re = re.compile(r'\\$',re.MULTILINE)
280 par_re = re.compile(r'\\$',re.MULTILINE)
286
281
287 # The "\n" symbol
282 # The "\n" symbol
288 newline_re = re.compile(r'\\n')
283 newline_re = re.compile(r'\\n')
289
284
290 # Now build the string for output:
285 # Now build the string for output:
291 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
286 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
292 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
287 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
293 strng)
288 strng)
294 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
289 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
295 strng = par_re.sub(r'\\\\',strng)
290 strng = par_re.sub(r'\\\\',strng)
296 strng = escape_re.sub(r'\\\1',strng)
291 strng = escape_re.sub(r'\\\1',strng)
297 strng = newline_re.sub(r'\\textbackslash{}n',strng)
292 strng = newline_re.sub(r'\\textbackslash{}n',strng)
298 return strng
293 return strng
299
294
300 def format_screen(self,strng):
295 def format_screen(self,strng):
301 """Format a string for screen printing.
296 """Format a string for screen printing.
302
297
303 This removes some latex-type format codes."""
298 This removes some latex-type format codes."""
304 # Paragraph continue
299 # Paragraph continue
305 par_re = re.compile(r'\\$',re.MULTILINE)
300 par_re = re.compile(r'\\$',re.MULTILINE)
306 strng = par_re.sub('',strng)
301 strng = par_re.sub('',strng)
307 return strng
302 return strng
308
303
309 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
304 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
310 """Parse options passed to an argument string.
305 """Parse options passed to an argument string.
311
306
312 The interface is similar to that of getopt(), but it returns back a
307 The interface is similar to that of getopt(), but it returns back a
313 Struct with the options as keys and the stripped argument string still
308 Struct with the options as keys and the stripped argument string still
314 as a string.
309 as a string.
315
310
316 arg_str is quoted as a true sys.argv vector by using shlex.split.
311 arg_str is quoted as a true sys.argv vector by using shlex.split.
317 This allows us to easily expand variables, glob files, quote
312 This allows us to easily expand variables, glob files, quote
318 arguments, etc.
313 arguments, etc.
319
314
320 Options:
315 Options:
321 -mode: default 'string'. If given as 'list', the argument string is
316 -mode: default 'string'. If given as 'list', the argument string is
322 returned as a list (split on whitespace) instead of a string.
317 returned as a list (split on whitespace) instead of a string.
323
318
324 -list_all: put all option values in lists. Normally only options
319 -list_all: put all option values in lists. Normally only options
325 appearing more than once are put in a list.
320 appearing more than once are put in a list.
326
321
327 -posix (True): whether to split the input line in POSIX mode or not,
322 -posix (True): whether to split the input line in POSIX mode or not,
328 as per the conventions outlined in the shlex module from the
323 as per the conventions outlined in the shlex module from the
329 standard library."""
324 standard library."""
330
325
331 # inject default options at the beginning of the input line
326 # inject default options at the beginning of the input line
332 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
327 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
333 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
328 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
334
329
335 mode = kw.get('mode','string')
330 mode = kw.get('mode','string')
336 if mode not in ['string','list']:
331 if mode not in ['string','list']:
337 raise ValueError,'incorrect mode given: %s' % mode
332 raise ValueError,'incorrect mode given: %s' % mode
338 # Get options
333 # Get options
339 list_all = kw.get('list_all',0)
334 list_all = kw.get('list_all',0)
340 posix = kw.get('posix',True)
335 posix = kw.get('posix',True)
341
336
342 # Check if we have more than one argument to warrant extra processing:
337 # Check if we have more than one argument to warrant extra processing:
343 odict = {} # Dictionary with options
338 odict = {} # Dictionary with options
344 args = arg_str.split()
339 args = arg_str.split()
345 if len(args) >= 1:
340 if len(args) >= 1:
346 # If the list of inputs only has 0 or 1 thing in it, there's no
341 # If the list of inputs only has 0 or 1 thing in it, there's no
347 # need to look for options
342 # need to look for options
348 argv = arg_split(arg_str,posix)
343 argv = arg_split(arg_str,posix)
349 # Do regular option processing
344 # Do regular option processing
350 try:
345 try:
351 opts,args = getopt(argv,opt_str,*long_opts)
346 opts,args = getopt(argv,opt_str,*long_opts)
352 except GetoptError,e:
347 except GetoptError,e:
353 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
348 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
354 " ".join(long_opts)))
349 " ".join(long_opts)))
355 for o,a in opts:
350 for o,a in opts:
356 if o.startswith('--'):
351 if o.startswith('--'):
357 o = o[2:]
352 o = o[2:]
358 else:
353 else:
359 o = o[1:]
354 o = o[1:]
360 try:
355 try:
361 odict[o].append(a)
356 odict[o].append(a)
362 except AttributeError:
357 except AttributeError:
363 odict[o] = [odict[o],a]
358 odict[o] = [odict[o],a]
364 except KeyError:
359 except KeyError:
365 if list_all:
360 if list_all:
366 odict[o] = [a]
361 odict[o] = [a]
367 else:
362 else:
368 odict[o] = a
363 odict[o] = a
369
364
370 # Prepare opts,args for return
365 # Prepare opts,args for return
371 opts = Struct(odict)
366 opts = Struct(odict)
372 if mode == 'string':
367 if mode == 'string':
373 args = ' '.join(args)
368 args = ' '.join(args)
374
369
375 return opts,args
370 return opts,args
376
371
377 #......................................................................
372 #......................................................................
378 # And now the actual magic functions
373 # And now the actual magic functions
379
374
380 # Functions for IPython shell work (vars,funcs, config, etc)
375 # Functions for IPython shell work (vars,funcs, config, etc)
381 def magic_lsmagic(self, parameter_s = ''):
376 def magic_lsmagic(self, parameter_s = ''):
382 """List currently available magic functions."""
377 """List currently available magic functions."""
383 mesc = self.shell.ESC_MAGIC
378 mesc = self.shell.ESC_MAGIC
384 print 'Available magic functions:\n'+mesc+\
379 print 'Available magic functions:\n'+mesc+\
385 (' '+mesc).join(self.lsmagic())
380 (' '+mesc).join(self.lsmagic())
386 print '\n' + Magic.auto_status[self.shell.rc.automagic]
381 print '\n' + Magic.auto_status[self.shell.rc.automagic]
387 return None
382 return None
388
383
389 def magic_magic(self, parameter_s = ''):
384 def magic_magic(self, parameter_s = ''):
390 """Print information about the magic function system.
385 """Print information about the magic function system.
391
386
392 Supported formats: -latex, -brief, -rest
387 Supported formats: -latex, -brief, -rest
393 """
388 """
394
389
395 mode = ''
390 mode = ''
396 try:
391 try:
397 if parameter_s.split()[0] == '-latex':
392 if parameter_s.split()[0] == '-latex':
398 mode = 'latex'
393 mode = 'latex'
399 if parameter_s.split()[0] == '-brief':
394 if parameter_s.split()[0] == '-brief':
400 mode = 'brief'
395 mode = 'brief'
401 if parameter_s.split()[0] == '-rest':
396 if parameter_s.split()[0] == '-rest':
402 mode = 'rest'
397 mode = 'rest'
403 rest_docs = []
398 rest_docs = []
404 except:
399 except:
405 pass
400 pass
406
401
407 magic_docs = []
402 magic_docs = []
408 for fname in self.lsmagic():
403 for fname in self.lsmagic():
409 mname = 'magic_' + fname
404 mname = 'magic_' + fname
410 for space in (Magic,self,self.__class__):
405 for space in (Magic,self,self.__class__):
411 try:
406 try:
412 fn = space.__dict__[mname]
407 fn = space.__dict__[mname]
413 except KeyError:
408 except KeyError:
414 pass
409 pass
415 else:
410 else:
416 break
411 break
417 if mode == 'brief':
412 if mode == 'brief':
418 # only first line
413 # only first line
419 if fn.__doc__:
414 if fn.__doc__:
420 fndoc = fn.__doc__.split('\n',1)[0]
415 fndoc = fn.__doc__.split('\n',1)[0]
421 else:
416 else:
422 fndoc = 'No documentation'
417 fndoc = 'No documentation'
423 else:
418 else:
424 fndoc = fn.__doc__.rstrip()
419 fndoc = fn.__doc__.rstrip()
425
420
426 if mode == 'rest':
421 if mode == 'rest':
427 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
422 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
428 fname,fndoc))
423 fname,fndoc))
429
424
430 else:
425 else:
431 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
426 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
432 fname,fndoc))
427 fname,fndoc))
433
428
434 magic_docs = ''.join(magic_docs)
429 magic_docs = ''.join(magic_docs)
435
430
436 if mode == 'rest':
431 if mode == 'rest':
437 return "".join(rest_docs)
432 return "".join(rest_docs)
438
433
439 if mode == 'latex':
434 if mode == 'latex':
440 print self.format_latex(magic_docs)
435 print self.format_latex(magic_docs)
441 return
436 return
442 else:
437 else:
443 magic_docs = self.format_screen(magic_docs)
438 magic_docs = self.format_screen(magic_docs)
444 if mode == 'brief':
439 if mode == 'brief':
445 return magic_docs
440 return magic_docs
446
441
447 outmsg = """
442 outmsg = """
448 IPython's 'magic' functions
443 IPython's 'magic' functions
449 ===========================
444 ===========================
450
445
451 The magic function system provides a series of functions which allow you to
446 The magic function system provides a series of functions which allow you to
452 control the behavior of IPython itself, plus a lot of system-type
447 control the behavior of IPython itself, plus a lot of system-type
453 features. All these functions are prefixed with a % character, but parameters
448 features. All these functions are prefixed with a % character, but parameters
454 are given without parentheses or quotes.
449 are given without parentheses or quotes.
455
450
456 NOTE: If you have 'automagic' enabled (via the command line option or with the
451 NOTE: If you have 'automagic' enabled (via the command line option or with the
457 %automagic function), you don't need to type in the % explicitly. By default,
452 %automagic function), you don't need to type in the % explicitly. By default,
458 IPython ships with automagic on, so you should only rarely need the % escape.
453 IPython ships with automagic on, so you should only rarely need the % escape.
459
454
460 Example: typing '%cd mydir' (without the quotes) changes you working directory
455 Example: typing '%cd mydir' (without the quotes) changes you working directory
461 to 'mydir', if it exists.
456 to 'mydir', if it exists.
462
457
463 You can define your own magic functions to extend the system. See the supplied
458 You can define your own magic functions to extend the system. See the supplied
464 ipythonrc and example-magic.py files for details (in your ipython
459 ipythonrc and example-magic.py files for details (in your ipython
465 configuration directory, typically $HOME/.ipython/).
460 configuration directory, typically $HOME/.ipython/).
466
461
467 You can also define your own aliased names for magic functions. In your
462 You can also define your own aliased names for magic functions. In your
468 ipythonrc file, placing a line like:
463 ipythonrc file, placing a line like:
469
464
470 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
465 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
471
466
472 will define %pf as a new name for %profile.
467 will define %pf as a new name for %profile.
473
468
474 You can also call magics in code using the ipmagic() function, which IPython
469 You can also call magics in code using the ipmagic() function, which IPython
475 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
470 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
476
471
477 For a list of the available magic functions, use %lsmagic. For a description
472 For a list of the available magic functions, use %lsmagic. For a description
478 of any of them, type %magic_name?, e.g. '%cd?'.
473 of any of them, type %magic_name?, e.g. '%cd?'.
479
474
480 Currently the magic system has the following functions:\n"""
475 Currently the magic system has the following functions:\n"""
481
476
482 mesc = self.shell.ESC_MAGIC
477 mesc = self.shell.ESC_MAGIC
483 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
478 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
484 "\n\n%s%s\n\n%s" % (outmsg,
479 "\n\n%s%s\n\n%s" % (outmsg,
485 magic_docs,mesc,mesc,
480 magic_docs,mesc,mesc,
486 (' '+mesc).join(self.lsmagic()),
481 (' '+mesc).join(self.lsmagic()),
487 Magic.auto_status[self.shell.rc.automagic] ) )
482 Magic.auto_status[self.shell.rc.automagic] ) )
488
483
489 page(outmsg,screen_lines=self.shell.rc.screen_length)
484 page(outmsg,screen_lines=self.shell.rc.screen_length)
490
485
491
486
492 def magic_autoindent(self, parameter_s = ''):
487 def magic_autoindent(self, parameter_s = ''):
493 """Toggle autoindent on/off (if available)."""
488 """Toggle autoindent on/off (if available)."""
494
489
495 self.shell.set_autoindent()
490 self.shell.set_autoindent()
496 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
491 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
497
492
498
493
499 def magic_automagic(self, parameter_s = ''):
494 def magic_automagic(self, parameter_s = ''):
500 """Make magic functions callable without having to type the initial %.
495 """Make magic functions callable without having to type the initial %.
501
496
502 Without argumentsl toggles on/off (when off, you must call it as
497 Without argumentsl toggles on/off (when off, you must call it as
503 %automagic, of course). With arguments it sets the value, and you can
498 %automagic, of course). With arguments it sets the value, and you can
504 use any of (case insensitive):
499 use any of (case insensitive):
505
500
506 - on,1,True: to activate
501 - on,1,True: to activate
507
502
508 - off,0,False: to deactivate.
503 - off,0,False: to deactivate.
509
504
510 Note that magic functions have lowest priority, so if there's a
505 Note that magic functions have lowest priority, so if there's a
511 variable whose name collides with that of a magic fn, automagic won't
506 variable whose name collides with that of a magic fn, automagic won't
512 work for that function (you get the variable instead). However, if you
507 work for that function (you get the variable instead). However, if you
513 delete the variable (del var), the previously shadowed magic function
508 delete the variable (del var), the previously shadowed magic function
514 becomes visible to automagic again."""
509 becomes visible to automagic again."""
515
510
516 rc = self.shell.rc
511 rc = self.shell.rc
517 arg = parameter_s.lower()
512 arg = parameter_s.lower()
518 if parameter_s in ('on','1','true'):
513 if parameter_s in ('on','1','true'):
519 rc.automagic = True
514 rc.automagic = True
520 elif parameter_s in ('off','0','false'):
515 elif parameter_s in ('off','0','false'):
521 rc.automagic = False
516 rc.automagic = False
522 else:
517 else:
523 rc.automagic = not rc.automagic
518 rc.automagic = not rc.automagic
524 print '\n' + Magic.auto_status[rc.automagic]
519 print '\n' + Magic.auto_status[rc.automagic]
525
520
526 @testdec.skip_doctest
521 @testdec.skip_doctest
527 def magic_autocall(self, parameter_s = ''):
522 def magic_autocall(self, parameter_s = ''):
528 """Make functions callable without having to type parentheses.
523 """Make functions callable without having to type parentheses.
529
524
530 Usage:
525 Usage:
531
526
532 %autocall [mode]
527 %autocall [mode]
533
528
534 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
529 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
535 value is toggled on and off (remembering the previous state).
530 value is toggled on and off (remembering the previous state).
536
531
537 In more detail, these values mean:
532 In more detail, these values mean:
538
533
539 0 -> fully disabled
534 0 -> fully disabled
540
535
541 1 -> active, but do not apply if there are no arguments on the line.
536 1 -> active, but do not apply if there are no arguments on the line.
542
537
543 In this mode, you get:
538 In this mode, you get:
544
539
545 In [1]: callable
540 In [1]: callable
546 Out[1]: <built-in function callable>
541 Out[1]: <built-in function callable>
547
542
548 In [2]: callable 'hello'
543 In [2]: callable 'hello'
549 ------> callable('hello')
544 ------> callable('hello')
550 Out[2]: False
545 Out[2]: False
551
546
552 2 -> Active always. Even if no arguments are present, the callable
547 2 -> Active always. Even if no arguments are present, the callable
553 object is called:
548 object is called:
554
549
555 In [2]: float
550 In [2]: float
556 ------> float()
551 ------> float()
557 Out[2]: 0.0
552 Out[2]: 0.0
558
553
559 Note that even with autocall off, you can still use '/' at the start of
554 Note that even with autocall off, you can still use '/' at the start of
560 a line to treat the first argument on the command line as a function
555 a line to treat the first argument on the command line as a function
561 and add parentheses to it:
556 and add parentheses to it:
562
557
563 In [8]: /str 43
558 In [8]: /str 43
564 ------> str(43)
559 ------> str(43)
565 Out[8]: '43'
560 Out[8]: '43'
566
561
567 # all-random (note for auto-testing)
562 # all-random (note for auto-testing)
568 """
563 """
569
564
570 rc = self.shell.rc
565 rc = self.shell.rc
571
566
572 if parameter_s:
567 if parameter_s:
573 arg = int(parameter_s)
568 arg = int(parameter_s)
574 else:
569 else:
575 arg = 'toggle'
570 arg = 'toggle'
576
571
577 if not arg in (0,1,2,'toggle'):
572 if not arg in (0,1,2,'toggle'):
578 error('Valid modes: (0->Off, 1->Smart, 2->Full')
573 error('Valid modes: (0->Off, 1->Smart, 2->Full')
579 return
574 return
580
575
581 if arg in (0,1,2):
576 if arg in (0,1,2):
582 rc.autocall = arg
577 rc.autocall = arg
583 else: # toggle
578 else: # toggle
584 if rc.autocall:
579 if rc.autocall:
585 self._magic_state.autocall_save = rc.autocall
580 self._magic_state.autocall_save = rc.autocall
586 rc.autocall = 0
581 rc.autocall = 0
587 else:
582 else:
588 try:
583 try:
589 rc.autocall = self._magic_state.autocall_save
584 rc.autocall = self._magic_state.autocall_save
590 except AttributeError:
585 except AttributeError:
591 rc.autocall = self._magic_state.autocall_save = 1
586 rc.autocall = self._magic_state.autocall_save = 1
592
587
593 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
588 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
594
589
595 def magic_system_verbose(self, parameter_s = ''):
590 def magic_system_verbose(self, parameter_s = ''):
596 """Set verbose printing of system calls.
591 """Set verbose printing of system calls.
597
592
598 If called without an argument, act as a toggle"""
593 If called without an argument, act as a toggle"""
599
594
600 if parameter_s:
595 if parameter_s:
601 val = bool(eval(parameter_s))
596 val = bool(eval(parameter_s))
602 else:
597 else:
603 val = None
598 val = None
604
599
605 self.shell.rc_set_toggle('system_verbose',val)
600 self.shell.rc_set_toggle('system_verbose',val)
606 print "System verbose printing is:",\
601 print "System verbose printing is:",\
607 ['OFF','ON'][self.shell.rc.system_verbose]
602 ['OFF','ON'][self.shell.rc.system_verbose]
608
603
609
604
610 def magic_page(self, parameter_s=''):
605 def magic_page(self, parameter_s=''):
611 """Pretty print the object and display it through a pager.
606 """Pretty print the object and display it through a pager.
612
607
613 %page [options] OBJECT
608 %page [options] OBJECT
614
609
615 If no object is given, use _ (last output).
610 If no object is given, use _ (last output).
616
611
617 Options:
612 Options:
618
613
619 -r: page str(object), don't pretty-print it."""
614 -r: page str(object), don't pretty-print it."""
620
615
621 # After a function contributed by Olivier Aubert, slightly modified.
616 # After a function contributed by Olivier Aubert, slightly modified.
622
617
623 # Process options/args
618 # Process options/args
624 opts,args = self.parse_options(parameter_s,'r')
619 opts,args = self.parse_options(parameter_s,'r')
625 raw = 'r' in opts
620 raw = 'r' in opts
626
621
627 oname = args and args or '_'
622 oname = args and args or '_'
628 info = self._ofind(oname)
623 info = self._ofind(oname)
629 if info['found']:
624 if info['found']:
630 txt = (raw and str or pformat)( info['obj'] )
625 txt = (raw and str or pformat)( info['obj'] )
631 page(txt)
626 page(txt)
632 else:
627 else:
633 print 'Object `%s` not found' % oname
628 print 'Object `%s` not found' % oname
634
629
635 def magic_profile(self, parameter_s=''):
630 def magic_profile(self, parameter_s=''):
636 """Print your currently active IPyhton profile."""
631 """Print your currently active IPyhton profile."""
637 if self.shell.rc.profile:
632 if self.shell.rc.profile:
638 printpl('Current IPython profile: $self.shell.rc.profile.')
633 printpl('Current IPython profile: $self.shell.rc.profile.')
639 else:
634 else:
640 print 'No profile active.'
635 print 'No profile active.'
641
636
642 def magic_pinfo(self, parameter_s='', namespaces=None):
637 def magic_pinfo(self, parameter_s='', namespaces=None):
643 """Provide detailed information about an object.
638 """Provide detailed information about an object.
644
639
645 '%pinfo object' is just a synonym for object? or ?object."""
640 '%pinfo object' is just a synonym for object? or ?object."""
646
641
647 #print 'pinfo par: <%s>' % parameter_s # dbg
642 #print 'pinfo par: <%s>' % parameter_s # dbg
648
643
649
644
650 # detail_level: 0 -> obj? , 1 -> obj??
645 # detail_level: 0 -> obj? , 1 -> obj??
651 detail_level = 0
646 detail_level = 0
652 # We need to detect if we got called as 'pinfo pinfo foo', which can
647 # We need to detect if we got called as 'pinfo pinfo foo', which can
653 # happen if the user types 'pinfo foo?' at the cmd line.
648 # happen if the user types 'pinfo foo?' at the cmd line.
654 pinfo,qmark1,oname,qmark2 = \
649 pinfo,qmark1,oname,qmark2 = \
655 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
650 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
656 if pinfo or qmark1 or qmark2:
651 if pinfo or qmark1 or qmark2:
657 detail_level = 1
652 detail_level = 1
658 if "*" in oname:
653 if "*" in oname:
659 self.magic_psearch(oname)
654 self.magic_psearch(oname)
660 else:
655 else:
661 self._inspect('pinfo', oname, detail_level=detail_level,
656 self._inspect('pinfo', oname, detail_level=detail_level,
662 namespaces=namespaces)
657 namespaces=namespaces)
663
658
664 def magic_pdef(self, parameter_s='', namespaces=None):
659 def magic_pdef(self, parameter_s='', namespaces=None):
665 """Print the definition header for any callable object.
660 """Print the definition header for any callable object.
666
661
667 If the object is a class, print the constructor information."""
662 If the object is a class, print the constructor information."""
668 self._inspect('pdef',parameter_s, namespaces)
663 self._inspect('pdef',parameter_s, namespaces)
669
664
670 def magic_pdoc(self, parameter_s='', namespaces=None):
665 def magic_pdoc(self, parameter_s='', namespaces=None):
671 """Print the docstring for an object.
666 """Print the docstring for an object.
672
667
673 If the given object is a class, it will print both the class and the
668 If the given object is a class, it will print both the class and the
674 constructor docstrings."""
669 constructor docstrings."""
675 self._inspect('pdoc',parameter_s, namespaces)
670 self._inspect('pdoc',parameter_s, namespaces)
676
671
677 def magic_psource(self, parameter_s='', namespaces=None):
672 def magic_psource(self, parameter_s='', namespaces=None):
678 """Print (or run through pager) the source code for an object."""
673 """Print (or run through pager) the source code for an object."""
679 self._inspect('psource',parameter_s, namespaces)
674 self._inspect('psource',parameter_s, namespaces)
680
675
681 def magic_pfile(self, parameter_s=''):
676 def magic_pfile(self, parameter_s=''):
682 """Print (or run through pager) the file where an object is defined.
677 """Print (or run through pager) the file where an object is defined.
683
678
684 The file opens at the line where the object definition begins. IPython
679 The file opens at the line where the object definition begins. IPython
685 will honor the environment variable PAGER if set, and otherwise will
680 will honor the environment variable PAGER if set, and otherwise will
686 do its best to print the file in a convenient form.
681 do its best to print the file in a convenient form.
687
682
688 If the given argument is not an object currently defined, IPython will
683 If the given argument is not an object currently defined, IPython will
689 try to interpret it as a filename (automatically adding a .py extension
684 try to interpret it as a filename (automatically adding a .py extension
690 if needed). You can thus use %pfile as a syntax highlighting code
685 if needed). You can thus use %pfile as a syntax highlighting code
691 viewer."""
686 viewer."""
692
687
693 # first interpret argument as an object name
688 # first interpret argument as an object name
694 out = self._inspect('pfile',parameter_s)
689 out = self._inspect('pfile',parameter_s)
695 # if not, try the input as a filename
690 # if not, try the input as a filename
696 if out == 'not found':
691 if out == 'not found':
697 try:
692 try:
698 filename = get_py_filename(parameter_s)
693 filename = get_py_filename(parameter_s)
699 except IOError,msg:
694 except IOError,msg:
700 print msg
695 print msg
701 return
696 return
702 page(self.shell.inspector.format(file(filename).read()))
697 page(self.shell.inspector.format(file(filename).read()))
703
698
704 def _inspect(self,meth,oname,namespaces=None,**kw):
699 def _inspect(self,meth,oname,namespaces=None,**kw):
705 """Generic interface to the inspector system.
700 """Generic interface to the inspector system.
706
701
707 This function is meant to be called by pdef, pdoc & friends."""
702 This function is meant to be called by pdef, pdoc & friends."""
708
703
709 #oname = oname.strip()
704 #oname = oname.strip()
710 #print '1- oname: <%r>' % oname # dbg
705 #print '1- oname: <%r>' % oname # dbg
711 try:
706 try:
712 oname = oname.strip().encode('ascii')
707 oname = oname.strip().encode('ascii')
713 #print '2- oname: <%r>' % oname # dbg
708 #print '2- oname: <%r>' % oname # dbg
714 except UnicodeEncodeError:
709 except UnicodeEncodeError:
715 print 'Python identifiers can only contain ascii characters.'
710 print 'Python identifiers can only contain ascii characters.'
716 return 'not found'
711 return 'not found'
717
712
718 info = Struct(self._ofind(oname, namespaces))
713 info = Struct(self._ofind(oname, namespaces))
719
714
720 if info.found:
715 if info.found:
721 try:
716 try:
722 IPython.generics.inspect_object(info.obj)
717 IPython.generics.inspect_object(info.obj)
723 return
718 return
724 except IPython.ipapi.TryNext:
719 except IPython.ipapi.TryNext:
725 pass
720 pass
726 # Get the docstring of the class property if it exists.
721 # Get the docstring of the class property if it exists.
727 path = oname.split('.')
722 path = oname.split('.')
728 root = '.'.join(path[:-1])
723 root = '.'.join(path[:-1])
729 if info.parent is not None:
724 if info.parent is not None:
730 try:
725 try:
731 target = getattr(info.parent, '__class__')
726 target = getattr(info.parent, '__class__')
732 # The object belongs to a class instance.
727 # The object belongs to a class instance.
733 try:
728 try:
734 target = getattr(target, path[-1])
729 target = getattr(target, path[-1])
735 # The class defines the object.
730 # The class defines the object.
736 if isinstance(target, property):
731 if isinstance(target, property):
737 oname = root + '.__class__.' + path[-1]
732 oname = root + '.__class__.' + path[-1]
738 info = Struct(self._ofind(oname))
733 info = Struct(self._ofind(oname))
739 except AttributeError: pass
734 except AttributeError: pass
740 except AttributeError: pass
735 except AttributeError: pass
741
736
742 pmethod = getattr(self.shell.inspector,meth)
737 pmethod = getattr(self.shell.inspector,meth)
743 formatter = info.ismagic and self.format_screen or None
738 formatter = info.ismagic and self.format_screen or None
744 if meth == 'pdoc':
739 if meth == 'pdoc':
745 pmethod(info.obj,oname,formatter)
740 pmethod(info.obj,oname,formatter)
746 elif meth == 'pinfo':
741 elif meth == 'pinfo':
747 pmethod(info.obj,oname,formatter,info,**kw)
742 pmethod(info.obj,oname,formatter,info,**kw)
748 else:
743 else:
749 pmethod(info.obj,oname)
744 pmethod(info.obj,oname)
750 else:
745 else:
751 print 'Object `%s` not found.' % oname
746 print 'Object `%s` not found.' % oname
752 return 'not found' # so callers can take other action
747 return 'not found' # so callers can take other action
753
748
754 def magic_psearch(self, parameter_s=''):
749 def magic_psearch(self, parameter_s=''):
755 """Search for object in namespaces by wildcard.
750 """Search for object in namespaces by wildcard.
756
751
757 %psearch [options] PATTERN [OBJECT TYPE]
752 %psearch [options] PATTERN [OBJECT TYPE]
758
753
759 Note: ? can be used as a synonym for %psearch, at the beginning or at
754 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
755 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
756 rest of the command line must be unchanged (options come first), so
762 for example the following forms are equivalent
757 for example the following forms are equivalent
763
758
764 %psearch -i a* function
759 %psearch -i a* function
765 -i a* function?
760 -i a* function?
766 ?-i a* function
761 ?-i a* function
767
762
768 Arguments:
763 Arguments:
769
764
770 PATTERN
765 PATTERN
771
766
772 where PATTERN is a string containing * as a wildcard similar to its
767 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
768 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
769 search path. By default objects starting with a single _ are not
775 matched, many IPython generated objects have a single
770 matched, many IPython generated objects have a single
776 underscore. The default is case insensitive matching. Matching is
771 underscore. The default is case insensitive matching. Matching is
777 also done on the attributes of objects and not only on the objects
772 also done on the attributes of objects and not only on the objects
778 in a module.
773 in a module.
779
774
780 [OBJECT TYPE]
775 [OBJECT TYPE]
781
776
782 Is the name of a python type from the types module. The name is
777 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
778 given in lowercase without the ending type, ex. StringType is
784 written string. By adding a type here only objects matching the
779 written string. By adding a type here only objects matching the
785 given type are matched. Using all here makes the pattern match all
780 given type are matched. Using all here makes the pattern match all
786 types (this is the default).
781 types (this is the default).
787
782
788 Options:
783 Options:
789
784
790 -a: makes the pattern match even objects whose names start with a
785 -a: makes the pattern match even objects whose names start with a
791 single underscore. These names are normally ommitted from the
786 single underscore. These names are normally ommitted from the
792 search.
787 search.
793
788
794 -i/-c: make the pattern case insensitive/sensitive. If neither of
789 -i/-c: make the pattern case insensitive/sensitive. If neither of
795 these options is given, the default is read from your ipythonrc
790 these options is given, the default is read from your ipythonrc
796 file. The option name which sets this value is
791 file. The option name which sets this value is
797 'wildcards_case_sensitive'. If this option is not specified in your
792 'wildcards_case_sensitive'. If this option is not specified in your
798 ipythonrc file, IPython's internal default is to do a case sensitive
793 ipythonrc file, IPython's internal default is to do a case sensitive
799 search.
794 search.
800
795
801 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
796 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
802 specifiy can be searched in any of the following namespaces:
797 specifiy can be searched in any of the following namespaces:
803 'builtin', 'user', 'user_global','internal', 'alias', where
798 'builtin', 'user', 'user_global','internal', 'alias', where
804 'builtin' and 'user' are the search defaults. Note that you should
799 'builtin' and 'user' are the search defaults. Note that you should
805 not use quotes when specifying namespaces.
800 not use quotes when specifying namespaces.
806
801
807 'Builtin' contains the python module builtin, 'user' contains all
802 'Builtin' contains the python module builtin, 'user' contains all
808 user data, 'alias' only contain the shell aliases and no python
803 user data, 'alias' only contain the shell aliases and no python
809 objects, 'internal' contains objects used by IPython. The
804 objects, 'internal' contains objects used by IPython. The
810 'user_global' namespace is only used by embedded IPython instances,
805 'user_global' namespace is only used by embedded IPython instances,
811 and it contains module-level globals. You can add namespaces to the
806 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
807 search with -s or exclude them with -e (these options can be given
813 more than once).
808 more than once).
814
809
815 Examples:
810 Examples:
816
811
817 %psearch a* -> objects beginning with an a
812 %psearch a* -> objects beginning with an a
818 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
813 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
819 %psearch a* function -> all functions beginning with an a
814 %psearch a* function -> all functions beginning with an a
820 %psearch re.e* -> objects beginning with an e in module re
815 %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
816 %psearch r*.e* -> objects that start with e in modules starting in r
822 %psearch r*.* string -> all strings in modules beginning with r
817 %psearch r*.* string -> all strings in modules beginning with r
823
818
824 Case sensitve search:
819 Case sensitve search:
825
820
826 %psearch -c a* list all object beginning with lower case a
821 %psearch -c a* list all object beginning with lower case a
827
822
828 Show objects beginning with a single _:
823 Show objects beginning with a single _:
829
824
830 %psearch -a _* list objects beginning with a single underscore"""
825 %psearch -a _* list objects beginning with a single underscore"""
831 try:
826 try:
832 parameter_s = parameter_s.encode('ascii')
827 parameter_s = parameter_s.encode('ascii')
833 except UnicodeEncodeError:
828 except UnicodeEncodeError:
834 print 'Python identifiers can only contain ascii characters.'
829 print 'Python identifiers can only contain ascii characters.'
835 return
830 return
836
831
837 # default namespaces to be searched
832 # default namespaces to be searched
838 def_search = ['user','builtin']
833 def_search = ['user','builtin']
839
834
840 # Process options/args
835 # Process options/args
841 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)
842 opt = opts.get
837 opt = opts.get
843 shell = self.shell
838 shell = self.shell
844 psearch = shell.inspector.psearch
839 psearch = shell.inspector.psearch
845
840
846 # select case options
841 # select case options
847 if opts.has_key('i'):
842 if opts.has_key('i'):
848 ignore_case = True
843 ignore_case = True
849 elif opts.has_key('c'):
844 elif opts.has_key('c'):
850 ignore_case = False
845 ignore_case = False
851 else:
846 else:
852 ignore_case = not shell.rc.wildcards_case_sensitive
847 ignore_case = not shell.rc.wildcards_case_sensitive
853
848
854 # Build list of namespaces to search from user options
849 # Build list of namespaces to search from user options
855 def_search.extend(opt('s',[]))
850 def_search.extend(opt('s',[]))
856 ns_exclude = ns_exclude=opt('e',[])
851 ns_exclude = ns_exclude=opt('e',[])
857 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]
858
853
859 # Call the actual search
854 # Call the actual search
860 try:
855 try:
861 psearch(args,shell.ns_table,ns_search,
856 psearch(args,shell.ns_table,ns_search,
862 show_all=opt('a'),ignore_case=ignore_case)
857 show_all=opt('a'),ignore_case=ignore_case)
863 except:
858 except:
864 shell.showtraceback()
859 shell.showtraceback()
865
860
866 def magic_who_ls(self, parameter_s=''):
861 def magic_who_ls(self, parameter_s=''):
867 """Return a sorted list of all interactive variables.
862 """Return a sorted list of all interactive variables.
868
863
869 If arguments are given, only variables of types matching these
864 If arguments are given, only variables of types matching these
870 arguments are returned."""
865 arguments are returned."""
871
866
872 user_ns = self.shell.user_ns
867 user_ns = self.shell.user_ns
873 internal_ns = self.shell.internal_ns
868 internal_ns = self.shell.internal_ns
874 user_config_ns = self.shell.user_config_ns
869 user_config_ns = self.shell.user_config_ns
875 out = []
870 out = []
876 typelist = parameter_s.split()
871 typelist = parameter_s.split()
877
872
878 for i in user_ns:
873 for i in user_ns:
879 if not (i.startswith('_') or i.startswith('_i')) \
874 if not (i.startswith('_') or i.startswith('_i')) \
880 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):
881 if typelist:
876 if typelist:
882 if type(user_ns[i]).__name__ in typelist:
877 if type(user_ns[i]).__name__ in typelist:
883 out.append(i)
878 out.append(i)
884 else:
879 else:
885 out.append(i)
880 out.append(i)
886 out.sort()
881 out.sort()
887 return out
882 return out
888
883
889 def magic_who(self, parameter_s=''):
884 def magic_who(self, parameter_s=''):
890 """Print all interactive variables, with some minimal formatting.
885 """Print all interactive variables, with some minimal formatting.
891
886
892 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
893 these are printed. For example:
888 these are printed. For example:
894
889
895 %who function str
890 %who function str
896
891
897 will only list functions and strings, excluding all other types of
892 will only list functions and strings, excluding all other types of
898 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
899 command line to see how python prints type names. For example:
894 command line to see how python prints type names. For example:
900
895
901 In [1]: type('hello')\\
896 In [1]: type('hello')\\
902 Out[1]: <type 'str'>
897 Out[1]: <type 'str'>
903
898
904 indicates that the type name for strings is 'str'.
899 indicates that the type name for strings is 'str'.
905
900
906 %who always excludes executed names loaded through your configuration
901 %who always excludes executed names loaded through your configuration
907 file and things which are internal to IPython.
902 file and things which are internal to IPython.
908
903
909 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
910 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."""
911
906
912 varlist = self.magic_who_ls(parameter_s)
907 varlist = self.magic_who_ls(parameter_s)
913 if not varlist:
908 if not varlist:
914 if parameter_s:
909 if parameter_s:
915 print 'No variables match your requested type.'
910 print 'No variables match your requested type.'
916 else:
911 else:
917 print 'Interactive namespace is empty.'
912 print 'Interactive namespace is empty.'
918 return
913 return
919
914
920 # if we have variables, move on...
915 # if we have variables, move on...
921 count = 0
916 count = 0
922 for i in varlist:
917 for i in varlist:
923 print i+'\t',
918 print i+'\t',
924 count += 1
919 count += 1
925 if count > 8:
920 if count > 8:
926 count = 0
921 count = 0
927 print
922 print
928 print
923 print
929
924
930 def magic_whos(self, parameter_s=''):
925 def magic_whos(self, parameter_s=''):
931 """Like %who, but gives some extra information about each variable.
926 """Like %who, but gives some extra information about each variable.
932
927
933 The same type filtering of %who can be applied here.
928 The same type filtering of %who can be applied here.
934
929
935 For all variables, the type is printed. Additionally it prints:
930 For all variables, the type is printed. Additionally it prints:
936
931
937 - For {},[],(): their length.
932 - For {},[],(): their length.
938
933
939 - For numpy and Numeric arrays, a summary with shape, number of
934 - For numpy and Numeric arrays, a summary with shape, number of
940 elements, typecode and size in memory.
935 elements, typecode and size in memory.
941
936
942 - Everything else: a string representation, snipping their middle if
937 - Everything else: a string representation, snipping their middle if
943 too long."""
938 too long."""
944
939
945 varnames = self.magic_who_ls(parameter_s)
940 varnames = self.magic_who_ls(parameter_s)
946 if not varnames:
941 if not varnames:
947 if parameter_s:
942 if parameter_s:
948 print 'No variables match your requested type.'
943 print 'No variables match your requested type.'
949 else:
944 else:
950 print 'Interactive namespace is empty.'
945 print 'Interactive namespace is empty.'
951 return
946 return
952
947
953 # if we have variables, move on...
948 # if we have variables, move on...
954
949
955 # for these types, show len() instead of data:
950 # for these types, show len() instead of data:
956 seq_types = [types.DictType,types.ListType,types.TupleType]
951 seq_types = [types.DictType,types.ListType,types.TupleType]
957
952
958 # for numpy/Numeric arrays, display summary info
953 # for numpy/Numeric arrays, display summary info
959 try:
954 try:
960 import numpy
955 import numpy
961 except ImportError:
956 except ImportError:
962 ndarray_type = None
957 ndarray_type = None
963 else:
958 else:
964 ndarray_type = numpy.ndarray.__name__
959 ndarray_type = numpy.ndarray.__name__
965 try:
960 try:
966 import Numeric
961 import Numeric
967 except ImportError:
962 except ImportError:
968 array_type = None
963 array_type = None
969 else:
964 else:
970 array_type = Numeric.ArrayType.__name__
965 array_type = Numeric.ArrayType.__name__
971
966
972 # Find all variable names and types so we can figure out column sizes
967 # Find all variable names and types so we can figure out column sizes
973 def get_vars(i):
968 def get_vars(i):
974 return self.shell.user_ns[i]
969 return self.shell.user_ns[i]
975
970
976 # some types are well known and can be shorter
971 # some types are well known and can be shorter
977 abbrevs = {'IPython.macro.Macro' : 'Macro'}
972 abbrevs = {'IPython.macro.Macro' : 'Macro'}
978 def type_name(v):
973 def type_name(v):
979 tn = type(v).__name__
974 tn = type(v).__name__
980 return abbrevs.get(tn,tn)
975 return abbrevs.get(tn,tn)
981
976
982 varlist = map(get_vars,varnames)
977 varlist = map(get_vars,varnames)
983
978
984 typelist = []
979 typelist = []
985 for vv in varlist:
980 for vv in varlist:
986 tt = type_name(vv)
981 tt = type_name(vv)
987
982
988 if tt=='instance':
983 if tt=='instance':
989 typelist.append( abbrevs.get(str(vv.__class__),
984 typelist.append( abbrevs.get(str(vv.__class__),
990 str(vv.__class__)))
985 str(vv.__class__)))
991 else:
986 else:
992 typelist.append(tt)
987 typelist.append(tt)
993
988
994 # column labels and # of spaces as separator
989 # column labels and # of spaces as separator
995 varlabel = 'Variable'
990 varlabel = 'Variable'
996 typelabel = 'Type'
991 typelabel = 'Type'
997 datalabel = 'Data/Info'
992 datalabel = 'Data/Info'
998 colsep = 3
993 colsep = 3
999 # variable format strings
994 # variable format strings
1000 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
995 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1001 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
996 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1002 aformat = "%s: %s elems, type `%s`, %s bytes"
997 aformat = "%s: %s elems, type `%s`, %s bytes"
1003 # find the size of the columns to format the output nicely
998 # find the size of the columns to format the output nicely
1004 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
999 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1005 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1000 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1006 # table header
1001 # table header
1007 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1002 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1008 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1003 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1009 # and the table itself
1004 # and the table itself
1010 kb = 1024
1005 kb = 1024
1011 Mb = 1048576 # kb**2
1006 Mb = 1048576 # kb**2
1012 for vname,var,vtype in zip(varnames,varlist,typelist):
1007 for vname,var,vtype in zip(varnames,varlist,typelist):
1013 print itpl(vformat),
1008 print itpl(vformat),
1014 if vtype in seq_types:
1009 if vtype in seq_types:
1015 print len(var)
1010 print len(var)
1016 elif vtype in [array_type,ndarray_type]:
1011 elif vtype in [array_type,ndarray_type]:
1017 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1012 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1018 if vtype==ndarray_type:
1013 if vtype==ndarray_type:
1019 # numpy
1014 # numpy
1020 vsize = var.size
1015 vsize = var.size
1021 vbytes = vsize*var.itemsize
1016 vbytes = vsize*var.itemsize
1022 vdtype = var.dtype
1017 vdtype = var.dtype
1023 else:
1018 else:
1024 # Numeric
1019 # Numeric
1025 vsize = Numeric.size(var)
1020 vsize = Numeric.size(var)
1026 vbytes = vsize*var.itemsize()
1021 vbytes = vsize*var.itemsize()
1027 vdtype = var.typecode()
1022 vdtype = var.typecode()
1028
1023
1029 if vbytes < 100000:
1024 if vbytes < 100000:
1030 print aformat % (vshape,vsize,vdtype,vbytes)
1025 print aformat % (vshape,vsize,vdtype,vbytes)
1031 else:
1026 else:
1032 print aformat % (vshape,vsize,vdtype,vbytes),
1027 print aformat % (vshape,vsize,vdtype,vbytes),
1033 if vbytes < Mb:
1028 if vbytes < Mb:
1034 print '(%s kb)' % (vbytes/kb,)
1029 print '(%s kb)' % (vbytes/kb,)
1035 else:
1030 else:
1036 print '(%s Mb)' % (vbytes/Mb,)
1031 print '(%s Mb)' % (vbytes/Mb,)
1037 else:
1032 else:
1038 try:
1033 try:
1039 vstr = str(var)
1034 vstr = str(var)
1040 except UnicodeEncodeError:
1035 except UnicodeEncodeError:
1041 vstr = unicode(var).encode(sys.getdefaultencoding(),
1036 vstr = unicode(var).encode(sys.getdefaultencoding(),
1042 'backslashreplace')
1037 'backslashreplace')
1043 vstr = vstr.replace('\n','\\n')
1038 vstr = vstr.replace('\n','\\n')
1044 if len(vstr) < 50:
1039 if len(vstr) < 50:
1045 print vstr
1040 print vstr
1046 else:
1041 else:
1047 printpl(vfmt_short)
1042 printpl(vfmt_short)
1048
1043
1049 def magic_reset(self, parameter_s=''):
1044 def magic_reset(self, parameter_s=''):
1050 """Resets the namespace by removing all names defined by the user.
1045 """Resets the namespace by removing all names defined by the user.
1051
1046
1052 Input/Output history are left around in case you need them."""
1047 Input/Output history are left around in case you need them.
1048
1049 Parameters
1050 ----------
1051 -y : force reset without asking for confirmation.
1052
1053 Examples
1054 --------
1055 In [6]: a = 1
1056
1057 In [7]: a
1058 Out[7]: 1
1059
1060 In [8]: 'a' in _ip.user_ns
1061 Out[8]: True
1062
1063 In [9]: %reset -f
1053
1064
1054 ans = self.shell.ask_yes_no(
1065 In [10]: 'a' in _ip.user_ns
1055 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1066 Out[10]: False
1067 """
1068
1069 if parameter_s == '-f':
1070 ans = True
1071 else:
1072 ans = self.shell.ask_yes_no(
1073 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1056 if not ans:
1074 if not ans:
1057 print 'Nothing done.'
1075 print 'Nothing done.'
1058 return
1076 return
1059 user_ns = self.shell.user_ns
1077 user_ns = self.shell.user_ns
1060 for i in self.magic_who_ls():
1078 for i in self.magic_who_ls():
1061 del(user_ns[i])
1079 del(user_ns[i])
1062
1080
1063 # Also flush the private list of module references kept for script
1081 # Also flush the private list of module references kept for script
1064 # execution protection
1082 # execution protection
1065 self.shell._user_main_modules[:] = []
1083 self.shell.clear_main_mod_cache()
1066
1084
1067 def magic_logstart(self,parameter_s=''):
1085 def magic_logstart(self,parameter_s=''):
1068 """Start logging anywhere in a session.
1086 """Start logging anywhere in a session.
1069
1087
1070 %logstart [-o|-r|-t] [log_name [log_mode]]
1088 %logstart [-o|-r|-t] [log_name [log_mode]]
1071
1089
1072 If no name is given, it defaults to a file named 'ipython_log.py' in your
1090 If no name is given, it defaults to a file named 'ipython_log.py' in your
1073 current directory, in 'rotate' mode (see below).
1091 current directory, in 'rotate' mode (see below).
1074
1092
1075 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1093 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1076 history up to that point and then continues logging.
1094 history up to that point and then continues logging.
1077
1095
1078 %logstart takes a second optional parameter: logging mode. This can be one
1096 %logstart takes a second optional parameter: logging mode. This can be one
1079 of (note that the modes are given unquoted):\\
1097 of (note that the modes are given unquoted):\\
1080 append: well, that says it.\\
1098 append: well, that says it.\\
1081 backup: rename (if exists) to name~ and start name.\\
1099 backup: rename (if exists) to name~ and start name.\\
1082 global: single logfile in your home dir, appended to.\\
1100 global: single logfile in your home dir, appended to.\\
1083 over : overwrite existing log.\\
1101 over : overwrite existing log.\\
1084 rotate: create rotating logs name.1~, name.2~, etc.
1102 rotate: create rotating logs name.1~, name.2~, etc.
1085
1103
1086 Options:
1104 Options:
1087
1105
1088 -o: log also IPython's output. In this mode, all commands which
1106 -o: log also IPython's output. In this mode, all commands which
1089 generate an Out[NN] prompt are recorded to the logfile, right after
1107 generate an Out[NN] prompt are recorded to the logfile, right after
1090 their corresponding input line. The output lines are always
1108 their corresponding input line. The output lines are always
1091 prepended with a '#[Out]# ' marker, so that the log remains valid
1109 prepended with a '#[Out]# ' marker, so that the log remains valid
1092 Python code.
1110 Python code.
1093
1111
1094 Since this marker is always the same, filtering only the output from
1112 Since this marker is always the same, filtering only the output from
1095 a log is very easy, using for example a simple awk call:
1113 a log is very easy, using for example a simple awk call:
1096
1114
1097 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1115 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1098
1116
1099 -r: log 'raw' input. Normally, IPython's logs contain the processed
1117 -r: log 'raw' input. Normally, IPython's logs contain the processed
1100 input, so that user lines are logged in their final form, converted
1118 input, so that user lines are logged in their final form, converted
1101 into valid Python. For example, %Exit is logged as
1119 into valid Python. For example, %Exit is logged as
1102 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1120 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1103 exactly as typed, with no transformations applied.
1121 exactly as typed, with no transformations applied.
1104
1122
1105 -t: put timestamps before each input line logged (these are put in
1123 -t: put timestamps before each input line logged (these are put in
1106 comments)."""
1124 comments)."""
1107
1125
1108 opts,par = self.parse_options(parameter_s,'ort')
1126 opts,par = self.parse_options(parameter_s,'ort')
1109 log_output = 'o' in opts
1127 log_output = 'o' in opts
1110 log_raw_input = 'r' in opts
1128 log_raw_input = 'r' in opts
1111 timestamp = 't' in opts
1129 timestamp = 't' in opts
1112
1130
1113 rc = self.shell.rc
1131 rc = self.shell.rc
1114 logger = self.shell.logger
1132 logger = self.shell.logger
1115
1133
1116 # if no args are given, the defaults set in the logger constructor by
1134 # if no args are given, the defaults set in the logger constructor by
1117 # ipytohn remain valid
1135 # ipytohn remain valid
1118 if par:
1136 if par:
1119 try:
1137 try:
1120 logfname,logmode = par.split()
1138 logfname,logmode = par.split()
1121 except:
1139 except:
1122 logfname = par
1140 logfname = par
1123 logmode = 'backup'
1141 logmode = 'backup'
1124 else:
1142 else:
1125 logfname = logger.logfname
1143 logfname = logger.logfname
1126 logmode = logger.logmode
1144 logmode = logger.logmode
1127 # put logfname into rc struct as if it had been called on the command
1145 # put logfname into rc struct as if it had been called on the command
1128 # line, so it ends up saved in the log header Save it in case we need
1146 # line, so it ends up saved in the log header Save it in case we need
1129 # to restore it...
1147 # to restore it...
1130 old_logfile = rc.opts.get('logfile','')
1148 old_logfile = rc.opts.get('logfile','')
1131 if logfname:
1149 if logfname:
1132 logfname = os.path.expanduser(logfname)
1150 logfname = os.path.expanduser(logfname)
1133 rc.opts.logfile = logfname
1151 rc.opts.logfile = logfname
1134 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1152 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1135 try:
1153 try:
1136 started = logger.logstart(logfname,loghead,logmode,
1154 started = logger.logstart(logfname,loghead,logmode,
1137 log_output,timestamp,log_raw_input)
1155 log_output,timestamp,log_raw_input)
1138 except:
1156 except:
1139 rc.opts.logfile = old_logfile
1157 rc.opts.logfile = old_logfile
1140 warn("Couldn't start log: %s" % sys.exc_info()[1])
1158 warn("Couldn't start log: %s" % sys.exc_info()[1])
1141 else:
1159 else:
1142 # log input history up to this point, optionally interleaving
1160 # log input history up to this point, optionally interleaving
1143 # output if requested
1161 # output if requested
1144
1162
1145 if timestamp:
1163 if timestamp:
1146 # disable timestamping for the previous history, since we've
1164 # disable timestamping for the previous history, since we've
1147 # lost those already (no time machine here).
1165 # lost those already (no time machine here).
1148 logger.timestamp = False
1166 logger.timestamp = False
1149
1167
1150 if log_raw_input:
1168 if log_raw_input:
1151 input_hist = self.shell.input_hist_raw
1169 input_hist = self.shell.input_hist_raw
1152 else:
1170 else:
1153 input_hist = self.shell.input_hist
1171 input_hist = self.shell.input_hist
1154
1172
1155 if log_output:
1173 if log_output:
1156 log_write = logger.log_write
1174 log_write = logger.log_write
1157 output_hist = self.shell.output_hist
1175 output_hist = self.shell.output_hist
1158 for n in range(1,len(input_hist)-1):
1176 for n in range(1,len(input_hist)-1):
1159 log_write(input_hist[n].rstrip())
1177 log_write(input_hist[n].rstrip())
1160 if n in output_hist:
1178 if n in output_hist:
1161 log_write(repr(output_hist[n]),'output')
1179 log_write(repr(output_hist[n]),'output')
1162 else:
1180 else:
1163 logger.log_write(input_hist[1:])
1181 logger.log_write(input_hist[1:])
1164 if timestamp:
1182 if timestamp:
1165 # re-enable timestamping
1183 # re-enable timestamping
1166 logger.timestamp = True
1184 logger.timestamp = True
1167
1185
1168 print ('Activating auto-logging. '
1186 print ('Activating auto-logging. '
1169 'Current session state plus future input saved.')
1187 'Current session state plus future input saved.')
1170 logger.logstate()
1188 logger.logstate()
1171
1189
1172 def magic_logstop(self,parameter_s=''):
1190 def magic_logstop(self,parameter_s=''):
1173 """Fully stop logging and close log file.
1191 """Fully stop logging and close log file.
1174
1192
1175 In order to start logging again, a new %logstart call needs to be made,
1193 In order to start logging again, a new %logstart call needs to be made,
1176 possibly (though not necessarily) with a new filename, mode and other
1194 possibly (though not necessarily) with a new filename, mode and other
1177 options."""
1195 options."""
1178 self.logger.logstop()
1196 self.logger.logstop()
1179
1197
1180 def magic_logoff(self,parameter_s=''):
1198 def magic_logoff(self,parameter_s=''):
1181 """Temporarily stop logging.
1199 """Temporarily stop logging.
1182
1200
1183 You must have previously started logging."""
1201 You must have previously started logging."""
1184 self.shell.logger.switch_log(0)
1202 self.shell.logger.switch_log(0)
1185
1203
1186 def magic_logon(self,parameter_s=''):
1204 def magic_logon(self,parameter_s=''):
1187 """Restart logging.
1205 """Restart logging.
1188
1206
1189 This function is for restarting logging which you've temporarily
1207 This function is for restarting logging which you've temporarily
1190 stopped with %logoff. For starting logging for the first time, you
1208 stopped with %logoff. For starting logging for the first time, you
1191 must use the %logstart function, which allows you to specify an
1209 must use the %logstart function, which allows you to specify an
1192 optional log filename."""
1210 optional log filename."""
1193
1211
1194 self.shell.logger.switch_log(1)
1212 self.shell.logger.switch_log(1)
1195
1213
1196 def magic_logstate(self,parameter_s=''):
1214 def magic_logstate(self,parameter_s=''):
1197 """Print the status of the logging system."""
1215 """Print the status of the logging system."""
1198
1216
1199 self.shell.logger.logstate()
1217 self.shell.logger.logstate()
1200
1218
1201 def magic_pdb(self, parameter_s=''):
1219 def magic_pdb(self, parameter_s=''):
1202 """Control the automatic calling of the pdb interactive debugger.
1220 """Control the automatic calling of the pdb interactive debugger.
1203
1221
1204 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1222 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1205 argument it works as a toggle.
1223 argument it works as a toggle.
1206
1224
1207 When an exception is triggered, IPython can optionally call the
1225 When an exception is triggered, IPython can optionally call the
1208 interactive pdb debugger after the traceback printout. %pdb toggles
1226 interactive pdb debugger after the traceback printout. %pdb toggles
1209 this feature on and off.
1227 this feature on and off.
1210
1228
1211 The initial state of this feature is set in your ipythonrc
1229 The initial state of this feature is set in your ipythonrc
1212 configuration file (the variable is called 'pdb').
1230 configuration file (the variable is called 'pdb').
1213
1231
1214 If you want to just activate the debugger AFTER an exception has fired,
1232 If you want to just activate the debugger AFTER an exception has fired,
1215 without having to type '%pdb on' and rerunning your code, you can use
1233 without having to type '%pdb on' and rerunning your code, you can use
1216 the %debug magic."""
1234 the %debug magic."""
1217
1235
1218 par = parameter_s.strip().lower()
1236 par = parameter_s.strip().lower()
1219
1237
1220 if par:
1238 if par:
1221 try:
1239 try:
1222 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1240 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1223 except KeyError:
1241 except KeyError:
1224 print ('Incorrect argument. Use on/1, off/0, '
1242 print ('Incorrect argument. Use on/1, off/0, '
1225 'or nothing for a toggle.')
1243 'or nothing for a toggle.')
1226 return
1244 return
1227 else:
1245 else:
1228 # toggle
1246 # toggle
1229 new_pdb = not self.shell.call_pdb
1247 new_pdb = not self.shell.call_pdb
1230
1248
1231 # set on the shell
1249 # set on the shell
1232 self.shell.call_pdb = new_pdb
1250 self.shell.call_pdb = new_pdb
1233 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1251 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1234
1252
1235 def magic_debug(self, parameter_s=''):
1253 def magic_debug(self, parameter_s=''):
1236 """Activate the interactive debugger in post-mortem mode.
1254 """Activate the interactive debugger in post-mortem mode.
1237
1255
1238 If an exception has just occurred, this lets you inspect its stack
1256 If an exception has just occurred, this lets you inspect its stack
1239 frames interactively. Note that this will always work only on the last
1257 frames interactively. Note that this will always work only on the last
1240 traceback that occurred, so you must call this quickly after an
1258 traceback that occurred, so you must call this quickly after an
1241 exception that you wish to inspect has fired, because if another one
1259 exception that you wish to inspect has fired, because if another one
1242 occurs, it clobbers the previous one.
1260 occurs, it clobbers the previous one.
1243
1261
1244 If you want IPython to automatically do this on every exception, see
1262 If you want IPython to automatically do this on every exception, see
1245 the %pdb magic for more details.
1263 the %pdb magic for more details.
1246 """
1264 """
1247
1265
1248 self.shell.debugger(force=True)
1266 self.shell.debugger(force=True)
1249
1267
1250 @testdec.skip_doctest
1268 @testdec.skip_doctest
1251 def magic_prun(self, parameter_s ='',user_mode=1,
1269 def magic_prun(self, parameter_s ='',user_mode=1,
1252 opts=None,arg_lst=None,prog_ns=None):
1270 opts=None,arg_lst=None,prog_ns=None):
1253
1271
1254 """Run a statement through the python code profiler.
1272 """Run a statement through the python code profiler.
1255
1273
1256 Usage:
1274 Usage:
1257 %prun [options] statement
1275 %prun [options] statement
1258
1276
1259 The given statement (which doesn't require quote marks) is run via the
1277 The given statement (which doesn't require quote marks) is run via the
1260 python profiler in a manner similar to the profile.run() function.
1278 python profiler in a manner similar to the profile.run() function.
1261 Namespaces are internally managed to work correctly; profile.run
1279 Namespaces are internally managed to work correctly; profile.run
1262 cannot be used in IPython because it makes certain assumptions about
1280 cannot be used in IPython because it makes certain assumptions about
1263 namespaces which do not hold under IPython.
1281 namespaces which do not hold under IPython.
1264
1282
1265 Options:
1283 Options:
1266
1284
1267 -l <limit>: you can place restrictions on what or how much of the
1285 -l <limit>: you can place restrictions on what or how much of the
1268 profile gets printed. The limit value can be:
1286 profile gets printed. The limit value can be:
1269
1287
1270 * A string: only information for function names containing this string
1288 * A string: only information for function names containing this string
1271 is printed.
1289 is printed.
1272
1290
1273 * An integer: only these many lines are printed.
1291 * An integer: only these many lines are printed.
1274
1292
1275 * A float (between 0 and 1): this fraction of the report is printed
1293 * A float (between 0 and 1): this fraction of the report is printed
1276 (for example, use a limit of 0.4 to see the topmost 40% only).
1294 (for example, use a limit of 0.4 to see the topmost 40% only).
1277
1295
1278 You can combine several limits with repeated use of the option. For
1296 You can combine several limits with repeated use of the option. For
1279 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1297 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1280 information about class constructors.
1298 information about class constructors.
1281
1299
1282 -r: return the pstats.Stats object generated by the profiling. This
1300 -r: return the pstats.Stats object generated by the profiling. This
1283 object has all the information about the profile in it, and you can
1301 object has all the information about the profile in it, and you can
1284 later use it for further analysis or in other functions.
1302 later use it for further analysis or in other functions.
1285
1303
1286 -s <key>: sort profile by given key. You can provide more than one key
1304 -s <key>: sort profile by given key. You can provide more than one key
1287 by using the option several times: '-s key1 -s key2 -s key3...'. The
1305 by using the option several times: '-s key1 -s key2 -s key3...'. The
1288 default sorting key is 'time'.
1306 default sorting key is 'time'.
1289
1307
1290 The following is copied verbatim from the profile documentation
1308 The following is copied verbatim from the profile documentation
1291 referenced below:
1309 referenced below:
1292
1310
1293 When more than one key is provided, additional keys are used as
1311 When more than one key is provided, additional keys are used as
1294 secondary criteria when the there is equality in all keys selected
1312 secondary criteria when the there is equality in all keys selected
1295 before them.
1313 before them.
1296
1314
1297 Abbreviations can be used for any key names, as long as the
1315 Abbreviations can be used for any key names, as long as the
1298 abbreviation is unambiguous. The following are the keys currently
1316 abbreviation is unambiguous. The following are the keys currently
1299 defined:
1317 defined:
1300
1318
1301 Valid Arg Meaning
1319 Valid Arg Meaning
1302 "calls" call count
1320 "calls" call count
1303 "cumulative" cumulative time
1321 "cumulative" cumulative time
1304 "file" file name
1322 "file" file name
1305 "module" file name
1323 "module" file name
1306 "pcalls" primitive call count
1324 "pcalls" primitive call count
1307 "line" line number
1325 "line" line number
1308 "name" function name
1326 "name" function name
1309 "nfl" name/file/line
1327 "nfl" name/file/line
1310 "stdname" standard name
1328 "stdname" standard name
1311 "time" internal time
1329 "time" internal time
1312
1330
1313 Note that all sorts on statistics are in descending order (placing
1331 Note that all sorts on statistics are in descending order (placing
1314 most time consuming items first), where as name, file, and line number
1332 most time consuming items first), where as name, file, and line number
1315 searches are in ascending order (i.e., alphabetical). The subtle
1333 searches are in ascending order (i.e., alphabetical). The subtle
1316 distinction between "nfl" and "stdname" is that the standard name is a
1334 distinction between "nfl" and "stdname" is that the standard name is a
1317 sort of the name as printed, which means that the embedded line
1335 sort of the name as printed, which means that the embedded line
1318 numbers get compared in an odd way. For example, lines 3, 20, and 40
1336 numbers get compared in an odd way. For example, lines 3, 20, and 40
1319 would (if the file names were the same) appear in the string order
1337 would (if the file names were the same) appear in the string order
1320 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1338 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1321 line numbers. In fact, sort_stats("nfl") is the same as
1339 line numbers. In fact, sort_stats("nfl") is the same as
1322 sort_stats("name", "file", "line").
1340 sort_stats("name", "file", "line").
1323
1341
1324 -T <filename>: save profile results as shown on screen to a text
1342 -T <filename>: save profile results as shown on screen to a text
1325 file. The profile is still shown on screen.
1343 file. The profile is still shown on screen.
1326
1344
1327 -D <filename>: save (via dump_stats) profile statistics to given
1345 -D <filename>: save (via dump_stats) profile statistics to given
1328 filename. This data is in a format understod by the pstats module, and
1346 filename. This data is in a format understod by the pstats module, and
1329 is generated by a call to the dump_stats() method of profile
1347 is generated by a call to the dump_stats() method of profile
1330 objects. The profile is still shown on screen.
1348 objects. The profile is still shown on screen.
1331
1349
1332 If you want to run complete programs under the profiler's control, use
1350 If you want to run complete programs under the profiler's control, use
1333 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1351 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1334 contains profiler specific options as described here.
1352 contains profiler specific options as described here.
1335
1353
1336 You can read the complete documentation for the profile module with::
1354 You can read the complete documentation for the profile module with::
1337
1355
1338 In [1]: import profile; profile.help()
1356 In [1]: import profile; profile.help()
1339 """
1357 """
1340
1358
1341 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1359 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1342 # protect user quote marks
1360 # protect user quote marks
1343 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1361 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1344
1362
1345 if user_mode: # regular user call
1363 if user_mode: # regular user call
1346 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1364 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1347 list_all=1)
1365 list_all=1)
1348 namespace = self.shell.user_ns
1366 namespace = self.shell.user_ns
1349 else: # called to run a program by %run -p
1367 else: # called to run a program by %run -p
1350 try:
1368 try:
1351 filename = get_py_filename(arg_lst[0])
1369 filename = get_py_filename(arg_lst[0])
1352 except IOError,msg:
1370 except IOError,msg:
1353 error(msg)
1371 error(msg)
1354 return
1372 return
1355
1373
1356 arg_str = 'execfile(filename,prog_ns)'
1374 arg_str = 'execfile(filename,prog_ns)'
1357 namespace = locals()
1375 namespace = locals()
1358
1376
1359 opts.merge(opts_def)
1377 opts.merge(opts_def)
1360
1378
1361 prof = profile.Profile()
1379 prof = profile.Profile()
1362 try:
1380 try:
1363 prof = prof.runctx(arg_str,namespace,namespace)
1381 prof = prof.runctx(arg_str,namespace,namespace)
1364 sys_exit = ''
1382 sys_exit = ''
1365 except SystemExit:
1383 except SystemExit:
1366 sys_exit = """*** SystemExit exception caught in code being profiled."""
1384 sys_exit = """*** SystemExit exception caught in code being profiled."""
1367
1385
1368 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1386 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1369
1387
1370 lims = opts.l
1388 lims = opts.l
1371 if lims:
1389 if lims:
1372 lims = [] # rebuild lims with ints/floats/strings
1390 lims = [] # rebuild lims with ints/floats/strings
1373 for lim in opts.l:
1391 for lim in opts.l:
1374 try:
1392 try:
1375 lims.append(int(lim))
1393 lims.append(int(lim))
1376 except ValueError:
1394 except ValueError:
1377 try:
1395 try:
1378 lims.append(float(lim))
1396 lims.append(float(lim))
1379 except ValueError:
1397 except ValueError:
1380 lims.append(lim)
1398 lims.append(lim)
1381
1399
1382 # Trap output.
1400 # Trap output.
1383 stdout_trap = StringIO()
1401 stdout_trap = StringIO()
1384
1402
1385 if hasattr(stats,'stream'):
1403 if hasattr(stats,'stream'):
1386 # In newer versions of python, the stats object has a 'stream'
1404 # In newer versions of python, the stats object has a 'stream'
1387 # attribute to write into.
1405 # attribute to write into.
1388 stats.stream = stdout_trap
1406 stats.stream = stdout_trap
1389 stats.print_stats(*lims)
1407 stats.print_stats(*lims)
1390 else:
1408 else:
1391 # For older versions, we manually redirect stdout during printing
1409 # For older versions, we manually redirect stdout during printing
1392 sys_stdout = sys.stdout
1410 sys_stdout = sys.stdout
1393 try:
1411 try:
1394 sys.stdout = stdout_trap
1412 sys.stdout = stdout_trap
1395 stats.print_stats(*lims)
1413 stats.print_stats(*lims)
1396 finally:
1414 finally:
1397 sys.stdout = sys_stdout
1415 sys.stdout = sys_stdout
1398
1416
1399 output = stdout_trap.getvalue()
1417 output = stdout_trap.getvalue()
1400 output = output.rstrip()
1418 output = output.rstrip()
1401
1419
1402 page(output,screen_lines=self.shell.rc.screen_length)
1420 page(output,screen_lines=self.shell.rc.screen_length)
1403 print sys_exit,
1421 print sys_exit,
1404
1422
1405 dump_file = opts.D[0]
1423 dump_file = opts.D[0]
1406 text_file = opts.T[0]
1424 text_file = opts.T[0]
1407 if dump_file:
1425 if dump_file:
1408 prof.dump_stats(dump_file)
1426 prof.dump_stats(dump_file)
1409 print '\n*** Profile stats marshalled to file',\
1427 print '\n*** Profile stats marshalled to file',\
1410 `dump_file`+'.',sys_exit
1428 `dump_file`+'.',sys_exit
1411 if text_file:
1429 if text_file:
1412 pfile = file(text_file,'w')
1430 pfile = file(text_file,'w')
1413 pfile.write(output)
1431 pfile.write(output)
1414 pfile.close()
1432 pfile.close()
1415 print '\n*** Profile printout saved to text file',\
1433 print '\n*** Profile printout saved to text file',\
1416 `text_file`+'.',sys_exit
1434 `text_file`+'.',sys_exit
1417
1435
1418 if opts.has_key('r'):
1436 if opts.has_key('r'):
1419 return stats
1437 return stats
1420 else:
1438 else:
1421 return None
1439 return None
1422
1440
1423 @testdec.skip_doctest
1441 @testdec.skip_doctest
1424 def magic_run(self, parameter_s ='',runner=None,
1442 def magic_run(self, parameter_s ='',runner=None,
1425 file_finder=get_py_filename):
1443 file_finder=get_py_filename):
1426 """Run the named file inside IPython as a program.
1444 """Run the named file inside IPython as a program.
1427
1445
1428 Usage:\\
1446 Usage:\\
1429 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1447 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1430
1448
1431 Parameters after the filename are passed as command-line arguments to
1449 Parameters after the filename are passed as command-line arguments to
1432 the program (put in sys.argv). Then, control returns to IPython's
1450 the program (put in sys.argv). Then, control returns to IPython's
1433 prompt.
1451 prompt.
1434
1452
1435 This is similar to running at a system prompt:\\
1453 This is similar to running at a system prompt:\\
1436 $ python file args\\
1454 $ python file args\\
1437 but with the advantage of giving you IPython's tracebacks, and of
1455 but with the advantage of giving you IPython's tracebacks, and of
1438 loading all variables into your interactive namespace for further use
1456 loading all variables into your interactive namespace for further use
1439 (unless -p is used, see below).
1457 (unless -p is used, see below).
1440
1458
1441 The file is executed in a namespace initially consisting only of
1459 The file is executed in a namespace initially consisting only of
1442 __name__=='__main__' and sys.argv constructed as indicated. It thus
1460 __name__=='__main__' and sys.argv constructed as indicated. It thus
1443 sees its environment as if it were being run as a stand-alone program
1461 sees its environment as if it were being run as a stand-alone program
1444 (except for sharing global objects such as previously imported
1462 (except for sharing global objects such as previously imported
1445 modules). But after execution, the IPython interactive namespace gets
1463 modules). But after execution, the IPython interactive namespace gets
1446 updated with all variables defined in the program (except for __name__
1464 updated with all variables defined in the program (except for __name__
1447 and sys.argv). This allows for very convenient loading of code for
1465 and sys.argv). This allows for very convenient loading of code for
1448 interactive work, while giving each program a 'clean sheet' to run in.
1466 interactive work, while giving each program a 'clean sheet' to run in.
1449
1467
1450 Options:
1468 Options:
1451
1469
1452 -n: __name__ is NOT set to '__main__', but to the running file's name
1470 -n: __name__ is NOT set to '__main__', but to the running file's name
1453 without extension (as python does under import). This allows running
1471 without extension (as python does under import). This allows running
1454 scripts and reloading the definitions in them without calling code
1472 scripts and reloading the definitions in them without calling code
1455 protected by an ' if __name__ == "__main__" ' clause.
1473 protected by an ' if __name__ == "__main__" ' clause.
1456
1474
1457 -i: run the file in IPython's namespace instead of an empty one. This
1475 -i: run the file in IPython's namespace instead of an empty one. This
1458 is useful if you are experimenting with code written in a text editor
1476 is useful if you are experimenting with code written in a text editor
1459 which depends on variables defined interactively.
1477 which depends on variables defined interactively.
1460
1478
1461 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1479 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1462 being run. This is particularly useful if IPython is being used to
1480 being run. This is particularly useful if IPython is being used to
1463 run unittests, which always exit with a sys.exit() call. In such
1481 run unittests, which always exit with a sys.exit() call. In such
1464 cases you are interested in the output of the test results, not in
1482 cases you are interested in the output of the test results, not in
1465 seeing a traceback of the unittest module.
1483 seeing a traceback of the unittest module.
1466
1484
1467 -t: print timing information at the end of the run. IPython will give
1485 -t: print timing information at the end of the run. IPython will give
1468 you an estimated CPU time consumption for your script, which under
1486 you an estimated CPU time consumption for your script, which under
1469 Unix uses the resource module to avoid the wraparound problems of
1487 Unix uses the resource module to avoid the wraparound problems of
1470 time.clock(). Under Unix, an estimate of time spent on system tasks
1488 time.clock(). Under Unix, an estimate of time spent on system tasks
1471 is also given (for Windows platforms this is reported as 0.0).
1489 is also given (for Windows platforms this is reported as 0.0).
1472
1490
1473 If -t is given, an additional -N<N> option can be given, where <N>
1491 If -t is given, an additional -N<N> option can be given, where <N>
1474 must be an integer indicating how many times you want the script to
1492 must be an integer indicating how many times you want the script to
1475 run. The final timing report will include total and per run results.
1493 run. The final timing report will include total and per run results.
1476
1494
1477 For example (testing the script uniq_stable.py):
1495 For example (testing the script uniq_stable.py):
1478
1496
1479 In [1]: run -t uniq_stable
1497 In [1]: run -t uniq_stable
1480
1498
1481 IPython CPU timings (estimated):\\
1499 IPython CPU timings (estimated):\\
1482 User : 0.19597 s.\\
1500 User : 0.19597 s.\\
1483 System: 0.0 s.\\
1501 System: 0.0 s.\\
1484
1502
1485 In [2]: run -t -N5 uniq_stable
1503 In [2]: run -t -N5 uniq_stable
1486
1504
1487 IPython CPU timings (estimated):\\
1505 IPython CPU timings (estimated):\\
1488 Total runs performed: 5\\
1506 Total runs performed: 5\\
1489 Times : Total Per run\\
1507 Times : Total Per run\\
1490 User : 0.910862 s, 0.1821724 s.\\
1508 User : 0.910862 s, 0.1821724 s.\\
1491 System: 0.0 s, 0.0 s.
1509 System: 0.0 s, 0.0 s.
1492
1510
1493 -d: run your program under the control of pdb, the Python debugger.
1511 -d: run your program under the control of pdb, the Python debugger.
1494 This allows you to execute your program step by step, watch variables,
1512 This allows you to execute your program step by step, watch variables,
1495 etc. Internally, what IPython does is similar to calling:
1513 etc. Internally, what IPython does is similar to calling:
1496
1514
1497 pdb.run('execfile("YOURFILENAME")')
1515 pdb.run('execfile("YOURFILENAME")')
1498
1516
1499 with a breakpoint set on line 1 of your file. You can change the line
1517 with a breakpoint set on line 1 of your file. You can change the line
1500 number for this automatic breakpoint to be <N> by using the -bN option
1518 number for this automatic breakpoint to be <N> by using the -bN option
1501 (where N must be an integer). For example:
1519 (where N must be an integer). For example:
1502
1520
1503 %run -d -b40 myscript
1521 %run -d -b40 myscript
1504
1522
1505 will set the first breakpoint at line 40 in myscript.py. Note that
1523 will set the first breakpoint at line 40 in myscript.py. Note that
1506 the first breakpoint must be set on a line which actually does
1524 the first breakpoint must be set on a line which actually does
1507 something (not a comment or docstring) for it to stop execution.
1525 something (not a comment or docstring) for it to stop execution.
1508
1526
1509 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1527 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1510 first enter 'c' (without qoutes) to start execution up to the first
1528 first enter 'c' (without qoutes) to start execution up to the first
1511 breakpoint.
1529 breakpoint.
1512
1530
1513 Entering 'help' gives information about the use of the debugger. You
1531 Entering 'help' gives information about the use of the debugger. You
1514 can easily see pdb's full documentation with "import pdb;pdb.help()"
1532 can easily see pdb's full documentation with "import pdb;pdb.help()"
1515 at a prompt.
1533 at a prompt.
1516
1534
1517 -p: run program under the control of the Python profiler module (which
1535 -p: run program under the control of the Python profiler module (which
1518 prints a detailed report of execution times, function calls, etc).
1536 prints a detailed report of execution times, function calls, etc).
1519
1537
1520 You can pass other options after -p which affect the behavior of the
1538 You can pass other options after -p which affect the behavior of the
1521 profiler itself. See the docs for %prun for details.
1539 profiler itself. See the docs for %prun for details.
1522
1540
1523 In this mode, the program's variables do NOT propagate back to the
1541 In this mode, the program's variables do NOT propagate back to the
1524 IPython interactive namespace (because they remain in the namespace
1542 IPython interactive namespace (because they remain in the namespace
1525 where the profiler executes them).
1543 where the profiler executes them).
1526
1544
1527 Internally this triggers a call to %prun, see its documentation for
1545 Internally this triggers a call to %prun, see its documentation for
1528 details on the options available specifically for profiling.
1546 details on the options available specifically for profiling.
1529
1547
1530 There is one special usage for which the text above doesn't apply:
1548 There is one special usage for which the text above doesn't apply:
1531 if the filename ends with .ipy, the file is run as ipython script,
1549 if the filename ends with .ipy, the file is run as ipython script,
1532 just as if the commands were written on IPython prompt.
1550 just as if the commands were written on IPython prompt.
1533 """
1551 """
1534
1552
1535 # get arguments and set sys.argv for program to be run.
1553 # get arguments and set sys.argv for program to be run.
1536 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1554 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1537 mode='list',list_all=1)
1555 mode='list',list_all=1)
1538
1556
1539 try:
1557 try:
1540 filename = file_finder(arg_lst[0])
1558 filename = file_finder(arg_lst[0])
1541 except IndexError:
1559 except IndexError:
1542 warn('you must provide at least a filename.')
1560 warn('you must provide at least a filename.')
1543 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1561 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1544 return
1562 return
1545 except IOError,msg:
1563 except IOError,msg:
1546 error(msg)
1564 error(msg)
1547 return
1565 return
1548
1566
1549 if filename.lower().endswith('.ipy'):
1567 if filename.lower().endswith('.ipy'):
1550 self.api.runlines(open(filename).read())
1568 self.api.runlines(open(filename).read())
1551 return
1569 return
1552
1570
1553 # Control the response to exit() calls made by the script being run
1571 # Control the response to exit() calls made by the script being run
1554 exit_ignore = opts.has_key('e')
1572 exit_ignore = opts.has_key('e')
1555
1573
1556 # Make sure that the running script gets a proper sys.argv as if it
1574 # Make sure that the running script gets a proper sys.argv as if it
1557 # were run from a system shell.
1575 # were run from a system shell.
1558 save_argv = sys.argv # save it for later restoring
1576 save_argv = sys.argv # save it for later restoring
1559 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1577 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1560
1578
1561 if opts.has_key('i'):
1579 if opts.has_key('i'):
1562 # Run in user's interactive namespace
1580 # Run in user's interactive namespace
1563 prog_ns = self.shell.user_ns
1581 prog_ns = self.shell.user_ns
1564 __name__save = self.shell.user_ns['__name__']
1582 __name__save = self.shell.user_ns['__name__']
1565 prog_ns['__name__'] = '__main__'
1583 prog_ns['__name__'] = '__main__'
1566 main_mod = FakeModule(prog_ns)
1584 main_mod = FakeModule(prog_ns)
1567 else:
1585 else:
1568 # Run in a fresh, empty namespace
1586 # Run in a fresh, empty namespace
1569 if opts.has_key('n'):
1587 if opts.has_key('n'):
1570 name = os.path.splitext(os.path.basename(filename))[0]
1588 name = os.path.splitext(os.path.basename(filename))[0]
1571 else:
1589 else:
1572 name = '__main__'
1590 name = '__main__'
1573 main_mod = FakeModule()
1591 main_mod = FakeModule()
1574 prog_ns = main_mod.__dict__
1592 prog_ns = main_mod.__dict__
1575 prog_ns['__name__'] = name
1593 prog_ns['__name__'] = name
1576
1594
1577 # The shell MUST hold a reference to main_mod so after %run exits,
1595 # The shell MUST hold a reference to main_mod so after %run exits,
1578 # the python deletion mechanism doesn't zero it out (leaving
1596 # the python deletion mechanism doesn't zero it out (leaving
1579 # dangling references)
1597 # dangling references). However, we should drop old versions of
1580
1598 # main_mod. There is now a proper API to manage this caching in
1581 # XXX - the note above was written without further detail, but this
1599 # the main shell object, we use that.
1582 # code actually causes problems. By holding references to the
1600 self.shell.cache_main_mod(main_mod)
1583 # namespace where every script is executed, we effectively disable
1584 # just about all possible variable cleanup. In particular,
1585 # generator expressions and other variables that point to open
1586 # files are kept alive, and as a user session lives on, it may run
1587 # out of available file descriptors. Such a bug has already been
1588 # reported by JD Hunter. I'm disabling this for now, but we need
1589 # to clarify exactly (and add tests) what from main_mod needs to be
1590 # kept alive and what is save to remove... In fact, see note
1591 # below, where we append main_mod to sys.modules and then delete it
1592 # again. The final cleanup is rendered moot by this reference kept
1593 # in _user_main_modules(), so we really need to look into this.
1594
1595 self.shell._user_main_modules.append(main_mod)
1596
1597 # /XXX
1598
1601
1599 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1602 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1600 # set the __file__ global in the script's namespace
1603 # set the __file__ global in the script's namespace
1601 prog_ns['__file__'] = filename
1604 prog_ns['__file__'] = filename
1602
1605
1603 # pickle fix. See iplib for an explanation. But we need to make sure
1606 # pickle fix. See iplib for an explanation. But we need to make sure
1604 # that, if we overwrite __main__, we replace it at the end
1607 # that, if we overwrite __main__, we replace it at the end
1605 main_mod_name = prog_ns['__name__']
1608 main_mod_name = prog_ns['__name__']
1606
1609
1607 if main_mod_name == '__main__':
1610 if main_mod_name == '__main__':
1608 restore_main = sys.modules['__main__']
1611 restore_main = sys.modules['__main__']
1609 else:
1612 else:
1610 restore_main = False
1613 restore_main = False
1611
1614
1612 # This needs to be undone at the end to prevent holding references to
1615 # This needs to be undone at the end to prevent holding references to
1613 # every single object ever created.
1616 # every single object ever created.
1614 sys.modules[main_mod_name] = main_mod
1617 sys.modules[main_mod_name] = main_mod
1615
1618
1616 stats = None
1619 stats = None
1617 try:
1620 try:
1618 self.shell.savehist()
1621 self.shell.savehist()
1619
1622
1620 if opts.has_key('p'):
1623 if opts.has_key('p'):
1621 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1624 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1622 else:
1625 else:
1623 if opts.has_key('d'):
1626 if opts.has_key('d'):
1624 deb = Debugger.Pdb(self.shell.rc.colors)
1627 deb = Debugger.Pdb(self.shell.rc.colors)
1625 # reset Breakpoint state, which is moronically kept
1628 # reset Breakpoint state, which is moronically kept
1626 # in a class
1629 # in a class
1627 bdb.Breakpoint.next = 1
1630 bdb.Breakpoint.next = 1
1628 bdb.Breakpoint.bplist = {}
1631 bdb.Breakpoint.bplist = {}
1629 bdb.Breakpoint.bpbynumber = [None]
1632 bdb.Breakpoint.bpbynumber = [None]
1630 # Set an initial breakpoint to stop execution
1633 # Set an initial breakpoint to stop execution
1631 maxtries = 10
1634 maxtries = 10
1632 bp = int(opts.get('b',[1])[0])
1635 bp = int(opts.get('b',[1])[0])
1633 checkline = deb.checkline(filename,bp)
1636 checkline = deb.checkline(filename,bp)
1634 if not checkline:
1637 if not checkline:
1635 for bp in range(bp+1,bp+maxtries+1):
1638 for bp in range(bp+1,bp+maxtries+1):
1636 if deb.checkline(filename,bp):
1639 if deb.checkline(filename,bp):
1637 break
1640 break
1638 else:
1641 else:
1639 msg = ("\nI failed to find a valid line to set "
1642 msg = ("\nI failed to find a valid line to set "
1640 "a breakpoint\n"
1643 "a breakpoint\n"
1641 "after trying up to line: %s.\n"
1644 "after trying up to line: %s.\n"
1642 "Please set a valid breakpoint manually "
1645 "Please set a valid breakpoint manually "
1643 "with the -b option." % bp)
1646 "with the -b option." % bp)
1644 error(msg)
1647 error(msg)
1645 return
1648 return
1646 # if we find a good linenumber, set the breakpoint
1649 # if we find a good linenumber, set the breakpoint
1647 deb.do_break('%s:%s' % (filename,bp))
1650 deb.do_break('%s:%s' % (filename,bp))
1648 # Start file run
1651 # Start file run
1649 print "NOTE: Enter 'c' at the",
1652 print "NOTE: Enter 'c' at the",
1650 print "%s prompt to start your script." % deb.prompt
1653 print "%s prompt to start your script." % deb.prompt
1651 try:
1654 try:
1652 deb.run('execfile("%s")' % filename,prog_ns)
1655 deb.run('execfile("%s")' % filename,prog_ns)
1653
1656
1654 except:
1657 except:
1655 etype, value, tb = sys.exc_info()
1658 etype, value, tb = sys.exc_info()
1656 # Skip three frames in the traceback: the %run one,
1659 # Skip three frames in the traceback: the %run one,
1657 # one inside bdb.py, and the command-line typed by the
1660 # one inside bdb.py, and the command-line typed by the
1658 # user (run by exec in pdb itself).
1661 # user (run by exec in pdb itself).
1659 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1662 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1660 else:
1663 else:
1661 if runner is None:
1664 if runner is None:
1662 runner = self.shell.safe_execfile
1665 runner = self.shell.safe_execfile
1663 if opts.has_key('t'):
1666 if opts.has_key('t'):
1664 # timed execution
1667 # timed execution
1665 try:
1668 try:
1666 nruns = int(opts['N'][0])
1669 nruns = int(opts['N'][0])
1667 if nruns < 1:
1670 if nruns < 1:
1668 error('Number of runs must be >=1')
1671 error('Number of runs must be >=1')
1669 return
1672 return
1670 except (KeyError):
1673 except (KeyError):
1671 nruns = 1
1674 nruns = 1
1672 if nruns == 1:
1675 if nruns == 1:
1673 t0 = clock2()
1676 t0 = clock2()
1674 runner(filename,prog_ns,prog_ns,
1677 runner(filename,prog_ns,prog_ns,
1675 exit_ignore=exit_ignore)
1678 exit_ignore=exit_ignore)
1676 t1 = clock2()
1679 t1 = clock2()
1677 t_usr = t1[0]-t0[0]
1680 t_usr = t1[0]-t0[0]
1678 t_sys = t1[1]-t1[1]
1681 t_sys = t1[1]-t1[1]
1679 print "\nIPython CPU timings (estimated):"
1682 print "\nIPython CPU timings (estimated):"
1680 print " User : %10s s." % t_usr
1683 print " User : %10s s." % t_usr
1681 print " System: %10s s." % t_sys
1684 print " System: %10s s." % t_sys
1682 else:
1685 else:
1683 runs = range(nruns)
1686 runs = range(nruns)
1684 t0 = clock2()
1687 t0 = clock2()
1685 for nr in runs:
1688 for nr in runs:
1686 runner(filename,prog_ns,prog_ns,
1689 runner(filename,prog_ns,prog_ns,
1687 exit_ignore=exit_ignore)
1690 exit_ignore=exit_ignore)
1688 t1 = clock2()
1691 t1 = clock2()
1689 t_usr = t1[0]-t0[0]
1692 t_usr = t1[0]-t0[0]
1690 t_sys = t1[1]-t1[1]
1693 t_sys = t1[1]-t1[1]
1691 print "\nIPython CPU timings (estimated):"
1694 print "\nIPython CPU timings (estimated):"
1692 print "Total runs performed:",nruns
1695 print "Total runs performed:",nruns
1693 print " Times : %10s %10s" % ('Total','Per run')
1696 print " Times : %10s %10s" % ('Total','Per run')
1694 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1697 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1695 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1698 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1696
1699
1697 else:
1700 else:
1698 # regular execution
1701 # regular execution
1699 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1702 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1700 if opts.has_key('i'):
1703 if opts.has_key('i'):
1701 self.shell.user_ns['__name__'] = __name__save
1704 self.shell.user_ns['__name__'] = __name__save
1702 else:
1705 else:
1703 # update IPython interactive namespace
1706 # update IPython interactive namespace
1704 del prog_ns['__name__']
1707 del prog_ns['__name__']
1705 self.shell.user_ns.update(prog_ns)
1708 self.shell.user_ns.update(prog_ns)
1706 finally:
1709 finally:
1707 # Ensure key global structures are restored
1710 # Ensure key global structures are restored
1708 sys.argv = save_argv
1711 sys.argv = save_argv
1709 if restore_main:
1712 if restore_main:
1710 sys.modules['__main__'] = restore_main
1713 sys.modules['__main__'] = restore_main
1711 else:
1714 else:
1712 # Remove from sys.modules the reference to main_mod we'd
1715 # Remove from sys.modules the reference to main_mod we'd
1713 # added. Otherwise it will trap references to objects
1716 # added. Otherwise it will trap references to objects
1714 # contained therein.
1717 # contained therein.
1715 del sys.modules[main_mod_name]
1718 del sys.modules[main_mod_name]
1716 self.shell.reloadhist()
1719 self.shell.reloadhist()
1717
1720
1718 return stats
1721 return stats
1719
1722
1720 def magic_runlog(self, parameter_s =''):
1723 def magic_runlog(self, parameter_s =''):
1721 """Run files as logs.
1724 """Run files as logs.
1722
1725
1723 Usage:\\
1726 Usage:\\
1724 %runlog file1 file2 ...
1727 %runlog file1 file2 ...
1725
1728
1726 Run the named files (treating them as log files) in sequence inside
1729 Run the named files (treating them as log files) in sequence inside
1727 the interpreter, and return to the prompt. This is much slower than
1730 the interpreter, and return to the prompt. This is much slower than
1728 %run because each line is executed in a try/except block, but it
1731 %run because each line is executed in a try/except block, but it
1729 allows running files with syntax errors in them.
1732 allows running files with syntax errors in them.
1730
1733
1731 Normally IPython will guess when a file is one of its own logfiles, so
1734 Normally IPython will guess when a file is one of its own logfiles, so
1732 you can typically use %run even for logs. This shorthand allows you to
1735 you can typically use %run even for logs. This shorthand allows you to
1733 force any file to be treated as a log file."""
1736 force any file to be treated as a log file."""
1734
1737
1735 for f in parameter_s.split():
1738 for f in parameter_s.split():
1736 self.shell.safe_execfile(f,self.shell.user_ns,
1739 self.shell.safe_execfile(f,self.shell.user_ns,
1737 self.shell.user_ns,islog=1)
1740 self.shell.user_ns,islog=1)
1738
1741
1739 @testdec.skip_doctest
1742 @testdec.skip_doctest
1740 def magic_timeit(self, parameter_s =''):
1743 def magic_timeit(self, parameter_s =''):
1741 """Time execution of a Python statement or expression
1744 """Time execution of a Python statement or expression
1742
1745
1743 Usage:\\
1746 Usage:\\
1744 %timeit [-n<N> -r<R> [-t|-c]] statement
1747 %timeit [-n<N> -r<R> [-t|-c]] statement
1745
1748
1746 Time execution of a Python statement or expression using the timeit
1749 Time execution of a Python statement or expression using the timeit
1747 module.
1750 module.
1748
1751
1749 Options:
1752 Options:
1750 -n<N>: execute the given statement <N> times in a loop. If this value
1753 -n<N>: execute the given statement <N> times in a loop. If this value
1751 is not given, a fitting value is chosen.
1754 is not given, a fitting value is chosen.
1752
1755
1753 -r<R>: repeat the loop iteration <R> times and take the best result.
1756 -r<R>: repeat the loop iteration <R> times and take the best result.
1754 Default: 3
1757 Default: 3
1755
1758
1756 -t: use time.time to measure the time, which is the default on Unix.
1759 -t: use time.time to measure the time, which is the default on Unix.
1757 This function measures wall time.
1760 This function measures wall time.
1758
1761
1759 -c: use time.clock to measure the time, which is the default on
1762 -c: use time.clock to measure the time, which is the default on
1760 Windows and measures wall time. On Unix, resource.getrusage is used
1763 Windows and measures wall time. On Unix, resource.getrusage is used
1761 instead and returns the CPU user time.
1764 instead and returns the CPU user time.
1762
1765
1763 -p<P>: use a precision of <P> digits to display the timing result.
1766 -p<P>: use a precision of <P> digits to display the timing result.
1764 Default: 3
1767 Default: 3
1765
1768
1766
1769
1767 Examples:
1770 Examples:
1768
1771
1769 In [1]: %timeit pass
1772 In [1]: %timeit pass
1770 10000000 loops, best of 3: 53.3 ns per loop
1773 10000000 loops, best of 3: 53.3 ns per loop
1771
1774
1772 In [2]: u = None
1775 In [2]: u = None
1773
1776
1774 In [3]: %timeit u is None
1777 In [3]: %timeit u is None
1775 10000000 loops, best of 3: 184 ns per loop
1778 10000000 loops, best of 3: 184 ns per loop
1776
1779
1777 In [4]: %timeit -r 4 u == None
1780 In [4]: %timeit -r 4 u == None
1778 1000000 loops, best of 4: 242 ns per loop
1781 1000000 loops, best of 4: 242 ns per loop
1779
1782
1780 In [5]: import time
1783 In [5]: import time
1781
1784
1782 In [6]: %timeit -n1 time.sleep(2)
1785 In [6]: %timeit -n1 time.sleep(2)
1783 1 loops, best of 3: 2 s per loop
1786 1 loops, best of 3: 2 s per loop
1784
1787
1785
1788
1786 The times reported by %timeit will be slightly higher than those
1789 The times reported by %timeit will be slightly higher than those
1787 reported by the timeit.py script when variables are accessed. This is
1790 reported by the timeit.py script when variables are accessed. This is
1788 due to the fact that %timeit executes the statement in the namespace
1791 due to the fact that %timeit executes the statement in the namespace
1789 of the shell, compared with timeit.py, which uses a single setup
1792 of the shell, compared with timeit.py, which uses a single setup
1790 statement to import function or create variables. Generally, the bias
1793 statement to import function or create variables. Generally, the bias
1791 does not matter as long as results from timeit.py are not mixed with
1794 does not matter as long as results from timeit.py are not mixed with
1792 those from %timeit."""
1795 those from %timeit."""
1793
1796
1794 import timeit
1797 import timeit
1795 import math
1798 import math
1796
1799
1797 units = [u"s", u"ms", u"\xb5s", u"ns"]
1800 units = [u"s", u"ms", u"\xb5s", u"ns"]
1798 scaling = [1, 1e3, 1e6, 1e9]
1801 scaling = [1, 1e3, 1e6, 1e9]
1799
1802
1800 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1803 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1801 posix=False)
1804 posix=False)
1802 if stmt == "":
1805 if stmt == "":
1803 return
1806 return
1804 timefunc = timeit.default_timer
1807 timefunc = timeit.default_timer
1805 number = int(getattr(opts, "n", 0))
1808 number = int(getattr(opts, "n", 0))
1806 repeat = int(getattr(opts, "r", timeit.default_repeat))
1809 repeat = int(getattr(opts, "r", timeit.default_repeat))
1807 precision = int(getattr(opts, "p", 3))
1810 precision = int(getattr(opts, "p", 3))
1808 if hasattr(opts, "t"):
1811 if hasattr(opts, "t"):
1809 timefunc = time.time
1812 timefunc = time.time
1810 if hasattr(opts, "c"):
1813 if hasattr(opts, "c"):
1811 timefunc = clock
1814 timefunc = clock
1812
1815
1813 timer = timeit.Timer(timer=timefunc)
1816 timer = timeit.Timer(timer=timefunc)
1814 # this code has tight coupling to the inner workings of timeit.Timer,
1817 # this code has tight coupling to the inner workings of timeit.Timer,
1815 # but is there a better way to achieve that the code stmt has access
1818 # but is there a better way to achieve that the code stmt has access
1816 # to the shell namespace?
1819 # to the shell namespace?
1817
1820
1818 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1821 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1819 'setup': "pass"}
1822 'setup': "pass"}
1820 # Track compilation time so it can be reported if too long
1823 # Track compilation time so it can be reported if too long
1821 # Minimum time above which compilation time will be reported
1824 # Minimum time above which compilation time will be reported
1822 tc_min = 0.1
1825 tc_min = 0.1
1823
1826
1824 t0 = clock()
1827 t0 = clock()
1825 code = compile(src, "<magic-timeit>", "exec")
1828 code = compile(src, "<magic-timeit>", "exec")
1826 tc = clock()-t0
1829 tc = clock()-t0
1827
1830
1828 ns = {}
1831 ns = {}
1829 exec code in self.shell.user_ns, ns
1832 exec code in self.shell.user_ns, ns
1830 timer.inner = ns["inner"]
1833 timer.inner = ns["inner"]
1831
1834
1832 if number == 0:
1835 if number == 0:
1833 # determine number so that 0.2 <= total time < 2.0
1836 # determine number so that 0.2 <= total time < 2.0
1834 number = 1
1837 number = 1
1835 for i in range(1, 10):
1838 for i in range(1, 10):
1836 number *= 10
1839 number *= 10
1837 if timer.timeit(number) >= 0.2:
1840 if timer.timeit(number) >= 0.2:
1838 break
1841 break
1839
1842
1840 best = min(timer.repeat(repeat, number)) / number
1843 best = min(timer.repeat(repeat, number)) / number
1841
1844
1842 if best > 0.0:
1845 if best > 0.0:
1843 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1846 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1844 else:
1847 else:
1845 order = 3
1848 order = 3
1846 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1849 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1847 precision,
1850 precision,
1848 best * scaling[order],
1851 best * scaling[order],
1849 units[order])
1852 units[order])
1850 if tc > tc_min:
1853 if tc > tc_min:
1851 print "Compiler time: %.2f s" % tc
1854 print "Compiler time: %.2f s" % tc
1852
1855
1853 @testdec.skip_doctest
1856 @testdec.skip_doctest
1854 def magic_time(self,parameter_s = ''):
1857 def magic_time(self,parameter_s = ''):
1855 """Time execution of a Python statement or expression.
1858 """Time execution of a Python statement or expression.
1856
1859
1857 The CPU and wall clock times are printed, and the value of the
1860 The CPU and wall clock times are printed, and the value of the
1858 expression (if any) is returned. Note that under Win32, system time
1861 expression (if any) is returned. Note that under Win32, system time
1859 is always reported as 0, since it can not be measured.
1862 is always reported as 0, since it can not be measured.
1860
1863
1861 This function provides very basic timing functionality. In Python
1864 This function provides very basic timing functionality. In Python
1862 2.3, the timeit module offers more control and sophistication, so this
1865 2.3, the timeit module offers more control and sophistication, so this
1863 could be rewritten to use it (patches welcome).
1866 could be rewritten to use it (patches welcome).
1864
1867
1865 Some examples:
1868 Some examples:
1866
1869
1867 In [1]: time 2**128
1870 In [1]: time 2**128
1868 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1871 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1869 Wall time: 0.00
1872 Wall time: 0.00
1870 Out[1]: 340282366920938463463374607431768211456L
1873 Out[1]: 340282366920938463463374607431768211456L
1871
1874
1872 In [2]: n = 1000000
1875 In [2]: n = 1000000
1873
1876
1874 In [3]: time sum(range(n))
1877 In [3]: time sum(range(n))
1875 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1878 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1876 Wall time: 1.37
1879 Wall time: 1.37
1877 Out[3]: 499999500000L
1880 Out[3]: 499999500000L
1878
1881
1879 In [4]: time print 'hello world'
1882 In [4]: time print 'hello world'
1880 hello world
1883 hello world
1881 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1884 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1882 Wall time: 0.00
1885 Wall time: 0.00
1883
1886
1884 Note that the time needed by Python to compile the given expression
1887 Note that the time needed by Python to compile the given expression
1885 will be reported if it is more than 0.1s. In this example, the
1888 will be reported if it is more than 0.1s. In this example, the
1886 actual exponentiation is done by Python at compilation time, so while
1889 actual exponentiation is done by Python at compilation time, so while
1887 the expression can take a noticeable amount of time to compute, that
1890 the expression can take a noticeable amount of time to compute, that
1888 time is purely due to the compilation:
1891 time is purely due to the compilation:
1889
1892
1890 In [5]: time 3**9999;
1893 In [5]: time 3**9999;
1891 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1894 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1892 Wall time: 0.00 s
1895 Wall time: 0.00 s
1893
1896
1894 In [6]: time 3**999999;
1897 In [6]: time 3**999999;
1895 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1898 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1896 Wall time: 0.00 s
1899 Wall time: 0.00 s
1897 Compiler : 0.78 s
1900 Compiler : 0.78 s
1898 """
1901 """
1899
1902
1900 # fail immediately if the given expression can't be compiled
1903 # fail immediately if the given expression can't be compiled
1901
1904
1902 expr = self.shell.prefilter(parameter_s,False)
1905 expr = self.shell.prefilter(parameter_s,False)
1903
1906
1904 # Minimum time above which compilation time will be reported
1907 # Minimum time above which compilation time will be reported
1905 tc_min = 0.1
1908 tc_min = 0.1
1906
1909
1907 try:
1910 try:
1908 mode = 'eval'
1911 mode = 'eval'
1909 t0 = clock()
1912 t0 = clock()
1910 code = compile(expr,'<timed eval>',mode)
1913 code = compile(expr,'<timed eval>',mode)
1911 tc = clock()-t0
1914 tc = clock()-t0
1912 except SyntaxError:
1915 except SyntaxError:
1913 mode = 'exec'
1916 mode = 'exec'
1914 t0 = clock()
1917 t0 = clock()
1915 code = compile(expr,'<timed exec>',mode)
1918 code = compile(expr,'<timed exec>',mode)
1916 tc = clock()-t0
1919 tc = clock()-t0
1917 # skew measurement as little as possible
1920 # skew measurement as little as possible
1918 glob = self.shell.user_ns
1921 glob = self.shell.user_ns
1919 clk = clock2
1922 clk = clock2
1920 wtime = time.time
1923 wtime = time.time
1921 # time execution
1924 # time execution
1922 wall_st = wtime()
1925 wall_st = wtime()
1923 if mode=='eval':
1926 if mode=='eval':
1924 st = clk()
1927 st = clk()
1925 out = eval(code,glob)
1928 out = eval(code,glob)
1926 end = clk()
1929 end = clk()
1927 else:
1930 else:
1928 st = clk()
1931 st = clk()
1929 exec code in glob
1932 exec code in glob
1930 end = clk()
1933 end = clk()
1931 out = None
1934 out = None
1932 wall_end = wtime()
1935 wall_end = wtime()
1933 # Compute actual times and report
1936 # Compute actual times and report
1934 wall_time = wall_end-wall_st
1937 wall_time = wall_end-wall_st
1935 cpu_user = end[0]-st[0]
1938 cpu_user = end[0]-st[0]
1936 cpu_sys = end[1]-st[1]
1939 cpu_sys = end[1]-st[1]
1937 cpu_tot = cpu_user+cpu_sys
1940 cpu_tot = cpu_user+cpu_sys
1938 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1941 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1939 (cpu_user,cpu_sys,cpu_tot)
1942 (cpu_user,cpu_sys,cpu_tot)
1940 print "Wall time: %.2f s" % wall_time
1943 print "Wall time: %.2f s" % wall_time
1941 if tc > tc_min:
1944 if tc > tc_min:
1942 print "Compiler : %.2f s" % tc
1945 print "Compiler : %.2f s" % tc
1943 return out
1946 return out
1944
1947
1945 @testdec.skip_doctest
1948 @testdec.skip_doctest
1946 def magic_macro(self,parameter_s = ''):
1949 def magic_macro(self,parameter_s = ''):
1947 """Define a set of input lines as a macro for future re-execution.
1950 """Define a set of input lines as a macro for future re-execution.
1948
1951
1949 Usage:\\
1952 Usage:\\
1950 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1953 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1951
1954
1952 Options:
1955 Options:
1953
1956
1954 -r: use 'raw' input. By default, the 'processed' history is used,
1957 -r: use 'raw' input. By default, the 'processed' history is used,
1955 so that magics are loaded in their transformed version to valid
1958 so that magics are loaded in their transformed version to valid
1956 Python. If this option is given, the raw input as typed as the
1959 Python. If this option is given, the raw input as typed as the
1957 command line is used instead.
1960 command line is used instead.
1958
1961
1959 This will define a global variable called `name` which is a string
1962 This will define a global variable called `name` which is a string
1960 made of joining the slices and lines you specify (n1,n2,... numbers
1963 made of joining the slices and lines you specify (n1,n2,... numbers
1961 above) from your input history into a single string. This variable
1964 above) from your input history into a single string. This variable
1962 acts like an automatic function which re-executes those lines as if
1965 acts like an automatic function which re-executes those lines as if
1963 you had typed them. You just type 'name' at the prompt and the code
1966 you had typed them. You just type 'name' at the prompt and the code
1964 executes.
1967 executes.
1965
1968
1966 The notation for indicating number ranges is: n1-n2 means 'use line
1969 The notation for indicating number ranges is: n1-n2 means 'use line
1967 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1970 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1968 using the lines numbered 5,6 and 7.
1971 using the lines numbered 5,6 and 7.
1969
1972
1970 Note: as a 'hidden' feature, you can also use traditional python slice
1973 Note: as a 'hidden' feature, you can also use traditional python slice
1971 notation, where N:M means numbers N through M-1.
1974 notation, where N:M means numbers N through M-1.
1972
1975
1973 For example, if your history contains (%hist prints it):
1976 For example, if your history contains (%hist prints it):
1974
1977
1975 44: x=1
1978 44: x=1
1976 45: y=3
1979 45: y=3
1977 46: z=x+y
1980 46: z=x+y
1978 47: print x
1981 47: print x
1979 48: a=5
1982 48: a=5
1980 49: print 'x',x,'y',y
1983 49: print 'x',x,'y',y
1981
1984
1982 you can create a macro with lines 44 through 47 (included) and line 49
1985 you can create a macro with lines 44 through 47 (included) and line 49
1983 called my_macro with:
1986 called my_macro with:
1984
1987
1985 In [55]: %macro my_macro 44-47 49
1988 In [55]: %macro my_macro 44-47 49
1986
1989
1987 Now, typing `my_macro` (without quotes) will re-execute all this code
1990 Now, typing `my_macro` (without quotes) will re-execute all this code
1988 in one pass.
1991 in one pass.
1989
1992
1990 You don't need to give the line-numbers in order, and any given line
1993 You don't need to give the line-numbers in order, and any given line
1991 number can appear multiple times. You can assemble macros with any
1994 number can appear multiple times. You can assemble macros with any
1992 lines from your input history in any order.
1995 lines from your input history in any order.
1993
1996
1994 The macro is a simple object which holds its value in an attribute,
1997 The macro is a simple object which holds its value in an attribute,
1995 but IPython's display system checks for macros and executes them as
1998 but IPython's display system checks for macros and executes them as
1996 code instead of printing them when you type their name.
1999 code instead of printing them when you type their name.
1997
2000
1998 You can view a macro's contents by explicitly printing it with:
2001 You can view a macro's contents by explicitly printing it with:
1999
2002
2000 'print macro_name'.
2003 'print macro_name'.
2001
2004
2002 For one-off cases which DON'T contain magic function calls in them you
2005 For one-off cases which DON'T contain magic function calls in them you
2003 can obtain similar results by explicitly executing slices from your
2006 can obtain similar results by explicitly executing slices from your
2004 input history with:
2007 input history with:
2005
2008
2006 In [60]: exec In[44:48]+In[49]"""
2009 In [60]: exec In[44:48]+In[49]"""
2007
2010
2008 opts,args = self.parse_options(parameter_s,'r',mode='list')
2011 opts,args = self.parse_options(parameter_s,'r',mode='list')
2009 if not args:
2012 if not args:
2010 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2013 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2011 macs.sort()
2014 macs.sort()
2012 return macs
2015 return macs
2013 if len(args) == 1:
2016 if len(args) == 1:
2014 raise UsageError(
2017 raise UsageError(
2015 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2018 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2016 name,ranges = args[0], args[1:]
2019 name,ranges = args[0], args[1:]
2017
2020
2018 #print 'rng',ranges # dbg
2021 #print 'rng',ranges # dbg
2019 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2022 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2020 macro = Macro(lines)
2023 macro = Macro(lines)
2021 self.shell.user_ns.update({name:macro})
2024 self.shell.user_ns.update({name:macro})
2022 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2025 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2023 print 'Macro contents:'
2026 print 'Macro contents:'
2024 print macro,
2027 print macro,
2025
2028
2026 def magic_save(self,parameter_s = ''):
2029 def magic_save(self,parameter_s = ''):
2027 """Save a set of lines to a given filename.
2030 """Save a set of lines to a given filename.
2028
2031
2029 Usage:\\
2032 Usage:\\
2030 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2033 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2031
2034
2032 Options:
2035 Options:
2033
2036
2034 -r: use 'raw' input. By default, the 'processed' history is used,
2037 -r: use 'raw' input. By default, the 'processed' history is used,
2035 so that magics are loaded in their transformed version to valid
2038 so that magics are loaded in their transformed version to valid
2036 Python. If this option is given, the raw input as typed as the
2039 Python. If this option is given, the raw input as typed as the
2037 command line is used instead.
2040 command line is used instead.
2038
2041
2039 This function uses the same syntax as %macro for line extraction, but
2042 This function uses the same syntax as %macro for line extraction, but
2040 instead of creating a macro it saves the resulting string to the
2043 instead of creating a macro it saves the resulting string to the
2041 filename you specify.
2044 filename you specify.
2042
2045
2043 It adds a '.py' extension to the file if you don't do so yourself, and
2046 It adds a '.py' extension to the file if you don't do so yourself, and
2044 it asks for confirmation before overwriting existing files."""
2047 it asks for confirmation before overwriting existing files."""
2045
2048
2046 opts,args = self.parse_options(parameter_s,'r',mode='list')
2049 opts,args = self.parse_options(parameter_s,'r',mode='list')
2047 fname,ranges = args[0], args[1:]
2050 fname,ranges = args[0], args[1:]
2048 if not fname.endswith('.py'):
2051 if not fname.endswith('.py'):
2049 fname += '.py'
2052 fname += '.py'
2050 if os.path.isfile(fname):
2053 if os.path.isfile(fname):
2051 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2054 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2052 if ans.lower() not in ['y','yes']:
2055 if ans.lower() not in ['y','yes']:
2053 print 'Operation cancelled.'
2056 print 'Operation cancelled.'
2054 return
2057 return
2055 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2058 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2056 f = file(fname,'w')
2059 f = file(fname,'w')
2057 f.write(cmds)
2060 f.write(cmds)
2058 f.close()
2061 f.close()
2059 print 'The following commands were written to file `%s`:' % fname
2062 print 'The following commands were written to file `%s`:' % fname
2060 print cmds
2063 print cmds
2061
2064
2062 def _edit_macro(self,mname,macro):
2065 def _edit_macro(self,mname,macro):
2063 """open an editor with the macro data in a file"""
2066 """open an editor with the macro data in a file"""
2064 filename = self.shell.mktempfile(macro.value)
2067 filename = self.shell.mktempfile(macro.value)
2065 self.shell.hooks.editor(filename)
2068 self.shell.hooks.editor(filename)
2066
2069
2067 # and make a new macro object, to replace the old one
2070 # and make a new macro object, to replace the old one
2068 mfile = open(filename)
2071 mfile = open(filename)
2069 mvalue = mfile.read()
2072 mvalue = mfile.read()
2070 mfile.close()
2073 mfile.close()
2071 self.shell.user_ns[mname] = Macro(mvalue)
2074 self.shell.user_ns[mname] = Macro(mvalue)
2072
2075
2073 def magic_ed(self,parameter_s=''):
2076 def magic_ed(self,parameter_s=''):
2074 """Alias to %edit."""
2077 """Alias to %edit."""
2075 return self.magic_edit(parameter_s)
2078 return self.magic_edit(parameter_s)
2076
2079
2077 @testdec.skip_doctest
2080 @testdec.skip_doctest
2078 def magic_edit(self,parameter_s='',last_call=['','']):
2081 def magic_edit(self,parameter_s='',last_call=['','']):
2079 """Bring up an editor and execute the resulting code.
2082 """Bring up an editor and execute the resulting code.
2080
2083
2081 Usage:
2084 Usage:
2082 %edit [options] [args]
2085 %edit [options] [args]
2083
2086
2084 %edit runs IPython's editor hook. The default version of this hook is
2087 %edit runs IPython's editor hook. The default version of this hook is
2085 set to call the __IPYTHON__.rc.editor command. This is read from your
2088 set to call the __IPYTHON__.rc.editor command. This is read from your
2086 environment variable $EDITOR. If this isn't found, it will default to
2089 environment variable $EDITOR. If this isn't found, it will default to
2087 vi under Linux/Unix and to notepad under Windows. See the end of this
2090 vi under Linux/Unix and to notepad under Windows. See the end of this
2088 docstring for how to change the editor hook.
2091 docstring for how to change the editor hook.
2089
2092
2090 You can also set the value of this editor via the command line option
2093 You can also set the value of this editor via the command line option
2091 '-editor' or in your ipythonrc file. This is useful if you wish to use
2094 '-editor' or in your ipythonrc file. This is useful if you wish to use
2092 specifically for IPython an editor different from your typical default
2095 specifically for IPython an editor different from your typical default
2093 (and for Windows users who typically don't set environment variables).
2096 (and for Windows users who typically don't set environment variables).
2094
2097
2095 This command allows you to conveniently edit multi-line code right in
2098 This command allows you to conveniently edit multi-line code right in
2096 your IPython session.
2099 your IPython session.
2097
2100
2098 If called without arguments, %edit opens up an empty editor with a
2101 If called without arguments, %edit opens up an empty editor with a
2099 temporary file and will execute the contents of this file when you
2102 temporary file and will execute the contents of this file when you
2100 close it (don't forget to save it!).
2103 close it (don't forget to save it!).
2101
2104
2102
2105
2103 Options:
2106 Options:
2104
2107
2105 -n <number>: open the editor at a specified line number. By default,
2108 -n <number>: open the editor at a specified line number. By default,
2106 the IPython editor hook uses the unix syntax 'editor +N filename', but
2109 the IPython editor hook uses the unix syntax 'editor +N filename', but
2107 you can configure this by providing your own modified hook if your
2110 you can configure this by providing your own modified hook if your
2108 favorite editor supports line-number specifications with a different
2111 favorite editor supports line-number specifications with a different
2109 syntax.
2112 syntax.
2110
2113
2111 -p: this will call the editor with the same data as the previous time
2114 -p: this will call the editor with the same data as the previous time
2112 it was used, regardless of how long ago (in your current session) it
2115 it was used, regardless of how long ago (in your current session) it
2113 was.
2116 was.
2114
2117
2115 -r: use 'raw' input. This option only applies to input taken from the
2118 -r: use 'raw' input. This option only applies to input taken from the
2116 user's history. By default, the 'processed' history is used, so that
2119 user's history. By default, the 'processed' history is used, so that
2117 magics are loaded in their transformed version to valid Python. If
2120 magics are loaded in their transformed version to valid Python. If
2118 this option is given, the raw input as typed as the command line is
2121 this option is given, the raw input as typed as the command line is
2119 used instead. When you exit the editor, it will be executed by
2122 used instead. When you exit the editor, it will be executed by
2120 IPython's own processor.
2123 IPython's own processor.
2121
2124
2122 -x: do not execute the edited code immediately upon exit. This is
2125 -x: do not execute the edited code immediately upon exit. This is
2123 mainly useful if you are editing programs which need to be called with
2126 mainly useful if you are editing programs which need to be called with
2124 command line arguments, which you can then do using %run.
2127 command line arguments, which you can then do using %run.
2125
2128
2126
2129
2127 Arguments:
2130 Arguments:
2128
2131
2129 If arguments are given, the following possibilites exist:
2132 If arguments are given, the following possibilites exist:
2130
2133
2131 - The arguments are numbers or pairs of colon-separated numbers (like
2134 - The arguments are numbers or pairs of colon-separated numbers (like
2132 1 4:8 9). These are interpreted as lines of previous input to be
2135 1 4:8 9). These are interpreted as lines of previous input to be
2133 loaded into the editor. The syntax is the same of the %macro command.
2136 loaded into the editor. The syntax is the same of the %macro command.
2134
2137
2135 - If the argument doesn't start with a number, it is evaluated as a
2138 - If the argument doesn't start with a number, it is evaluated as a
2136 variable and its contents loaded into the editor. You can thus edit
2139 variable and its contents loaded into the editor. You can thus edit
2137 any string which contains python code (including the result of
2140 any string which contains python code (including the result of
2138 previous edits).
2141 previous edits).
2139
2142
2140 - If the argument is the name of an object (other than a string),
2143 - If the argument is the name of an object (other than a string),
2141 IPython will try to locate the file where it was defined and open the
2144 IPython will try to locate the file where it was defined and open the
2142 editor at the point where it is defined. You can use `%edit function`
2145 editor at the point where it is defined. You can use `%edit function`
2143 to load an editor exactly at the point where 'function' is defined,
2146 to load an editor exactly at the point where 'function' is defined,
2144 edit it and have the file be executed automatically.
2147 edit it and have the file be executed automatically.
2145
2148
2146 If the object is a macro (see %macro for details), this opens up your
2149 If the object is a macro (see %macro for details), this opens up your
2147 specified editor with a temporary file containing the macro's data.
2150 specified editor with a temporary file containing the macro's data.
2148 Upon exit, the macro is reloaded with the contents of the file.
2151 Upon exit, the macro is reloaded with the contents of the file.
2149
2152
2150 Note: opening at an exact line is only supported under Unix, and some
2153 Note: opening at an exact line is only supported under Unix, and some
2151 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2154 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2152 '+NUMBER' parameter necessary for this feature. Good editors like
2155 '+NUMBER' parameter necessary for this feature. Good editors like
2153 (X)Emacs, vi, jed, pico and joe all do.
2156 (X)Emacs, vi, jed, pico and joe all do.
2154
2157
2155 - If the argument is not found as a variable, IPython will look for a
2158 - If the argument is not found as a variable, IPython will look for a
2156 file with that name (adding .py if necessary) and load it into the
2159 file with that name (adding .py if necessary) and load it into the
2157 editor. It will execute its contents with execfile() when you exit,
2160 editor. It will execute its contents with execfile() when you exit,
2158 loading any code in the file into your interactive namespace.
2161 loading any code in the file into your interactive namespace.
2159
2162
2160 After executing your code, %edit will return as output the code you
2163 After executing your code, %edit will return as output the code you
2161 typed in the editor (except when it was an existing file). This way
2164 typed in the editor (except when it was an existing file). This way
2162 you can reload the code in further invocations of %edit as a variable,
2165 you can reload the code in further invocations of %edit as a variable,
2163 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2166 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2164 the output.
2167 the output.
2165
2168
2166 Note that %edit is also available through the alias %ed.
2169 Note that %edit is also available through the alias %ed.
2167
2170
2168 This is an example of creating a simple function inside the editor and
2171 This is an example of creating a simple function inside the editor and
2169 then modifying it. First, start up the editor:
2172 then modifying it. First, start up the editor:
2170
2173
2171 In [1]: ed
2174 In [1]: ed
2172 Editing... done. Executing edited code...
2175 Editing... done. Executing edited code...
2173 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2176 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2174
2177
2175 We can then call the function foo():
2178 We can then call the function foo():
2176
2179
2177 In [2]: foo()
2180 In [2]: foo()
2178 foo() was defined in an editing session
2181 foo() was defined in an editing session
2179
2182
2180 Now we edit foo. IPython automatically loads the editor with the
2183 Now we edit foo. IPython automatically loads the editor with the
2181 (temporary) file where foo() was previously defined:
2184 (temporary) file where foo() was previously defined:
2182
2185
2183 In [3]: ed foo
2186 In [3]: ed foo
2184 Editing... done. Executing edited code...
2187 Editing... done. Executing edited code...
2185
2188
2186 And if we call foo() again we get the modified version:
2189 And if we call foo() again we get the modified version:
2187
2190
2188 In [4]: foo()
2191 In [4]: foo()
2189 foo() has now been changed!
2192 foo() has now been changed!
2190
2193
2191 Here is an example of how to edit a code snippet successive
2194 Here is an example of how to edit a code snippet successive
2192 times. First we call the editor:
2195 times. First we call the editor:
2193
2196
2194 In [5]: ed
2197 In [5]: ed
2195 Editing... done. Executing edited code...
2198 Editing... done. Executing edited code...
2196 hello
2199 hello
2197 Out[5]: "print 'hello'n"
2200 Out[5]: "print 'hello'n"
2198
2201
2199 Now we call it again with the previous output (stored in _):
2202 Now we call it again with the previous output (stored in _):
2200
2203
2201 In [6]: ed _
2204 In [6]: ed _
2202 Editing... done. Executing edited code...
2205 Editing... done. Executing edited code...
2203 hello world
2206 hello world
2204 Out[6]: "print 'hello world'n"
2207 Out[6]: "print 'hello world'n"
2205
2208
2206 Now we call it with the output #8 (stored in _8, also as Out[8]):
2209 Now we call it with the output #8 (stored in _8, also as Out[8]):
2207
2210
2208 In [7]: ed _8
2211 In [7]: ed _8
2209 Editing... done. Executing edited code...
2212 Editing... done. Executing edited code...
2210 hello again
2213 hello again
2211 Out[7]: "print 'hello again'n"
2214 Out[7]: "print 'hello again'n"
2212
2215
2213
2216
2214 Changing the default editor hook:
2217 Changing the default editor hook:
2215
2218
2216 If you wish to write your own editor hook, you can put it in a
2219 If you wish to write your own editor hook, you can put it in a
2217 configuration file which you load at startup time. The default hook
2220 configuration file which you load at startup time. The default hook
2218 is defined in the IPython.hooks module, and you can use that as a
2221 is defined in the IPython.hooks module, and you can use that as a
2219 starting example for further modifications. That file also has
2222 starting example for further modifications. That file also has
2220 general instructions on how to set a new hook for use once you've
2223 general instructions on how to set a new hook for use once you've
2221 defined it."""
2224 defined it."""
2222
2225
2223 # FIXME: This function has become a convoluted mess. It needs a
2226 # FIXME: This function has become a convoluted mess. It needs a
2224 # ground-up rewrite with clean, simple logic.
2227 # ground-up rewrite with clean, simple logic.
2225
2228
2226 def make_filename(arg):
2229 def make_filename(arg):
2227 "Make a filename from the given args"
2230 "Make a filename from the given args"
2228 try:
2231 try:
2229 filename = get_py_filename(arg)
2232 filename = get_py_filename(arg)
2230 except IOError:
2233 except IOError:
2231 if args.endswith('.py'):
2234 if args.endswith('.py'):
2232 filename = arg
2235 filename = arg
2233 else:
2236 else:
2234 filename = None
2237 filename = None
2235 return filename
2238 return filename
2236
2239
2237 # custom exceptions
2240 # custom exceptions
2238 class DataIsObject(Exception): pass
2241 class DataIsObject(Exception): pass
2239
2242
2240 opts,args = self.parse_options(parameter_s,'prxn:')
2243 opts,args = self.parse_options(parameter_s,'prxn:')
2241 # Set a few locals from the options for convenience:
2244 # Set a few locals from the options for convenience:
2242 opts_p = opts.has_key('p')
2245 opts_p = opts.has_key('p')
2243 opts_r = opts.has_key('r')
2246 opts_r = opts.has_key('r')
2244
2247
2245 # Default line number value
2248 # Default line number value
2246 lineno = opts.get('n',None)
2249 lineno = opts.get('n',None)
2247
2250
2248 if opts_p:
2251 if opts_p:
2249 args = '_%s' % last_call[0]
2252 args = '_%s' % last_call[0]
2250 if not self.shell.user_ns.has_key(args):
2253 if not self.shell.user_ns.has_key(args):
2251 args = last_call[1]
2254 args = last_call[1]
2252
2255
2253 # use last_call to remember the state of the previous call, but don't
2256 # use last_call to remember the state of the previous call, but don't
2254 # let it be clobbered by successive '-p' calls.
2257 # let it be clobbered by successive '-p' calls.
2255 try:
2258 try:
2256 last_call[0] = self.shell.outputcache.prompt_count
2259 last_call[0] = self.shell.outputcache.prompt_count
2257 if not opts_p:
2260 if not opts_p:
2258 last_call[1] = parameter_s
2261 last_call[1] = parameter_s
2259 except:
2262 except:
2260 pass
2263 pass
2261
2264
2262 # by default this is done with temp files, except when the given
2265 # by default this is done with temp files, except when the given
2263 # arg is a filename
2266 # arg is a filename
2264 use_temp = 1
2267 use_temp = 1
2265
2268
2266 if re.match(r'\d',args):
2269 if re.match(r'\d',args):
2267 # Mode where user specifies ranges of lines, like in %macro.
2270 # Mode where user specifies ranges of lines, like in %macro.
2268 # This means that you can't edit files whose names begin with
2271 # This means that you can't edit files whose names begin with
2269 # numbers this way. Tough.
2272 # numbers this way. Tough.
2270 ranges = args.split()
2273 ranges = args.split()
2271 data = ''.join(self.extract_input_slices(ranges,opts_r))
2274 data = ''.join(self.extract_input_slices(ranges,opts_r))
2272 elif args.endswith('.py'):
2275 elif args.endswith('.py'):
2273 filename = make_filename(args)
2276 filename = make_filename(args)
2274 data = ''
2277 data = ''
2275 use_temp = 0
2278 use_temp = 0
2276 elif args:
2279 elif args:
2277 try:
2280 try:
2278 # Load the parameter given as a variable. If not a string,
2281 # Load the parameter given as a variable. If not a string,
2279 # process it as an object instead (below)
2282 # process it as an object instead (below)
2280
2283
2281 #print '*** args',args,'type',type(args) # dbg
2284 #print '*** args',args,'type',type(args) # dbg
2282 data = eval(args,self.shell.user_ns)
2285 data = eval(args,self.shell.user_ns)
2283 if not type(data) in StringTypes:
2286 if not type(data) in StringTypes:
2284 raise DataIsObject
2287 raise DataIsObject
2285
2288
2286 except (NameError,SyntaxError):
2289 except (NameError,SyntaxError):
2287 # given argument is not a variable, try as a filename
2290 # given argument is not a variable, try as a filename
2288 filename = make_filename(args)
2291 filename = make_filename(args)
2289 if filename is None:
2292 if filename is None:
2290 warn("Argument given (%s) can't be found as a variable "
2293 warn("Argument given (%s) can't be found as a variable "
2291 "or as a filename." % args)
2294 "or as a filename." % args)
2292 return
2295 return
2293
2296
2294 data = ''
2297 data = ''
2295 use_temp = 0
2298 use_temp = 0
2296 except DataIsObject:
2299 except DataIsObject:
2297
2300
2298 # macros have a special edit function
2301 # macros have a special edit function
2299 if isinstance(data,Macro):
2302 if isinstance(data,Macro):
2300 self._edit_macro(args,data)
2303 self._edit_macro(args,data)
2301 return
2304 return
2302
2305
2303 # For objects, try to edit the file where they are defined
2306 # For objects, try to edit the file where they are defined
2304 try:
2307 try:
2305 filename = inspect.getabsfile(data)
2308 filename = inspect.getabsfile(data)
2306 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2309 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2307 # class created by %edit? Try to find source
2310 # class created by %edit? Try to find source
2308 # by looking for method definitions instead, the
2311 # by looking for method definitions instead, the
2309 # __module__ in those classes is FakeModule.
2312 # __module__ in those classes is FakeModule.
2310 attrs = [getattr(data, aname) for aname in dir(data)]
2313 attrs = [getattr(data, aname) for aname in dir(data)]
2311 for attr in attrs:
2314 for attr in attrs:
2312 if not inspect.ismethod(attr):
2315 if not inspect.ismethod(attr):
2313 continue
2316 continue
2314 filename = inspect.getabsfile(attr)
2317 filename = inspect.getabsfile(attr)
2315 if filename and 'fakemodule' not in filename.lower():
2318 if filename and 'fakemodule' not in filename.lower():
2316 # change the attribute to be the edit target instead
2319 # change the attribute to be the edit target instead
2317 data = attr
2320 data = attr
2318 break
2321 break
2319
2322
2320 datafile = 1
2323 datafile = 1
2321 except TypeError:
2324 except TypeError:
2322 filename = make_filename(args)
2325 filename = make_filename(args)
2323 datafile = 1
2326 datafile = 1
2324 warn('Could not find file where `%s` is defined.\n'
2327 warn('Could not find file where `%s` is defined.\n'
2325 'Opening a file named `%s`' % (args,filename))
2328 'Opening a file named `%s`' % (args,filename))
2326 # Now, make sure we can actually read the source (if it was in
2329 # Now, make sure we can actually read the source (if it was in
2327 # a temp file it's gone by now).
2330 # a temp file it's gone by now).
2328 if datafile:
2331 if datafile:
2329 try:
2332 try:
2330 if lineno is None:
2333 if lineno is None:
2331 lineno = inspect.getsourcelines(data)[1]
2334 lineno = inspect.getsourcelines(data)[1]
2332 except IOError:
2335 except IOError:
2333 filename = make_filename(args)
2336 filename = make_filename(args)
2334 if filename is None:
2337 if filename is None:
2335 warn('The file `%s` where `%s` was defined cannot '
2338 warn('The file `%s` where `%s` was defined cannot '
2336 'be read.' % (filename,data))
2339 'be read.' % (filename,data))
2337 return
2340 return
2338 use_temp = 0
2341 use_temp = 0
2339 else:
2342 else:
2340 data = ''
2343 data = ''
2341
2344
2342 if use_temp:
2345 if use_temp:
2343 filename = self.shell.mktempfile(data)
2346 filename = self.shell.mktempfile(data)
2344 print 'IPython will make a temporary file named:',filename
2347 print 'IPython will make a temporary file named:',filename
2345
2348
2346 # do actual editing here
2349 # do actual editing here
2347 print 'Editing...',
2350 print 'Editing...',
2348 sys.stdout.flush()
2351 sys.stdout.flush()
2349 self.shell.hooks.editor(filename,lineno)
2352 self.shell.hooks.editor(filename,lineno)
2350
2353
2351 # XXX TODO: should this be generalized for all string vars?
2354 # XXX TODO: should this be generalized for all string vars?
2352 # For now, this is special-cased to blocks created by cpaste
2355 # For now, this is special-cased to blocks created by cpaste
2353 if args.strip() == 'pasted_block':
2356 if args.strip() == 'pasted_block':
2354 self.shell.user_ns['pasted_block'] = file_read(filename)
2357 self.shell.user_ns['pasted_block'] = file_read(filename)
2355
2358
2356 if opts.has_key('x'): # -x prevents actual execution
2359 if opts.has_key('x'): # -x prevents actual execution
2357 print
2360 print
2358 else:
2361 else:
2359 print 'done. Executing edited code...'
2362 print 'done. Executing edited code...'
2360 if opts_r:
2363 if opts_r:
2361 self.shell.runlines(file_read(filename))
2364 self.shell.runlines(file_read(filename))
2362 else:
2365 else:
2363 self.shell.safe_execfile(filename,self.shell.user_ns,
2366 self.shell.safe_execfile(filename,self.shell.user_ns,
2364 self.shell.user_ns)
2367 self.shell.user_ns)
2365
2368
2366
2369
2367 if use_temp:
2370 if use_temp:
2368 try:
2371 try:
2369 return open(filename).read()
2372 return open(filename).read()
2370 except IOError,msg:
2373 except IOError,msg:
2371 if msg.filename == filename:
2374 if msg.filename == filename:
2372 warn('File not found. Did you forget to save?')
2375 warn('File not found. Did you forget to save?')
2373 return
2376 return
2374 else:
2377 else:
2375 self.shell.showtraceback()
2378 self.shell.showtraceback()
2376
2379
2377 def magic_xmode(self,parameter_s = ''):
2380 def magic_xmode(self,parameter_s = ''):
2378 """Switch modes for the exception handlers.
2381 """Switch modes for the exception handlers.
2379
2382
2380 Valid modes: Plain, Context and Verbose.
2383 Valid modes: Plain, Context and Verbose.
2381
2384
2382 If called without arguments, acts as a toggle."""
2385 If called without arguments, acts as a toggle."""
2383
2386
2384 def xmode_switch_err(name):
2387 def xmode_switch_err(name):
2385 warn('Error changing %s exception modes.\n%s' %
2388 warn('Error changing %s exception modes.\n%s' %
2386 (name,sys.exc_info()[1]))
2389 (name,sys.exc_info()[1]))
2387
2390
2388 shell = self.shell
2391 shell = self.shell
2389 new_mode = parameter_s.strip().capitalize()
2392 new_mode = parameter_s.strip().capitalize()
2390 try:
2393 try:
2391 shell.InteractiveTB.set_mode(mode=new_mode)
2394 shell.InteractiveTB.set_mode(mode=new_mode)
2392 print 'Exception reporting mode:',shell.InteractiveTB.mode
2395 print 'Exception reporting mode:',shell.InteractiveTB.mode
2393 except:
2396 except:
2394 xmode_switch_err('user')
2397 xmode_switch_err('user')
2395
2398
2396 # threaded shells use a special handler in sys.excepthook
2399 # threaded shells use a special handler in sys.excepthook
2397 if shell.isthreaded:
2400 if shell.isthreaded:
2398 try:
2401 try:
2399 shell.sys_excepthook.set_mode(mode=new_mode)
2402 shell.sys_excepthook.set_mode(mode=new_mode)
2400 except:
2403 except:
2401 xmode_switch_err('threaded')
2404 xmode_switch_err('threaded')
2402
2405
2403 def magic_colors(self,parameter_s = ''):
2406 def magic_colors(self,parameter_s = ''):
2404 """Switch color scheme for prompts, info system and exception handlers.
2407 """Switch color scheme for prompts, info system and exception handlers.
2405
2408
2406 Currently implemented schemes: NoColor, Linux, LightBG.
2409 Currently implemented schemes: NoColor, Linux, LightBG.
2407
2410
2408 Color scheme names are not case-sensitive."""
2411 Color scheme names are not case-sensitive."""
2409
2412
2410 def color_switch_err(name):
2413 def color_switch_err(name):
2411 warn('Error changing %s color schemes.\n%s' %
2414 warn('Error changing %s color schemes.\n%s' %
2412 (name,sys.exc_info()[1]))
2415 (name,sys.exc_info()[1]))
2413
2416
2414
2417
2415 new_scheme = parameter_s.strip()
2418 new_scheme = parameter_s.strip()
2416 if not new_scheme:
2419 if not new_scheme:
2417 raise UsageError(
2420 raise UsageError(
2418 "%colors: you must specify a color scheme. See '%colors?'")
2421 "%colors: you must specify a color scheme. See '%colors?'")
2419 return
2422 return
2420 # local shortcut
2423 # local shortcut
2421 shell = self.shell
2424 shell = self.shell
2422
2425
2423 import IPython.rlineimpl as readline
2426 import IPython.rlineimpl as readline
2424
2427
2425 if not readline.have_readline and sys.platform == "win32":
2428 if not readline.have_readline and sys.platform == "win32":
2426 msg = """\
2429 msg = """\
2427 Proper color support under MS Windows requires the pyreadline library.
2430 Proper color support under MS Windows requires the pyreadline library.
2428 You can find it at:
2431 You can find it at:
2429 http://ipython.scipy.org/moin/PyReadline/Intro
2432 http://ipython.scipy.org/moin/PyReadline/Intro
2430 Gary's readline needs the ctypes module, from:
2433 Gary's readline needs the ctypes module, from:
2431 http://starship.python.net/crew/theller/ctypes
2434 http://starship.python.net/crew/theller/ctypes
2432 (Note that ctypes is already part of Python versions 2.5 and newer).
2435 (Note that ctypes is already part of Python versions 2.5 and newer).
2433
2436
2434 Defaulting color scheme to 'NoColor'"""
2437 Defaulting color scheme to 'NoColor'"""
2435 new_scheme = 'NoColor'
2438 new_scheme = 'NoColor'
2436 warn(msg)
2439 warn(msg)
2437
2440
2438 # readline option is 0
2441 # readline option is 0
2439 if not shell.has_readline:
2442 if not shell.has_readline:
2440 new_scheme = 'NoColor'
2443 new_scheme = 'NoColor'
2441
2444
2442 # Set prompt colors
2445 # Set prompt colors
2443 try:
2446 try:
2444 shell.outputcache.set_colors(new_scheme)
2447 shell.outputcache.set_colors(new_scheme)
2445 except:
2448 except:
2446 color_switch_err('prompt')
2449 color_switch_err('prompt')
2447 else:
2450 else:
2448 shell.rc.colors = \
2451 shell.rc.colors = \
2449 shell.outputcache.color_table.active_scheme_name
2452 shell.outputcache.color_table.active_scheme_name
2450 # Set exception colors
2453 # Set exception colors
2451 try:
2454 try:
2452 shell.InteractiveTB.set_colors(scheme = new_scheme)
2455 shell.InteractiveTB.set_colors(scheme = new_scheme)
2453 shell.SyntaxTB.set_colors(scheme = new_scheme)
2456 shell.SyntaxTB.set_colors(scheme = new_scheme)
2454 except:
2457 except:
2455 color_switch_err('exception')
2458 color_switch_err('exception')
2456
2459
2457 # threaded shells use a verbose traceback in sys.excepthook
2460 # threaded shells use a verbose traceback in sys.excepthook
2458 if shell.isthreaded:
2461 if shell.isthreaded:
2459 try:
2462 try:
2460 shell.sys_excepthook.set_colors(scheme=new_scheme)
2463 shell.sys_excepthook.set_colors(scheme=new_scheme)
2461 except:
2464 except:
2462 color_switch_err('system exception handler')
2465 color_switch_err('system exception handler')
2463
2466
2464 # Set info (for 'object?') colors
2467 # Set info (for 'object?') colors
2465 if shell.rc.color_info:
2468 if shell.rc.color_info:
2466 try:
2469 try:
2467 shell.inspector.set_active_scheme(new_scheme)
2470 shell.inspector.set_active_scheme(new_scheme)
2468 except:
2471 except:
2469 color_switch_err('object inspector')
2472 color_switch_err('object inspector')
2470 else:
2473 else:
2471 shell.inspector.set_active_scheme('NoColor')
2474 shell.inspector.set_active_scheme('NoColor')
2472
2475
2473 def magic_color_info(self,parameter_s = ''):
2476 def magic_color_info(self,parameter_s = ''):
2474 """Toggle color_info.
2477 """Toggle color_info.
2475
2478
2476 The color_info configuration parameter controls whether colors are
2479 The color_info configuration parameter controls whether colors are
2477 used for displaying object details (by things like %psource, %pfile or
2480 used for displaying object details (by things like %psource, %pfile or
2478 the '?' system). This function toggles this value with each call.
2481 the '?' system). This function toggles this value with each call.
2479
2482
2480 Note that unless you have a fairly recent pager (less works better
2483 Note that unless you have a fairly recent pager (less works better
2481 than more) in your system, using colored object information displays
2484 than more) in your system, using colored object information displays
2482 will not work properly. Test it and see."""
2485 will not work properly. Test it and see."""
2483
2486
2484 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2487 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2485 self.magic_colors(self.shell.rc.colors)
2488 self.magic_colors(self.shell.rc.colors)
2486 print 'Object introspection functions have now coloring:',
2489 print 'Object introspection functions have now coloring:',
2487 print ['OFF','ON'][self.shell.rc.color_info]
2490 print ['OFF','ON'][self.shell.rc.color_info]
2488
2491
2489 def magic_Pprint(self, parameter_s=''):
2492 def magic_Pprint(self, parameter_s=''):
2490 """Toggle pretty printing on/off."""
2493 """Toggle pretty printing on/off."""
2491
2494
2492 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2495 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2493 print 'Pretty printing has been turned', \
2496 print 'Pretty printing has been turned', \
2494 ['OFF','ON'][self.shell.rc.pprint]
2497 ['OFF','ON'][self.shell.rc.pprint]
2495
2498
2496 def magic_exit(self, parameter_s=''):
2499 def magic_exit(self, parameter_s=''):
2497 """Exit IPython, confirming if configured to do so.
2500 """Exit IPython, confirming if configured to do so.
2498
2501
2499 You can configure whether IPython asks for confirmation upon exit by
2502 You can configure whether IPython asks for confirmation upon exit by
2500 setting the confirm_exit flag in the ipythonrc file."""
2503 setting the confirm_exit flag in the ipythonrc file."""
2501
2504
2502 self.shell.exit()
2505 self.shell.exit()
2503
2506
2504 def magic_quit(self, parameter_s=''):
2507 def magic_quit(self, parameter_s=''):
2505 """Exit IPython, confirming if configured to do so (like %exit)"""
2508 """Exit IPython, confirming if configured to do so (like %exit)"""
2506
2509
2507 self.shell.exit()
2510 self.shell.exit()
2508
2511
2509 def magic_Exit(self, parameter_s=''):
2512 def magic_Exit(self, parameter_s=''):
2510 """Exit IPython without confirmation."""
2513 """Exit IPython without confirmation."""
2511
2514
2512 self.shell.ask_exit()
2515 self.shell.ask_exit()
2513
2516
2514 #......................................................................
2517 #......................................................................
2515 # Functions to implement unix shell-type things
2518 # Functions to implement unix shell-type things
2516
2519
2517 @testdec.skip_doctest
2520 @testdec.skip_doctest
2518 def magic_alias(self, parameter_s = ''):
2521 def magic_alias(self, parameter_s = ''):
2519 """Define an alias for a system command.
2522 """Define an alias for a system command.
2520
2523
2521 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2524 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2522
2525
2523 Then, typing 'alias_name params' will execute the system command 'cmd
2526 Then, typing 'alias_name params' will execute the system command 'cmd
2524 params' (from your underlying operating system).
2527 params' (from your underlying operating system).
2525
2528
2526 Aliases have lower precedence than magic functions and Python normal
2529 Aliases have lower precedence than magic functions and Python normal
2527 variables, so if 'foo' is both a Python variable and an alias, the
2530 variables, so if 'foo' is both a Python variable and an alias, the
2528 alias can not be executed until 'del foo' removes the Python variable.
2531 alias can not be executed until 'del foo' removes the Python variable.
2529
2532
2530 You can use the %l specifier in an alias definition to represent the
2533 You can use the %l specifier in an alias definition to represent the
2531 whole line when the alias is called. For example:
2534 whole line when the alias is called. For example:
2532
2535
2533 In [2]: alias all echo "Input in brackets: <%l>"
2536 In [2]: alias all echo "Input in brackets: <%l>"
2534 In [3]: all hello world
2537 In [3]: all hello world
2535 Input in brackets: <hello world>
2538 Input in brackets: <hello world>
2536
2539
2537 You can also define aliases with parameters using %s specifiers (one
2540 You can also define aliases with parameters using %s specifiers (one
2538 per parameter):
2541 per parameter):
2539
2542
2540 In [1]: alias parts echo first %s second %s
2543 In [1]: alias parts echo first %s second %s
2541 In [2]: %parts A B
2544 In [2]: %parts A B
2542 first A second B
2545 first A second B
2543 In [3]: %parts A
2546 In [3]: %parts A
2544 Incorrect number of arguments: 2 expected.
2547 Incorrect number of arguments: 2 expected.
2545 parts is an alias to: 'echo first %s second %s'
2548 parts is an alias to: 'echo first %s second %s'
2546
2549
2547 Note that %l and %s are mutually exclusive. You can only use one or
2550 Note that %l and %s are mutually exclusive. You can only use one or
2548 the other in your aliases.
2551 the other in your aliases.
2549
2552
2550 Aliases expand Python variables just like system calls using ! or !!
2553 Aliases expand Python variables just like system calls using ! or !!
2551 do: all expressions prefixed with '$' get expanded. For details of
2554 do: all expressions prefixed with '$' get expanded. For details of
2552 the semantic rules, see PEP-215:
2555 the semantic rules, see PEP-215:
2553 http://www.python.org/peps/pep-0215.html. This is the library used by
2556 http://www.python.org/peps/pep-0215.html. This is the library used by
2554 IPython for variable expansion. If you want to access a true shell
2557 IPython for variable expansion. If you want to access a true shell
2555 variable, an extra $ is necessary to prevent its expansion by IPython:
2558 variable, an extra $ is necessary to prevent its expansion by IPython:
2556
2559
2557 In [6]: alias show echo
2560 In [6]: alias show echo
2558 In [7]: PATH='A Python string'
2561 In [7]: PATH='A Python string'
2559 In [8]: show $PATH
2562 In [8]: show $PATH
2560 A Python string
2563 A Python string
2561 In [9]: show $$PATH
2564 In [9]: show $$PATH
2562 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2565 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2563
2566
2564 You can use the alias facility to acess all of $PATH. See the %rehash
2567 You can use the alias facility to acess all of $PATH. See the %rehash
2565 and %rehashx functions, which automatically create aliases for the
2568 and %rehashx functions, which automatically create aliases for the
2566 contents of your $PATH.
2569 contents of your $PATH.
2567
2570
2568 If called with no parameters, %alias prints the current alias table."""
2571 If called with no parameters, %alias prints the current alias table."""
2569
2572
2570 par = parameter_s.strip()
2573 par = parameter_s.strip()
2571 if not par:
2574 if not par:
2572 stored = self.db.get('stored_aliases', {} )
2575 stored = self.db.get('stored_aliases', {} )
2573 atab = self.shell.alias_table
2576 atab = self.shell.alias_table
2574 aliases = atab.keys()
2577 aliases = atab.keys()
2575 aliases.sort()
2578 aliases.sort()
2576 res = []
2579 res = []
2577 showlast = []
2580 showlast = []
2578 for alias in aliases:
2581 for alias in aliases:
2579 special = False
2582 special = False
2580 try:
2583 try:
2581 tgt = atab[alias][1]
2584 tgt = atab[alias][1]
2582 except (TypeError, AttributeError):
2585 except (TypeError, AttributeError):
2583 # unsubscriptable? probably a callable
2586 # unsubscriptable? probably a callable
2584 tgt = atab[alias]
2587 tgt = atab[alias]
2585 special = True
2588 special = True
2586 # 'interesting' aliases
2589 # 'interesting' aliases
2587 if (alias in stored or
2590 if (alias in stored or
2588 special or
2591 special or
2589 alias.lower() != os.path.splitext(tgt)[0].lower() or
2592 alias.lower() != os.path.splitext(tgt)[0].lower() or
2590 ' ' in tgt):
2593 ' ' in tgt):
2591 showlast.append((alias, tgt))
2594 showlast.append((alias, tgt))
2592 else:
2595 else:
2593 res.append((alias, tgt ))
2596 res.append((alias, tgt ))
2594
2597
2595 # show most interesting aliases last
2598 # show most interesting aliases last
2596 res.extend(showlast)
2599 res.extend(showlast)
2597 print "Total number of aliases:",len(aliases)
2600 print "Total number of aliases:",len(aliases)
2598 return res
2601 return res
2599 try:
2602 try:
2600 alias,cmd = par.split(None,1)
2603 alias,cmd = par.split(None,1)
2601 except:
2604 except:
2602 print OInspect.getdoc(self.magic_alias)
2605 print OInspect.getdoc(self.magic_alias)
2603 else:
2606 else:
2604 nargs = cmd.count('%s')
2607 nargs = cmd.count('%s')
2605 if nargs>0 and cmd.find('%l')>=0:
2608 if nargs>0 and cmd.find('%l')>=0:
2606 error('The %s and %l specifiers are mutually exclusive '
2609 error('The %s and %l specifiers are mutually exclusive '
2607 'in alias definitions.')
2610 'in alias definitions.')
2608 else: # all looks OK
2611 else: # all looks OK
2609 self.shell.alias_table[alias] = (nargs,cmd)
2612 self.shell.alias_table[alias] = (nargs,cmd)
2610 self.shell.alias_table_validate(verbose=0)
2613 self.shell.alias_table_validate(verbose=0)
2611 # end magic_alias
2614 # end magic_alias
2612
2615
2613 def magic_unalias(self, parameter_s = ''):
2616 def magic_unalias(self, parameter_s = ''):
2614 """Remove an alias"""
2617 """Remove an alias"""
2615
2618
2616 aname = parameter_s.strip()
2619 aname = parameter_s.strip()
2617 if aname in self.shell.alias_table:
2620 if aname in self.shell.alias_table:
2618 del self.shell.alias_table[aname]
2621 del self.shell.alias_table[aname]
2619 stored = self.db.get('stored_aliases', {} )
2622 stored = self.db.get('stored_aliases', {} )
2620 if aname in stored:
2623 if aname in stored:
2621 print "Removing %stored alias",aname
2624 print "Removing %stored alias",aname
2622 del stored[aname]
2625 del stored[aname]
2623 self.db['stored_aliases'] = stored
2626 self.db['stored_aliases'] = stored
2624
2627
2625
2628
2626 def magic_rehashx(self, parameter_s = ''):
2629 def magic_rehashx(self, parameter_s = ''):
2627 """Update the alias table with all executable files in $PATH.
2630 """Update the alias table with all executable files in $PATH.
2628
2631
2629 This version explicitly checks that every entry in $PATH is a file
2632 This version explicitly checks that every entry in $PATH is a file
2630 with execute access (os.X_OK), so it is much slower than %rehash.
2633 with execute access (os.X_OK), so it is much slower than %rehash.
2631
2634
2632 Under Windows, it checks executability as a match agains a
2635 Under Windows, it checks executability as a match agains a
2633 '|'-separated string of extensions, stored in the IPython config
2636 '|'-separated string of extensions, stored in the IPython config
2634 variable win_exec_ext. This defaults to 'exe|com|bat'.
2637 variable win_exec_ext. This defaults to 'exe|com|bat'.
2635
2638
2636 This function also resets the root module cache of module completer,
2639 This function also resets the root module cache of module completer,
2637 used on slow filesystems.
2640 used on slow filesystems.
2638 """
2641 """
2639
2642
2640
2643
2641 ip = self.api
2644 ip = self.api
2642
2645
2643 # for the benefit of module completer in ipy_completers.py
2646 # for the benefit of module completer in ipy_completers.py
2644 del ip.db['rootmodules']
2647 del ip.db['rootmodules']
2645
2648
2646 path = [os.path.abspath(os.path.expanduser(p)) for p in
2649 path = [os.path.abspath(os.path.expanduser(p)) for p in
2647 os.environ.get('PATH','').split(os.pathsep)]
2650 os.environ.get('PATH','').split(os.pathsep)]
2648 path = filter(os.path.isdir,path)
2651 path = filter(os.path.isdir,path)
2649
2652
2650 alias_table = self.shell.alias_table
2653 alias_table = self.shell.alias_table
2651 syscmdlist = []
2654 syscmdlist = []
2652 if os.name == 'posix':
2655 if os.name == 'posix':
2653 isexec = lambda fname:os.path.isfile(fname) and \
2656 isexec = lambda fname:os.path.isfile(fname) and \
2654 os.access(fname,os.X_OK)
2657 os.access(fname,os.X_OK)
2655 else:
2658 else:
2656
2659
2657 try:
2660 try:
2658 winext = os.environ['pathext'].replace(';','|').replace('.','')
2661 winext = os.environ['pathext'].replace(';','|').replace('.','')
2659 except KeyError:
2662 except KeyError:
2660 winext = 'exe|com|bat|py'
2663 winext = 'exe|com|bat|py'
2661 if 'py' not in winext:
2664 if 'py' not in winext:
2662 winext += '|py'
2665 winext += '|py'
2663 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2666 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2664 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2667 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2665 savedir = os.getcwd()
2668 savedir = os.getcwd()
2666 try:
2669 try:
2667 # write the whole loop for posix/Windows so we don't have an if in
2670 # write the whole loop for posix/Windows so we don't have an if in
2668 # the innermost part
2671 # the innermost part
2669 if os.name == 'posix':
2672 if os.name == 'posix':
2670 for pdir in path:
2673 for pdir in path:
2671 os.chdir(pdir)
2674 os.chdir(pdir)
2672 for ff in os.listdir(pdir):
2675 for ff in os.listdir(pdir):
2673 if isexec(ff) and ff not in self.shell.no_alias:
2676 if isexec(ff) and ff not in self.shell.no_alias:
2674 # each entry in the alias table must be (N,name),
2677 # each entry in the alias table must be (N,name),
2675 # where N is the number of positional arguments of the
2678 # where N is the number of positional arguments of the
2676 # alias.
2679 # alias.
2677 # Dots will be removed from alias names, since ipython
2680 # Dots will be removed from alias names, since ipython
2678 # assumes names with dots to be python code
2681 # assumes names with dots to be python code
2679 alias_table[ff.replace('.','')] = (0,ff)
2682 alias_table[ff.replace('.','')] = (0,ff)
2680 syscmdlist.append(ff)
2683 syscmdlist.append(ff)
2681 else:
2684 else:
2682 for pdir in path:
2685 for pdir in path:
2683 os.chdir(pdir)
2686 os.chdir(pdir)
2684 for ff in os.listdir(pdir):
2687 for ff in os.listdir(pdir):
2685 base, ext = os.path.splitext(ff)
2688 base, ext = os.path.splitext(ff)
2686 if isexec(ff) and base.lower() not in self.shell.no_alias:
2689 if isexec(ff) and base.lower() not in self.shell.no_alias:
2687 if ext.lower() == '.exe':
2690 if ext.lower() == '.exe':
2688 ff = base
2691 ff = base
2689 alias_table[base.lower().replace('.','')] = (0,ff)
2692 alias_table[base.lower().replace('.','')] = (0,ff)
2690 syscmdlist.append(ff)
2693 syscmdlist.append(ff)
2691 # Make sure the alias table doesn't contain keywords or builtins
2694 # Make sure the alias table doesn't contain keywords or builtins
2692 self.shell.alias_table_validate()
2695 self.shell.alias_table_validate()
2693 # Call again init_auto_alias() so we get 'rm -i' and other
2696 # Call again init_auto_alias() so we get 'rm -i' and other
2694 # modified aliases since %rehashx will probably clobber them
2697 # modified aliases since %rehashx will probably clobber them
2695
2698
2696 # no, we don't want them. if %rehashx clobbers them, good,
2699 # no, we don't want them. if %rehashx clobbers them, good,
2697 # we'll probably get better versions
2700 # we'll probably get better versions
2698 # self.shell.init_auto_alias()
2701 # self.shell.init_auto_alias()
2699 db = ip.db
2702 db = ip.db
2700 db['syscmdlist'] = syscmdlist
2703 db['syscmdlist'] = syscmdlist
2701 finally:
2704 finally:
2702 os.chdir(savedir)
2705 os.chdir(savedir)
2703
2706
2704 def magic_pwd(self, parameter_s = ''):
2707 def magic_pwd(self, parameter_s = ''):
2705 """Return the current working directory path."""
2708 """Return the current working directory path."""
2706 return os.getcwd()
2709 return os.getcwd()
2707
2710
2708 def magic_cd(self, parameter_s=''):
2711 def magic_cd(self, parameter_s=''):
2709 """Change the current working directory.
2712 """Change the current working directory.
2710
2713
2711 This command automatically maintains an internal list of directories
2714 This command automatically maintains an internal list of directories
2712 you visit during your IPython session, in the variable _dh. The
2715 you visit during your IPython session, in the variable _dh. The
2713 command %dhist shows this history nicely formatted. You can also
2716 command %dhist shows this history nicely formatted. You can also
2714 do 'cd -<tab>' to see directory history conveniently.
2717 do 'cd -<tab>' to see directory history conveniently.
2715
2718
2716 Usage:
2719 Usage:
2717
2720
2718 cd 'dir': changes to directory 'dir'.
2721 cd 'dir': changes to directory 'dir'.
2719
2722
2720 cd -: changes to the last visited directory.
2723 cd -: changes to the last visited directory.
2721
2724
2722 cd -<n>: changes to the n-th directory in the directory history.
2725 cd -<n>: changes to the n-th directory in the directory history.
2723
2726
2724 cd --foo: change to directory that matches 'foo' in history
2727 cd --foo: change to directory that matches 'foo' in history
2725
2728
2726 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2729 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2727 (note: cd <bookmark_name> is enough if there is no
2730 (note: cd <bookmark_name> is enough if there is no
2728 directory <bookmark_name>, but a bookmark with the name exists.)
2731 directory <bookmark_name>, but a bookmark with the name exists.)
2729 'cd -b <tab>' allows you to tab-complete bookmark names.
2732 'cd -b <tab>' allows you to tab-complete bookmark names.
2730
2733
2731 Options:
2734 Options:
2732
2735
2733 -q: quiet. Do not print the working directory after the cd command is
2736 -q: quiet. Do not print the working directory after the cd command is
2734 executed. By default IPython's cd command does print this directory,
2737 executed. By default IPython's cd command does print this directory,
2735 since the default prompts do not display path information.
2738 since the default prompts do not display path information.
2736
2739
2737 Note that !cd doesn't work for this purpose because the shell where
2740 Note that !cd doesn't work for this purpose because the shell where
2738 !command runs is immediately discarded after executing 'command'."""
2741 !command runs is immediately discarded after executing 'command'."""
2739
2742
2740 parameter_s = parameter_s.strip()
2743 parameter_s = parameter_s.strip()
2741 #bkms = self.shell.persist.get("bookmarks",{})
2744 #bkms = self.shell.persist.get("bookmarks",{})
2742
2745
2743 oldcwd = os.getcwd()
2746 oldcwd = os.getcwd()
2744 numcd = re.match(r'(-)(\d+)$',parameter_s)
2747 numcd = re.match(r'(-)(\d+)$',parameter_s)
2745 # jump in directory history by number
2748 # jump in directory history by number
2746 if numcd:
2749 if numcd:
2747 nn = int(numcd.group(2))
2750 nn = int(numcd.group(2))
2748 try:
2751 try:
2749 ps = self.shell.user_ns['_dh'][nn]
2752 ps = self.shell.user_ns['_dh'][nn]
2750 except IndexError:
2753 except IndexError:
2751 print 'The requested directory does not exist in history.'
2754 print 'The requested directory does not exist in history.'
2752 return
2755 return
2753 else:
2756 else:
2754 opts = {}
2757 opts = {}
2755 elif parameter_s.startswith('--'):
2758 elif parameter_s.startswith('--'):
2756 ps = None
2759 ps = None
2757 fallback = None
2760 fallback = None
2758 pat = parameter_s[2:]
2761 pat = parameter_s[2:]
2759 dh = self.shell.user_ns['_dh']
2762 dh = self.shell.user_ns['_dh']
2760 # first search only by basename (last component)
2763 # first search only by basename (last component)
2761 for ent in reversed(dh):
2764 for ent in reversed(dh):
2762 if pat in os.path.basename(ent) and os.path.isdir(ent):
2765 if pat in os.path.basename(ent) and os.path.isdir(ent):
2763 ps = ent
2766 ps = ent
2764 break
2767 break
2765
2768
2766 if fallback is None and pat in ent and os.path.isdir(ent):
2769 if fallback is None and pat in ent and os.path.isdir(ent):
2767 fallback = ent
2770 fallback = ent
2768
2771
2769 # if we have no last part match, pick the first full path match
2772 # if we have no last part match, pick the first full path match
2770 if ps is None:
2773 if ps is None:
2771 ps = fallback
2774 ps = fallback
2772
2775
2773 if ps is None:
2776 if ps is None:
2774 print "No matching entry in directory history"
2777 print "No matching entry in directory history"
2775 return
2778 return
2776 else:
2779 else:
2777 opts = {}
2780 opts = {}
2778
2781
2779
2782
2780 else:
2783 else:
2781 #turn all non-space-escaping backslashes to slashes,
2784 #turn all non-space-escaping backslashes to slashes,
2782 # for c:\windows\directory\names\
2785 # for c:\windows\directory\names\
2783 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2786 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2784 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2787 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2785 # jump to previous
2788 # jump to previous
2786 if ps == '-':
2789 if ps == '-':
2787 try:
2790 try:
2788 ps = self.shell.user_ns['_dh'][-2]
2791 ps = self.shell.user_ns['_dh'][-2]
2789 except IndexError:
2792 except IndexError:
2790 raise UsageError('%cd -: No previous directory to change to.')
2793 raise UsageError('%cd -: No previous directory to change to.')
2791 # jump to bookmark if needed
2794 # jump to bookmark if needed
2792 else:
2795 else:
2793 if not os.path.isdir(ps) or opts.has_key('b'):
2796 if not os.path.isdir(ps) or opts.has_key('b'):
2794 bkms = self.db.get('bookmarks', {})
2797 bkms = self.db.get('bookmarks', {})
2795
2798
2796 if bkms.has_key(ps):
2799 if bkms.has_key(ps):
2797 target = bkms[ps]
2800 target = bkms[ps]
2798 print '(bookmark:%s) -> %s' % (ps,target)
2801 print '(bookmark:%s) -> %s' % (ps,target)
2799 ps = target
2802 ps = target
2800 else:
2803 else:
2801 if opts.has_key('b'):
2804 if opts.has_key('b'):
2802 raise UsageError("Bookmark '%s' not found. "
2805 raise UsageError("Bookmark '%s' not found. "
2803 "Use '%%bookmark -l' to see your bookmarks." % ps)
2806 "Use '%%bookmark -l' to see your bookmarks." % ps)
2804
2807
2805 # at this point ps should point to the target dir
2808 # at this point ps should point to the target dir
2806 if ps:
2809 if ps:
2807 try:
2810 try:
2808 os.chdir(os.path.expanduser(ps))
2811 os.chdir(os.path.expanduser(ps))
2809 if self.shell.rc.term_title:
2812 if self.shell.rc.term_title:
2810 #print 'set term title:',self.shell.rc.term_title # dbg
2813 #print 'set term title:',self.shell.rc.term_title # dbg
2811 platutils.set_term_title('IPy ' + abbrev_cwd())
2814 platutils.set_term_title('IPy ' + abbrev_cwd())
2812 except OSError:
2815 except OSError:
2813 print sys.exc_info()[1]
2816 print sys.exc_info()[1]
2814 else:
2817 else:
2815 cwd = os.getcwd()
2818 cwd = os.getcwd()
2816 dhist = self.shell.user_ns['_dh']
2819 dhist = self.shell.user_ns['_dh']
2817 if oldcwd != cwd:
2820 if oldcwd != cwd:
2818 dhist.append(cwd)
2821 dhist.append(cwd)
2819 self.db['dhist'] = compress_dhist(dhist)[-100:]
2822 self.db['dhist'] = compress_dhist(dhist)[-100:]
2820
2823
2821 else:
2824 else:
2822 os.chdir(self.shell.home_dir)
2825 os.chdir(self.shell.home_dir)
2823 if self.shell.rc.term_title:
2826 if self.shell.rc.term_title:
2824 platutils.set_term_title("IPy ~")
2827 platutils.set_term_title("IPy ~")
2825 cwd = os.getcwd()
2828 cwd = os.getcwd()
2826 dhist = self.shell.user_ns['_dh']
2829 dhist = self.shell.user_ns['_dh']
2827
2830
2828 if oldcwd != cwd:
2831 if oldcwd != cwd:
2829 dhist.append(cwd)
2832 dhist.append(cwd)
2830 self.db['dhist'] = compress_dhist(dhist)[-100:]
2833 self.db['dhist'] = compress_dhist(dhist)[-100:]
2831 if not 'q' in opts and self.shell.user_ns['_dh']:
2834 if not 'q' in opts and self.shell.user_ns['_dh']:
2832 print self.shell.user_ns['_dh'][-1]
2835 print self.shell.user_ns['_dh'][-1]
2833
2836
2834
2837
2835 def magic_env(self, parameter_s=''):
2838 def magic_env(self, parameter_s=''):
2836 """List environment variables."""
2839 """List environment variables."""
2837
2840
2838 return os.environ.data
2841 return os.environ.data
2839
2842
2840 def magic_pushd(self, parameter_s=''):
2843 def magic_pushd(self, parameter_s=''):
2841 """Place the current dir on stack and change directory.
2844 """Place the current dir on stack and change directory.
2842
2845
2843 Usage:\\
2846 Usage:\\
2844 %pushd ['dirname']
2847 %pushd ['dirname']
2845 """
2848 """
2846
2849
2847 dir_s = self.shell.dir_stack
2850 dir_s = self.shell.dir_stack
2848 tgt = os.path.expanduser(parameter_s)
2851 tgt = os.path.expanduser(parameter_s)
2849 cwd = os.getcwd().replace(self.home_dir,'~')
2852 cwd = os.getcwd().replace(self.home_dir,'~')
2850 if tgt:
2853 if tgt:
2851 self.magic_cd(parameter_s)
2854 self.magic_cd(parameter_s)
2852 dir_s.insert(0,cwd)
2855 dir_s.insert(0,cwd)
2853 return self.magic_dirs()
2856 return self.magic_dirs()
2854
2857
2855 def magic_popd(self, parameter_s=''):
2858 def magic_popd(self, parameter_s=''):
2856 """Change to directory popped off the top of the stack.
2859 """Change to directory popped off the top of the stack.
2857 """
2860 """
2858 if not self.shell.dir_stack:
2861 if not self.shell.dir_stack:
2859 raise UsageError("%popd on empty stack")
2862 raise UsageError("%popd on empty stack")
2860 top = self.shell.dir_stack.pop(0)
2863 top = self.shell.dir_stack.pop(0)
2861 self.magic_cd(top)
2864 self.magic_cd(top)
2862 print "popd ->",top
2865 print "popd ->",top
2863
2866
2864 def magic_dirs(self, parameter_s=''):
2867 def magic_dirs(self, parameter_s=''):
2865 """Return the current directory stack."""
2868 """Return the current directory stack."""
2866
2869
2867 return self.shell.dir_stack
2870 return self.shell.dir_stack
2868
2871
2869 def magic_dhist(self, parameter_s=''):
2872 def magic_dhist(self, parameter_s=''):
2870 """Print your history of visited directories.
2873 """Print your history of visited directories.
2871
2874
2872 %dhist -> print full history\\
2875 %dhist -> print full history\\
2873 %dhist n -> print last n entries only\\
2876 %dhist n -> print last n entries only\\
2874 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2877 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2875
2878
2876 This history is automatically maintained by the %cd command, and
2879 This history is automatically maintained by the %cd command, and
2877 always available as the global list variable _dh. You can use %cd -<n>
2880 always available as the global list variable _dh. You can use %cd -<n>
2878 to go to directory number <n>.
2881 to go to directory number <n>.
2879
2882
2880 Note that most of time, you should view directory history by entering
2883 Note that most of time, you should view directory history by entering
2881 cd -<TAB>.
2884 cd -<TAB>.
2882
2885
2883 """
2886 """
2884
2887
2885 dh = self.shell.user_ns['_dh']
2888 dh = self.shell.user_ns['_dh']
2886 if parameter_s:
2889 if parameter_s:
2887 try:
2890 try:
2888 args = map(int,parameter_s.split())
2891 args = map(int,parameter_s.split())
2889 except:
2892 except:
2890 self.arg_err(Magic.magic_dhist)
2893 self.arg_err(Magic.magic_dhist)
2891 return
2894 return
2892 if len(args) == 1:
2895 if len(args) == 1:
2893 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2896 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2894 elif len(args) == 2:
2897 elif len(args) == 2:
2895 ini,fin = args
2898 ini,fin = args
2896 else:
2899 else:
2897 self.arg_err(Magic.magic_dhist)
2900 self.arg_err(Magic.magic_dhist)
2898 return
2901 return
2899 else:
2902 else:
2900 ini,fin = 0,len(dh)
2903 ini,fin = 0,len(dh)
2901 nlprint(dh,
2904 nlprint(dh,
2902 header = 'Directory history (kept in _dh)',
2905 header = 'Directory history (kept in _dh)',
2903 start=ini,stop=fin)
2906 start=ini,stop=fin)
2904
2907
2905 @testdec.skip_doctest
2908 @testdec.skip_doctest
2906 def magic_sc(self, parameter_s=''):
2909 def magic_sc(self, parameter_s=''):
2907 """Shell capture - execute a shell command and capture its output.
2910 """Shell capture - execute a shell command and capture its output.
2908
2911
2909 DEPRECATED. Suboptimal, retained for backwards compatibility.
2912 DEPRECATED. Suboptimal, retained for backwards compatibility.
2910
2913
2911 You should use the form 'var = !command' instead. Example:
2914 You should use the form 'var = !command' instead. Example:
2912
2915
2913 "%sc -l myfiles = ls ~" should now be written as
2916 "%sc -l myfiles = ls ~" should now be written as
2914
2917
2915 "myfiles = !ls ~"
2918 "myfiles = !ls ~"
2916
2919
2917 myfiles.s, myfiles.l and myfiles.n still apply as documented
2920 myfiles.s, myfiles.l and myfiles.n still apply as documented
2918 below.
2921 below.
2919
2922
2920 --
2923 --
2921 %sc [options] varname=command
2924 %sc [options] varname=command
2922
2925
2923 IPython will run the given command using commands.getoutput(), and
2926 IPython will run the given command using commands.getoutput(), and
2924 will then update the user's interactive namespace with a variable
2927 will then update the user's interactive namespace with a variable
2925 called varname, containing the value of the call. Your command can
2928 called varname, containing the value of the call. Your command can
2926 contain shell wildcards, pipes, etc.
2929 contain shell wildcards, pipes, etc.
2927
2930
2928 The '=' sign in the syntax is mandatory, and the variable name you
2931 The '=' sign in the syntax is mandatory, and the variable name you
2929 supply must follow Python's standard conventions for valid names.
2932 supply must follow Python's standard conventions for valid names.
2930
2933
2931 (A special format without variable name exists for internal use)
2934 (A special format without variable name exists for internal use)
2932
2935
2933 Options:
2936 Options:
2934
2937
2935 -l: list output. Split the output on newlines into a list before
2938 -l: list output. Split the output on newlines into a list before
2936 assigning it to the given variable. By default the output is stored
2939 assigning it to the given variable. By default the output is stored
2937 as a single string.
2940 as a single string.
2938
2941
2939 -v: verbose. Print the contents of the variable.
2942 -v: verbose. Print the contents of the variable.
2940
2943
2941 In most cases you should not need to split as a list, because the
2944 In most cases you should not need to split as a list, because the
2942 returned value is a special type of string which can automatically
2945 returned value is a special type of string which can automatically
2943 provide its contents either as a list (split on newlines) or as a
2946 provide its contents either as a list (split on newlines) or as a
2944 space-separated string. These are convenient, respectively, either
2947 space-separated string. These are convenient, respectively, either
2945 for sequential processing or to be passed to a shell command.
2948 for sequential processing or to be passed to a shell command.
2946
2949
2947 For example:
2950 For example:
2948
2951
2949 # all-random
2952 # all-random
2950
2953
2951 # Capture into variable a
2954 # Capture into variable a
2952 In [1]: sc a=ls *py
2955 In [1]: sc a=ls *py
2953
2956
2954 # a is a string with embedded newlines
2957 # a is a string with embedded newlines
2955 In [2]: a
2958 In [2]: a
2956 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2959 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2957
2960
2958 # which can be seen as a list:
2961 # which can be seen as a list:
2959 In [3]: a.l
2962 In [3]: a.l
2960 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2963 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2961
2964
2962 # or as a whitespace-separated string:
2965 # or as a whitespace-separated string:
2963 In [4]: a.s
2966 In [4]: a.s
2964 Out[4]: 'setup.py win32_manual_post_install.py'
2967 Out[4]: 'setup.py win32_manual_post_install.py'
2965
2968
2966 # a.s is useful to pass as a single command line:
2969 # a.s is useful to pass as a single command line:
2967 In [5]: !wc -l $a.s
2970 In [5]: !wc -l $a.s
2968 146 setup.py
2971 146 setup.py
2969 130 win32_manual_post_install.py
2972 130 win32_manual_post_install.py
2970 276 total
2973 276 total
2971
2974
2972 # while the list form is useful to loop over:
2975 # while the list form is useful to loop over:
2973 In [6]: for f in a.l:
2976 In [6]: for f in a.l:
2974 ...: !wc -l $f
2977 ...: !wc -l $f
2975 ...:
2978 ...:
2976 146 setup.py
2979 146 setup.py
2977 130 win32_manual_post_install.py
2980 130 win32_manual_post_install.py
2978
2981
2979 Similiarly, the lists returned by the -l option are also special, in
2982 Similiarly, the lists returned by the -l option are also special, in
2980 the sense that you can equally invoke the .s attribute on them to
2983 the sense that you can equally invoke the .s attribute on them to
2981 automatically get a whitespace-separated string from their contents:
2984 automatically get a whitespace-separated string from their contents:
2982
2985
2983 In [7]: sc -l b=ls *py
2986 In [7]: sc -l b=ls *py
2984
2987
2985 In [8]: b
2988 In [8]: b
2986 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2989 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2987
2990
2988 In [9]: b.s
2991 In [9]: b.s
2989 Out[9]: 'setup.py win32_manual_post_install.py'
2992 Out[9]: 'setup.py win32_manual_post_install.py'
2990
2993
2991 In summary, both the lists and strings used for ouptut capture have
2994 In summary, both the lists and strings used for ouptut capture have
2992 the following special attributes:
2995 the following special attributes:
2993
2996
2994 .l (or .list) : value as list.
2997 .l (or .list) : value as list.
2995 .n (or .nlstr): value as newline-separated string.
2998 .n (or .nlstr): value as newline-separated string.
2996 .s (or .spstr): value as space-separated string.
2999 .s (or .spstr): value as space-separated string.
2997 """
3000 """
2998
3001
2999 opts,args = self.parse_options(parameter_s,'lv')
3002 opts,args = self.parse_options(parameter_s,'lv')
3000 # Try to get a variable name and command to run
3003 # Try to get a variable name and command to run
3001 try:
3004 try:
3002 # the variable name must be obtained from the parse_options
3005 # the variable name must be obtained from the parse_options
3003 # output, which uses shlex.split to strip options out.
3006 # output, which uses shlex.split to strip options out.
3004 var,_ = args.split('=',1)
3007 var,_ = args.split('=',1)
3005 var = var.strip()
3008 var = var.strip()
3006 # But the the command has to be extracted from the original input
3009 # But the the command has to be extracted from the original input
3007 # parameter_s, not on what parse_options returns, to avoid the
3010 # parameter_s, not on what parse_options returns, to avoid the
3008 # quote stripping which shlex.split performs on it.
3011 # quote stripping which shlex.split performs on it.
3009 _,cmd = parameter_s.split('=',1)
3012 _,cmd = parameter_s.split('=',1)
3010 except ValueError:
3013 except ValueError:
3011 var,cmd = '',''
3014 var,cmd = '',''
3012 # If all looks ok, proceed
3015 # If all looks ok, proceed
3013 out,err = self.shell.getoutputerror(cmd)
3016 out,err = self.shell.getoutputerror(cmd)
3014 if err:
3017 if err:
3015 print >> Term.cerr,err
3018 print >> Term.cerr,err
3016 if opts.has_key('l'):
3019 if opts.has_key('l'):
3017 out = SList(out.split('\n'))
3020 out = SList(out.split('\n'))
3018 else:
3021 else:
3019 out = LSString(out)
3022 out = LSString(out)
3020 if opts.has_key('v'):
3023 if opts.has_key('v'):
3021 print '%s ==\n%s' % (var,pformat(out))
3024 print '%s ==\n%s' % (var,pformat(out))
3022 if var:
3025 if var:
3023 self.shell.user_ns.update({var:out})
3026 self.shell.user_ns.update({var:out})
3024 else:
3027 else:
3025 return out
3028 return out
3026
3029
3027 def magic_sx(self, parameter_s=''):
3030 def magic_sx(self, parameter_s=''):
3028 """Shell execute - run a shell command and capture its output.
3031 """Shell execute - run a shell command and capture its output.
3029
3032
3030 %sx command
3033 %sx command
3031
3034
3032 IPython will run the given command using commands.getoutput(), and
3035 IPython will run the given command using commands.getoutput(), and
3033 return the result formatted as a list (split on '\\n'). Since the
3036 return the result formatted as a list (split on '\\n'). Since the
3034 output is _returned_, it will be stored in ipython's regular output
3037 output is _returned_, it will be stored in ipython's regular output
3035 cache Out[N] and in the '_N' automatic variables.
3038 cache Out[N] and in the '_N' automatic variables.
3036
3039
3037 Notes:
3040 Notes:
3038
3041
3039 1) If an input line begins with '!!', then %sx is automatically
3042 1) If an input line begins with '!!', then %sx is automatically
3040 invoked. That is, while:
3043 invoked. That is, while:
3041 !ls
3044 !ls
3042 causes ipython to simply issue system('ls'), typing
3045 causes ipython to simply issue system('ls'), typing
3043 !!ls
3046 !!ls
3044 is a shorthand equivalent to:
3047 is a shorthand equivalent to:
3045 %sx ls
3048 %sx ls
3046
3049
3047 2) %sx differs from %sc in that %sx automatically splits into a list,
3050 2) %sx differs from %sc in that %sx automatically splits into a list,
3048 like '%sc -l'. The reason for this is to make it as easy as possible
3051 like '%sc -l'. The reason for this is to make it as easy as possible
3049 to process line-oriented shell output via further python commands.
3052 to process line-oriented shell output via further python commands.
3050 %sc is meant to provide much finer control, but requires more
3053 %sc is meant to provide much finer control, but requires more
3051 typing.
3054 typing.
3052
3055
3053 3) Just like %sc -l, this is a list with special attributes:
3056 3) Just like %sc -l, this is a list with special attributes:
3054
3057
3055 .l (or .list) : value as list.
3058 .l (or .list) : value as list.
3056 .n (or .nlstr): value as newline-separated string.
3059 .n (or .nlstr): value as newline-separated string.
3057 .s (or .spstr): value as whitespace-separated string.
3060 .s (or .spstr): value as whitespace-separated string.
3058
3061
3059 This is very useful when trying to use such lists as arguments to
3062 This is very useful when trying to use such lists as arguments to
3060 system commands."""
3063 system commands."""
3061
3064
3062 if parameter_s:
3065 if parameter_s:
3063 out,err = self.shell.getoutputerror(parameter_s)
3066 out,err = self.shell.getoutputerror(parameter_s)
3064 if err:
3067 if err:
3065 print >> Term.cerr,err
3068 print >> Term.cerr,err
3066 return SList(out.split('\n'))
3069 return SList(out.split('\n'))
3067
3070
3068 def magic_bg(self, parameter_s=''):
3071 def magic_bg(self, parameter_s=''):
3069 """Run a job in the background, in a separate thread.
3072 """Run a job in the background, in a separate thread.
3070
3073
3071 For example,
3074 For example,
3072
3075
3073 %bg myfunc(x,y,z=1)
3076 %bg myfunc(x,y,z=1)
3074
3077
3075 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3078 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3076 execution starts, a message will be printed indicating the job
3079 execution starts, a message will be printed indicating the job
3077 number. If your job number is 5, you can use
3080 number. If your job number is 5, you can use
3078
3081
3079 myvar = jobs.result(5) or myvar = jobs[5].result
3082 myvar = jobs.result(5) or myvar = jobs[5].result
3080
3083
3081 to assign this result to variable 'myvar'.
3084 to assign this result to variable 'myvar'.
3082
3085
3083 IPython has a job manager, accessible via the 'jobs' object. You can
3086 IPython has a job manager, accessible via the 'jobs' object. You can
3084 type jobs? to get more information about it, and use jobs.<TAB> to see
3087 type jobs? to get more information about it, and use jobs.<TAB> to see
3085 its attributes. All attributes not starting with an underscore are
3088 its attributes. All attributes not starting with an underscore are
3086 meant for public use.
3089 meant for public use.
3087
3090
3088 In particular, look at the jobs.new() method, which is used to create
3091 In particular, look at the jobs.new() method, which is used to create
3089 new jobs. This magic %bg function is just a convenience wrapper
3092 new jobs. This magic %bg function is just a convenience wrapper
3090 around jobs.new(), for expression-based jobs. If you want to create a
3093 around jobs.new(), for expression-based jobs. If you want to create a
3091 new job with an explicit function object and arguments, you must call
3094 new job with an explicit function object and arguments, you must call
3092 jobs.new() directly.
3095 jobs.new() directly.
3093
3096
3094 The jobs.new docstring also describes in detail several important
3097 The jobs.new docstring also describes in detail several important
3095 caveats associated with a thread-based model for background job
3098 caveats associated with a thread-based model for background job
3096 execution. Type jobs.new? for details.
3099 execution. Type jobs.new? for details.
3097
3100
3098 You can check the status of all jobs with jobs.status().
3101 You can check the status of all jobs with jobs.status().
3099
3102
3100 The jobs variable is set by IPython into the Python builtin namespace.
3103 The jobs variable is set by IPython into the Python builtin namespace.
3101 If you ever declare a variable named 'jobs', you will shadow this
3104 If you ever declare a variable named 'jobs', you will shadow this
3102 name. You can either delete your global jobs variable to regain
3105 name. You can either delete your global jobs variable to regain
3103 access to the job manager, or make a new name and assign it manually
3106 access to the job manager, or make a new name and assign it manually
3104 to the manager (stored in IPython's namespace). For example, to
3107 to the manager (stored in IPython's namespace). For example, to
3105 assign the job manager to the Jobs name, use:
3108 assign the job manager to the Jobs name, use:
3106
3109
3107 Jobs = __builtins__.jobs"""
3110 Jobs = __builtins__.jobs"""
3108
3111
3109 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3112 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3110
3113
3111 def magic_r(self, parameter_s=''):
3114 def magic_r(self, parameter_s=''):
3112 """Repeat previous input.
3115 """Repeat previous input.
3113
3116
3114 Note: Consider using the more powerfull %rep instead!
3117 Note: Consider using the more powerfull %rep instead!
3115
3118
3116 If given an argument, repeats the previous command which starts with
3119 If given an argument, repeats the previous command which starts with
3117 the same string, otherwise it just repeats the previous input.
3120 the same string, otherwise it just repeats the previous input.
3118
3121
3119 Shell escaped commands (with ! as first character) are not recognized
3122 Shell escaped commands (with ! as first character) are not recognized
3120 by this system, only pure python code and magic commands.
3123 by this system, only pure python code and magic commands.
3121 """
3124 """
3122
3125
3123 start = parameter_s.strip()
3126 start = parameter_s.strip()
3124 esc_magic = self.shell.ESC_MAGIC
3127 esc_magic = self.shell.ESC_MAGIC
3125 # Identify magic commands even if automagic is on (which means
3128 # Identify magic commands even if automagic is on (which means
3126 # the in-memory version is different from that typed by the user).
3129 # the in-memory version is different from that typed by the user).
3127 if self.shell.rc.automagic:
3130 if self.shell.rc.automagic:
3128 start_magic = esc_magic+start
3131 start_magic = esc_magic+start
3129 else:
3132 else:
3130 start_magic = start
3133 start_magic = start
3131 # Look through the input history in reverse
3134 # Look through the input history in reverse
3132 for n in range(len(self.shell.input_hist)-2,0,-1):
3135 for n in range(len(self.shell.input_hist)-2,0,-1):
3133 input = self.shell.input_hist[n]
3136 input = self.shell.input_hist[n]
3134 # skip plain 'r' lines so we don't recurse to infinity
3137 # skip plain 'r' lines so we don't recurse to infinity
3135 if input != '_ip.magic("r")\n' and \
3138 if input != '_ip.magic("r")\n' and \
3136 (input.startswith(start) or input.startswith(start_magic)):
3139 (input.startswith(start) or input.startswith(start_magic)):
3137 #print 'match',`input` # dbg
3140 #print 'match',`input` # dbg
3138 print 'Executing:',input,
3141 print 'Executing:',input,
3139 self.shell.runlines(input)
3142 self.shell.runlines(input)
3140 return
3143 return
3141 print 'No previous input matching `%s` found.' % start
3144 print 'No previous input matching `%s` found.' % start
3142
3145
3143
3146
3144 def magic_bookmark(self, parameter_s=''):
3147 def magic_bookmark(self, parameter_s=''):
3145 """Manage IPython's bookmark system.
3148 """Manage IPython's bookmark system.
3146
3149
3147 %bookmark <name> - set bookmark to current dir
3150 %bookmark <name> - set bookmark to current dir
3148 %bookmark <name> <dir> - set bookmark to <dir>
3151 %bookmark <name> <dir> - set bookmark to <dir>
3149 %bookmark -l - list all bookmarks
3152 %bookmark -l - list all bookmarks
3150 %bookmark -d <name> - remove bookmark
3153 %bookmark -d <name> - remove bookmark
3151 %bookmark -r - remove all bookmarks
3154 %bookmark -r - remove all bookmarks
3152
3155
3153 You can later on access a bookmarked folder with:
3156 You can later on access a bookmarked folder with:
3154 %cd -b <name>
3157 %cd -b <name>
3155 or simply '%cd <name>' if there is no directory called <name> AND
3158 or simply '%cd <name>' if there is no directory called <name> AND
3156 there is such a bookmark defined.
3159 there is such a bookmark defined.
3157
3160
3158 Your bookmarks persist through IPython sessions, but they are
3161 Your bookmarks persist through IPython sessions, but they are
3159 associated with each profile."""
3162 associated with each profile."""
3160
3163
3161 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3164 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3162 if len(args) > 2:
3165 if len(args) > 2:
3163 raise UsageError("%bookmark: too many arguments")
3166 raise UsageError("%bookmark: too many arguments")
3164
3167
3165 bkms = self.db.get('bookmarks',{})
3168 bkms = self.db.get('bookmarks',{})
3166
3169
3167 if opts.has_key('d'):
3170 if opts.has_key('d'):
3168 try:
3171 try:
3169 todel = args[0]
3172 todel = args[0]
3170 except IndexError:
3173 except IndexError:
3171 raise UsageError(
3174 raise UsageError(
3172 "%bookmark -d: must provide a bookmark to delete")
3175 "%bookmark -d: must provide a bookmark to delete")
3173 else:
3176 else:
3174 try:
3177 try:
3175 del bkms[todel]
3178 del bkms[todel]
3176 except KeyError:
3179 except KeyError:
3177 raise UsageError(
3180 raise UsageError(
3178 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3181 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3179
3182
3180 elif opts.has_key('r'):
3183 elif opts.has_key('r'):
3181 bkms = {}
3184 bkms = {}
3182 elif opts.has_key('l'):
3185 elif opts.has_key('l'):
3183 bks = bkms.keys()
3186 bks = bkms.keys()
3184 bks.sort()
3187 bks.sort()
3185 if bks:
3188 if bks:
3186 size = max(map(len,bks))
3189 size = max(map(len,bks))
3187 else:
3190 else:
3188 size = 0
3191 size = 0
3189 fmt = '%-'+str(size)+'s -> %s'
3192 fmt = '%-'+str(size)+'s -> %s'
3190 print 'Current bookmarks:'
3193 print 'Current bookmarks:'
3191 for bk in bks:
3194 for bk in bks:
3192 print fmt % (bk,bkms[bk])
3195 print fmt % (bk,bkms[bk])
3193 else:
3196 else:
3194 if not args:
3197 if not args:
3195 raise UsageError("%bookmark: You must specify the bookmark name")
3198 raise UsageError("%bookmark: You must specify the bookmark name")
3196 elif len(args)==1:
3199 elif len(args)==1:
3197 bkms[args[0]] = os.getcwd()
3200 bkms[args[0]] = os.getcwd()
3198 elif len(args)==2:
3201 elif len(args)==2:
3199 bkms[args[0]] = args[1]
3202 bkms[args[0]] = args[1]
3200 self.db['bookmarks'] = bkms
3203 self.db['bookmarks'] = bkms
3201
3204
3202 def magic_pycat(self, parameter_s=''):
3205 def magic_pycat(self, parameter_s=''):
3203 """Show a syntax-highlighted file through a pager.
3206 """Show a syntax-highlighted file through a pager.
3204
3207
3205 This magic is similar to the cat utility, but it will assume the file
3208 This magic is similar to the cat utility, but it will assume the file
3206 to be Python source and will show it with syntax highlighting. """
3209 to be Python source and will show it with syntax highlighting. """
3207
3210
3208 try:
3211 try:
3209 filename = get_py_filename(parameter_s)
3212 filename = get_py_filename(parameter_s)
3210 cont = file_read(filename)
3213 cont = file_read(filename)
3211 except IOError:
3214 except IOError:
3212 try:
3215 try:
3213 cont = eval(parameter_s,self.user_ns)
3216 cont = eval(parameter_s,self.user_ns)
3214 except NameError:
3217 except NameError:
3215 cont = None
3218 cont = None
3216 if cont is None:
3219 if cont is None:
3217 print "Error: no such file or variable"
3220 print "Error: no such file or variable"
3218 return
3221 return
3219
3222
3220 page(self.shell.pycolorize(cont),
3223 page(self.shell.pycolorize(cont),
3221 screen_lines=self.shell.rc.screen_length)
3224 screen_lines=self.shell.rc.screen_length)
3222
3225
3223 def magic_cpaste(self, parameter_s=''):
3226 def magic_cpaste(self, parameter_s=''):
3224 """Allows you to paste & execute a pre-formatted code block from clipboard.
3227 """Allows you to paste & execute a pre-formatted code block from clipboard.
3225
3228
3226 You must terminate the block with '--' (two minus-signs) alone on the
3229 You must terminate the block with '--' (two minus-signs) alone on the
3227 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3230 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3228 is the new sentinel for this operation)
3231 is the new sentinel for this operation)
3229
3232
3230 The block is dedented prior to execution to enable execution of method
3233 The block is dedented prior to execution to enable execution of method
3231 definitions. '>' and '+' characters at the beginning of a line are
3234 definitions. '>' and '+' characters at the beginning of a line are
3232 ignored, to allow pasting directly from e-mails, diff files and
3235 ignored, to allow pasting directly from e-mails, diff files and
3233 doctests (the '...' continuation prompt is also stripped). The
3236 doctests (the '...' continuation prompt is also stripped). The
3234 executed block is also assigned to variable named 'pasted_block' for
3237 executed block is also assigned to variable named 'pasted_block' for
3235 later editing with '%edit pasted_block'.
3238 later editing with '%edit pasted_block'.
3236
3239
3237 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3240 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3238 This assigns the pasted block to variable 'foo' as string, without
3241 This assigns the pasted block to variable 'foo' as string, without
3239 dedenting or executing it (preceding >>> and + is still stripped)
3242 dedenting or executing it (preceding >>> and + is still stripped)
3240
3243
3241 '%cpaste -r' re-executes the block previously entered by cpaste.
3244 '%cpaste -r' re-executes the block previously entered by cpaste.
3242
3245
3243 Do not be alarmed by garbled output on Windows (it's a readline bug).
3246 Do not be alarmed by garbled output on Windows (it's a readline bug).
3244 Just press enter and type -- (and press enter again) and the block
3247 Just press enter and type -- (and press enter again) and the block
3245 will be what was just pasted.
3248 will be what was just pasted.
3246
3249
3247 IPython statements (magics, shell escapes) are not supported (yet).
3250 IPython statements (magics, shell escapes) are not supported (yet).
3248 """
3251 """
3249 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3252 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3250 par = args.strip()
3253 par = args.strip()
3251 if opts.has_key('r'):
3254 if opts.has_key('r'):
3252 b = self.user_ns.get('pasted_block', None)
3255 b = self.user_ns.get('pasted_block', None)
3253 if b is None:
3256 if b is None:
3254 raise UsageError('No previous pasted block available')
3257 raise UsageError('No previous pasted block available')
3255 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3258 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3256 exec b in self.user_ns
3259 exec b in self.user_ns
3257 return
3260 return
3258
3261
3259 sentinel = opts.get('s','--')
3262 sentinel = opts.get('s','--')
3260
3263
3261 # Regular expressions that declare text we strip from the input:
3264 # Regular expressions that declare text we strip from the input:
3262 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3265 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3263 r'^\s*(\s?>)+', # Python input prompt
3266 r'^\s*(\s?>)+', # Python input prompt
3264 r'^\s*\.{3,}', # Continuation prompts
3267 r'^\s*\.{3,}', # Continuation prompts
3265 r'^\++',
3268 r'^\++',
3266 ]
3269 ]
3267
3270
3268 strip_from_start = map(re.compile,strip_re)
3271 strip_from_start = map(re.compile,strip_re)
3269
3272
3270 from IPython import iplib
3273 from IPython import iplib
3271 lines = []
3274 lines = []
3272 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3275 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3273 while 1:
3276 while 1:
3274 l = iplib.raw_input_original(':')
3277 l = iplib.raw_input_original(':')
3275 if l ==sentinel:
3278 if l ==sentinel:
3276 break
3279 break
3277
3280
3278 for pat in strip_from_start:
3281 for pat in strip_from_start:
3279 l = pat.sub('',l)
3282 l = pat.sub('',l)
3280 lines.append(l)
3283 lines.append(l)
3281
3284
3282 block = "\n".join(lines) + '\n'
3285 block = "\n".join(lines) + '\n'
3283 #print "block:\n",block
3286 #print "block:\n",block
3284 if not par:
3287 if not par:
3285 b = textwrap.dedent(block)
3288 b = textwrap.dedent(block)
3286 self.user_ns['pasted_block'] = b
3289 self.user_ns['pasted_block'] = b
3287 exec b in self.user_ns
3290 exec b in self.user_ns
3288 else:
3291 else:
3289 self.user_ns[par] = SList(block.splitlines())
3292 self.user_ns[par] = SList(block.splitlines())
3290 print "Block assigned to '%s'" % par
3293 print "Block assigned to '%s'" % par
3291
3294
3292 def magic_quickref(self,arg):
3295 def magic_quickref(self,arg):
3293 """ Show a quick reference sheet """
3296 """ Show a quick reference sheet """
3294 import IPython.usage
3297 import IPython.usage
3295 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3298 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3296
3299
3297 page(qr)
3300 page(qr)
3298
3301
3299 def magic_upgrade(self,arg):
3302 def magic_upgrade(self,arg):
3300 """ Upgrade your IPython installation
3303 """ Upgrade your IPython installation
3301
3304
3302 This will copy the config files that don't yet exist in your
3305 This will copy the config files that don't yet exist in your
3303 ipython dir from the system config dir. Use this after upgrading
3306 ipython dir from the system config dir. Use this after upgrading
3304 IPython if you don't wish to delete your .ipython dir.
3307 IPython if you don't wish to delete your .ipython dir.
3305
3308
3306 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3309 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3307 new users)
3310 new users)
3308
3311
3309 """
3312 """
3310 ip = self.getapi()
3313 ip = self.getapi()
3311 ipinstallation = path(IPython.__file__).dirname()
3314 ipinstallation = path(IPython.__file__).dirname()
3312 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3315 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3313 src_config = ipinstallation / 'UserConfig'
3316 src_config = ipinstallation / 'UserConfig'
3314 userdir = path(ip.options.ipythondir)
3317 userdir = path(ip.options.ipythondir)
3315 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3318 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3316 print ">",cmd
3319 print ">",cmd
3317 shell(cmd)
3320 shell(cmd)
3318 if arg == '-nolegacy':
3321 if arg == '-nolegacy':
3319 legacy = userdir.files('ipythonrc*')
3322 legacy = userdir.files('ipythonrc*')
3320 print "Nuking legacy files:",legacy
3323 print "Nuking legacy files:",legacy
3321
3324
3322 [p.remove() for p in legacy]
3325 [p.remove() for p in legacy]
3323 suffix = (sys.platform == 'win32' and '.ini' or '')
3326 suffix = (sys.platform == 'win32' and '.ini' or '')
3324 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3327 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3325
3328
3326
3329
3327 def magic_doctest_mode(self,parameter_s=''):
3330 def magic_doctest_mode(self,parameter_s=''):
3328 """Toggle doctest mode on and off.
3331 """Toggle doctest mode on and off.
3329
3332
3330 This mode allows you to toggle the prompt behavior between normal
3333 This mode allows you to toggle the prompt behavior between normal
3331 IPython prompts and ones that are as similar to the default IPython
3334 IPython prompts and ones that are as similar to the default IPython
3332 interpreter as possible.
3335 interpreter as possible.
3333
3336
3334 It also supports the pasting of code snippets that have leading '>>>'
3337 It also supports the pasting of code snippets that have leading '>>>'
3335 and '...' prompts in them. This means that you can paste doctests from
3338 and '...' prompts in them. This means that you can paste doctests from
3336 files or docstrings (even if they have leading whitespace), and the
3339 files or docstrings (even if they have leading whitespace), and the
3337 code will execute correctly. You can then use '%history -tn' to see
3340 code will execute correctly. You can then use '%history -tn' to see
3338 the translated history without line numbers; this will give you the
3341 the translated history without line numbers; this will give you the
3339 input after removal of all the leading prompts and whitespace, which
3342 input after removal of all the leading prompts and whitespace, which
3340 can be pasted back into an editor.
3343 can be pasted back into an editor.
3341
3344
3342 With these features, you can switch into this mode easily whenever you
3345 With these features, you can switch into this mode easily whenever you
3343 need to do testing and changes to doctests, without having to leave
3346 need to do testing and changes to doctests, without having to leave
3344 your existing IPython session.
3347 your existing IPython session.
3345 """
3348 """
3346
3349
3347 # XXX - Fix this to have cleaner activate/deactivate calls.
3350 # XXX - Fix this to have cleaner activate/deactivate calls.
3348 from IPython.Extensions import InterpreterPasteInput as ipaste
3351 from IPython.Extensions import InterpreterPasteInput as ipaste
3349 from IPython.ipstruct import Struct
3352 from IPython.ipstruct import Struct
3350
3353
3351 # Shorthands
3354 # Shorthands
3352 shell = self.shell
3355 shell = self.shell
3353 oc = shell.outputcache
3356 oc = shell.outputcache
3354 rc = shell.rc
3357 rc = shell.rc
3355 meta = shell.meta
3358 meta = shell.meta
3356 # dstore is a data store kept in the instance metadata bag to track any
3359 # dstore is a data store kept in the instance metadata bag to track any
3357 # changes we make, so we can undo them later.
3360 # changes we make, so we can undo them later.
3358 dstore = meta.setdefault('doctest_mode',Struct())
3361 dstore = meta.setdefault('doctest_mode',Struct())
3359 save_dstore = dstore.setdefault
3362 save_dstore = dstore.setdefault
3360
3363
3361 # save a few values we'll need to recover later
3364 # save a few values we'll need to recover later
3362 mode = save_dstore('mode',False)
3365 mode = save_dstore('mode',False)
3363 save_dstore('rc_pprint',rc.pprint)
3366 save_dstore('rc_pprint',rc.pprint)
3364 save_dstore('xmode',shell.InteractiveTB.mode)
3367 save_dstore('xmode',shell.InteractiveTB.mode)
3365 save_dstore('rc_separate_out',rc.separate_out)
3368 save_dstore('rc_separate_out',rc.separate_out)
3366 save_dstore('rc_separate_out2',rc.separate_out2)
3369 save_dstore('rc_separate_out2',rc.separate_out2)
3367 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3370 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3368 save_dstore('rc_separate_in',rc.separate_in)
3371 save_dstore('rc_separate_in',rc.separate_in)
3369
3372
3370 if mode == False:
3373 if mode == False:
3371 # turn on
3374 # turn on
3372 ipaste.activate_prefilter()
3375 ipaste.activate_prefilter()
3373
3376
3374 oc.prompt1.p_template = '>>> '
3377 oc.prompt1.p_template = '>>> '
3375 oc.prompt2.p_template = '... '
3378 oc.prompt2.p_template = '... '
3376 oc.prompt_out.p_template = ''
3379 oc.prompt_out.p_template = ''
3377
3380
3378 # Prompt separators like plain python
3381 # Prompt separators like plain python
3379 oc.input_sep = oc.prompt1.sep = ''
3382 oc.input_sep = oc.prompt1.sep = ''
3380 oc.output_sep = ''
3383 oc.output_sep = ''
3381 oc.output_sep2 = ''
3384 oc.output_sep2 = ''
3382
3385
3383 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3386 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3384 oc.prompt_out.pad_left = False
3387 oc.prompt_out.pad_left = False
3385
3388
3386 rc.pprint = False
3389 rc.pprint = False
3387
3390
3388 shell.magic_xmode('Plain')
3391 shell.magic_xmode('Plain')
3389
3392
3390 else:
3393 else:
3391 # turn off
3394 # turn off
3392 ipaste.deactivate_prefilter()
3395 ipaste.deactivate_prefilter()
3393
3396
3394 oc.prompt1.p_template = rc.prompt_in1
3397 oc.prompt1.p_template = rc.prompt_in1
3395 oc.prompt2.p_template = rc.prompt_in2
3398 oc.prompt2.p_template = rc.prompt_in2
3396 oc.prompt_out.p_template = rc.prompt_out
3399 oc.prompt_out.p_template = rc.prompt_out
3397
3400
3398 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3401 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3399
3402
3400 oc.output_sep = dstore.rc_separate_out
3403 oc.output_sep = dstore.rc_separate_out
3401 oc.output_sep2 = dstore.rc_separate_out2
3404 oc.output_sep2 = dstore.rc_separate_out2
3402
3405
3403 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3406 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3404 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3407 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3405
3408
3406 rc.pprint = dstore.rc_pprint
3409 rc.pprint = dstore.rc_pprint
3407
3410
3408 shell.magic_xmode(dstore.xmode)
3411 shell.magic_xmode(dstore.xmode)
3409
3412
3410 # Store new mode and inform
3413 # Store new mode and inform
3411 dstore.mode = bool(1-int(mode))
3414 dstore.mode = bool(1-int(mode))
3412 print 'Doctest mode is:',
3415 print 'Doctest mode is:',
3413 print ['OFF','ON'][dstore.mode]
3416 print ['OFF','ON'][dstore.mode]
3414
3417
3415 # end Magic
3418 # end Magic
@@ -1,2679 +1,2729 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.4 or newer.
5 Requires Python 2.4 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
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #
16 #
17 # Note: this code originally subclassed code.InteractiveConsole from the
17 # Note: this code originally subclassed code.InteractiveConsole from the
18 # Python standard library. Over time, all of that class has been copied
18 # Python standard library. Over time, all of that class has been copied
19 # verbatim here for modifications which could not be accomplished by
19 # verbatim here for modifications which could not be accomplished by
20 # subclassing. At this point, there are no dependencies at all on the code
20 # subclassing. At this point, there are no dependencies at all on the code
21 # module anymore (it is not even imported). The Python License (sec. 2)
21 # module anymore (it is not even imported). The Python License (sec. 2)
22 # allows for this, but it's always nice to acknowledge credit where credit is
22 # allows for this, but it's always nice to acknowledge credit where credit is
23 # due.
23 # due.
24 #*****************************************************************************
24 #*****************************************************************************
25
25
26 #****************************************************************************
26 #****************************************************************************
27 # Modules and globals
27 # Modules and globals
28
28
29 # Python standard modules
29 # Python standard modules
30 import __main__
30 import __main__
31 import __builtin__
31 import __builtin__
32 import StringIO
32 import StringIO
33 import bdb
33 import bdb
34 import cPickle as pickle
34 import cPickle as pickle
35 import codeop
35 import codeop
36 import exceptions
36 import exceptions
37 import glob
37 import glob
38 import inspect
38 import inspect
39 import keyword
39 import keyword
40 import new
40 import new
41 import os
41 import os
42 import pydoc
42 import pydoc
43 import re
43 import re
44 import shutil
44 import shutil
45 import string
45 import string
46 import sys
46 import sys
47 import tempfile
47 import tempfile
48 import traceback
48 import traceback
49 import types
49 import types
50 import warnings
50 import warnings
51 warnings.filterwarnings('ignore', r'.*sets module*')
51 warnings.filterwarnings('ignore', r'.*sets module*')
52 from sets import Set
52 from sets import Set
53 from pprint import pprint, pformat
53 from pprint import pprint, pformat
54
54
55 # IPython's own modules
55 # IPython's own modules
56 #import IPython
56 #import IPython
57 from IPython import Debugger,OInspect,PyColorize,ultraTB
57 from IPython import Debugger,OInspect,PyColorize,ultraTB
58 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
58 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
59 from IPython.Extensions import pickleshare
59 from IPython.Extensions import pickleshare
60 from IPython.FakeModule import FakeModule
60 from IPython.FakeModule import FakeModule
61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 from IPython.Logger import Logger
62 from IPython.Logger import Logger
63 from IPython.Magic import Magic
63 from IPython.Magic import Magic
64 from IPython.Prompts import CachedOutput
64 from IPython.Prompts import CachedOutput
65 from IPython.ipstruct import Struct
65 from IPython.ipstruct import Struct
66 from IPython.background_jobs import BackgroundJobManager
66 from IPython.background_jobs import BackgroundJobManager
67 from IPython.usage import cmd_line_usage,interactive_usage
67 from IPython.usage import cmd_line_usage,interactive_usage
68 from IPython.genutils import *
68 from IPython.genutils import *
69 from IPython.strdispatch import StrDispatch
69 from IPython.strdispatch import StrDispatch
70 import IPython.ipapi
70 import IPython.ipapi
71 import IPython.history
71 import IPython.history
72 import IPython.prefilter as prefilter
72 import IPython.prefilter as prefilter
73 import IPython.shadowns
73 import IPython.shadowns
74 # Globals
74 # Globals
75
75
76 # store the builtin raw_input globally, and use this always, in case user code
76 # store the builtin raw_input globally, and use this always, in case user code
77 # overwrites it (like wx.py.PyShell does)
77 # overwrites it (like wx.py.PyShell does)
78 raw_input_original = raw_input
78 raw_input_original = raw_input
79
79
80 # compiled regexps for autoindent management
80 # compiled regexps for autoindent management
81 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
81 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
82
82
83
83
84 #****************************************************************************
84 #****************************************************************************
85 # Some utility function definitions
85 # Some utility function definitions
86
86
87 ini_spaces_re = re.compile(r'^(\s+)')
87 ini_spaces_re = re.compile(r'^(\s+)')
88
88
89 def num_ini_spaces(strng):
89 def num_ini_spaces(strng):
90 """Return the number of initial spaces in a string"""
90 """Return the number of initial spaces in a string"""
91
91
92 ini_spaces = ini_spaces_re.match(strng)
92 ini_spaces = ini_spaces_re.match(strng)
93 if ini_spaces:
93 if ini_spaces:
94 return ini_spaces.end()
94 return ini_spaces.end()
95 else:
95 else:
96 return 0
96 return 0
97
97
98 def softspace(file, newvalue):
98 def softspace(file, newvalue):
99 """Copied from code.py, to remove the dependency"""
99 """Copied from code.py, to remove the dependency"""
100
100
101 oldvalue = 0
101 oldvalue = 0
102 try:
102 try:
103 oldvalue = file.softspace
103 oldvalue = file.softspace
104 except AttributeError:
104 except AttributeError:
105 pass
105 pass
106 try:
106 try:
107 file.softspace = newvalue
107 file.softspace = newvalue
108 except (AttributeError, TypeError):
108 except (AttributeError, TypeError):
109 # "attribute-less object" or "read-only attributes"
109 # "attribute-less object" or "read-only attributes"
110 pass
110 pass
111 return oldvalue
111 return oldvalue
112
112
113
113
114 #****************************************************************************
114 #****************************************************************************
115 # Local use exceptions
115 # Local use exceptions
116 class SpaceInInput(exceptions.Exception): pass
116 class SpaceInInput(exceptions.Exception): pass
117
117
118
118
119 #****************************************************************************
119 #****************************************************************************
120 # Local use classes
120 # Local use classes
121 class Bunch: pass
121 class Bunch: pass
122
122
123 class Undefined: pass
123 class Undefined: pass
124
124
125 class Quitter(object):
125 class Quitter(object):
126 """Simple class to handle exit, similar to Python 2.5's.
126 """Simple class to handle exit, similar to Python 2.5's.
127
127
128 It handles exiting in an ipython-safe manner, which the one in Python 2.5
128 It handles exiting in an ipython-safe manner, which the one in Python 2.5
129 doesn't do (obviously, since it doesn't know about ipython)."""
129 doesn't do (obviously, since it doesn't know about ipython)."""
130
130
131 def __init__(self,shell,name):
131 def __init__(self,shell,name):
132 self.shell = shell
132 self.shell = shell
133 self.name = name
133 self.name = name
134
134
135 def __repr__(self):
135 def __repr__(self):
136 return 'Type %s() to exit.' % self.name
136 return 'Type %s() to exit.' % self.name
137 __str__ = __repr__
137 __str__ = __repr__
138
138
139 def __call__(self):
139 def __call__(self):
140 self.shell.exit()
140 self.shell.exit()
141
141
142 class InputList(list):
142 class InputList(list):
143 """Class to store user input.
143 """Class to store user input.
144
144
145 It's basically a list, but slices return a string instead of a list, thus
145 It's basically a list, but slices return a string instead of a list, thus
146 allowing things like (assuming 'In' is an instance):
146 allowing things like (assuming 'In' is an instance):
147
147
148 exec In[4:7]
148 exec In[4:7]
149
149
150 or
150 or
151
151
152 exec In[5:9] + In[14] + In[21:25]"""
152 exec In[5:9] + In[14] + In[21:25]"""
153
153
154 def __getslice__(self,i,j):
154 def __getslice__(self,i,j):
155 return ''.join(list.__getslice__(self,i,j))
155 return ''.join(list.__getslice__(self,i,j))
156
156
157 class SyntaxTB(ultraTB.ListTB):
157 class SyntaxTB(ultraTB.ListTB):
158 """Extension which holds some state: the last exception value"""
158 """Extension which holds some state: the last exception value"""
159
159
160 def __init__(self,color_scheme = 'NoColor'):
160 def __init__(self,color_scheme = 'NoColor'):
161 ultraTB.ListTB.__init__(self,color_scheme)
161 ultraTB.ListTB.__init__(self,color_scheme)
162 self.last_syntax_error = None
162 self.last_syntax_error = None
163
163
164 def __call__(self, etype, value, elist):
164 def __call__(self, etype, value, elist):
165 self.last_syntax_error = value
165 self.last_syntax_error = value
166 ultraTB.ListTB.__call__(self,etype,value,elist)
166 ultraTB.ListTB.__call__(self,etype,value,elist)
167
167
168 def clear_err_state(self):
168 def clear_err_state(self):
169 """Return the current error state and clear it"""
169 """Return the current error state and clear it"""
170 e = self.last_syntax_error
170 e = self.last_syntax_error
171 self.last_syntax_error = None
171 self.last_syntax_error = None
172 return e
172 return e
173
173
174 #****************************************************************************
174 #****************************************************************************
175 # Main IPython class
175 # Main IPython class
176
176
177 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
177 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
178 # until a full rewrite is made. I've cleaned all cross-class uses of
178 # until a full rewrite is made. I've cleaned all cross-class uses of
179 # attributes and methods, but too much user code out there relies on the
179 # attributes and methods, but too much user code out there relies on the
180 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
180 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
181 #
181 #
182 # But at least now, all the pieces have been separated and we could, in
182 # But at least now, all the pieces have been separated and we could, in
183 # principle, stop using the mixin. This will ease the transition to the
183 # principle, stop using the mixin. This will ease the transition to the
184 # chainsaw branch.
184 # chainsaw branch.
185
185
186 # For reference, the following is the list of 'self.foo' uses in the Magic
186 # For reference, the following is the list of 'self.foo' uses in the Magic
187 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
187 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
188 # class, to prevent clashes.
188 # class, to prevent clashes.
189
189
190 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
190 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
191 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
191 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
192 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
192 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
193 # 'self.value']
193 # 'self.value']
194
194
195 class InteractiveShell(object,Magic):
195 class InteractiveShell(object,Magic):
196 """An enhanced console for Python."""
196 """An enhanced console for Python."""
197
197
198 # class attribute to indicate whether the class supports threads or not.
198 # class attribute to indicate whether the class supports threads or not.
199 # Subclasses with thread support should override this as needed.
199 # Subclasses with thread support should override this as needed.
200 isthreaded = False
200 isthreaded = False
201
201
202 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
202 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
203 user_ns=None,user_global_ns=None,banner2='',
203 user_ns=None,user_global_ns=None,banner2='',
204 custom_exceptions=((),None),embedded=False):
204 custom_exceptions=((),None),embedded=False):
205
205
206 # log system
206 # log system
207 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
207 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
208
208
209 # Job manager (for jobs run as background threads)
209 # Job manager (for jobs run as background threads)
210 self.jobs = BackgroundJobManager()
210 self.jobs = BackgroundJobManager()
211
211
212 # Store the actual shell's name
212 # Store the actual shell's name
213 self.name = name
213 self.name = name
214 self.more = False
214 self.more = False
215
215
216 # We need to know whether the instance is meant for embedding, since
216 # We need to know whether the instance is meant for embedding, since
217 # global/local namespaces need to be handled differently in that case
217 # global/local namespaces need to be handled differently in that case
218 self.embedded = embedded
218 self.embedded = embedded
219 if embedded:
219 if embedded:
220 # Control variable so users can, from within the embedded instance,
220 # Control variable so users can, from within the embedded instance,
221 # permanently deactivate it.
221 # permanently deactivate it.
222 self.embedded_active = True
222 self.embedded_active = True
223
223
224 # command compiler
224 # command compiler
225 self.compile = codeop.CommandCompiler()
225 self.compile = codeop.CommandCompiler()
226
226
227 # User input buffer
227 # User input buffer
228 self.buffer = []
228 self.buffer = []
229
229
230 # Default name given in compilation of code
230 # Default name given in compilation of code
231 self.filename = '<ipython console>'
231 self.filename = '<ipython console>'
232
232
233 # Install our own quitter instead of the builtins. For python2.3-2.4,
233 # Install our own quitter instead of the builtins. For python2.3-2.4,
234 # this brings in behavior like 2.5, and for 2.5 it's identical.
234 # this brings in behavior like 2.5, and for 2.5 it's identical.
235 __builtin__.exit = Quitter(self,'exit')
235 __builtin__.exit = Quitter(self,'exit')
236 __builtin__.quit = Quitter(self,'quit')
236 __builtin__.quit = Quitter(self,'quit')
237
237
238 # Make an empty namespace, which extension writers can rely on both
238 # Make an empty namespace, which extension writers can rely on both
239 # existing and NEVER being used by ipython itself. This gives them a
239 # existing and NEVER being used by ipython itself. This gives them a
240 # convenient location for storing additional information and state
240 # convenient location for storing additional information and state
241 # their extensions may require, without fear of collisions with other
241 # their extensions may require, without fear of collisions with other
242 # ipython names that may develop later.
242 # ipython names that may develop later.
243 self.meta = Struct()
243 self.meta = Struct()
244
244
245 # Create the namespace where the user will operate. user_ns is
245 # Create the namespace where the user will operate. user_ns is
246 # normally the only one used, and it is passed to the exec calls as
246 # normally the only one used, and it is passed to the exec calls as
247 # the locals argument. But we do carry a user_global_ns namespace
247 # the locals argument. But we do carry a user_global_ns namespace
248 # given as the exec 'globals' argument, This is useful in embedding
248 # given as the exec 'globals' argument, This is useful in embedding
249 # situations where the ipython shell opens in a context where the
249 # situations where the ipython shell opens in a context where the
250 # distinction between locals and globals is meaningful. For
250 # distinction between locals and globals is meaningful. For
251 # non-embedded contexts, it is just the same object as the user_ns dict.
251 # non-embedded contexts, it is just the same object as the user_ns dict.
252
252
253 # FIXME. For some strange reason, __builtins__ is showing up at user
253 # FIXME. For some strange reason, __builtins__ is showing up at user
254 # level as a dict instead of a module. This is a manual fix, but I
254 # level as a dict instead of a module. This is a manual fix, but I
255 # should really track down where the problem is coming from. Alex
255 # should really track down where the problem is coming from. Alex
256 # Schmolck reported this problem first.
256 # Schmolck reported this problem first.
257
257
258 # A useful post by Alex Martelli on this topic:
258 # A useful post by Alex Martelli on this topic:
259 # Re: inconsistent value from __builtins__
259 # Re: inconsistent value from __builtins__
260 # Von: Alex Martelli <aleaxit@yahoo.com>
260 # Von: Alex Martelli <aleaxit@yahoo.com>
261 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
261 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
262 # Gruppen: comp.lang.python
262 # Gruppen: comp.lang.python
263
263
264 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
264 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
265 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
265 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
266 # > <type 'dict'>
266 # > <type 'dict'>
267 # > >>> print type(__builtins__)
267 # > >>> print type(__builtins__)
268 # > <type 'module'>
268 # > <type 'module'>
269 # > Is this difference in return value intentional?
269 # > Is this difference in return value intentional?
270
270
271 # Well, it's documented that '__builtins__' can be either a dictionary
271 # Well, it's documented that '__builtins__' can be either a dictionary
272 # or a module, and it's been that way for a long time. Whether it's
272 # or a module, and it's been that way for a long time. Whether it's
273 # intentional (or sensible), I don't know. In any case, the idea is
273 # intentional (or sensible), I don't know. In any case, the idea is
274 # that if you need to access the built-in namespace directly, you
274 # that if you need to access the built-in namespace directly, you
275 # should start with "import __builtin__" (note, no 's') which will
275 # should start with "import __builtin__" (note, no 's') which will
276 # definitely give you a module. Yeah, it's somewhat confusing:-(.
276 # definitely give you a module. Yeah, it's somewhat confusing:-(.
277
277
278 # These routines return properly built dicts as needed by the rest of
278 # These routines return properly built dicts as needed by the rest of
279 # the code, and can also be used by extension writers to generate
279 # the code, and can also be used by extension writers to generate
280 # properly initialized namespaces.
280 # properly initialized namespaces.
281 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
281 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
282 user_global_ns)
282 user_global_ns)
283
283
284 # Assign namespaces
284 # Assign namespaces
285 # This is the namespace where all normal user variables live
285 # This is the namespace where all normal user variables live
286 self.user_ns = user_ns
286 self.user_ns = user_ns
287 self.user_global_ns = user_global_ns
287 self.user_global_ns = user_global_ns
288 # A namespace to keep track of internal data structures to prevent
288 # A namespace to keep track of internal data structures to prevent
289 # them from cluttering user-visible stuff. Will be updated later
289 # them from cluttering user-visible stuff. Will be updated later
290 self.internal_ns = {}
290 self.internal_ns = {}
291
291
292 # Namespace of system aliases. Each entry in the alias
292 # Namespace of system aliases. Each entry in the alias
293 # table must be a 2-tuple of the form (N,name), where N is the number
293 # table must be a 2-tuple of the form (N,name), where N is the number
294 # of positional arguments of the alias.
294 # of positional arguments of the alias.
295 self.alias_table = {}
295 self.alias_table = {}
296
296
297 # A table holding all the namespaces IPython deals with, so that
297 # A table holding all the namespaces IPython deals with, so that
298 # introspection facilities can search easily.
298 # introspection facilities can search easily.
299 self.ns_table = {'user':user_ns,
299 self.ns_table = {'user':user_ns,
300 'user_global':user_global_ns,
300 'user_global':user_global_ns,
301 'alias':self.alias_table,
301 'alias':self.alias_table,
302 'internal':self.internal_ns,
302 'internal':self.internal_ns,
303 'builtin':__builtin__.__dict__
303 'builtin':__builtin__.__dict__
304 }
304 }
305 # The user namespace MUST have a pointer to the shell itself.
305 # The user namespace MUST have a pointer to the shell itself.
306 self.user_ns[name] = self
306 self.user_ns[name] = self
307
307
308 # We need to insert into sys.modules something that looks like a
308 # We need to insert into sys.modules something that looks like a
309 # module but which accesses the IPython namespace, for shelve and
309 # module but which accesses the IPython namespace, for shelve and
310 # pickle to work interactively. Normally they rely on getting
310 # pickle to work interactively. Normally they rely on getting
311 # everything out of __main__, but for embedding purposes each IPython
311 # everything out of __main__, but for embedding purposes each IPython
312 # instance has its own private namespace, so we can't go shoving
312 # instance has its own private namespace, so we can't go shoving
313 # everything into __main__.
313 # everything into __main__.
314
314
315 # note, however, that we should only do this for non-embedded
315 # note, however, that we should only do this for non-embedded
316 # ipythons, which really mimic the __main__.__dict__ with their own
316 # ipythons, which really mimic the __main__.__dict__ with their own
317 # namespace. Embedded instances, on the other hand, should not do
317 # namespace. Embedded instances, on the other hand, should not do
318 # this because they need to manage the user local/global namespaces
318 # this because they need to manage the user local/global namespaces
319 # only, but they live within a 'normal' __main__ (meaning, they
319 # only, but they live within a 'normal' __main__ (meaning, they
320 # shouldn't overtake the execution environment of the script they're
320 # shouldn't overtake the execution environment of the script they're
321 # embedded in).
321 # embedded in).
322
322
323 if not embedded:
323 if not embedded:
324 try:
324 try:
325 main_name = self.user_ns['__name__']
325 main_name = self.user_ns['__name__']
326 except KeyError:
326 except KeyError:
327 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
327 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
328 else:
328 else:
329 #print "pickle hack in place" # dbg
329 #print "pickle hack in place" # dbg
330 #print 'main_name:',main_name # dbg
330 #print 'main_name:',main_name # dbg
331 sys.modules[main_name] = FakeModule(self.user_ns)
331 sys.modules[main_name] = FakeModule(self.user_ns)
332
332
333 # Now that FakeModule produces a real module, we've run into a nasty
333 # Now that FakeModule produces a real module, we've run into a nasty
334 # problem: after script execution (via %run), the module where the user
334 # problem: after script execution (via %run), the module where the user
335 # code ran is deleted. Now that this object is a true module (needed
335 # code ran is deleted. Now that this object is a true module (needed
336 # so docetst and other tools work correctly), the Python module
336 # so docetst and other tools work correctly), the Python module
337 # teardown mechanism runs over it, and sets to None every variable
337 # teardown mechanism runs over it, and sets to None every variable
338 # present in that module. This means that later calls to functions
338 # present in that module. Top-level references to objects from the
339 # defined in the script (which have become interactively visible after
339 # script survive, because the user_ns is updated with them. However,
340 # script exit) fail, because they hold references to objects that have
340 # calling functions defined in the script that use other things from
341 # become overwritten into None. The only solution I see right now is
341 # the script will fail, because the function's closure had references
342 # to protect every FakeModule used by %run by holding an internal
342 # to the original objects, which are now all None. So we must protect
343 # reference to it. This private list will be used for that. The
343 # these modules from deletion by keeping a cache. To avoid keeping
344 # %reset command will flush it as well.
344 # stale modules around (we only need the one from the last run), we use
345 self._user_main_modules = []
345 # a dict keyed with the full path to the script, so only the last
346
346 # version of the module is held in the cache. The %reset command will
347 # flush this cache. See the cache_main_mod() and clear_main_mod_cache()
348 # methods for details on use.
349 self._user_main_modules = {}
350
347 # List of input with multi-line handling.
351 # List of input with multi-line handling.
348 # Fill its zero entry, user counter starts at 1
352 # Fill its zero entry, user counter starts at 1
349 self.input_hist = InputList(['\n'])
353 self.input_hist = InputList(['\n'])
350 # This one will hold the 'raw' input history, without any
354 # This one will hold the 'raw' input history, without any
351 # pre-processing. This will allow users to retrieve the input just as
355 # pre-processing. This will allow users to retrieve the input just as
352 # it was exactly typed in by the user, with %hist -r.
356 # it was exactly typed in by the user, with %hist -r.
353 self.input_hist_raw = InputList(['\n'])
357 self.input_hist_raw = InputList(['\n'])
354
358
355 # list of visited directories
359 # list of visited directories
356 try:
360 try:
357 self.dir_hist = [os.getcwd()]
361 self.dir_hist = [os.getcwd()]
358 except OSError:
362 except OSError:
359 self.dir_hist = []
363 self.dir_hist = []
360
364
361 # dict of output history
365 # dict of output history
362 self.output_hist = {}
366 self.output_hist = {}
363
367
364 # Get system encoding at startup time. Certain terminals (like Emacs
368 # Get system encoding at startup time. Certain terminals (like Emacs
365 # under Win32 have it set to None, and we need to have a known valid
369 # under Win32 have it set to None, and we need to have a known valid
366 # encoding to use in the raw_input() method
370 # encoding to use in the raw_input() method
367 try:
371 try:
368 self.stdin_encoding = sys.stdin.encoding or 'ascii'
372 self.stdin_encoding = sys.stdin.encoding or 'ascii'
369 except AttributeError:
373 except AttributeError:
370 self.stdin_encoding = 'ascii'
374 self.stdin_encoding = 'ascii'
371
375
372 # dict of things NOT to alias (keywords, builtins and some magics)
376 # dict of things NOT to alias (keywords, builtins and some magics)
373 no_alias = {}
377 no_alias = {}
374 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
378 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
375 for key in keyword.kwlist + no_alias_magics:
379 for key in keyword.kwlist + no_alias_magics:
376 no_alias[key] = 1
380 no_alias[key] = 1
377 no_alias.update(__builtin__.__dict__)
381 no_alias.update(__builtin__.__dict__)
378 self.no_alias = no_alias
382 self.no_alias = no_alias
379
383
380 # make global variables for user access to these
384 # make global variables for user access to these
381 self.user_ns['_ih'] = self.input_hist
385 self.user_ns['_ih'] = self.input_hist
382 self.user_ns['_oh'] = self.output_hist
386 self.user_ns['_oh'] = self.output_hist
383 self.user_ns['_dh'] = self.dir_hist
387 self.user_ns['_dh'] = self.dir_hist
384
388
385 # user aliases to input and output histories
389 # user aliases to input and output histories
386 self.user_ns['In'] = self.input_hist
390 self.user_ns['In'] = self.input_hist
387 self.user_ns['Out'] = self.output_hist
391 self.user_ns['Out'] = self.output_hist
388
392
389 self.user_ns['_sh'] = IPython.shadowns
393 self.user_ns['_sh'] = IPython.shadowns
390 # Object variable to store code object waiting execution. This is
394 # Object variable to store code object waiting execution. This is
391 # used mainly by the multithreaded shells, but it can come in handy in
395 # used mainly by the multithreaded shells, but it can come in handy in
392 # other situations. No need to use a Queue here, since it's a single
396 # other situations. No need to use a Queue here, since it's a single
393 # item which gets cleared once run.
397 # item which gets cleared once run.
394 self.code_to_run = None
398 self.code_to_run = None
395
399
396 # escapes for automatic behavior on the command line
400 # escapes for automatic behavior on the command line
397 self.ESC_SHELL = '!'
401 self.ESC_SHELL = '!'
398 self.ESC_SH_CAP = '!!'
402 self.ESC_SH_CAP = '!!'
399 self.ESC_HELP = '?'
403 self.ESC_HELP = '?'
400 self.ESC_MAGIC = '%'
404 self.ESC_MAGIC = '%'
401 self.ESC_QUOTE = ','
405 self.ESC_QUOTE = ','
402 self.ESC_QUOTE2 = ';'
406 self.ESC_QUOTE2 = ';'
403 self.ESC_PAREN = '/'
407 self.ESC_PAREN = '/'
404
408
405 # And their associated handlers
409 # And their associated handlers
406 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
410 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
407 self.ESC_QUOTE : self.handle_auto,
411 self.ESC_QUOTE : self.handle_auto,
408 self.ESC_QUOTE2 : self.handle_auto,
412 self.ESC_QUOTE2 : self.handle_auto,
409 self.ESC_MAGIC : self.handle_magic,
413 self.ESC_MAGIC : self.handle_magic,
410 self.ESC_HELP : self.handle_help,
414 self.ESC_HELP : self.handle_help,
411 self.ESC_SHELL : self.handle_shell_escape,
415 self.ESC_SHELL : self.handle_shell_escape,
412 self.ESC_SH_CAP : self.handle_shell_escape,
416 self.ESC_SH_CAP : self.handle_shell_escape,
413 }
417 }
414
418
415 # class initializations
419 # class initializations
416 Magic.__init__(self,self)
420 Magic.__init__(self,self)
417
421
418 # Python source parser/formatter for syntax highlighting
422 # Python source parser/formatter for syntax highlighting
419 pyformat = PyColorize.Parser().format
423 pyformat = PyColorize.Parser().format
420 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
424 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
421
425
422 # hooks holds pointers used for user-side customizations
426 # hooks holds pointers used for user-side customizations
423 self.hooks = Struct()
427 self.hooks = Struct()
424
428
425 self.strdispatchers = {}
429 self.strdispatchers = {}
426
430
427 # Set all default hooks, defined in the IPython.hooks module.
431 # Set all default hooks, defined in the IPython.hooks module.
428 hooks = IPython.hooks
432 hooks = IPython.hooks
429 for hook_name in hooks.__all__:
433 for hook_name in hooks.__all__:
430 # default hooks have priority 100, i.e. low; user hooks should have
434 # default hooks have priority 100, i.e. low; user hooks should have
431 # 0-100 priority
435 # 0-100 priority
432 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
436 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
433 #print "bound hook",hook_name
437 #print "bound hook",hook_name
434
438
435 # Flag to mark unconditional exit
439 # Flag to mark unconditional exit
436 self.exit_now = False
440 self.exit_now = False
437
441
438 self.usage_min = """\
442 self.usage_min = """\
439 An enhanced console for Python.
443 An enhanced console for Python.
440 Some of its features are:
444 Some of its features are:
441 - Readline support if the readline library is present.
445 - Readline support if the readline library is present.
442 - Tab completion in the local namespace.
446 - Tab completion in the local namespace.
443 - Logging of input, see command-line options.
447 - Logging of input, see command-line options.
444 - System shell escape via ! , eg !ls.
448 - System shell escape via ! , eg !ls.
445 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
449 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
446 - Keeps track of locally defined variables via %who, %whos.
450 - Keeps track of locally defined variables via %who, %whos.
447 - Show object information with a ? eg ?x or x? (use ?? for more info).
451 - Show object information with a ? eg ?x or x? (use ?? for more info).
448 """
452 """
449 if usage: self.usage = usage
453 if usage: self.usage = usage
450 else: self.usage = self.usage_min
454 else: self.usage = self.usage_min
451
455
452 # Storage
456 # Storage
453 self.rc = rc # This will hold all configuration information
457 self.rc = rc # This will hold all configuration information
454 self.pager = 'less'
458 self.pager = 'less'
455 # temporary files used for various purposes. Deleted at exit.
459 # temporary files used for various purposes. Deleted at exit.
456 self.tempfiles = []
460 self.tempfiles = []
457
461
458 # Keep track of readline usage (later set by init_readline)
462 # Keep track of readline usage (later set by init_readline)
459 self.has_readline = False
463 self.has_readline = False
460
464
461 # template for logfile headers. It gets resolved at runtime by the
465 # template for logfile headers. It gets resolved at runtime by the
462 # logstart method.
466 # logstart method.
463 self.loghead_tpl = \
467 self.loghead_tpl = \
464 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
468 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
465 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
469 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
466 #log# opts = %s
470 #log# opts = %s
467 #log# args = %s
471 #log# args = %s
468 #log# It is safe to make manual edits below here.
472 #log# It is safe to make manual edits below here.
469 #log#-----------------------------------------------------------------------
473 #log#-----------------------------------------------------------------------
470 """
474 """
471 # for pushd/popd management
475 # for pushd/popd management
472 try:
476 try:
473 self.home_dir = get_home_dir()
477 self.home_dir = get_home_dir()
474 except HomeDirError,msg:
478 except HomeDirError,msg:
475 fatal(msg)
479 fatal(msg)
476
480
477 self.dir_stack = []
481 self.dir_stack = []
478
482
479 # Functions to call the underlying shell.
483 # Functions to call the underlying shell.
480
484
481 # The first is similar to os.system, but it doesn't return a value,
485 # The first is similar to os.system, but it doesn't return a value,
482 # and it allows interpolation of variables in the user's namespace.
486 # and it allows interpolation of variables in the user's namespace.
483 self.system = lambda cmd: \
487 self.system = lambda cmd: \
484 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
488 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
485
489
486 # These are for getoutput and getoutputerror:
490 # These are for getoutput and getoutputerror:
487 self.getoutput = lambda cmd: \
491 self.getoutput = lambda cmd: \
488 getoutput(self.var_expand(cmd,depth=2),
492 getoutput(self.var_expand(cmd,depth=2),
489 header=self.rc.system_header,
493 header=self.rc.system_header,
490 verbose=self.rc.system_verbose)
494 verbose=self.rc.system_verbose)
491
495
492 self.getoutputerror = lambda cmd: \
496 self.getoutputerror = lambda cmd: \
493 getoutputerror(self.var_expand(cmd,depth=2),
497 getoutputerror(self.var_expand(cmd,depth=2),
494 header=self.rc.system_header,
498 header=self.rc.system_header,
495 verbose=self.rc.system_verbose)
499 verbose=self.rc.system_verbose)
496
500
497
501
498 # keep track of where we started running (mainly for crash post-mortem)
502 # keep track of where we started running (mainly for crash post-mortem)
499 self.starting_dir = os.getcwd()
503 self.starting_dir = os.getcwd()
500
504
501 # Various switches which can be set
505 # Various switches which can be set
502 self.CACHELENGTH = 5000 # this is cheap, it's just text
506 self.CACHELENGTH = 5000 # this is cheap, it's just text
503 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
507 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
504 self.banner2 = banner2
508 self.banner2 = banner2
505
509
506 # TraceBack handlers:
510 # TraceBack handlers:
507
511
508 # Syntax error handler.
512 # Syntax error handler.
509 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
513 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
510
514
511 # The interactive one is initialized with an offset, meaning we always
515 # The interactive one is initialized with an offset, meaning we always
512 # want to remove the topmost item in the traceback, which is our own
516 # want to remove the topmost item in the traceback, which is our own
513 # internal code. Valid modes: ['Plain','Context','Verbose']
517 # internal code. Valid modes: ['Plain','Context','Verbose']
514 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
518 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
515 color_scheme='NoColor',
519 color_scheme='NoColor',
516 tb_offset = 1)
520 tb_offset = 1)
517
521
518 # IPython itself shouldn't crash. This will produce a detailed
522 # IPython itself shouldn't crash. This will produce a detailed
519 # post-mortem if it does. But we only install the crash handler for
523 # post-mortem if it does. But we only install the crash handler for
520 # non-threaded shells, the threaded ones use a normal verbose reporter
524 # non-threaded shells, the threaded ones use a normal verbose reporter
521 # and lose the crash handler. This is because exceptions in the main
525 # and lose the crash handler. This is because exceptions in the main
522 # thread (such as in GUI code) propagate directly to sys.excepthook,
526 # thread (such as in GUI code) propagate directly to sys.excepthook,
523 # and there's no point in printing crash dumps for every user exception.
527 # and there's no point in printing crash dumps for every user exception.
524 if self.isthreaded:
528 if self.isthreaded:
525 ipCrashHandler = ultraTB.FormattedTB()
529 ipCrashHandler = ultraTB.FormattedTB()
526 else:
530 else:
527 from IPython import CrashHandler
531 from IPython import CrashHandler
528 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
532 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
529 self.set_crash_handler(ipCrashHandler)
533 self.set_crash_handler(ipCrashHandler)
530
534
531 # and add any custom exception handlers the user may have specified
535 # and add any custom exception handlers the user may have specified
532 self.set_custom_exc(*custom_exceptions)
536 self.set_custom_exc(*custom_exceptions)
533
537
534 # indentation management
538 # indentation management
535 self.autoindent = False
539 self.autoindent = False
536 self.indent_current_nsp = 0
540 self.indent_current_nsp = 0
537
541
538 # Make some aliases automatically
542 # Make some aliases automatically
539 # Prepare list of shell aliases to auto-define
543 # Prepare list of shell aliases to auto-define
540 if os.name == 'posix':
544 if os.name == 'posix':
541 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
545 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
542 'mv mv -i','rm rm -i','cp cp -i',
546 'mv mv -i','rm rm -i','cp cp -i',
543 'cat cat','less less','clear clear',
547 'cat cat','less less','clear clear',
544 # a better ls
548 # a better ls
545 'ls ls -F',
549 'ls ls -F',
546 # long ls
550 # long ls
547 'll ls -lF')
551 'll ls -lF')
548 # Extra ls aliases with color, which need special treatment on BSD
552 # Extra ls aliases with color, which need special treatment on BSD
549 # variants
553 # variants
550 ls_extra = ( # color ls
554 ls_extra = ( # color ls
551 'lc ls -F -o --color',
555 'lc ls -F -o --color',
552 # ls normal files only
556 # ls normal files only
553 'lf ls -F -o --color %l | grep ^-',
557 'lf ls -F -o --color %l | grep ^-',
554 # ls symbolic links
558 # ls symbolic links
555 'lk ls -F -o --color %l | grep ^l',
559 'lk ls -F -o --color %l | grep ^l',
556 # directories or links to directories,
560 # directories or links to directories,
557 'ldir ls -F -o --color %l | grep /$',
561 'ldir ls -F -o --color %l | grep /$',
558 # things which are executable
562 # things which are executable
559 'lx ls -F -o --color %l | grep ^-..x',
563 'lx ls -F -o --color %l | grep ^-..x',
560 )
564 )
561 # The BSDs don't ship GNU ls, so they don't understand the
565 # The BSDs don't ship GNU ls, so they don't understand the
562 # --color switch out of the box
566 # --color switch out of the box
563 if 'bsd' in sys.platform:
567 if 'bsd' in sys.platform:
564 ls_extra = ( # ls normal files only
568 ls_extra = ( # ls normal files only
565 'lf ls -lF | grep ^-',
569 'lf ls -lF | grep ^-',
566 # ls symbolic links
570 # ls symbolic links
567 'lk ls -lF | grep ^l',
571 'lk ls -lF | grep ^l',
568 # directories or links to directories,
572 # directories or links to directories,
569 'ldir ls -lF | grep /$',
573 'ldir ls -lF | grep /$',
570 # things which are executable
574 # things which are executable
571 'lx ls -lF | grep ^-..x',
575 'lx ls -lF | grep ^-..x',
572 )
576 )
573 auto_alias = auto_alias + ls_extra
577 auto_alias = auto_alias + ls_extra
574 elif os.name in ['nt','dos']:
578 elif os.name in ['nt','dos']:
575 auto_alias = ('ls dir /on',
579 auto_alias = ('ls dir /on',
576 'ddir dir /ad /on', 'ldir dir /ad /on',
580 'ddir dir /ad /on', 'ldir dir /ad /on',
577 'mkdir mkdir','rmdir rmdir','echo echo',
581 'mkdir mkdir','rmdir rmdir','echo echo',
578 'ren ren','cls cls','copy copy')
582 'ren ren','cls cls','copy copy')
579 else:
583 else:
580 auto_alias = ()
584 auto_alias = ()
581 self.auto_alias = [s.split(None,1) for s in auto_alias]
585 self.auto_alias = [s.split(None,1) for s in auto_alias]
582
586
583
587
584 # Produce a public API instance
588 # Produce a public API instance
585 self.api = IPython.ipapi.IPApi(self)
589 self.api = IPython.ipapi.IPApi(self)
586
590
587 # Call the actual (public) initializer
591 # Call the actual (public) initializer
588 self.init_auto_alias()
592 self.init_auto_alias()
589
593
590 # track which builtins we add, so we can clean up later
594 # track which builtins we add, so we can clean up later
591 self.builtins_added = {}
595 self.builtins_added = {}
592 # This method will add the necessary builtins for operation, but
596 # This method will add the necessary builtins for operation, but
593 # tracking what it did via the builtins_added dict.
597 # tracking what it did via the builtins_added dict.
594
598
595 #TODO: remove this, redundant
599 #TODO: remove this, redundant
596 self.add_builtins()
600 self.add_builtins()
597
598
599
600
601 # end __init__
601 # end __init__
602
602
603 def var_expand(self,cmd,depth=0):
603 def var_expand(self,cmd,depth=0):
604 """Expand python variables in a string.
604 """Expand python variables in a string.
605
605
606 The depth argument indicates how many frames above the caller should
606 The depth argument indicates how many frames above the caller should
607 be walked to look for the local namespace where to expand variables.
607 be walked to look for the local namespace where to expand variables.
608
608
609 The global namespace for expansion is always the user's interactive
609 The global namespace for expansion is always the user's interactive
610 namespace.
610 namespace.
611 """
611 """
612
612
613 return str(ItplNS(cmd,
613 return str(ItplNS(cmd,
614 self.user_ns, # globals
614 self.user_ns, # globals
615 # Skip our own frame in searching for locals:
615 # Skip our own frame in searching for locals:
616 sys._getframe(depth+1).f_locals # locals
616 sys._getframe(depth+1).f_locals # locals
617 ))
617 ))
618
618
619 def pre_config_initialization(self):
619 def pre_config_initialization(self):
620 """Pre-configuration init method
620 """Pre-configuration init method
621
621
622 This is called before the configuration files are processed to
622 This is called before the configuration files are processed to
623 prepare the services the config files might need.
623 prepare the services the config files might need.
624
624
625 self.rc already has reasonable default values at this point.
625 self.rc already has reasonable default values at this point.
626 """
626 """
627 rc = self.rc
627 rc = self.rc
628 try:
628 try:
629 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
629 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
630 except exceptions.UnicodeDecodeError:
630 except exceptions.UnicodeDecodeError:
631 print "Your ipythondir can't be decoded to unicode!"
631 print "Your ipythondir can't be decoded to unicode!"
632 print "Please set HOME environment variable to something that"
632 print "Please set HOME environment variable to something that"
633 print r"only has ASCII characters, e.g. c:\home"
633 print r"only has ASCII characters, e.g. c:\home"
634 print "Now it is",rc.ipythondir
634 print "Now it is",rc.ipythondir
635 sys.exit()
635 sys.exit()
636 self.shadowhist = IPython.history.ShadowHist(self.db)
636 self.shadowhist = IPython.history.ShadowHist(self.db)
637
637
638
639 def post_config_initialization(self):
638 def post_config_initialization(self):
640 """Post configuration init method
639 """Post configuration init method
641
640
642 This is called after the configuration files have been processed to
641 This is called after the configuration files have been processed to
643 'finalize' the initialization."""
642 'finalize' the initialization."""
644
643
645 rc = self.rc
644 rc = self.rc
646
645
647 # Object inspector
646 # Object inspector
648 self.inspector = OInspect.Inspector(OInspect.InspectColors,
647 self.inspector = OInspect.Inspector(OInspect.InspectColors,
649 PyColorize.ANSICodeColors,
648 PyColorize.ANSICodeColors,
650 'NoColor',
649 'NoColor',
651 rc.object_info_string_level)
650 rc.object_info_string_level)
652
651
653 self.rl_next_input = None
652 self.rl_next_input = None
654 self.rl_do_indent = False
653 self.rl_do_indent = False
655 # Load readline proper
654 # Load readline proper
656 if rc.readline:
655 if rc.readline:
657 self.init_readline()
656 self.init_readline()
658
657
659
658
660 # local shortcut, this is used a LOT
659 # local shortcut, this is used a LOT
661 self.log = self.logger.log
660 self.log = self.logger.log
662
661
663 # Initialize cache, set in/out prompts and printing system
662 # Initialize cache, set in/out prompts and printing system
664 self.outputcache = CachedOutput(self,
663 self.outputcache = CachedOutput(self,
665 rc.cache_size,
664 rc.cache_size,
666 rc.pprint,
665 rc.pprint,
667 input_sep = rc.separate_in,
666 input_sep = rc.separate_in,
668 output_sep = rc.separate_out,
667 output_sep = rc.separate_out,
669 output_sep2 = rc.separate_out2,
668 output_sep2 = rc.separate_out2,
670 ps1 = rc.prompt_in1,
669 ps1 = rc.prompt_in1,
671 ps2 = rc.prompt_in2,
670 ps2 = rc.prompt_in2,
672 ps_out = rc.prompt_out,
671 ps_out = rc.prompt_out,
673 pad_left = rc.prompts_pad_left)
672 pad_left = rc.prompts_pad_left)
674
673
675 # user may have over-ridden the default print hook:
674 # user may have over-ridden the default print hook:
676 try:
675 try:
677 self.outputcache.__class__.display = self.hooks.display
676 self.outputcache.__class__.display = self.hooks.display
678 except AttributeError:
677 except AttributeError:
679 pass
678 pass
680
679
681 # I don't like assigning globally to sys, because it means when
680 # I don't like assigning globally to sys, because it means when
682 # embedding instances, each embedded instance overrides the previous
681 # embedding instances, each embedded instance overrides the previous
683 # choice. But sys.displayhook seems to be called internally by exec,
682 # choice. But sys.displayhook seems to be called internally by exec,
684 # so I don't see a way around it. We first save the original and then
683 # so I don't see a way around it. We first save the original and then
685 # overwrite it.
684 # overwrite it.
686 self.sys_displayhook = sys.displayhook
685 self.sys_displayhook = sys.displayhook
687 sys.displayhook = self.outputcache
686 sys.displayhook = self.outputcache
688
687
689 # Do a proper resetting of doctest, including the necessary displayhook
688 # Do a proper resetting of doctest, including the necessary displayhook
690 # monkeypatching
689 # monkeypatching
691 try:
690 try:
692 doctest_reload()
691 doctest_reload()
693 except ImportError:
692 except ImportError:
694 warn("doctest module does not exist.")
693 warn("doctest module does not exist.")
695
694
696 # Set user colors (don't do it in the constructor above so that it
695 # Set user colors (don't do it in the constructor above so that it
697 # doesn't crash if colors option is invalid)
696 # doesn't crash if colors option is invalid)
698 self.magic_colors(rc.colors)
697 self.magic_colors(rc.colors)
699
698
700 # Set calling of pdb on exceptions
699 # Set calling of pdb on exceptions
701 self.call_pdb = rc.pdb
700 self.call_pdb = rc.pdb
702
701
703 # Load user aliases
702 # Load user aliases
704 for alias in rc.alias:
703 for alias in rc.alias:
705 self.magic_alias(alias)
704 self.magic_alias(alias)
706
705
707 self.hooks.late_startup_hook()
706 self.hooks.late_startup_hook()
708
707
709 for cmd in self.rc.autoexec:
708 for cmd in self.rc.autoexec:
710 #print "autoexec>",cmd #dbg
709 #print "autoexec>",cmd #dbg
711 self.api.runlines(cmd)
710 self.api.runlines(cmd)
712
711
713 batchrun = False
712 batchrun = False
714 for batchfile in [path(arg) for arg in self.rc.args
713 for batchfile in [path(arg) for arg in self.rc.args
715 if arg.lower().endswith('.ipy')]:
714 if arg.lower().endswith('.ipy')]:
716 if not batchfile.isfile():
715 if not batchfile.isfile():
717 print "No such batch file:", batchfile
716 print "No such batch file:", batchfile
718 continue
717 continue
719 self.api.runlines(batchfile.text())
718 self.api.runlines(batchfile.text())
720 batchrun = True
719 batchrun = True
721 # without -i option, exit after running the batch file
720 # without -i option, exit after running the batch file
722 if batchrun and not self.rc.interact:
721 if batchrun and not self.rc.interact:
723 self.ask_exit()
722 self.ask_exit()
724
723
725 def add_builtins(self):
724 def add_builtins(self):
726 """Store ipython references into the builtin namespace.
725 """Store ipython references into the builtin namespace.
727
726
728 Some parts of ipython operate via builtins injected here, which hold a
727 Some parts of ipython operate via builtins injected here, which hold a
729 reference to IPython itself."""
728 reference to IPython itself."""
730
729
731 # TODO: deprecate all of these, they are unsafe
730 # TODO: deprecate all of these, they are unsafe
732 builtins_new = dict(__IPYTHON__ = self,
731 builtins_new = dict(__IPYTHON__ = self,
733 ip_set_hook = self.set_hook,
732 ip_set_hook = self.set_hook,
734 jobs = self.jobs,
733 jobs = self.jobs,
735 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
734 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
736 ipalias = wrap_deprecated(self.ipalias),
735 ipalias = wrap_deprecated(self.ipalias),
737 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
736 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
738 #_ip = self.api
737 #_ip = self.api
739 )
738 )
740 for biname,bival in builtins_new.items():
739 for biname,bival in builtins_new.items():
741 try:
740 try:
742 # store the orignal value so we can restore it
741 # store the orignal value so we can restore it
743 self.builtins_added[biname] = __builtin__.__dict__[biname]
742 self.builtins_added[biname] = __builtin__.__dict__[biname]
744 except KeyError:
743 except KeyError:
745 # or mark that it wasn't defined, and we'll just delete it at
744 # or mark that it wasn't defined, and we'll just delete it at
746 # cleanup
745 # cleanup
747 self.builtins_added[biname] = Undefined
746 self.builtins_added[biname] = Undefined
748 __builtin__.__dict__[biname] = bival
747 __builtin__.__dict__[biname] = bival
749
748
750 # Keep in the builtins a flag for when IPython is active. We set it
749 # Keep in the builtins a flag for when IPython is active. We set it
751 # with setdefault so that multiple nested IPythons don't clobber one
750 # with setdefault so that multiple nested IPythons don't clobber one
752 # another. Each will increase its value by one upon being activated,
751 # another. Each will increase its value by one upon being activated,
753 # which also gives us a way to determine the nesting level.
752 # which also gives us a way to determine the nesting level.
754 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
753 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
755
754
756 def clean_builtins(self):
755 def clean_builtins(self):
757 """Remove any builtins which might have been added by add_builtins, or
756 """Remove any builtins which might have been added by add_builtins, or
758 restore overwritten ones to their previous values."""
757 restore overwritten ones to their previous values."""
759 for biname,bival in self.builtins_added.items():
758 for biname,bival in self.builtins_added.items():
760 if bival is Undefined:
759 if bival is Undefined:
761 del __builtin__.__dict__[biname]
760 del __builtin__.__dict__[biname]
762 else:
761 else:
763 __builtin__.__dict__[biname] = bival
762 __builtin__.__dict__[biname] = bival
764 self.builtins_added.clear()
763 self.builtins_added.clear()
765
764
766 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
765 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
767 """set_hook(name,hook) -> sets an internal IPython hook.
766 """set_hook(name,hook) -> sets an internal IPython hook.
768
767
769 IPython exposes some of its internal API as user-modifiable hooks. By
768 IPython exposes some of its internal API as user-modifiable hooks. By
770 adding your function to one of these hooks, you can modify IPython's
769 adding your function to one of these hooks, you can modify IPython's
771 behavior to call at runtime your own routines."""
770 behavior to call at runtime your own routines."""
772
771
773 # At some point in the future, this should validate the hook before it
772 # At some point in the future, this should validate the hook before it
774 # accepts it. Probably at least check that the hook takes the number
773 # accepts it. Probably at least check that the hook takes the number
775 # of args it's supposed to.
774 # of args it's supposed to.
776
775
777 f = new.instancemethod(hook,self,self.__class__)
776 f = new.instancemethod(hook,self,self.__class__)
778
777
779 # check if the hook is for strdispatcher first
778 # check if the hook is for strdispatcher first
780 if str_key is not None:
779 if str_key is not None:
781 sdp = self.strdispatchers.get(name, StrDispatch())
780 sdp = self.strdispatchers.get(name, StrDispatch())
782 sdp.add_s(str_key, f, priority )
781 sdp.add_s(str_key, f, priority )
783 self.strdispatchers[name] = sdp
782 self.strdispatchers[name] = sdp
784 return
783 return
785 if re_key is not None:
784 if re_key is not None:
786 sdp = self.strdispatchers.get(name, StrDispatch())
785 sdp = self.strdispatchers.get(name, StrDispatch())
787 sdp.add_re(re.compile(re_key), f, priority )
786 sdp.add_re(re.compile(re_key), f, priority )
788 self.strdispatchers[name] = sdp
787 self.strdispatchers[name] = sdp
789 return
788 return
790
789
791 dp = getattr(self.hooks, name, None)
790 dp = getattr(self.hooks, name, None)
792 if name not in IPython.hooks.__all__:
791 if name not in IPython.hooks.__all__:
793 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
792 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
794 if not dp:
793 if not dp:
795 dp = IPython.hooks.CommandChainDispatcher()
794 dp = IPython.hooks.CommandChainDispatcher()
796
795
797 try:
796 try:
798 dp.add(f,priority)
797 dp.add(f,priority)
799 except AttributeError:
798 except AttributeError:
800 # it was not commandchain, plain old func - replace
799 # it was not commandchain, plain old func - replace
801 dp = f
800 dp = f
802
801
803 setattr(self.hooks,name, dp)
802 setattr(self.hooks,name, dp)
804
803
805
804
806 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
805 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
807
806
808 def set_crash_handler(self,crashHandler):
807 def set_crash_handler(self,crashHandler):
809 """Set the IPython crash handler.
808 """Set the IPython crash handler.
810
809
811 This must be a callable with a signature suitable for use as
810 This must be a callable with a signature suitable for use as
812 sys.excepthook."""
811 sys.excepthook."""
813
812
814 # Install the given crash handler as the Python exception hook
813 # Install the given crash handler as the Python exception hook
815 sys.excepthook = crashHandler
814 sys.excepthook = crashHandler
816
815
817 # The instance will store a pointer to this, so that runtime code
816 # The instance will store a pointer to this, so that runtime code
818 # (such as magics) can access it. This is because during the
817 # (such as magics) can access it. This is because during the
819 # read-eval loop, it gets temporarily overwritten (to deal with GUI
818 # read-eval loop, it gets temporarily overwritten (to deal with GUI
820 # frameworks).
819 # frameworks).
821 self.sys_excepthook = sys.excepthook
820 self.sys_excepthook = sys.excepthook
822
821
823
822
824 def set_custom_exc(self,exc_tuple,handler):
823 def set_custom_exc(self,exc_tuple,handler):
825 """set_custom_exc(exc_tuple,handler)
824 """set_custom_exc(exc_tuple,handler)
826
825
827 Set a custom exception handler, which will be called if any of the
826 Set a custom exception handler, which will be called if any of the
828 exceptions in exc_tuple occur in the mainloop (specifically, in the
827 exceptions in exc_tuple occur in the mainloop (specifically, in the
829 runcode() method.
828 runcode() method.
830
829
831 Inputs:
830 Inputs:
832
831
833 - exc_tuple: a *tuple* of valid exceptions to call the defined
832 - exc_tuple: a *tuple* of valid exceptions to call the defined
834 handler for. It is very important that you use a tuple, and NOT A
833 handler for. It is very important that you use a tuple, and NOT A
835 LIST here, because of the way Python's except statement works. If
834 LIST here, because of the way Python's except statement works. If
836 you only want to trap a single exception, use a singleton tuple:
835 you only want to trap a single exception, use a singleton tuple:
837
836
838 exc_tuple == (MyCustomException,)
837 exc_tuple == (MyCustomException,)
839
838
840 - handler: this must be defined as a function with the following
839 - handler: this must be defined as a function with the following
841 basic interface: def my_handler(self,etype,value,tb).
840 basic interface: def my_handler(self,etype,value,tb).
842
841
843 This will be made into an instance method (via new.instancemethod)
842 This will be made into an instance method (via new.instancemethod)
844 of IPython itself, and it will be called if any of the exceptions
843 of IPython itself, and it will be called if any of the exceptions
845 listed in the exc_tuple are caught. If the handler is None, an
844 listed in the exc_tuple are caught. If the handler is None, an
846 internal basic one is used, which just prints basic info.
845 internal basic one is used, which just prints basic info.
847
846
848 WARNING: by putting in your own exception handler into IPython's main
847 WARNING: by putting in your own exception handler into IPython's main
849 execution loop, you run a very good chance of nasty crashes. This
848 execution loop, you run a very good chance of nasty crashes. This
850 facility should only be used if you really know what you are doing."""
849 facility should only be used if you really know what you are doing."""
851
850
852 assert type(exc_tuple)==type(()) , \
851 assert type(exc_tuple)==type(()) , \
853 "The custom exceptions must be given AS A TUPLE."
852 "The custom exceptions must be given AS A TUPLE."
854
853
855 def dummy_handler(self,etype,value,tb):
854 def dummy_handler(self,etype,value,tb):
856 print '*** Simple custom exception handler ***'
855 print '*** Simple custom exception handler ***'
857 print 'Exception type :',etype
856 print 'Exception type :',etype
858 print 'Exception value:',value
857 print 'Exception value:',value
859 print 'Traceback :',tb
858 print 'Traceback :',tb
860 print 'Source code :','\n'.join(self.buffer)
859 print 'Source code :','\n'.join(self.buffer)
861
860
862 if handler is None: handler = dummy_handler
861 if handler is None: handler = dummy_handler
863
862
864 self.CustomTB = new.instancemethod(handler,self,self.__class__)
863 self.CustomTB = new.instancemethod(handler,self,self.__class__)
865 self.custom_exceptions = exc_tuple
864 self.custom_exceptions = exc_tuple
866
865
867 def set_custom_completer(self,completer,pos=0):
866 def set_custom_completer(self,completer,pos=0):
868 """set_custom_completer(completer,pos=0)
867 """set_custom_completer(completer,pos=0)
869
868
870 Adds a new custom completer function.
869 Adds a new custom completer function.
871
870
872 The position argument (defaults to 0) is the index in the completers
871 The position argument (defaults to 0) is the index in the completers
873 list where you want the completer to be inserted."""
872 list where you want the completer to be inserted."""
874
873
875 newcomp = new.instancemethod(completer,self.Completer,
874 newcomp = new.instancemethod(completer,self.Completer,
876 self.Completer.__class__)
875 self.Completer.__class__)
877 self.Completer.matchers.insert(pos,newcomp)
876 self.Completer.matchers.insert(pos,newcomp)
878
877
879 def set_completer(self):
878 def set_completer(self):
880 """reset readline's completer to be our own."""
879 """reset readline's completer to be our own."""
881 self.readline.set_completer(self.Completer.complete)
880 self.readline.set_completer(self.Completer.complete)
882
881
883 def _get_call_pdb(self):
882 def _get_call_pdb(self):
884 return self._call_pdb
883 return self._call_pdb
885
884
886 def _set_call_pdb(self,val):
885 def _set_call_pdb(self,val):
887
886
888 if val not in (0,1,False,True):
887 if val not in (0,1,False,True):
889 raise ValueError,'new call_pdb value must be boolean'
888 raise ValueError,'new call_pdb value must be boolean'
890
889
891 # store value in instance
890 # store value in instance
892 self._call_pdb = val
891 self._call_pdb = val
893
892
894 # notify the actual exception handlers
893 # notify the actual exception handlers
895 self.InteractiveTB.call_pdb = val
894 self.InteractiveTB.call_pdb = val
896 if self.isthreaded:
895 if self.isthreaded:
897 try:
896 try:
898 self.sys_excepthook.call_pdb = val
897 self.sys_excepthook.call_pdb = val
899 except:
898 except:
900 warn('Failed to activate pdb for threaded exception handler')
899 warn('Failed to activate pdb for threaded exception handler')
901
900
902 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
901 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
903 'Control auto-activation of pdb at exceptions')
902 'Control auto-activation of pdb at exceptions')
904
903
905
906 # These special functions get installed in the builtin namespace, to
904 # These special functions get installed in the builtin namespace, to
907 # provide programmatic (pure python) access to magics, aliases and system
905 # provide programmatic (pure python) access to magics, aliases and system
908 # calls. This is important for logging, user scripting, and more.
906 # calls. This is important for logging, user scripting, and more.
909
907
910 # We are basically exposing, via normal python functions, the three
908 # We are basically exposing, via normal python functions, the three
911 # mechanisms in which ipython offers special call modes (magics for
909 # mechanisms in which ipython offers special call modes (magics for
912 # internal control, aliases for direct system access via pre-selected
910 # internal control, aliases for direct system access via pre-selected
913 # names, and !cmd for calling arbitrary system commands).
911 # names, and !cmd for calling arbitrary system commands).
914
912
915 def ipmagic(self,arg_s):
913 def ipmagic(self,arg_s):
916 """Call a magic function by name.
914 """Call a magic function by name.
917
915
918 Input: a string containing the name of the magic function to call and any
916 Input: a string containing the name of the magic function to call and any
919 additional arguments to be passed to the magic.
917 additional arguments to be passed to the magic.
920
918
921 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
919 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
922 prompt:
920 prompt:
923
921
924 In[1]: %name -opt foo bar
922 In[1]: %name -opt foo bar
925
923
926 To call a magic without arguments, simply use ipmagic('name').
924 To call a magic without arguments, simply use ipmagic('name').
927
925
928 This provides a proper Python function to call IPython's magics in any
926 This provides a proper Python function to call IPython's magics in any
929 valid Python code you can type at the interpreter, including loops and
927 valid Python code you can type at the interpreter, including loops and
930 compound statements. It is added by IPython to the Python builtin
928 compound statements. It is added by IPython to the Python builtin
931 namespace upon initialization."""
929 namespace upon initialization."""
932
930
933 args = arg_s.split(' ',1)
931 args = arg_s.split(' ',1)
934 magic_name = args[0]
932 magic_name = args[0]
935 magic_name = magic_name.lstrip(self.ESC_MAGIC)
933 magic_name = magic_name.lstrip(self.ESC_MAGIC)
936
934
937 try:
935 try:
938 magic_args = args[1]
936 magic_args = args[1]
939 except IndexError:
937 except IndexError:
940 magic_args = ''
938 magic_args = ''
941 fn = getattr(self,'magic_'+magic_name,None)
939 fn = getattr(self,'magic_'+magic_name,None)
942 if fn is None:
940 if fn is None:
943 error("Magic function `%s` not found." % magic_name)
941 error("Magic function `%s` not found." % magic_name)
944 else:
942 else:
945 magic_args = self.var_expand(magic_args,1)
943 magic_args = self.var_expand(magic_args,1)
946 return fn(magic_args)
944 return fn(magic_args)
947
945
948 def ipalias(self,arg_s):
946 def ipalias(self,arg_s):
949 """Call an alias by name.
947 """Call an alias by name.
950
948
951 Input: a string containing the name of the alias to call and any
949 Input: a string containing the name of the alias to call and any
952 additional arguments to be passed to the magic.
950 additional arguments to be passed to the magic.
953
951
954 ipalias('name -opt foo bar') is equivalent to typing at the ipython
952 ipalias('name -opt foo bar') is equivalent to typing at the ipython
955 prompt:
953 prompt:
956
954
957 In[1]: name -opt foo bar
955 In[1]: name -opt foo bar
958
956
959 To call an alias without arguments, simply use ipalias('name').
957 To call an alias without arguments, simply use ipalias('name').
960
958
961 This provides a proper Python function to call IPython's aliases in any
959 This provides a proper Python function to call IPython's aliases in any
962 valid Python code you can type at the interpreter, including loops and
960 valid Python code you can type at the interpreter, including loops and
963 compound statements. It is added by IPython to the Python builtin
961 compound statements. It is added by IPython to the Python builtin
964 namespace upon initialization."""
962 namespace upon initialization."""
965
963
966 args = arg_s.split(' ',1)
964 args = arg_s.split(' ',1)
967 alias_name = args[0]
965 alias_name = args[0]
968 try:
966 try:
969 alias_args = args[1]
967 alias_args = args[1]
970 except IndexError:
968 except IndexError:
971 alias_args = ''
969 alias_args = ''
972 if alias_name in self.alias_table:
970 if alias_name in self.alias_table:
973 self.call_alias(alias_name,alias_args)
971 self.call_alias(alias_name,alias_args)
974 else:
972 else:
975 error("Alias `%s` not found." % alias_name)
973 error("Alias `%s` not found." % alias_name)
976
974
977 def ipsystem(self,arg_s):
975 def ipsystem(self,arg_s):
978 """Make a system call, using IPython."""
976 """Make a system call, using IPython."""
979
977
980 self.system(arg_s)
978 self.system(arg_s)
981
979
982 def complete(self,text):
980 def complete(self,text):
983 """Return a sorted list of all possible completions on text.
981 """Return a sorted list of all possible completions on text.
984
982
985 Inputs:
983 Inputs:
986
984
987 - text: a string of text to be completed on.
985 - text: a string of text to be completed on.
988
986
989 This is a wrapper around the completion mechanism, similar to what
987 This is a wrapper around the completion mechanism, similar to what
990 readline does at the command line when the TAB key is hit. By
988 readline does at the command line when the TAB key is hit. By
991 exposing it as a method, it can be used by other non-readline
989 exposing it as a method, it can be used by other non-readline
992 environments (such as GUIs) for text completion.
990 environments (such as GUIs) for text completion.
993
991
994 Simple usage example:
992 Simple usage example:
995
993
996 In [7]: x = 'hello'
994 In [7]: x = 'hello'
997
995
998 In [8]: x
996 In [8]: x
999 Out[8]: 'hello'
997 Out[8]: 'hello'
1000
998
1001 In [9]: print x
999 In [9]: print x
1002 hello
1000 hello
1003
1001
1004 In [10]: _ip.IP.complete('x.l')
1002 In [10]: _ip.IP.complete('x.l')
1005 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1003 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1006 """
1004 """
1007
1005
1008 complete = self.Completer.complete
1006 complete = self.Completer.complete
1009 state = 0
1007 state = 0
1010 # use a dict so we get unique keys, since ipyhton's multiple
1008 # use a dict so we get unique keys, since ipyhton's multiple
1011 # completers can return duplicates. When we make 2.4 a requirement,
1009 # completers can return duplicates. When we make 2.4 a requirement,
1012 # start using sets instead, which are faster.
1010 # start using sets instead, which are faster.
1013 comps = {}
1011 comps = {}
1014 while True:
1012 while True:
1015 newcomp = complete(text,state,line_buffer=text)
1013 newcomp = complete(text,state,line_buffer=text)
1016 if newcomp is None:
1014 if newcomp is None:
1017 break
1015 break
1018 comps[newcomp] = 1
1016 comps[newcomp] = 1
1019 state += 1
1017 state += 1
1020 outcomps = comps.keys()
1018 outcomps = comps.keys()
1021 outcomps.sort()
1019 outcomps.sort()
1022 #print "T:",text,"OC:",outcomps # dbg
1020 #print "T:",text,"OC:",outcomps # dbg
1023 #print "vars:",self.user_ns.keys()
1021 #print "vars:",self.user_ns.keys()
1024 return outcomps
1022 return outcomps
1025
1023
1026 def set_completer_frame(self, frame=None):
1024 def set_completer_frame(self, frame=None):
1027 if frame:
1025 if frame:
1028 self.Completer.namespace = frame.f_locals
1026 self.Completer.namespace = frame.f_locals
1029 self.Completer.global_namespace = frame.f_globals
1027 self.Completer.global_namespace = frame.f_globals
1030 else:
1028 else:
1031 self.Completer.namespace = self.user_ns
1029 self.Completer.namespace = self.user_ns
1032 self.Completer.global_namespace = self.user_global_ns
1030 self.Completer.global_namespace = self.user_global_ns
1033
1031
1034 def init_auto_alias(self):
1032 def init_auto_alias(self):
1035 """Define some aliases automatically.
1033 """Define some aliases automatically.
1036
1034
1037 These are ALL parameter-less aliases"""
1035 These are ALL parameter-less aliases"""
1038
1036
1039 for alias,cmd in self.auto_alias:
1037 for alias,cmd in self.auto_alias:
1040 self.getapi().defalias(alias,cmd)
1038 self.getapi().defalias(alias,cmd)
1041
1039
1042
1040
1043 def alias_table_validate(self,verbose=0):
1041 def alias_table_validate(self,verbose=0):
1044 """Update information about the alias table.
1042 """Update information about the alias table.
1045
1043
1046 In particular, make sure no Python keywords/builtins are in it."""
1044 In particular, make sure no Python keywords/builtins are in it."""
1047
1045
1048 no_alias = self.no_alias
1046 no_alias = self.no_alias
1049 for k in self.alias_table.keys():
1047 for k in self.alias_table.keys():
1050 if k in no_alias:
1048 if k in no_alias:
1051 del self.alias_table[k]
1049 del self.alias_table[k]
1052 if verbose:
1050 if verbose:
1053 print ("Deleting alias <%s>, it's a Python "
1051 print ("Deleting alias <%s>, it's a Python "
1054 "keyword or builtin." % k)
1052 "keyword or builtin." % k)
1055
1053
1056 def set_autoindent(self,value=None):
1054 def set_autoindent(self,value=None):
1057 """Set the autoindent flag, checking for readline support.
1055 """Set the autoindent flag, checking for readline support.
1058
1056
1059 If called with no arguments, it acts as a toggle."""
1057 If called with no arguments, it acts as a toggle."""
1060
1058
1061 if not self.has_readline:
1059 if not self.has_readline:
1062 if os.name == 'posix':
1060 if os.name == 'posix':
1063 warn("The auto-indent feature requires the readline library")
1061 warn("The auto-indent feature requires the readline library")
1064 self.autoindent = 0
1062 self.autoindent = 0
1065 return
1063 return
1066 if value is None:
1064 if value is None:
1067 self.autoindent = not self.autoindent
1065 self.autoindent = not self.autoindent
1068 else:
1066 else:
1069 self.autoindent = value
1067 self.autoindent = value
1070
1068
1071 def rc_set_toggle(self,rc_field,value=None):
1069 def rc_set_toggle(self,rc_field,value=None):
1072 """Set or toggle a field in IPython's rc config. structure.
1070 """Set or toggle a field in IPython's rc config. structure.
1073
1071
1074 If called with no arguments, it acts as a toggle.
1072 If called with no arguments, it acts as a toggle.
1075
1073
1076 If called with a non-existent field, the resulting AttributeError
1074 If called with a non-existent field, the resulting AttributeError
1077 exception will propagate out."""
1075 exception will propagate out."""
1078
1076
1079 rc_val = getattr(self.rc,rc_field)
1077 rc_val = getattr(self.rc,rc_field)
1080 if value is None:
1078 if value is None:
1081 value = not rc_val
1079 value = not rc_val
1082 setattr(self.rc,rc_field,value)
1080 setattr(self.rc,rc_field,value)
1083
1081
1084 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1082 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1085 """Install the user configuration directory.
1083 """Install the user configuration directory.
1086
1084
1087 Can be called when running for the first time or to upgrade the user's
1085 Can be called when running for the first time or to upgrade the user's
1088 .ipython/ directory with the mode parameter. Valid modes are 'install'
1086 .ipython/ directory with the mode parameter. Valid modes are 'install'
1089 and 'upgrade'."""
1087 and 'upgrade'."""
1090
1088
1091 def wait():
1089 def wait():
1092 try:
1090 try:
1093 raw_input("Please press <RETURN> to start IPython.")
1091 raw_input("Please press <RETURN> to start IPython.")
1094 except EOFError:
1092 except EOFError:
1095 print >> Term.cout
1093 print >> Term.cout
1096 print '*'*70
1094 print '*'*70
1097
1095
1098 cwd = os.getcwd() # remember where we started
1096 cwd = os.getcwd() # remember where we started
1099 glb = glob.glob
1097 glb = glob.glob
1100 print '*'*70
1098 print '*'*70
1101 if mode == 'install':
1099 if mode == 'install':
1102 print \
1100 print \
1103 """Welcome to IPython. I will try to create a personal configuration directory
1101 """Welcome to IPython. I will try to create a personal configuration directory
1104 where you can customize many aspects of IPython's functionality in:\n"""
1102 where you can customize many aspects of IPython's functionality in:\n"""
1105 else:
1103 else:
1106 print 'I am going to upgrade your configuration in:'
1104 print 'I am going to upgrade your configuration in:'
1107
1105
1108 print ipythondir
1106 print ipythondir
1109
1107
1110 rcdirend = os.path.join('IPython','UserConfig')
1108 rcdirend = os.path.join('IPython','UserConfig')
1111 cfg = lambda d: os.path.join(d,rcdirend)
1109 cfg = lambda d: os.path.join(d,rcdirend)
1112 try:
1110 try:
1113 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1111 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1114 print "Initializing from configuration",rcdir
1112 print "Initializing from configuration",rcdir
1115 except IndexError:
1113 except IndexError:
1116 warning = """
1114 warning = """
1117 Installation error. IPython's directory was not found.
1115 Installation error. IPython's directory was not found.
1118
1116
1119 Check the following:
1117 Check the following:
1120
1118
1121 The ipython/IPython directory should be in a directory belonging to your
1119 The ipython/IPython directory should be in a directory belonging to your
1122 PYTHONPATH environment variable (that is, it should be in a directory
1120 PYTHONPATH environment variable (that is, it should be in a directory
1123 belonging to sys.path). You can copy it explicitly there or just link to it.
1121 belonging to sys.path). You can copy it explicitly there or just link to it.
1124
1122
1125 IPython will create a minimal default configuration for you.
1123 IPython will create a minimal default configuration for you.
1126
1124
1127 """
1125 """
1128 warn(warning)
1126 warn(warning)
1129 wait()
1127 wait()
1130
1128
1131 if sys.platform =='win32':
1129 if sys.platform =='win32':
1132 inif = 'ipythonrc.ini'
1130 inif = 'ipythonrc.ini'
1133 else:
1131 else:
1134 inif = 'ipythonrc'
1132 inif = 'ipythonrc'
1135 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1133 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
1134 inif : '# intentionally left blank' }
1136 os.makedirs(ipythondir, mode = 0777)
1135 os.makedirs(ipythondir, mode = 0777)
1137 for f, cont in minimal_setup.items():
1136 for f, cont in minimal_setup.items():
1138 open(ipythondir + '/' + f,'w').write(cont)
1137 open(ipythondir + '/' + f,'w').write(cont)
1139
1138
1140 return
1139 return
1141
1140
1142 if mode == 'install':
1141 if mode == 'install':
1143 try:
1142 try:
1144 shutil.copytree(rcdir,ipythondir)
1143 shutil.copytree(rcdir,ipythondir)
1145 os.chdir(ipythondir)
1144 os.chdir(ipythondir)
1146 rc_files = glb("ipythonrc*")
1145 rc_files = glb("ipythonrc*")
1147 for rc_file in rc_files:
1146 for rc_file in rc_files:
1148 os.rename(rc_file,rc_file+rc_suffix)
1147 os.rename(rc_file,rc_file+rc_suffix)
1149 except:
1148 except:
1150 warning = """
1149 warning = """
1151
1150
1152 There was a problem with the installation:
1151 There was a problem with the installation:
1153 %s
1152 %s
1154 Try to correct it or contact the developers if you think it's a bug.
1153 Try to correct it or contact the developers if you think it's a bug.
1155 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1154 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1156 warn(warning)
1155 warn(warning)
1157 wait()
1156 wait()
1158 return
1157 return
1159
1158
1160 elif mode == 'upgrade':
1159 elif mode == 'upgrade':
1161 try:
1160 try:
1162 os.chdir(ipythondir)
1161 os.chdir(ipythondir)
1163 except:
1162 except:
1164 print """
1163 print """
1165 Can not upgrade: changing to directory %s failed. Details:
1164 Can not upgrade: changing to directory %s failed. Details:
1166 %s
1165 %s
1167 """ % (ipythondir,sys.exc_info()[1])
1166 """ % (ipythondir,sys.exc_info()[1])
1168 wait()
1167 wait()
1169 return
1168 return
1170 else:
1169 else:
1171 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1170 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1172 for new_full_path in sources:
1171 for new_full_path in sources:
1173 new_filename = os.path.basename(new_full_path)
1172 new_filename = os.path.basename(new_full_path)
1174 if new_filename.startswith('ipythonrc'):
1173 if new_filename.startswith('ipythonrc'):
1175 new_filename = new_filename + rc_suffix
1174 new_filename = new_filename + rc_suffix
1176 # The config directory should only contain files, skip any
1175 # The config directory should only contain files, skip any
1177 # directories which may be there (like CVS)
1176 # directories which may be there (like CVS)
1178 if os.path.isdir(new_full_path):
1177 if os.path.isdir(new_full_path):
1179 continue
1178 continue
1180 if os.path.exists(new_filename):
1179 if os.path.exists(new_filename):
1181 old_file = new_filename+'.old'
1180 old_file = new_filename+'.old'
1182 if os.path.exists(old_file):
1181 if os.path.exists(old_file):
1183 os.remove(old_file)
1182 os.remove(old_file)
1184 os.rename(new_filename,old_file)
1183 os.rename(new_filename,old_file)
1185 shutil.copy(new_full_path,new_filename)
1184 shutil.copy(new_full_path,new_filename)
1186 else:
1185 else:
1187 raise ValueError,'unrecognized mode for install:',`mode`
1186 raise ValueError,'unrecognized mode for install:',`mode`
1188
1187
1189 # Fix line-endings to those native to each platform in the config
1188 # Fix line-endings to those native to each platform in the config
1190 # directory.
1189 # directory.
1191 try:
1190 try:
1192 os.chdir(ipythondir)
1191 os.chdir(ipythondir)
1193 except:
1192 except:
1194 print """
1193 print """
1195 Problem: changing to directory %s failed.
1194 Problem: changing to directory %s failed.
1196 Details:
1195 Details:
1197 %s
1196 %s
1198
1197
1199 Some configuration files may have incorrect line endings. This should not
1198 Some configuration files may have incorrect line endings. This should not
1200 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1199 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1201 wait()
1200 wait()
1202 else:
1201 else:
1203 for fname in glb('ipythonrc*'):
1202 for fname in glb('ipythonrc*'):
1204 try:
1203 try:
1205 native_line_ends(fname,backup=0)
1204 native_line_ends(fname,backup=0)
1206 except IOError:
1205 except IOError:
1207 pass
1206 pass
1208
1207
1209 if mode == 'install':
1208 if mode == 'install':
1210 print """
1209 print """
1211 Successful installation!
1210 Successful installation!
1212
1211
1213 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1212 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1214 IPython manual (there are both HTML and PDF versions supplied with the
1213 IPython manual (there are both HTML and PDF versions supplied with the
1215 distribution) to make sure that your system environment is properly configured
1214 distribution) to make sure that your system environment is properly configured
1216 to take advantage of IPython's features.
1215 to take advantage of IPython's features.
1217
1216
1218 Important note: the configuration system has changed! The old system is
1217 Important note: the configuration system has changed! The old system is
1219 still in place, but its setting may be partly overridden by the settings in
1218 still in place, but its setting may be partly overridden by the settings in
1220 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1219 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1221 if some of the new settings bother you.
1220 if some of the new settings bother you.
1222
1221
1223 """
1222 """
1224 else:
1223 else:
1225 print """
1224 print """
1226 Successful upgrade!
1225 Successful upgrade!
1227
1226
1228 All files in your directory:
1227 All files in your directory:
1229 %(ipythondir)s
1228 %(ipythondir)s
1230 which would have been overwritten by the upgrade were backed up with a .old
1229 which would have been overwritten by the upgrade were backed up with a .old
1231 extension. If you had made particular customizations in those files you may
1230 extension. If you had made particular customizations in those files you may
1232 want to merge them back into the new files.""" % locals()
1231 want to merge them back into the new files.""" % locals()
1233 wait()
1232 wait()
1234 os.chdir(cwd)
1233 os.chdir(cwd)
1235 # end user_setup()
1234 # end user_setup()
1236
1235
1237 def atexit_operations(self):
1236 def atexit_operations(self):
1238 """This will be executed at the time of exit.
1237 """This will be executed at the time of exit.
1239
1238
1240 Saving of persistent data should be performed here. """
1239 Saving of persistent data should be performed here. """
1241
1240
1242 #print '*** IPython exit cleanup ***' # dbg
1241 #print '*** IPython exit cleanup ***' # dbg
1243 # input history
1242 # input history
1244 self.savehist()
1243 self.savehist()
1245
1244
1246 # Cleanup all tempfiles left around
1245 # Cleanup all tempfiles left around
1247 for tfile in self.tempfiles:
1246 for tfile in self.tempfiles:
1248 try:
1247 try:
1249 os.unlink(tfile)
1248 os.unlink(tfile)
1250 except OSError:
1249 except OSError:
1251 pass
1250 pass
1252
1251
1253 self.hooks.shutdown_hook()
1252 self.hooks.shutdown_hook()
1254
1253
1255 def savehist(self):
1254 def savehist(self):
1256 """Save input history to a file (via readline library)."""
1255 """Save input history to a file (via readline library)."""
1257
1256
1258 if not self.has_readline:
1257 if not self.has_readline:
1259 return
1258 return
1260
1259
1261 try:
1260 try:
1262 self.readline.write_history_file(self.histfile)
1261 self.readline.write_history_file(self.histfile)
1263 except:
1262 except:
1264 print 'Unable to save IPython command history to file: ' + \
1263 print 'Unable to save IPython command history to file: ' + \
1265 `self.histfile`
1264 `self.histfile`
1266
1265
1267 def reloadhist(self):
1266 def reloadhist(self):
1268 """Reload the input history from disk file."""
1267 """Reload the input history from disk file."""
1269
1268
1270 if self.has_readline:
1269 if self.has_readline:
1271 try:
1270 try:
1272 self.readline.clear_history()
1271 self.readline.clear_history()
1273 self.readline.read_history_file(self.shell.histfile)
1272 self.readline.read_history_file(self.shell.histfile)
1274 except AttributeError:
1273 except AttributeError:
1275 pass
1274 pass
1276
1275
1277
1276
1278 def history_saving_wrapper(self, func):
1277 def history_saving_wrapper(self, func):
1279 """ Wrap func for readline history saving
1278 """ Wrap func for readline history saving
1280
1279
1281 Convert func into callable that saves & restores
1280 Convert func into callable that saves & restores
1282 history around the call """
1281 history around the call """
1283
1282
1284 if not self.has_readline:
1283 if not self.has_readline:
1285 return func
1284 return func
1286
1285
1287 def wrapper():
1286 def wrapper():
1288 self.savehist()
1287 self.savehist()
1289 try:
1288 try:
1290 func()
1289 func()
1291 finally:
1290 finally:
1292 readline.read_history_file(self.histfile)
1291 readline.read_history_file(self.histfile)
1293 return wrapper
1292 return wrapper
1294
1295
1293
1296 def pre_readline(self):
1294 def pre_readline(self):
1297 """readline hook to be used at the start of each line.
1295 """readline hook to be used at the start of each line.
1298
1296
1299 Currently it handles auto-indent only."""
1297 Currently it handles auto-indent only."""
1300
1298
1301 #debugx('self.indent_current_nsp','pre_readline:')
1299 #debugx('self.indent_current_nsp','pre_readline:')
1302
1300
1303 if self.rl_do_indent:
1301 if self.rl_do_indent:
1304 self.readline.insert_text(self.indent_current_str())
1302 self.readline.insert_text(self.indent_current_str())
1305 if self.rl_next_input is not None:
1303 if self.rl_next_input is not None:
1306 self.readline.insert_text(self.rl_next_input)
1304 self.readline.insert_text(self.rl_next_input)
1307 self.rl_next_input = None
1305 self.rl_next_input = None
1308
1306
1309 def init_readline(self):
1307 def init_readline(self):
1310 """Command history completion/saving/reloading."""
1308 """Command history completion/saving/reloading."""
1311
1309
1312
1310
1313 import IPython.rlineimpl as readline
1311 import IPython.rlineimpl as readline
1314
1312
1315 if not readline.have_readline:
1313 if not readline.have_readline:
1316 self.has_readline = 0
1314 self.has_readline = 0
1317 self.readline = None
1315 self.readline = None
1318 # no point in bugging windows users with this every time:
1316 # no point in bugging windows users with this every time:
1319 warn('Readline services not available on this platform.')
1317 warn('Readline services not available on this platform.')
1320 else:
1318 else:
1321 sys.modules['readline'] = readline
1319 sys.modules['readline'] = readline
1322 import atexit
1320 import atexit
1323 from IPython.completer import IPCompleter
1321 from IPython.completer import IPCompleter
1324 self.Completer = IPCompleter(self,
1322 self.Completer = IPCompleter(self,
1325 self.user_ns,
1323 self.user_ns,
1326 self.user_global_ns,
1324 self.user_global_ns,
1327 self.rc.readline_omit__names,
1325 self.rc.readline_omit__names,
1328 self.alias_table)
1326 self.alias_table)
1329 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1327 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1330 self.strdispatchers['complete_command'] = sdisp
1328 self.strdispatchers['complete_command'] = sdisp
1331 self.Completer.custom_completers = sdisp
1329 self.Completer.custom_completers = sdisp
1332 # Platform-specific configuration
1330 # Platform-specific configuration
1333 if os.name == 'nt':
1331 if os.name == 'nt':
1334 self.readline_startup_hook = readline.set_pre_input_hook
1332 self.readline_startup_hook = readline.set_pre_input_hook
1335 else:
1333 else:
1336 self.readline_startup_hook = readline.set_startup_hook
1334 self.readline_startup_hook = readline.set_startup_hook
1337
1335
1338 # Load user's initrc file (readline config)
1336 # Load user's initrc file (readline config)
1339 # Or if libedit is used, load editrc.
1337 # Or if libedit is used, load editrc.
1340 inputrc_name = os.environ.get('INPUTRC')
1338 inputrc_name = os.environ.get('INPUTRC')
1341 if inputrc_name is None:
1339 if inputrc_name is None:
1342 home_dir = get_home_dir()
1340 home_dir = get_home_dir()
1343 if home_dir is not None:
1341 if home_dir is not None:
1344 inputrc_name = '.inputrc'
1342 inputrc_name = '.inputrc'
1345 if readline.uses_libedit:
1343 if readline.uses_libedit:
1346 inputrc_name = '.editrc'
1344 inputrc_name = '.editrc'
1347 inputrc_name = os.path.join(home_dir, inputrc_name)
1345 inputrc_name = os.path.join(home_dir, inputrc_name)
1348 if os.path.isfile(inputrc_name):
1346 if os.path.isfile(inputrc_name):
1349 try:
1347 try:
1350 readline.read_init_file(inputrc_name)
1348 readline.read_init_file(inputrc_name)
1351 except:
1349 except:
1352 warn('Problems reading readline initialization file <%s>'
1350 warn('Problems reading readline initialization file <%s>'
1353 % inputrc_name)
1351 % inputrc_name)
1354
1352
1355 self.has_readline = 1
1353 self.has_readline = 1
1356 self.readline = readline
1354 self.readline = readline
1357 # save this in sys so embedded copies can restore it properly
1355 # save this in sys so embedded copies can restore it properly
1358 sys.ipcompleter = self.Completer.complete
1356 sys.ipcompleter = self.Completer.complete
1359 self.set_completer()
1357 self.set_completer()
1360
1358
1361 # Configure readline according to user's prefs
1359 # Configure readline according to user's prefs
1362 # This is only done if GNU readline is being used. If libedit
1360 # This is only done if GNU readline is being used. If libedit
1363 # is being used (as on Leopard) the readline config is
1361 # is being used (as on Leopard) the readline config is
1364 # not run as the syntax for libedit is different.
1362 # not run as the syntax for libedit is different.
1365 if not readline.uses_libedit:
1363 if not readline.uses_libedit:
1366 for rlcommand in self.rc.readline_parse_and_bind:
1364 for rlcommand in self.rc.readline_parse_and_bind:
1367 readline.parse_and_bind(rlcommand)
1365 readline.parse_and_bind(rlcommand)
1368
1366
1369 # remove some chars from the delimiters list
1367 # remove some chars from the delimiters list
1370 delims = readline.get_completer_delims()
1368 delims = readline.get_completer_delims()
1371 delims = delims.translate(string._idmap,
1369 delims = delims.translate(string._idmap,
1372 self.rc.readline_remove_delims)
1370 self.rc.readline_remove_delims)
1373 readline.set_completer_delims(delims)
1371 readline.set_completer_delims(delims)
1374 # otherwise we end up with a monster history after a while:
1372 # otherwise we end up with a monster history after a while:
1375 readline.set_history_length(1000)
1373 readline.set_history_length(1000)
1376 try:
1374 try:
1377 #print '*** Reading readline history' # dbg
1375 #print '*** Reading readline history' # dbg
1378 readline.read_history_file(self.histfile)
1376 readline.read_history_file(self.histfile)
1379 except IOError:
1377 except IOError:
1380 pass # It doesn't exist yet.
1378 pass # It doesn't exist yet.
1381
1379
1382 atexit.register(self.atexit_operations)
1380 atexit.register(self.atexit_operations)
1383 del atexit
1381 del atexit
1384
1382
1385 # Configure auto-indent for all platforms
1383 # Configure auto-indent for all platforms
1386 self.set_autoindent(self.rc.autoindent)
1384 self.set_autoindent(self.rc.autoindent)
1387
1385
1388 def ask_yes_no(self,prompt,default=True):
1386 def ask_yes_no(self,prompt,default=True):
1389 if self.rc.quiet:
1387 if self.rc.quiet:
1390 return True
1388 return True
1391 return ask_yes_no(prompt,default)
1389 return ask_yes_no(prompt,default)
1392
1390
1391 def cache_main_mod(self,mod):
1392 """Cache a main module.
1393
1394 When scripts are executed via %run, we must keep a reference to their
1395 __main__ module (a FakeModule instance) around so that Python doesn't
1396 clear it, rendering objects defined therein useless.
1397
1398 This method keeps said reference in a private dict, keyed by the
1399 absolute path of the module object (which corresponds to the script
1400 path). This way, for multiple executions of the same script we only
1401 keep one copy of __main__ (the last one), thus preventing memory leaks
1402 from old references while allowing the objects from the last execution
1403 to be accessible.
1404
1405 Parameters
1406 ----------
1407 mod : a module object
1408
1409 Examples
1410 --------
1411
1412 In [10]: import IPython
1413
1414 In [11]: _ip.IP.cache_main_mod(IPython)
1415
1416 In [12]: IPython.__file__ in _ip.IP._user_main_modules
1417 Out[12]: True
1418 """
1419 self._user_main_modules[os.path.abspath(mod.__file__) ] = mod
1420
1421 def clear_main_mod_cache(self):
1422 """Clear the cache of main modules.
1423
1424 Mainly for use by utilities like %reset.
1425
1426 Examples
1427 --------
1428
1429 In [15]: import IPython
1430
1431 In [16]: _ip.IP.cache_main_mod(IPython)
1432
1433 In [17]: len(_ip.IP._user_main_modules) > 0
1434 Out[17]: True
1435
1436 In [18]: _ip.IP.clear_main_mod_cache()
1437
1438 In [19]: len(_ip.IP._user_main_modules) == 0
1439 Out[19]: True
1440 """
1441 self._user_main_modules.clear()
1442
1393 def _should_recompile(self,e):
1443 def _should_recompile(self,e):
1394 """Utility routine for edit_syntax_error"""
1444 """Utility routine for edit_syntax_error"""
1395
1445
1396 if e.filename in ('<ipython console>','<input>','<string>',
1446 if e.filename in ('<ipython console>','<input>','<string>',
1397 '<console>','<BackgroundJob compilation>',
1447 '<console>','<BackgroundJob compilation>',
1398 None):
1448 None):
1399
1449
1400 return False
1450 return False
1401 try:
1451 try:
1402 if (self.rc.autoedit_syntax and
1452 if (self.rc.autoedit_syntax and
1403 not self.ask_yes_no('Return to editor to correct syntax error? '
1453 not self.ask_yes_no('Return to editor to correct syntax error? '
1404 '[Y/n] ','y')):
1454 '[Y/n] ','y')):
1405 return False
1455 return False
1406 except EOFError:
1456 except EOFError:
1407 return False
1457 return False
1408
1458
1409 def int0(x):
1459 def int0(x):
1410 try:
1460 try:
1411 return int(x)
1461 return int(x)
1412 except TypeError:
1462 except TypeError:
1413 return 0
1463 return 0
1414 # always pass integer line and offset values to editor hook
1464 # always pass integer line and offset values to editor hook
1415 self.hooks.fix_error_editor(e.filename,
1465 self.hooks.fix_error_editor(e.filename,
1416 int0(e.lineno),int0(e.offset),e.msg)
1466 int0(e.lineno),int0(e.offset),e.msg)
1417 return True
1467 return True
1418
1468
1419 def edit_syntax_error(self):
1469 def edit_syntax_error(self):
1420 """The bottom half of the syntax error handler called in the main loop.
1470 """The bottom half of the syntax error handler called in the main loop.
1421
1471
1422 Loop until syntax error is fixed or user cancels.
1472 Loop until syntax error is fixed or user cancels.
1423 """
1473 """
1424
1474
1425 while self.SyntaxTB.last_syntax_error:
1475 while self.SyntaxTB.last_syntax_error:
1426 # copy and clear last_syntax_error
1476 # copy and clear last_syntax_error
1427 err = self.SyntaxTB.clear_err_state()
1477 err = self.SyntaxTB.clear_err_state()
1428 if not self._should_recompile(err):
1478 if not self._should_recompile(err):
1429 return
1479 return
1430 try:
1480 try:
1431 # may set last_syntax_error again if a SyntaxError is raised
1481 # may set last_syntax_error again if a SyntaxError is raised
1432 self.safe_execfile(err.filename,self.user_ns)
1482 self.safe_execfile(err.filename,self.user_ns)
1433 except:
1483 except:
1434 self.showtraceback()
1484 self.showtraceback()
1435 else:
1485 else:
1436 try:
1486 try:
1437 f = file(err.filename)
1487 f = file(err.filename)
1438 try:
1488 try:
1439 sys.displayhook(f.read())
1489 sys.displayhook(f.read())
1440 finally:
1490 finally:
1441 f.close()
1491 f.close()
1442 except:
1492 except:
1443 self.showtraceback()
1493 self.showtraceback()
1444
1494
1445 def showsyntaxerror(self, filename=None):
1495 def showsyntaxerror(self, filename=None):
1446 """Display the syntax error that just occurred.
1496 """Display the syntax error that just occurred.
1447
1497
1448 This doesn't display a stack trace because there isn't one.
1498 This doesn't display a stack trace because there isn't one.
1449
1499
1450 If a filename is given, it is stuffed in the exception instead
1500 If a filename is given, it is stuffed in the exception instead
1451 of what was there before (because Python's parser always uses
1501 of what was there before (because Python's parser always uses
1452 "<string>" when reading from a string).
1502 "<string>" when reading from a string).
1453 """
1503 """
1454 etype, value, last_traceback = sys.exc_info()
1504 etype, value, last_traceback = sys.exc_info()
1455
1505
1456 # See note about these variables in showtraceback() below
1506 # See note about these variables in showtraceback() below
1457 sys.last_type = etype
1507 sys.last_type = etype
1458 sys.last_value = value
1508 sys.last_value = value
1459 sys.last_traceback = last_traceback
1509 sys.last_traceback = last_traceback
1460
1510
1461 if filename and etype is SyntaxError:
1511 if filename and etype is SyntaxError:
1462 # Work hard to stuff the correct filename in the exception
1512 # Work hard to stuff the correct filename in the exception
1463 try:
1513 try:
1464 msg, (dummy_filename, lineno, offset, line) = value
1514 msg, (dummy_filename, lineno, offset, line) = value
1465 except:
1515 except:
1466 # Not the format we expect; leave it alone
1516 # Not the format we expect; leave it alone
1467 pass
1517 pass
1468 else:
1518 else:
1469 # Stuff in the right filename
1519 # Stuff in the right filename
1470 try:
1520 try:
1471 # Assume SyntaxError is a class exception
1521 # Assume SyntaxError is a class exception
1472 value = SyntaxError(msg, (filename, lineno, offset, line))
1522 value = SyntaxError(msg, (filename, lineno, offset, line))
1473 except:
1523 except:
1474 # If that failed, assume SyntaxError is a string
1524 # If that failed, assume SyntaxError is a string
1475 value = msg, (filename, lineno, offset, line)
1525 value = msg, (filename, lineno, offset, line)
1476 self.SyntaxTB(etype,value,[])
1526 self.SyntaxTB(etype,value,[])
1477
1527
1478 def debugger(self,force=False):
1528 def debugger(self,force=False):
1479 """Call the pydb/pdb debugger.
1529 """Call the pydb/pdb debugger.
1480
1530
1481 Keywords:
1531 Keywords:
1482
1532
1483 - force(False): by default, this routine checks the instance call_pdb
1533 - force(False): by default, this routine checks the instance call_pdb
1484 flag and does not actually invoke the debugger if the flag is false.
1534 flag and does not actually invoke the debugger if the flag is false.
1485 The 'force' option forces the debugger to activate even if the flag
1535 The 'force' option forces the debugger to activate even if the flag
1486 is false.
1536 is false.
1487 """
1537 """
1488
1538
1489 if not (force or self.call_pdb):
1539 if not (force or self.call_pdb):
1490 return
1540 return
1491
1541
1492 if not hasattr(sys,'last_traceback'):
1542 if not hasattr(sys,'last_traceback'):
1493 error('No traceback has been produced, nothing to debug.')
1543 error('No traceback has been produced, nothing to debug.')
1494 return
1544 return
1495
1545
1496 # use pydb if available
1546 # use pydb if available
1497 if Debugger.has_pydb:
1547 if Debugger.has_pydb:
1498 from pydb import pm
1548 from pydb import pm
1499 else:
1549 else:
1500 # fallback to our internal debugger
1550 # fallback to our internal debugger
1501 pm = lambda : self.InteractiveTB.debugger(force=True)
1551 pm = lambda : self.InteractiveTB.debugger(force=True)
1502 self.history_saving_wrapper(pm)()
1552 self.history_saving_wrapper(pm)()
1503
1553
1504 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1554 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1505 """Display the exception that just occurred.
1555 """Display the exception that just occurred.
1506
1556
1507 If nothing is known about the exception, this is the method which
1557 If nothing is known about the exception, this is the method which
1508 should be used throughout the code for presenting user tracebacks,
1558 should be used throughout the code for presenting user tracebacks,
1509 rather than directly invoking the InteractiveTB object.
1559 rather than directly invoking the InteractiveTB object.
1510
1560
1511 A specific showsyntaxerror() also exists, but this method can take
1561 A specific showsyntaxerror() also exists, but this method can take
1512 care of calling it if needed, so unless you are explicitly catching a
1562 care of calling it if needed, so unless you are explicitly catching a
1513 SyntaxError exception, don't try to analyze the stack manually and
1563 SyntaxError exception, don't try to analyze the stack manually and
1514 simply call this method."""
1564 simply call this method."""
1515
1565
1516
1566
1517 # Though this won't be called by syntax errors in the input line,
1567 # Though this won't be called by syntax errors in the input line,
1518 # there may be SyntaxError cases whith imported code.
1568 # there may be SyntaxError cases whith imported code.
1519
1569
1520 try:
1570 try:
1521 if exc_tuple is None:
1571 if exc_tuple is None:
1522 etype, value, tb = sys.exc_info()
1572 etype, value, tb = sys.exc_info()
1523 else:
1573 else:
1524 etype, value, tb = exc_tuple
1574 etype, value, tb = exc_tuple
1525
1575
1526 if etype is SyntaxError:
1576 if etype is SyntaxError:
1527 self.showsyntaxerror(filename)
1577 self.showsyntaxerror(filename)
1528 elif etype is IPython.ipapi.UsageError:
1578 elif etype is IPython.ipapi.UsageError:
1529 print "UsageError:", value
1579 print "UsageError:", value
1530 else:
1580 else:
1531 # WARNING: these variables are somewhat deprecated and not
1581 # WARNING: these variables are somewhat deprecated and not
1532 # necessarily safe to use in a threaded environment, but tools
1582 # necessarily safe to use in a threaded environment, but tools
1533 # like pdb depend on their existence, so let's set them. If we
1583 # like pdb depend on their existence, so let's set them. If we
1534 # find problems in the field, we'll need to revisit their use.
1584 # find problems in the field, we'll need to revisit their use.
1535 sys.last_type = etype
1585 sys.last_type = etype
1536 sys.last_value = value
1586 sys.last_value = value
1537 sys.last_traceback = tb
1587 sys.last_traceback = tb
1538
1588
1539 if etype in self.custom_exceptions:
1589 if etype in self.custom_exceptions:
1540 self.CustomTB(etype,value,tb)
1590 self.CustomTB(etype,value,tb)
1541 else:
1591 else:
1542 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1592 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1543 if self.InteractiveTB.call_pdb and self.has_readline:
1593 if self.InteractiveTB.call_pdb and self.has_readline:
1544 # pdb mucks up readline, fix it back
1594 # pdb mucks up readline, fix it back
1545 self.set_completer()
1595 self.set_completer()
1546 except KeyboardInterrupt:
1596 except KeyboardInterrupt:
1547 self.write("\nKeyboardInterrupt\n")
1597 self.write("\nKeyboardInterrupt\n")
1548
1549
1550
1598
1551 def mainloop(self,banner=None):
1599 def mainloop(self,banner=None):
1552 """Creates the local namespace and starts the mainloop.
1600 """Creates the local namespace and starts the mainloop.
1553
1601
1554 If an optional banner argument is given, it will override the
1602 If an optional banner argument is given, it will override the
1555 internally created default banner."""
1603 internally created default banner."""
1556
1604
1557 if self.rc.c: # Emulate Python's -c option
1605 if self.rc.c: # Emulate Python's -c option
1558 self.exec_init_cmd()
1606 self.exec_init_cmd()
1559 if banner is None:
1607 if banner is None:
1560 if not self.rc.banner:
1608 if not self.rc.banner:
1561 banner = ''
1609 banner = ''
1562 # banner is string? Use it directly!
1610 # banner is string? Use it directly!
1563 elif isinstance(self.rc.banner,basestring):
1611 elif isinstance(self.rc.banner,basestring):
1564 banner = self.rc.banner
1612 banner = self.rc.banner
1565 else:
1613 else:
1566 banner = self.BANNER+self.banner2
1614 banner = self.BANNER+self.banner2
1567
1615
1568 while 1:
1616 while 1:
1569 try:
1617 try:
1570 self.interact(banner)
1618 self.interact(banner)
1571 #self.interact_with_readline()
1619 #self.interact_with_readline()
1572 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1620
1621 # XXX for testing of a readline-decoupled repl loop, call
1622 # interact_with_readline above
1573
1623
1574 break
1624 break
1575 except KeyboardInterrupt:
1625 except KeyboardInterrupt:
1576 # this should not be necessary, but KeyboardInterrupt
1626 # this should not be necessary, but KeyboardInterrupt
1577 # handling seems rather unpredictable...
1627 # handling seems rather unpredictable...
1578 self.write("\nKeyboardInterrupt in interact()\n")
1628 self.write("\nKeyboardInterrupt in interact()\n")
1579
1629
1580 def exec_init_cmd(self):
1630 def exec_init_cmd(self):
1581 """Execute a command given at the command line.
1631 """Execute a command given at the command line.
1582
1632
1583 This emulates Python's -c option."""
1633 This emulates Python's -c option."""
1584
1634
1585 #sys.argv = ['-c']
1635 #sys.argv = ['-c']
1586 self.push(self.prefilter(self.rc.c, False))
1636 self.push(self.prefilter(self.rc.c, False))
1587 if not self.rc.interact:
1637 if not self.rc.interact:
1588 self.ask_exit()
1638 self.ask_exit()
1589
1639
1590 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1640 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1591 """Embeds IPython into a running python program.
1641 """Embeds IPython into a running python program.
1592
1642
1593 Input:
1643 Input:
1594
1644
1595 - header: An optional header message can be specified.
1645 - header: An optional header message can be specified.
1596
1646
1597 - local_ns, global_ns: working namespaces. If given as None, the
1647 - local_ns, global_ns: working namespaces. If given as None, the
1598 IPython-initialized one is updated with __main__.__dict__, so that
1648 IPython-initialized one is updated with __main__.__dict__, so that
1599 program variables become visible but user-specific configuration
1649 program variables become visible but user-specific configuration
1600 remains possible.
1650 remains possible.
1601
1651
1602 - stack_depth: specifies how many levels in the stack to go to
1652 - stack_depth: specifies how many levels in the stack to go to
1603 looking for namespaces (when local_ns and global_ns are None). This
1653 looking for namespaces (when local_ns and global_ns are None). This
1604 allows an intermediate caller to make sure that this function gets
1654 allows an intermediate caller to make sure that this function gets
1605 the namespace from the intended level in the stack. By default (0)
1655 the namespace from the intended level in the stack. By default (0)
1606 it will get its locals and globals from the immediate caller.
1656 it will get its locals and globals from the immediate caller.
1607
1657
1608 Warning: it's possible to use this in a program which is being run by
1658 Warning: it's possible to use this in a program which is being run by
1609 IPython itself (via %run), but some funny things will happen (a few
1659 IPython itself (via %run), but some funny things will happen (a few
1610 globals get overwritten). In the future this will be cleaned up, as
1660 globals get overwritten). In the future this will be cleaned up, as
1611 there is no fundamental reason why it can't work perfectly."""
1661 there is no fundamental reason why it can't work perfectly."""
1612
1662
1613 # Get locals and globals from caller
1663 # Get locals and globals from caller
1614 if local_ns is None or global_ns is None:
1664 if local_ns is None or global_ns is None:
1615 call_frame = sys._getframe(stack_depth).f_back
1665 call_frame = sys._getframe(stack_depth).f_back
1616
1666
1617 if local_ns is None:
1667 if local_ns is None:
1618 local_ns = call_frame.f_locals
1668 local_ns = call_frame.f_locals
1619 if global_ns is None:
1669 if global_ns is None:
1620 global_ns = call_frame.f_globals
1670 global_ns = call_frame.f_globals
1621
1671
1622 # Update namespaces and fire up interpreter
1672 # Update namespaces and fire up interpreter
1623
1673
1624 # The global one is easy, we can just throw it in
1674 # The global one is easy, we can just throw it in
1625 self.user_global_ns = global_ns
1675 self.user_global_ns = global_ns
1626
1676
1627 # but the user/local one is tricky: ipython needs it to store internal
1677 # but the user/local one is tricky: ipython needs it to store internal
1628 # data, but we also need the locals. We'll copy locals in the user
1678 # data, but we also need the locals. We'll copy locals in the user
1629 # one, but will track what got copied so we can delete them at exit.
1679 # one, but will track what got copied so we can delete them at exit.
1630 # This is so that a later embedded call doesn't see locals from a
1680 # This is so that a later embedded call doesn't see locals from a
1631 # previous call (which most likely existed in a separate scope).
1681 # previous call (which most likely existed in a separate scope).
1632 local_varnames = local_ns.keys()
1682 local_varnames = local_ns.keys()
1633 self.user_ns.update(local_ns)
1683 self.user_ns.update(local_ns)
1634 #self.user_ns['local_ns'] = local_ns # dbg
1684 #self.user_ns['local_ns'] = local_ns # dbg
1635
1685
1636 # Patch for global embedding to make sure that things don't overwrite
1686 # Patch for global embedding to make sure that things don't overwrite
1637 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1687 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1638 # FIXME. Test this a bit more carefully (the if.. is new)
1688 # FIXME. Test this a bit more carefully (the if.. is new)
1639 if local_ns is None and global_ns is None:
1689 if local_ns is None and global_ns is None:
1640 self.user_global_ns.update(__main__.__dict__)
1690 self.user_global_ns.update(__main__.__dict__)
1641
1691
1642 # make sure the tab-completer has the correct frame information, so it
1692 # make sure the tab-completer has the correct frame information, so it
1643 # actually completes using the frame's locals/globals
1693 # actually completes using the frame's locals/globals
1644 self.set_completer_frame()
1694 self.set_completer_frame()
1645
1695
1646 # before activating the interactive mode, we need to make sure that
1696 # before activating the interactive mode, we need to make sure that
1647 # all names in the builtin namespace needed by ipython point to
1697 # all names in the builtin namespace needed by ipython point to
1648 # ourselves, and not to other instances.
1698 # ourselves, and not to other instances.
1649 self.add_builtins()
1699 self.add_builtins()
1650
1700
1651 self.interact(header)
1701 self.interact(header)
1652
1702
1653 # now, purge out the user namespace from anything we might have added
1703 # now, purge out the user namespace from anything we might have added
1654 # from the caller's local namespace
1704 # from the caller's local namespace
1655 delvar = self.user_ns.pop
1705 delvar = self.user_ns.pop
1656 for var in local_varnames:
1706 for var in local_varnames:
1657 delvar(var,None)
1707 delvar(var,None)
1658 # and clean builtins we may have overridden
1708 # and clean builtins we may have overridden
1659 self.clean_builtins()
1709 self.clean_builtins()
1660
1710
1661 def interact_prompt(self):
1711 def interact_prompt(self):
1662 """ Print the prompt (in read-eval-print loop)
1712 """ Print the prompt (in read-eval-print loop)
1663
1713
1664 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1714 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1665 used in standard IPython flow.
1715 used in standard IPython flow.
1666 """
1716 """
1667 if self.more:
1717 if self.more:
1668 try:
1718 try:
1669 prompt = self.hooks.generate_prompt(True)
1719 prompt = self.hooks.generate_prompt(True)
1670 except:
1720 except:
1671 self.showtraceback()
1721 self.showtraceback()
1672 if self.autoindent:
1722 if self.autoindent:
1673 self.rl_do_indent = True
1723 self.rl_do_indent = True
1674
1724
1675 else:
1725 else:
1676 try:
1726 try:
1677 prompt = self.hooks.generate_prompt(False)
1727 prompt = self.hooks.generate_prompt(False)
1678 except:
1728 except:
1679 self.showtraceback()
1729 self.showtraceback()
1680 self.write(prompt)
1730 self.write(prompt)
1681
1731
1682 def interact_handle_input(self,line):
1732 def interact_handle_input(self,line):
1683 """ Handle the input line (in read-eval-print loop)
1733 """ Handle the input line (in read-eval-print loop)
1684
1734
1685 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1735 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1686 used in standard IPython flow.
1736 used in standard IPython flow.
1687 """
1737 """
1688 if line.lstrip() == line:
1738 if line.lstrip() == line:
1689 self.shadowhist.add(line.strip())
1739 self.shadowhist.add(line.strip())
1690 lineout = self.prefilter(line,self.more)
1740 lineout = self.prefilter(line,self.more)
1691
1741
1692 if line.strip():
1742 if line.strip():
1693 if self.more:
1743 if self.more:
1694 self.input_hist_raw[-1] += '%s\n' % line
1744 self.input_hist_raw[-1] += '%s\n' % line
1695 else:
1745 else:
1696 self.input_hist_raw.append('%s\n' % line)
1746 self.input_hist_raw.append('%s\n' % line)
1697
1747
1698
1748
1699 self.more = self.push(lineout)
1749 self.more = self.push(lineout)
1700 if (self.SyntaxTB.last_syntax_error and
1750 if (self.SyntaxTB.last_syntax_error and
1701 self.rc.autoedit_syntax):
1751 self.rc.autoedit_syntax):
1702 self.edit_syntax_error()
1752 self.edit_syntax_error()
1703
1753
1704 def interact_with_readline(self):
1754 def interact_with_readline(self):
1705 """ Demo of using interact_handle_input, interact_prompt
1755 """ Demo of using interact_handle_input, interact_prompt
1706
1756
1707 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1757 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1708 it should work like this.
1758 it should work like this.
1709 """
1759 """
1710 self.readline_startup_hook(self.pre_readline)
1760 self.readline_startup_hook(self.pre_readline)
1711 while not self.exit_now:
1761 while not self.exit_now:
1712 self.interact_prompt()
1762 self.interact_prompt()
1713 if self.more:
1763 if self.more:
1714 self.rl_do_indent = True
1764 self.rl_do_indent = True
1715 else:
1765 else:
1716 self.rl_do_indent = False
1766 self.rl_do_indent = False
1717 line = raw_input_original().decode(self.stdin_encoding)
1767 line = raw_input_original().decode(self.stdin_encoding)
1718 self.interact_handle_input(line)
1768 self.interact_handle_input(line)
1719
1769
1720
1770
1721 def interact(self, banner=None):
1771 def interact(self, banner=None):
1722 """Closely emulate the interactive Python console.
1772 """Closely emulate the interactive Python console.
1723
1773
1724 The optional banner argument specify the banner to print
1774 The optional banner argument specify the banner to print
1725 before the first interaction; by default it prints a banner
1775 before the first interaction; by default it prints a banner
1726 similar to the one printed by the real Python interpreter,
1776 similar to the one printed by the real Python interpreter,
1727 followed by the current class name in parentheses (so as not
1777 followed by the current class name in parentheses (so as not
1728 to confuse this with the real interpreter -- since it's so
1778 to confuse this with the real interpreter -- since it's so
1729 close!).
1779 close!).
1730
1780
1731 """
1781 """
1732
1782
1733 if self.exit_now:
1783 if self.exit_now:
1734 # batch run -> do not interact
1784 # batch run -> do not interact
1735 return
1785 return
1736 cprt = 'Type "copyright", "credits" or "license" for more information.'
1786 cprt = 'Type "copyright", "credits" or "license" for more information.'
1737 if banner is None:
1787 if banner is None:
1738 self.write("Python %s on %s\n%s\n(%s)\n" %
1788 self.write("Python %s on %s\n%s\n(%s)\n" %
1739 (sys.version, sys.platform, cprt,
1789 (sys.version, sys.platform, cprt,
1740 self.__class__.__name__))
1790 self.__class__.__name__))
1741 else:
1791 else:
1742 self.write(banner)
1792 self.write(banner)
1743
1793
1744 more = 0
1794 more = 0
1745
1795
1746 # Mark activity in the builtins
1796 # Mark activity in the builtins
1747 __builtin__.__dict__['__IPYTHON__active'] += 1
1797 __builtin__.__dict__['__IPYTHON__active'] += 1
1748
1798
1749 if self.has_readline:
1799 if self.has_readline:
1750 self.readline_startup_hook(self.pre_readline)
1800 self.readline_startup_hook(self.pre_readline)
1751 # exit_now is set by a call to %Exit or %Quit, through the
1801 # exit_now is set by a call to %Exit or %Quit, through the
1752 # ask_exit callback.
1802 # ask_exit callback.
1753
1803
1754 while not self.exit_now:
1804 while not self.exit_now:
1755 self.hooks.pre_prompt_hook()
1805 self.hooks.pre_prompt_hook()
1756 if more:
1806 if more:
1757 try:
1807 try:
1758 prompt = self.hooks.generate_prompt(True)
1808 prompt = self.hooks.generate_prompt(True)
1759 except:
1809 except:
1760 self.showtraceback()
1810 self.showtraceback()
1761 if self.autoindent:
1811 if self.autoindent:
1762 self.rl_do_indent = True
1812 self.rl_do_indent = True
1763
1813
1764 else:
1814 else:
1765 try:
1815 try:
1766 prompt = self.hooks.generate_prompt(False)
1816 prompt = self.hooks.generate_prompt(False)
1767 except:
1817 except:
1768 self.showtraceback()
1818 self.showtraceback()
1769 try:
1819 try:
1770 line = self.raw_input(prompt,more)
1820 line = self.raw_input(prompt,more)
1771 if self.exit_now:
1821 if self.exit_now:
1772 # quick exit on sys.std[in|out] close
1822 # quick exit on sys.std[in|out] close
1773 break
1823 break
1774 if self.autoindent:
1824 if self.autoindent:
1775 self.rl_do_indent = False
1825 self.rl_do_indent = False
1776
1826
1777 except KeyboardInterrupt:
1827 except KeyboardInterrupt:
1778 #double-guard against keyboardinterrupts during kbdint handling
1828 #double-guard against keyboardinterrupts during kbdint handling
1779 try:
1829 try:
1780 self.write('\nKeyboardInterrupt\n')
1830 self.write('\nKeyboardInterrupt\n')
1781 self.resetbuffer()
1831 self.resetbuffer()
1782 # keep cache in sync with the prompt counter:
1832 # keep cache in sync with the prompt counter:
1783 self.outputcache.prompt_count -= 1
1833 self.outputcache.prompt_count -= 1
1784
1834
1785 if self.autoindent:
1835 if self.autoindent:
1786 self.indent_current_nsp = 0
1836 self.indent_current_nsp = 0
1787 more = 0
1837 more = 0
1788 except KeyboardInterrupt:
1838 except KeyboardInterrupt:
1789 pass
1839 pass
1790 except EOFError:
1840 except EOFError:
1791 if self.autoindent:
1841 if self.autoindent:
1792 self.rl_do_indent = False
1842 self.rl_do_indent = False
1793 self.readline_startup_hook(None)
1843 self.readline_startup_hook(None)
1794 self.write('\n')
1844 self.write('\n')
1795 self.exit()
1845 self.exit()
1796 except bdb.BdbQuit:
1846 except bdb.BdbQuit:
1797 warn('The Python debugger has exited with a BdbQuit exception.\n'
1847 warn('The Python debugger has exited with a BdbQuit exception.\n'
1798 'Because of how pdb handles the stack, it is impossible\n'
1848 'Because of how pdb handles the stack, it is impossible\n'
1799 'for IPython to properly format this particular exception.\n'
1849 'for IPython to properly format this particular exception.\n'
1800 'IPython will resume normal operation.')
1850 'IPython will resume normal operation.')
1801 except:
1851 except:
1802 # exceptions here are VERY RARE, but they can be triggered
1852 # exceptions here are VERY RARE, but they can be triggered
1803 # asynchronously by signal handlers, for example.
1853 # asynchronously by signal handlers, for example.
1804 self.showtraceback()
1854 self.showtraceback()
1805 else:
1855 else:
1806 more = self.push(line)
1856 more = self.push(line)
1807 if (self.SyntaxTB.last_syntax_error and
1857 if (self.SyntaxTB.last_syntax_error and
1808 self.rc.autoedit_syntax):
1858 self.rc.autoedit_syntax):
1809 self.edit_syntax_error()
1859 self.edit_syntax_error()
1810
1860
1811 # We are off again...
1861 # We are off again...
1812 __builtin__.__dict__['__IPYTHON__active'] -= 1
1862 __builtin__.__dict__['__IPYTHON__active'] -= 1
1813
1863
1814 def excepthook(self, etype, value, tb):
1864 def excepthook(self, etype, value, tb):
1815 """One more defense for GUI apps that call sys.excepthook.
1865 """One more defense for GUI apps that call sys.excepthook.
1816
1866
1817 GUI frameworks like wxPython trap exceptions and call
1867 GUI frameworks like wxPython trap exceptions and call
1818 sys.excepthook themselves. I guess this is a feature that
1868 sys.excepthook themselves. I guess this is a feature that
1819 enables them to keep running after exceptions that would
1869 enables them to keep running after exceptions that would
1820 otherwise kill their mainloop. This is a bother for IPython
1870 otherwise kill their mainloop. This is a bother for IPython
1821 which excepts to catch all of the program exceptions with a try:
1871 which excepts to catch all of the program exceptions with a try:
1822 except: statement.
1872 except: statement.
1823
1873
1824 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1874 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1825 any app directly invokes sys.excepthook, it will look to the user like
1875 any app directly invokes sys.excepthook, it will look to the user like
1826 IPython crashed. In order to work around this, we can disable the
1876 IPython crashed. In order to work around this, we can disable the
1827 CrashHandler and replace it with this excepthook instead, which prints a
1877 CrashHandler and replace it with this excepthook instead, which prints a
1828 regular traceback using our InteractiveTB. In this fashion, apps which
1878 regular traceback using our InteractiveTB. In this fashion, apps which
1829 call sys.excepthook will generate a regular-looking exception from
1879 call sys.excepthook will generate a regular-looking exception from
1830 IPython, and the CrashHandler will only be triggered by real IPython
1880 IPython, and the CrashHandler will only be triggered by real IPython
1831 crashes.
1881 crashes.
1832
1882
1833 This hook should be used sparingly, only in places which are not likely
1883 This hook should be used sparingly, only in places which are not likely
1834 to be true IPython errors.
1884 to be true IPython errors.
1835 """
1885 """
1836 self.showtraceback((etype,value,tb),tb_offset=0)
1886 self.showtraceback((etype,value,tb),tb_offset=0)
1837
1887
1838 def expand_aliases(self,fn,rest):
1888 def expand_aliases(self,fn,rest):
1839 """ Expand multiple levels of aliases:
1889 """ Expand multiple levels of aliases:
1840
1890
1841 if:
1891 if:
1842
1892
1843 alias foo bar /tmp
1893 alias foo bar /tmp
1844 alias baz foo
1894 alias baz foo
1845
1895
1846 then:
1896 then:
1847
1897
1848 baz huhhahhei -> bar /tmp huhhahhei
1898 baz huhhahhei -> bar /tmp huhhahhei
1849
1899
1850 """
1900 """
1851 line = fn + " " + rest
1901 line = fn + " " + rest
1852
1902
1853 done = Set()
1903 done = Set()
1854 while 1:
1904 while 1:
1855 pre,fn,rest = prefilter.splitUserInput(line,
1905 pre,fn,rest = prefilter.splitUserInput(line,
1856 prefilter.shell_line_split)
1906 prefilter.shell_line_split)
1857 if fn in self.alias_table:
1907 if fn in self.alias_table:
1858 if fn in done:
1908 if fn in done:
1859 warn("Cyclic alias definition, repeated '%s'" % fn)
1909 warn("Cyclic alias definition, repeated '%s'" % fn)
1860 return ""
1910 return ""
1861 done.add(fn)
1911 done.add(fn)
1862
1912
1863 l2 = self.transform_alias(fn,rest)
1913 l2 = self.transform_alias(fn,rest)
1864 # dir -> dir
1914 # dir -> dir
1865 # print "alias",line, "->",l2 #dbg
1915 # print "alias",line, "->",l2 #dbg
1866 if l2 == line:
1916 if l2 == line:
1867 break
1917 break
1868 # ls -> ls -F should not recurse forever
1918 # ls -> ls -F should not recurse forever
1869 if l2.split(None,1)[0] == line.split(None,1)[0]:
1919 if l2.split(None,1)[0] == line.split(None,1)[0]:
1870 line = l2
1920 line = l2
1871 break
1921 break
1872
1922
1873 line=l2
1923 line=l2
1874
1924
1875
1925
1876 # print "al expand to",line #dbg
1926 # print "al expand to",line #dbg
1877 else:
1927 else:
1878 break
1928 break
1879
1929
1880 return line
1930 return line
1881
1931
1882 def transform_alias(self, alias,rest=''):
1932 def transform_alias(self, alias,rest=''):
1883 """ Transform alias to system command string.
1933 """ Transform alias to system command string.
1884 """
1934 """
1885 trg = self.alias_table[alias]
1935 trg = self.alias_table[alias]
1886
1936
1887 nargs,cmd = trg
1937 nargs,cmd = trg
1888 # print trg #dbg
1938 # print trg #dbg
1889 if ' ' in cmd and os.path.isfile(cmd):
1939 if ' ' in cmd and os.path.isfile(cmd):
1890 cmd = '"%s"' % cmd
1940 cmd = '"%s"' % cmd
1891
1941
1892 # Expand the %l special to be the user's input line
1942 # Expand the %l special to be the user's input line
1893 if cmd.find('%l') >= 0:
1943 if cmd.find('%l') >= 0:
1894 cmd = cmd.replace('%l',rest)
1944 cmd = cmd.replace('%l',rest)
1895 rest = ''
1945 rest = ''
1896 if nargs==0:
1946 if nargs==0:
1897 # Simple, argument-less aliases
1947 # Simple, argument-less aliases
1898 cmd = '%s %s' % (cmd,rest)
1948 cmd = '%s %s' % (cmd,rest)
1899 else:
1949 else:
1900 # Handle aliases with positional arguments
1950 # Handle aliases with positional arguments
1901 args = rest.split(None,nargs)
1951 args = rest.split(None,nargs)
1902 if len(args)< nargs:
1952 if len(args)< nargs:
1903 error('Alias <%s> requires %s arguments, %s given.' %
1953 error('Alias <%s> requires %s arguments, %s given.' %
1904 (alias,nargs,len(args)))
1954 (alias,nargs,len(args)))
1905 return None
1955 return None
1906 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1956 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1907 # Now call the macro, evaluating in the user's namespace
1957 # Now call the macro, evaluating in the user's namespace
1908 #print 'new command: <%r>' % cmd # dbg
1958 #print 'new command: <%r>' % cmd # dbg
1909 return cmd
1959 return cmd
1910
1960
1911 def call_alias(self,alias,rest=''):
1961 def call_alias(self,alias,rest=''):
1912 """Call an alias given its name and the rest of the line.
1962 """Call an alias given its name and the rest of the line.
1913
1963
1914 This is only used to provide backwards compatibility for users of
1964 This is only used to provide backwards compatibility for users of
1915 ipalias(), use of which is not recommended for anymore."""
1965 ipalias(), use of which is not recommended for anymore."""
1916
1966
1917 # Now call the macro, evaluating in the user's namespace
1967 # Now call the macro, evaluating in the user's namespace
1918 cmd = self.transform_alias(alias, rest)
1968 cmd = self.transform_alias(alias, rest)
1919 try:
1969 try:
1920 self.system(cmd)
1970 self.system(cmd)
1921 except:
1971 except:
1922 self.showtraceback()
1972 self.showtraceback()
1923
1973
1924 def indent_current_str(self):
1974 def indent_current_str(self):
1925 """return the current level of indentation as a string"""
1975 """return the current level of indentation as a string"""
1926 return self.indent_current_nsp * ' '
1976 return self.indent_current_nsp * ' '
1927
1977
1928 def autoindent_update(self,line):
1978 def autoindent_update(self,line):
1929 """Keep track of the indent level."""
1979 """Keep track of the indent level."""
1930
1980
1931 #debugx('line')
1981 #debugx('line')
1932 #debugx('self.indent_current_nsp')
1982 #debugx('self.indent_current_nsp')
1933 if self.autoindent:
1983 if self.autoindent:
1934 if line:
1984 if line:
1935 inisp = num_ini_spaces(line)
1985 inisp = num_ini_spaces(line)
1936 if inisp < self.indent_current_nsp:
1986 if inisp < self.indent_current_nsp:
1937 self.indent_current_nsp = inisp
1987 self.indent_current_nsp = inisp
1938
1988
1939 if line[-1] == ':':
1989 if line[-1] == ':':
1940 self.indent_current_nsp += 4
1990 self.indent_current_nsp += 4
1941 elif dedent_re.match(line):
1991 elif dedent_re.match(line):
1942 self.indent_current_nsp -= 4
1992 self.indent_current_nsp -= 4
1943 else:
1993 else:
1944 self.indent_current_nsp = 0
1994 self.indent_current_nsp = 0
1945
1995
1946 def runlines(self,lines):
1996 def runlines(self,lines):
1947 """Run a string of one or more lines of source.
1997 """Run a string of one or more lines of source.
1948
1998
1949 This method is capable of running a string containing multiple source
1999 This method is capable of running a string containing multiple source
1950 lines, as if they had been entered at the IPython prompt. Since it
2000 lines, as if they had been entered at the IPython prompt. Since it
1951 exposes IPython's processing machinery, the given strings can contain
2001 exposes IPython's processing machinery, the given strings can contain
1952 magic calls (%magic), special shell access (!cmd), etc."""
2002 magic calls (%magic), special shell access (!cmd), etc."""
1953
2003
1954 # We must start with a clean buffer, in case this is run from an
2004 # We must start with a clean buffer, in case this is run from an
1955 # interactive IPython session (via a magic, for example).
2005 # interactive IPython session (via a magic, for example).
1956 self.resetbuffer()
2006 self.resetbuffer()
1957 lines = lines.split('\n')
2007 lines = lines.split('\n')
1958 more = 0
2008 more = 0
1959
2009
1960 for line in lines:
2010 for line in lines:
1961 # skip blank lines so we don't mess up the prompt counter, but do
2011 # skip blank lines so we don't mess up the prompt counter, but do
1962 # NOT skip even a blank line if we are in a code block (more is
2012 # NOT skip even a blank line if we are in a code block (more is
1963 # true)
2013 # true)
1964
2014
1965
2015
1966 if line or more:
2016 if line or more:
1967 # push to raw history, so hist line numbers stay in sync
2017 # push to raw history, so hist line numbers stay in sync
1968 self.input_hist_raw.append("# " + line + "\n")
2018 self.input_hist_raw.append("# " + line + "\n")
1969 more = self.push(self.prefilter(line,more))
2019 more = self.push(self.prefilter(line,more))
1970 # IPython's runsource returns None if there was an error
2020 # IPython's runsource returns None if there was an error
1971 # compiling the code. This allows us to stop processing right
2021 # compiling the code. This allows us to stop processing right
1972 # away, so the user gets the error message at the right place.
2022 # away, so the user gets the error message at the right place.
1973 if more is None:
2023 if more is None:
1974 break
2024 break
1975 else:
2025 else:
1976 self.input_hist_raw.append("\n")
2026 self.input_hist_raw.append("\n")
1977 # final newline in case the input didn't have it, so that the code
2027 # final newline in case the input didn't have it, so that the code
1978 # actually does get executed
2028 # actually does get executed
1979 if more:
2029 if more:
1980 self.push('\n')
2030 self.push('\n')
1981
2031
1982 def runsource(self, source, filename='<input>', symbol='single'):
2032 def runsource(self, source, filename='<input>', symbol='single'):
1983 """Compile and run some source in the interpreter.
2033 """Compile and run some source in the interpreter.
1984
2034
1985 Arguments are as for compile_command().
2035 Arguments are as for compile_command().
1986
2036
1987 One several things can happen:
2037 One several things can happen:
1988
2038
1989 1) The input is incorrect; compile_command() raised an
2039 1) The input is incorrect; compile_command() raised an
1990 exception (SyntaxError or OverflowError). A syntax traceback
2040 exception (SyntaxError or OverflowError). A syntax traceback
1991 will be printed by calling the showsyntaxerror() method.
2041 will be printed by calling the showsyntaxerror() method.
1992
2042
1993 2) The input is incomplete, and more input is required;
2043 2) The input is incomplete, and more input is required;
1994 compile_command() returned None. Nothing happens.
2044 compile_command() returned None. Nothing happens.
1995
2045
1996 3) The input is complete; compile_command() returned a code
2046 3) The input is complete; compile_command() returned a code
1997 object. The code is executed by calling self.runcode() (which
2047 object. The code is executed by calling self.runcode() (which
1998 also handles run-time exceptions, except for SystemExit).
2048 also handles run-time exceptions, except for SystemExit).
1999
2049
2000 The return value is:
2050 The return value is:
2001
2051
2002 - True in case 2
2052 - True in case 2
2003
2053
2004 - False in the other cases, unless an exception is raised, where
2054 - False in the other cases, unless an exception is raised, where
2005 None is returned instead. This can be used by external callers to
2055 None is returned instead. This can be used by external callers to
2006 know whether to continue feeding input or not.
2056 know whether to continue feeding input or not.
2007
2057
2008 The return value can be used to decide whether to use sys.ps1 or
2058 The return value can be used to decide whether to use sys.ps1 or
2009 sys.ps2 to prompt the next line."""
2059 sys.ps2 to prompt the next line."""
2010
2060
2011 # if the source code has leading blanks, add 'if 1:\n' to it
2061 # if the source code has leading blanks, add 'if 1:\n' to it
2012 # this allows execution of indented pasted code. It is tempting
2062 # this allows execution of indented pasted code. It is tempting
2013 # to add '\n' at the end of source to run commands like ' a=1'
2063 # to add '\n' at the end of source to run commands like ' a=1'
2014 # directly, but this fails for more complicated scenarios
2064 # directly, but this fails for more complicated scenarios
2015 source=source.encode(self.stdin_encoding)
2065 source=source.encode(self.stdin_encoding)
2016 if source[:1] in [' ', '\t']:
2066 if source[:1] in [' ', '\t']:
2017 source = 'if 1:\n%s' % source
2067 source = 'if 1:\n%s' % source
2018
2068
2019 try:
2069 try:
2020 code = self.compile(source,filename,symbol)
2070 code = self.compile(source,filename,symbol)
2021 except (OverflowError, SyntaxError, ValueError, TypeError):
2071 except (OverflowError, SyntaxError, ValueError, TypeError):
2022 # Case 1
2072 # Case 1
2023 self.showsyntaxerror(filename)
2073 self.showsyntaxerror(filename)
2024 return None
2074 return None
2025
2075
2026 if code is None:
2076 if code is None:
2027 # Case 2
2077 # Case 2
2028 return True
2078 return True
2029
2079
2030 # Case 3
2080 # Case 3
2031 # We store the code object so that threaded shells and
2081 # We store the code object so that threaded shells and
2032 # custom exception handlers can access all this info if needed.
2082 # custom exception handlers can access all this info if needed.
2033 # The source corresponding to this can be obtained from the
2083 # The source corresponding to this can be obtained from the
2034 # buffer attribute as '\n'.join(self.buffer).
2084 # buffer attribute as '\n'.join(self.buffer).
2035 self.code_to_run = code
2085 self.code_to_run = code
2036 # now actually execute the code object
2086 # now actually execute the code object
2037 if self.runcode(code) == 0:
2087 if self.runcode(code) == 0:
2038 return False
2088 return False
2039 else:
2089 else:
2040 return None
2090 return None
2041
2091
2042 def runcode(self,code_obj):
2092 def runcode(self,code_obj):
2043 """Execute a code object.
2093 """Execute a code object.
2044
2094
2045 When an exception occurs, self.showtraceback() is called to display a
2095 When an exception occurs, self.showtraceback() is called to display a
2046 traceback.
2096 traceback.
2047
2097
2048 Return value: a flag indicating whether the code to be run completed
2098 Return value: a flag indicating whether the code to be run completed
2049 successfully:
2099 successfully:
2050
2100
2051 - 0: successful execution.
2101 - 0: successful execution.
2052 - 1: an error occurred.
2102 - 1: an error occurred.
2053 """
2103 """
2054
2104
2055 # Set our own excepthook in case the user code tries to call it
2105 # Set our own excepthook in case the user code tries to call it
2056 # directly, so that the IPython crash handler doesn't get triggered
2106 # directly, so that the IPython crash handler doesn't get triggered
2057 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2107 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2058
2108
2059 # we save the original sys.excepthook in the instance, in case config
2109 # we save the original sys.excepthook in the instance, in case config
2060 # code (such as magics) needs access to it.
2110 # code (such as magics) needs access to it.
2061 self.sys_excepthook = old_excepthook
2111 self.sys_excepthook = old_excepthook
2062 outflag = 1 # happens in more places, so it's easier as default
2112 outflag = 1 # happens in more places, so it's easier as default
2063 try:
2113 try:
2064 try:
2114 try:
2065 self.hooks.pre_runcode_hook()
2115 self.hooks.pre_runcode_hook()
2066 exec code_obj in self.user_global_ns, self.user_ns
2116 exec code_obj in self.user_global_ns, self.user_ns
2067 finally:
2117 finally:
2068 # Reset our crash handler in place
2118 # Reset our crash handler in place
2069 sys.excepthook = old_excepthook
2119 sys.excepthook = old_excepthook
2070 except SystemExit:
2120 except SystemExit:
2071 self.resetbuffer()
2121 self.resetbuffer()
2072 self.showtraceback()
2122 self.showtraceback()
2073 warn("Type %exit or %quit to exit IPython "
2123 warn("Type %exit or %quit to exit IPython "
2074 "(%Exit or %Quit do so unconditionally).",level=1)
2124 "(%Exit or %Quit do so unconditionally).",level=1)
2075 except self.custom_exceptions:
2125 except self.custom_exceptions:
2076 etype,value,tb = sys.exc_info()
2126 etype,value,tb = sys.exc_info()
2077 self.CustomTB(etype,value,tb)
2127 self.CustomTB(etype,value,tb)
2078 except:
2128 except:
2079 self.showtraceback()
2129 self.showtraceback()
2080 else:
2130 else:
2081 outflag = 0
2131 outflag = 0
2082 if softspace(sys.stdout, 0):
2132 if softspace(sys.stdout, 0):
2083 print
2133 print
2084 # Flush out code object which has been run (and source)
2134 # Flush out code object which has been run (and source)
2085 self.code_to_run = None
2135 self.code_to_run = None
2086 return outflag
2136 return outflag
2087
2137
2088 def push(self, line):
2138 def push(self, line):
2089 """Push a line to the interpreter.
2139 """Push a line to the interpreter.
2090
2140
2091 The line should not have a trailing newline; it may have
2141 The line should not have a trailing newline; it may have
2092 internal newlines. The line is appended to a buffer and the
2142 internal newlines. The line is appended to a buffer and the
2093 interpreter's runsource() method is called with the
2143 interpreter's runsource() method is called with the
2094 concatenated contents of the buffer as source. If this
2144 concatenated contents of the buffer as source. If this
2095 indicates that the command was executed or invalid, the buffer
2145 indicates that the command was executed or invalid, the buffer
2096 is reset; otherwise, the command is incomplete, and the buffer
2146 is reset; otherwise, the command is incomplete, and the buffer
2097 is left as it was after the line was appended. The return
2147 is left as it was after the line was appended. The return
2098 value is 1 if more input is required, 0 if the line was dealt
2148 value is 1 if more input is required, 0 if the line was dealt
2099 with in some way (this is the same as runsource()).
2149 with in some way (this is the same as runsource()).
2100 """
2150 """
2101
2151
2102 # autoindent management should be done here, and not in the
2152 # autoindent management should be done here, and not in the
2103 # interactive loop, since that one is only seen by keyboard input. We
2153 # interactive loop, since that one is only seen by keyboard input. We
2104 # need this done correctly even for code run via runlines (which uses
2154 # need this done correctly even for code run via runlines (which uses
2105 # push).
2155 # push).
2106
2156
2107 #print 'push line: <%s>' % line # dbg
2157 #print 'push line: <%s>' % line # dbg
2108 for subline in line.splitlines():
2158 for subline in line.splitlines():
2109 self.autoindent_update(subline)
2159 self.autoindent_update(subline)
2110 self.buffer.append(line)
2160 self.buffer.append(line)
2111 more = self.runsource('\n'.join(self.buffer), self.filename)
2161 more = self.runsource('\n'.join(self.buffer), self.filename)
2112 if not more:
2162 if not more:
2113 self.resetbuffer()
2163 self.resetbuffer()
2114 return more
2164 return more
2115
2165
2116 def split_user_input(self, line):
2166 def split_user_input(self, line):
2117 # This is really a hold-over to support ipapi and some extensions
2167 # This is really a hold-over to support ipapi and some extensions
2118 return prefilter.splitUserInput(line)
2168 return prefilter.splitUserInput(line)
2119
2169
2120 def resetbuffer(self):
2170 def resetbuffer(self):
2121 """Reset the input buffer."""
2171 """Reset the input buffer."""
2122 self.buffer[:] = []
2172 self.buffer[:] = []
2123
2173
2124 def raw_input(self,prompt='',continue_prompt=False):
2174 def raw_input(self,prompt='',continue_prompt=False):
2125 """Write a prompt and read a line.
2175 """Write a prompt and read a line.
2126
2176
2127 The returned line does not include the trailing newline.
2177 The returned line does not include the trailing newline.
2128 When the user enters the EOF key sequence, EOFError is raised.
2178 When the user enters the EOF key sequence, EOFError is raised.
2129
2179
2130 Optional inputs:
2180 Optional inputs:
2131
2181
2132 - prompt(''): a string to be printed to prompt the user.
2182 - prompt(''): a string to be printed to prompt the user.
2133
2183
2134 - continue_prompt(False): whether this line is the first one or a
2184 - continue_prompt(False): whether this line is the first one or a
2135 continuation in a sequence of inputs.
2185 continuation in a sequence of inputs.
2136 """
2186 """
2137
2187
2138 # Code run by the user may have modified the readline completer state.
2188 # Code run by the user may have modified the readline completer state.
2139 # We must ensure that our completer is back in place.
2189 # We must ensure that our completer is back in place.
2140 if self.has_readline:
2190 if self.has_readline:
2141 self.set_completer()
2191 self.set_completer()
2142
2192
2143 try:
2193 try:
2144 line = raw_input_original(prompt).decode(self.stdin_encoding)
2194 line = raw_input_original(prompt).decode(self.stdin_encoding)
2145 except ValueError:
2195 except ValueError:
2146 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2196 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2147 " or sys.stdout.close()!\nExiting IPython!")
2197 " or sys.stdout.close()!\nExiting IPython!")
2148 self.ask_exit()
2198 self.ask_exit()
2149 return ""
2199 return ""
2150
2200
2151 # Try to be reasonably smart about not re-indenting pasted input more
2201 # Try to be reasonably smart about not re-indenting pasted input more
2152 # than necessary. We do this by trimming out the auto-indent initial
2202 # than necessary. We do this by trimming out the auto-indent initial
2153 # spaces, if the user's actual input started itself with whitespace.
2203 # spaces, if the user's actual input started itself with whitespace.
2154 #debugx('self.buffer[-1]')
2204 #debugx('self.buffer[-1]')
2155
2205
2156 if self.autoindent:
2206 if self.autoindent:
2157 if num_ini_spaces(line) > self.indent_current_nsp:
2207 if num_ini_spaces(line) > self.indent_current_nsp:
2158 line = line[self.indent_current_nsp:]
2208 line = line[self.indent_current_nsp:]
2159 self.indent_current_nsp = 0
2209 self.indent_current_nsp = 0
2160
2210
2161 # store the unfiltered input before the user has any chance to modify
2211 # store the unfiltered input before the user has any chance to modify
2162 # it.
2212 # it.
2163 if line.strip():
2213 if line.strip():
2164 if continue_prompt:
2214 if continue_prompt:
2165 self.input_hist_raw[-1] += '%s\n' % line
2215 self.input_hist_raw[-1] += '%s\n' % line
2166 if self.has_readline: # and some config option is set?
2216 if self.has_readline: # and some config option is set?
2167 try:
2217 try:
2168 histlen = self.readline.get_current_history_length()
2218 histlen = self.readline.get_current_history_length()
2169 if histlen > 1:
2219 if histlen > 1:
2170 newhist = self.input_hist_raw[-1].rstrip()
2220 newhist = self.input_hist_raw[-1].rstrip()
2171 self.readline.remove_history_item(histlen-1)
2221 self.readline.remove_history_item(histlen-1)
2172 self.readline.replace_history_item(histlen-2,
2222 self.readline.replace_history_item(histlen-2,
2173 newhist.encode(self.stdin_encoding))
2223 newhist.encode(self.stdin_encoding))
2174 except AttributeError:
2224 except AttributeError:
2175 pass # re{move,place}_history_item are new in 2.4.
2225 pass # re{move,place}_history_item are new in 2.4.
2176 else:
2226 else:
2177 self.input_hist_raw.append('%s\n' % line)
2227 self.input_hist_raw.append('%s\n' % line)
2178 # only entries starting at first column go to shadow history
2228 # only entries starting at first column go to shadow history
2179 if line.lstrip() == line:
2229 if line.lstrip() == line:
2180 self.shadowhist.add(line.strip())
2230 self.shadowhist.add(line.strip())
2181 elif not continue_prompt:
2231 elif not continue_prompt:
2182 self.input_hist_raw.append('\n')
2232 self.input_hist_raw.append('\n')
2183 try:
2233 try:
2184 lineout = self.prefilter(line,continue_prompt)
2234 lineout = self.prefilter(line,continue_prompt)
2185 except:
2235 except:
2186 # blanket except, in case a user-defined prefilter crashes, so it
2236 # blanket except, in case a user-defined prefilter crashes, so it
2187 # can't take all of ipython with it.
2237 # can't take all of ipython with it.
2188 self.showtraceback()
2238 self.showtraceback()
2189 return ''
2239 return ''
2190 else:
2240 else:
2191 return lineout
2241 return lineout
2192
2242
2193 def _prefilter(self, line, continue_prompt):
2243 def _prefilter(self, line, continue_prompt):
2194 """Calls different preprocessors, depending on the form of line."""
2244 """Calls different preprocessors, depending on the form of line."""
2195
2245
2196 # All handlers *must* return a value, even if it's blank ('').
2246 # All handlers *must* return a value, even if it's blank ('').
2197
2247
2198 # Lines are NOT logged here. Handlers should process the line as
2248 # Lines are NOT logged here. Handlers should process the line as
2199 # needed, update the cache AND log it (so that the input cache array
2249 # needed, update the cache AND log it (so that the input cache array
2200 # stays synced).
2250 # stays synced).
2201
2251
2202 #.....................................................................
2252 #.....................................................................
2203 # Code begins
2253 # Code begins
2204
2254
2205 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2255 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2206
2256
2207 # save the line away in case we crash, so the post-mortem handler can
2257 # save the line away in case we crash, so the post-mortem handler can
2208 # record it
2258 # record it
2209 self._last_input_line = line
2259 self._last_input_line = line
2210
2260
2211 #print '***line: <%s>' % line # dbg
2261 #print '***line: <%s>' % line # dbg
2212
2262
2213 if not line:
2263 if not line:
2214 # Return immediately on purely empty lines, so that if the user
2264 # Return immediately on purely empty lines, so that if the user
2215 # previously typed some whitespace that started a continuation
2265 # previously typed some whitespace that started a continuation
2216 # prompt, he can break out of that loop with just an empty line.
2266 # prompt, he can break out of that loop with just an empty line.
2217 # This is how the default python prompt works.
2267 # This is how the default python prompt works.
2218
2268
2219 # Only return if the accumulated input buffer was just whitespace!
2269 # Only return if the accumulated input buffer was just whitespace!
2220 if ''.join(self.buffer).isspace():
2270 if ''.join(self.buffer).isspace():
2221 self.buffer[:] = []
2271 self.buffer[:] = []
2222 return ''
2272 return ''
2223
2273
2224 line_info = prefilter.LineInfo(line, continue_prompt)
2274 line_info = prefilter.LineInfo(line, continue_prompt)
2225
2275
2226 # the input history needs to track even empty lines
2276 # the input history needs to track even empty lines
2227 stripped = line.strip()
2277 stripped = line.strip()
2228
2278
2229 if not stripped:
2279 if not stripped:
2230 if not continue_prompt:
2280 if not continue_prompt:
2231 self.outputcache.prompt_count -= 1
2281 self.outputcache.prompt_count -= 1
2232 return self.handle_normal(line_info)
2282 return self.handle_normal(line_info)
2233
2283
2234 # print '***cont',continue_prompt # dbg
2284 # print '***cont',continue_prompt # dbg
2235 # special handlers are only allowed for single line statements
2285 # special handlers are only allowed for single line statements
2236 if continue_prompt and not self.rc.multi_line_specials:
2286 if continue_prompt and not self.rc.multi_line_specials:
2237 return self.handle_normal(line_info)
2287 return self.handle_normal(line_info)
2238
2288
2239
2289
2240 # See whether any pre-existing handler can take care of it
2290 # See whether any pre-existing handler can take care of it
2241 rewritten = self.hooks.input_prefilter(stripped)
2291 rewritten = self.hooks.input_prefilter(stripped)
2242 if rewritten != stripped: # ok, some prefilter did something
2292 if rewritten != stripped: # ok, some prefilter did something
2243 rewritten = line_info.pre + rewritten # add indentation
2293 rewritten = line_info.pre + rewritten # add indentation
2244 return self.handle_normal(prefilter.LineInfo(rewritten,
2294 return self.handle_normal(prefilter.LineInfo(rewritten,
2245 continue_prompt))
2295 continue_prompt))
2246
2296
2247 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2297 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2248
2298
2249 return prefilter.prefilter(line_info, self)
2299 return prefilter.prefilter(line_info, self)
2250
2300
2251
2301
2252 def _prefilter_dumb(self, line, continue_prompt):
2302 def _prefilter_dumb(self, line, continue_prompt):
2253 """simple prefilter function, for debugging"""
2303 """simple prefilter function, for debugging"""
2254 return self.handle_normal(line,continue_prompt)
2304 return self.handle_normal(line,continue_prompt)
2255
2305
2256
2306
2257 def multiline_prefilter(self, line, continue_prompt):
2307 def multiline_prefilter(self, line, continue_prompt):
2258 """ Run _prefilter for each line of input
2308 """ Run _prefilter for each line of input
2259
2309
2260 Covers cases where there are multiple lines in the user entry,
2310 Covers cases where there are multiple lines in the user entry,
2261 which is the case when the user goes back to a multiline history
2311 which is the case when the user goes back to a multiline history
2262 entry and presses enter.
2312 entry and presses enter.
2263
2313
2264 """
2314 """
2265 out = []
2315 out = []
2266 for l in line.rstrip('\n').split('\n'):
2316 for l in line.rstrip('\n').split('\n'):
2267 out.append(self._prefilter(l, continue_prompt))
2317 out.append(self._prefilter(l, continue_prompt))
2268 return '\n'.join(out)
2318 return '\n'.join(out)
2269
2319
2270 # Set the default prefilter() function (this can be user-overridden)
2320 # Set the default prefilter() function (this can be user-overridden)
2271 prefilter = multiline_prefilter
2321 prefilter = multiline_prefilter
2272
2322
2273 def handle_normal(self,line_info):
2323 def handle_normal(self,line_info):
2274 """Handle normal input lines. Use as a template for handlers."""
2324 """Handle normal input lines. Use as a template for handlers."""
2275
2325
2276 # With autoindent on, we need some way to exit the input loop, and I
2326 # With autoindent on, we need some way to exit the input loop, and I
2277 # don't want to force the user to have to backspace all the way to
2327 # don't want to force the user to have to backspace all the way to
2278 # clear the line. The rule will be in this case, that either two
2328 # clear the line. The rule will be in this case, that either two
2279 # lines of pure whitespace in a row, or a line of pure whitespace but
2329 # lines of pure whitespace in a row, or a line of pure whitespace but
2280 # of a size different to the indent level, will exit the input loop.
2330 # of a size different to the indent level, will exit the input loop.
2281 line = line_info.line
2331 line = line_info.line
2282 continue_prompt = line_info.continue_prompt
2332 continue_prompt = line_info.continue_prompt
2283
2333
2284 if (continue_prompt and self.autoindent and line.isspace() and
2334 if (continue_prompt and self.autoindent and line.isspace() and
2285 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2335 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2286 (self.buffer[-1]).isspace() )):
2336 (self.buffer[-1]).isspace() )):
2287 line = ''
2337 line = ''
2288
2338
2289 self.log(line,line,continue_prompt)
2339 self.log(line,line,continue_prompt)
2290 return line
2340 return line
2291
2341
2292 def handle_alias(self,line_info):
2342 def handle_alias(self,line_info):
2293 """Handle alias input lines. """
2343 """Handle alias input lines. """
2294 tgt = self.alias_table[line_info.iFun]
2344 tgt = self.alias_table[line_info.iFun]
2295 # print "=>",tgt #dbg
2345 # print "=>",tgt #dbg
2296 if callable(tgt):
2346 if callable(tgt):
2297 if '$' in line_info.line:
2347 if '$' in line_info.line:
2298 call_meth = '(_ip, _ip.itpl(%s))'
2348 call_meth = '(_ip, _ip.itpl(%s))'
2299 else:
2349 else:
2300 call_meth = '(_ip,%s)'
2350 call_meth = '(_ip,%s)'
2301 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2351 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2302 line_info.iFun,
2352 line_info.iFun,
2303 make_quoted_expr(line_info.line))
2353 make_quoted_expr(line_info.line))
2304 else:
2354 else:
2305 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2355 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2306
2356
2307 # pre is needed, because it carries the leading whitespace. Otherwise
2357 # pre is needed, because it carries the leading whitespace. Otherwise
2308 # aliases won't work in indented sections.
2358 # aliases won't work in indented sections.
2309 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2359 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2310 make_quoted_expr( transformed ))
2360 make_quoted_expr( transformed ))
2311
2361
2312 self.log(line_info.line,line_out,line_info.continue_prompt)
2362 self.log(line_info.line,line_out,line_info.continue_prompt)
2313 #print 'line out:',line_out # dbg
2363 #print 'line out:',line_out # dbg
2314 return line_out
2364 return line_out
2315
2365
2316 def handle_shell_escape(self, line_info):
2366 def handle_shell_escape(self, line_info):
2317 """Execute the line in a shell, empty return value"""
2367 """Execute the line in a shell, empty return value"""
2318 #print 'line in :', `line` # dbg
2368 #print 'line in :', `line` # dbg
2319 line = line_info.line
2369 line = line_info.line
2320 if line.lstrip().startswith('!!'):
2370 if line.lstrip().startswith('!!'):
2321 # rewrite LineInfo's line, iFun and theRest to properly hold the
2371 # rewrite LineInfo's line, iFun and theRest to properly hold the
2322 # call to %sx and the actual command to be executed, so
2372 # call to %sx and the actual command to be executed, so
2323 # handle_magic can work correctly. Note that this works even if
2373 # handle_magic can work correctly. Note that this works even if
2324 # the line is indented, so it handles multi_line_specials
2374 # the line is indented, so it handles multi_line_specials
2325 # properly.
2375 # properly.
2326 new_rest = line.lstrip()[2:]
2376 new_rest = line.lstrip()[2:]
2327 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2377 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2328 line_info.iFun = 'sx'
2378 line_info.iFun = 'sx'
2329 line_info.theRest = new_rest
2379 line_info.theRest = new_rest
2330 return self.handle_magic(line_info)
2380 return self.handle_magic(line_info)
2331 else:
2381 else:
2332 cmd = line.lstrip().lstrip('!')
2382 cmd = line.lstrip().lstrip('!')
2333 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2383 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2334 make_quoted_expr(cmd))
2384 make_quoted_expr(cmd))
2335 # update cache/log and return
2385 # update cache/log and return
2336 self.log(line,line_out,line_info.continue_prompt)
2386 self.log(line,line_out,line_info.continue_prompt)
2337 return line_out
2387 return line_out
2338
2388
2339 def handle_magic(self, line_info):
2389 def handle_magic(self, line_info):
2340 """Execute magic functions."""
2390 """Execute magic functions."""
2341 iFun = line_info.iFun
2391 iFun = line_info.iFun
2342 theRest = line_info.theRest
2392 theRest = line_info.theRest
2343 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2393 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2344 make_quoted_expr(iFun + " " + theRest))
2394 make_quoted_expr(iFun + " " + theRest))
2345 self.log(line_info.line,cmd,line_info.continue_prompt)
2395 self.log(line_info.line,cmd,line_info.continue_prompt)
2346 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2396 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2347 return cmd
2397 return cmd
2348
2398
2349 def handle_auto(self, line_info):
2399 def handle_auto(self, line_info):
2350 """Hande lines which can be auto-executed, quoting if requested."""
2400 """Hande lines which can be auto-executed, quoting if requested."""
2351
2401
2352 line = line_info.line
2402 line = line_info.line
2353 iFun = line_info.iFun
2403 iFun = line_info.iFun
2354 theRest = line_info.theRest
2404 theRest = line_info.theRest
2355 pre = line_info.pre
2405 pre = line_info.pre
2356 continue_prompt = line_info.continue_prompt
2406 continue_prompt = line_info.continue_prompt
2357 obj = line_info.ofind(self)['obj']
2407 obj = line_info.ofind(self)['obj']
2358
2408
2359 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2409 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2360
2410
2361 # This should only be active for single-line input!
2411 # This should only be active for single-line input!
2362 if continue_prompt:
2412 if continue_prompt:
2363 self.log(line,line,continue_prompt)
2413 self.log(line,line,continue_prompt)
2364 return line
2414 return line
2365
2415
2366 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2416 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2367 auto_rewrite = True
2417 auto_rewrite = True
2368
2418
2369 if pre == self.ESC_QUOTE:
2419 if pre == self.ESC_QUOTE:
2370 # Auto-quote splitting on whitespace
2420 # Auto-quote splitting on whitespace
2371 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2421 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2372 elif pre == self.ESC_QUOTE2:
2422 elif pre == self.ESC_QUOTE2:
2373 # Auto-quote whole string
2423 # Auto-quote whole string
2374 newcmd = '%s("%s")' % (iFun,theRest)
2424 newcmd = '%s("%s")' % (iFun,theRest)
2375 elif pre == self.ESC_PAREN:
2425 elif pre == self.ESC_PAREN:
2376 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2426 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2377 else:
2427 else:
2378 # Auto-paren.
2428 # Auto-paren.
2379 # We only apply it to argument-less calls if the autocall
2429 # We only apply it to argument-less calls if the autocall
2380 # parameter is set to 2. We only need to check that autocall is <
2430 # parameter is set to 2. We only need to check that autocall is <
2381 # 2, since this function isn't called unless it's at least 1.
2431 # 2, since this function isn't called unless it's at least 1.
2382 if not theRest and (self.rc.autocall < 2) and not force_auto:
2432 if not theRest and (self.rc.autocall < 2) and not force_auto:
2383 newcmd = '%s %s' % (iFun,theRest)
2433 newcmd = '%s %s' % (iFun,theRest)
2384 auto_rewrite = False
2434 auto_rewrite = False
2385 else:
2435 else:
2386 if not force_auto and theRest.startswith('['):
2436 if not force_auto and theRest.startswith('['):
2387 if hasattr(obj,'__getitem__'):
2437 if hasattr(obj,'__getitem__'):
2388 # Don't autocall in this case: item access for an object
2438 # Don't autocall in this case: item access for an object
2389 # which is BOTH callable and implements __getitem__.
2439 # which is BOTH callable and implements __getitem__.
2390 newcmd = '%s %s' % (iFun,theRest)
2440 newcmd = '%s %s' % (iFun,theRest)
2391 auto_rewrite = False
2441 auto_rewrite = False
2392 else:
2442 else:
2393 # if the object doesn't support [] access, go ahead and
2443 # if the object doesn't support [] access, go ahead and
2394 # autocall
2444 # autocall
2395 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2445 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2396 elif theRest.endswith(';'):
2446 elif theRest.endswith(';'):
2397 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2447 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2398 else:
2448 else:
2399 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2449 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2400
2450
2401 if auto_rewrite:
2451 if auto_rewrite:
2402 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2452 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2403
2453
2404 try:
2454 try:
2405 # plain ascii works better w/ pyreadline, on some machines, so
2455 # plain ascii works better w/ pyreadline, on some machines, so
2406 # we use it and only print uncolored rewrite if we have unicode
2456 # we use it and only print uncolored rewrite if we have unicode
2407 rw = str(rw)
2457 rw = str(rw)
2408 print >>Term.cout, rw
2458 print >>Term.cout, rw
2409 except UnicodeEncodeError:
2459 except UnicodeEncodeError:
2410 print "-------------->" + newcmd
2460 print "-------------->" + newcmd
2411
2461
2412 # log what is now valid Python, not the actual user input (without the
2462 # log what is now valid Python, not the actual user input (without the
2413 # final newline)
2463 # final newline)
2414 self.log(line,newcmd,continue_prompt)
2464 self.log(line,newcmd,continue_prompt)
2415 return newcmd
2465 return newcmd
2416
2466
2417 def handle_help(self, line_info):
2467 def handle_help(self, line_info):
2418 """Try to get some help for the object.
2468 """Try to get some help for the object.
2419
2469
2420 obj? or ?obj -> basic information.
2470 obj? or ?obj -> basic information.
2421 obj?? or ??obj -> more details.
2471 obj?? or ??obj -> more details.
2422 """
2472 """
2423
2473
2424 line = line_info.line
2474 line = line_info.line
2425 # We need to make sure that we don't process lines which would be
2475 # We need to make sure that we don't process lines which would be
2426 # otherwise valid python, such as "x=1 # what?"
2476 # otherwise valid python, such as "x=1 # what?"
2427 try:
2477 try:
2428 codeop.compile_command(line)
2478 codeop.compile_command(line)
2429 except SyntaxError:
2479 except SyntaxError:
2430 # We should only handle as help stuff which is NOT valid syntax
2480 # We should only handle as help stuff which is NOT valid syntax
2431 if line[0]==self.ESC_HELP:
2481 if line[0]==self.ESC_HELP:
2432 line = line[1:]
2482 line = line[1:]
2433 elif line[-1]==self.ESC_HELP:
2483 elif line[-1]==self.ESC_HELP:
2434 line = line[:-1]
2484 line = line[:-1]
2435 self.log(line,'#?'+line,line_info.continue_prompt)
2485 self.log(line,'#?'+line,line_info.continue_prompt)
2436 if line:
2486 if line:
2437 #print 'line:<%r>' % line # dbg
2487 #print 'line:<%r>' % line # dbg
2438 self.magic_pinfo(line)
2488 self.magic_pinfo(line)
2439 else:
2489 else:
2440 page(self.usage,screen_lines=self.rc.screen_length)
2490 page(self.usage,screen_lines=self.rc.screen_length)
2441 return '' # Empty string is needed here!
2491 return '' # Empty string is needed here!
2442 except:
2492 except:
2443 # Pass any other exceptions through to the normal handler
2493 # Pass any other exceptions through to the normal handler
2444 return self.handle_normal(line_info)
2494 return self.handle_normal(line_info)
2445 else:
2495 else:
2446 # If the code compiles ok, we should handle it normally
2496 # If the code compiles ok, we should handle it normally
2447 return self.handle_normal(line_info)
2497 return self.handle_normal(line_info)
2448
2498
2449 def getapi(self):
2499 def getapi(self):
2450 """ Get an IPApi object for this shell instance
2500 """ Get an IPApi object for this shell instance
2451
2501
2452 Getting an IPApi object is always preferable to accessing the shell
2502 Getting an IPApi object is always preferable to accessing the shell
2453 directly, but this holds true especially for extensions.
2503 directly, but this holds true especially for extensions.
2454
2504
2455 It should always be possible to implement an extension with IPApi
2505 It should always be possible to implement an extension with IPApi
2456 alone. If not, contact maintainer to request an addition.
2506 alone. If not, contact maintainer to request an addition.
2457
2507
2458 """
2508 """
2459 return self.api
2509 return self.api
2460
2510
2461 def handle_emacs(self, line_info):
2511 def handle_emacs(self, line_info):
2462 """Handle input lines marked by python-mode."""
2512 """Handle input lines marked by python-mode."""
2463
2513
2464 # Currently, nothing is done. Later more functionality can be added
2514 # Currently, nothing is done. Later more functionality can be added
2465 # here if needed.
2515 # here if needed.
2466
2516
2467 # The input cache shouldn't be updated
2517 # The input cache shouldn't be updated
2468 return line_info.line
2518 return line_info.line
2469
2519
2470
2520
2471 def mktempfile(self,data=None):
2521 def mktempfile(self,data=None):
2472 """Make a new tempfile and return its filename.
2522 """Make a new tempfile and return its filename.
2473
2523
2474 This makes a call to tempfile.mktemp, but it registers the created
2524 This makes a call to tempfile.mktemp, but it registers the created
2475 filename internally so ipython cleans it up at exit time.
2525 filename internally so ipython cleans it up at exit time.
2476
2526
2477 Optional inputs:
2527 Optional inputs:
2478
2528
2479 - data(None): if data is given, it gets written out to the temp file
2529 - data(None): if data is given, it gets written out to the temp file
2480 immediately, and the file is closed again."""
2530 immediately, and the file is closed again."""
2481
2531
2482 filename = tempfile.mktemp('.py','ipython_edit_')
2532 filename = tempfile.mktemp('.py','ipython_edit_')
2483 self.tempfiles.append(filename)
2533 self.tempfiles.append(filename)
2484
2534
2485 if data:
2535 if data:
2486 tmp_file = open(filename,'w')
2536 tmp_file = open(filename,'w')
2487 tmp_file.write(data)
2537 tmp_file.write(data)
2488 tmp_file.close()
2538 tmp_file.close()
2489 return filename
2539 return filename
2490
2540
2491 def write(self,data):
2541 def write(self,data):
2492 """Write a string to the default output"""
2542 """Write a string to the default output"""
2493 Term.cout.write(data)
2543 Term.cout.write(data)
2494
2544
2495 def write_err(self,data):
2545 def write_err(self,data):
2496 """Write a string to the default error output"""
2546 """Write a string to the default error output"""
2497 Term.cerr.write(data)
2547 Term.cerr.write(data)
2498
2548
2499 def ask_exit(self):
2549 def ask_exit(self):
2500 """ Call for exiting. Can be overiden and used as a callback. """
2550 """ Call for exiting. Can be overiden and used as a callback. """
2501 self.exit_now = True
2551 self.exit_now = True
2502
2552
2503 def exit(self):
2553 def exit(self):
2504 """Handle interactive exit.
2554 """Handle interactive exit.
2505
2555
2506 This method calls the ask_exit callback."""
2556 This method calls the ask_exit callback."""
2507
2557
2508 if self.rc.confirm_exit:
2558 if self.rc.confirm_exit:
2509 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2559 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2510 self.ask_exit()
2560 self.ask_exit()
2511 else:
2561 else:
2512 self.ask_exit()
2562 self.ask_exit()
2513
2563
2514 def safe_execfile(self,fname,*where,**kw):
2564 def safe_execfile(self,fname,*where,**kw):
2515 """A safe version of the builtin execfile().
2565 """A safe version of the builtin execfile().
2516
2566
2517 This version will never throw an exception, and knows how to handle
2567 This version will never throw an exception, and knows how to handle
2518 ipython logs as well.
2568 ipython logs as well.
2519
2569
2520 :Parameters:
2570 :Parameters:
2521 fname : string
2571 fname : string
2522 Name of the file to be executed.
2572 Name of the file to be executed.
2523
2573
2524 where : tuple
2574 where : tuple
2525 One or two namespaces, passed to execfile() as (globals,locals).
2575 One or two namespaces, passed to execfile() as (globals,locals).
2526 If only one is given, it is passed as both.
2576 If only one is given, it is passed as both.
2527
2577
2528 :Keywords:
2578 :Keywords:
2529 islog : boolean (False)
2579 islog : boolean (False)
2530
2580
2531 quiet : boolean (True)
2581 quiet : boolean (True)
2532
2582
2533 exit_ignore : boolean (False)
2583 exit_ignore : boolean (False)
2534 """
2584 """
2535
2585
2536 def syspath_cleanup():
2586 def syspath_cleanup():
2537 """Internal cleanup routine for sys.path."""
2587 """Internal cleanup routine for sys.path."""
2538 if add_dname:
2588 if add_dname:
2539 try:
2589 try:
2540 sys.path.remove(dname)
2590 sys.path.remove(dname)
2541 except ValueError:
2591 except ValueError:
2542 # For some reason the user has already removed it, ignore.
2592 # For some reason the user has already removed it, ignore.
2543 pass
2593 pass
2544
2594
2545 fname = os.path.expanduser(fname)
2595 fname = os.path.expanduser(fname)
2546
2596
2547 # Find things also in current directory. This is needed to mimic the
2597 # Find things also in current directory. This is needed to mimic the
2548 # behavior of running a script from the system command line, where
2598 # behavior of running a script from the system command line, where
2549 # Python inserts the script's directory into sys.path
2599 # Python inserts the script's directory into sys.path
2550 dname = os.path.dirname(os.path.abspath(fname))
2600 dname = os.path.dirname(os.path.abspath(fname))
2551 add_dname = False
2601 add_dname = False
2552 if dname not in sys.path:
2602 if dname not in sys.path:
2553 sys.path.insert(0,dname)
2603 sys.path.insert(0,dname)
2554 add_dname = True
2604 add_dname = True
2555
2605
2556 try:
2606 try:
2557 xfile = open(fname)
2607 xfile = open(fname)
2558 except:
2608 except:
2559 print >> Term.cerr, \
2609 print >> Term.cerr, \
2560 'Could not open file <%s> for safe execution.' % fname
2610 'Could not open file <%s> for safe execution.' % fname
2561 syspath_cleanup()
2611 syspath_cleanup()
2562 return None
2612 return None
2563
2613
2564 kw.setdefault('islog',0)
2614 kw.setdefault('islog',0)
2565 kw.setdefault('quiet',1)
2615 kw.setdefault('quiet',1)
2566 kw.setdefault('exit_ignore',0)
2616 kw.setdefault('exit_ignore',0)
2567
2617
2568 first = xfile.readline()
2618 first = xfile.readline()
2569 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2619 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2570 xfile.close()
2620 xfile.close()
2571 # line by line execution
2621 # line by line execution
2572 if first.startswith(loghead) or kw['islog']:
2622 if first.startswith(loghead) or kw['islog']:
2573 print 'Loading log file <%s> one line at a time...' % fname
2623 print 'Loading log file <%s> one line at a time...' % fname
2574 if kw['quiet']:
2624 if kw['quiet']:
2575 stdout_save = sys.stdout
2625 stdout_save = sys.stdout
2576 sys.stdout = StringIO.StringIO()
2626 sys.stdout = StringIO.StringIO()
2577 try:
2627 try:
2578 globs,locs = where[0:2]
2628 globs,locs = where[0:2]
2579 except:
2629 except:
2580 try:
2630 try:
2581 globs = locs = where[0]
2631 globs = locs = where[0]
2582 except:
2632 except:
2583 globs = locs = globals()
2633 globs = locs = globals()
2584 badblocks = []
2634 badblocks = []
2585
2635
2586 # we also need to identify indented blocks of code when replaying
2636 # we also need to identify indented blocks of code when replaying
2587 # logs and put them together before passing them to an exec
2637 # logs and put them together before passing them to an exec
2588 # statement. This takes a bit of regexp and look-ahead work in the
2638 # statement. This takes a bit of regexp and look-ahead work in the
2589 # file. It's easiest if we swallow the whole thing in memory
2639 # file. It's easiest if we swallow the whole thing in memory
2590 # first, and manually walk through the lines list moving the
2640 # first, and manually walk through the lines list moving the
2591 # counter ourselves.
2641 # counter ourselves.
2592 indent_re = re.compile('\s+\S')
2642 indent_re = re.compile('\s+\S')
2593 xfile = open(fname)
2643 xfile = open(fname)
2594 filelines = xfile.readlines()
2644 filelines = xfile.readlines()
2595 xfile.close()
2645 xfile.close()
2596 nlines = len(filelines)
2646 nlines = len(filelines)
2597 lnum = 0
2647 lnum = 0
2598 while lnum < nlines:
2648 while lnum < nlines:
2599 line = filelines[lnum]
2649 line = filelines[lnum]
2600 lnum += 1
2650 lnum += 1
2601 # don't re-insert logger status info into cache
2651 # don't re-insert logger status info into cache
2602 if line.startswith('#log#'):
2652 if line.startswith('#log#'):
2603 continue
2653 continue
2604 else:
2654 else:
2605 # build a block of code (maybe a single line) for execution
2655 # build a block of code (maybe a single line) for execution
2606 block = line
2656 block = line
2607 try:
2657 try:
2608 next = filelines[lnum] # lnum has already incremented
2658 next = filelines[lnum] # lnum has already incremented
2609 except:
2659 except:
2610 next = None
2660 next = None
2611 while next and indent_re.match(next):
2661 while next and indent_re.match(next):
2612 block += next
2662 block += next
2613 lnum += 1
2663 lnum += 1
2614 try:
2664 try:
2615 next = filelines[lnum]
2665 next = filelines[lnum]
2616 except:
2666 except:
2617 next = None
2667 next = None
2618 # now execute the block of one or more lines
2668 # now execute the block of one or more lines
2619 try:
2669 try:
2620 exec block in globs,locs
2670 exec block in globs,locs
2621 except SystemExit:
2671 except SystemExit:
2622 pass
2672 pass
2623 except:
2673 except:
2624 badblocks.append(block.rstrip())
2674 badblocks.append(block.rstrip())
2625 if kw['quiet']: # restore stdout
2675 if kw['quiet']: # restore stdout
2626 sys.stdout.close()
2676 sys.stdout.close()
2627 sys.stdout = stdout_save
2677 sys.stdout = stdout_save
2628 print 'Finished replaying log file <%s>' % fname
2678 print 'Finished replaying log file <%s>' % fname
2629 if badblocks:
2679 if badblocks:
2630 print >> sys.stderr, ('\nThe following lines/blocks in file '
2680 print >> sys.stderr, ('\nThe following lines/blocks in file '
2631 '<%s> reported errors:' % fname)
2681 '<%s> reported errors:' % fname)
2632
2682
2633 for badline in badblocks:
2683 for badline in badblocks:
2634 print >> sys.stderr, badline
2684 print >> sys.stderr, badline
2635 else: # regular file execution
2685 else: # regular file execution
2636 try:
2686 try:
2637 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2687 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2638 # Work around a bug in Python for Windows. The bug was
2688 # Work around a bug in Python for Windows. The bug was
2639 # fixed in in Python 2.5 r54159 and 54158, but that's still
2689 # fixed in in Python 2.5 r54159 and 54158, but that's still
2640 # SVN Python as of March/07. For details, see:
2690 # SVN Python as of March/07. For details, see:
2641 # http://projects.scipy.org/ipython/ipython/ticket/123
2691 # http://projects.scipy.org/ipython/ipython/ticket/123
2642 try:
2692 try:
2643 globs,locs = where[0:2]
2693 globs,locs = where[0:2]
2644 except:
2694 except:
2645 try:
2695 try:
2646 globs = locs = where[0]
2696 globs = locs = where[0]
2647 except:
2697 except:
2648 globs = locs = globals()
2698 globs = locs = globals()
2649 exec file(fname) in globs,locs
2699 exec file(fname) in globs,locs
2650 else:
2700 else:
2651 execfile(fname,*where)
2701 execfile(fname,*where)
2652 except SyntaxError:
2702 except SyntaxError:
2653 self.showsyntaxerror()
2703 self.showsyntaxerror()
2654 warn('Failure executing file: <%s>' % fname)
2704 warn('Failure executing file: <%s>' % fname)
2655 except SystemExit,status:
2705 except SystemExit,status:
2656 # Code that correctly sets the exit status flag to success (0)
2706 # Code that correctly sets the exit status flag to success (0)
2657 # shouldn't be bothered with a traceback. Note that a plain
2707 # shouldn't be bothered with a traceback. Note that a plain
2658 # sys.exit() does NOT set the message to 0 (it's empty) so that
2708 # sys.exit() does NOT set the message to 0 (it's empty) so that
2659 # will still get a traceback. Note that the structure of the
2709 # will still get a traceback. Note that the structure of the
2660 # SystemExit exception changed between Python 2.4 and 2.5, so
2710 # SystemExit exception changed between Python 2.4 and 2.5, so
2661 # the checks must be done in a version-dependent way.
2711 # the checks must be done in a version-dependent way.
2662 show = False
2712 show = False
2663
2713
2664 if sys.version_info[:2] > (2,5):
2714 if sys.version_info[:2] > (2,5):
2665 if status.message!=0 and not kw['exit_ignore']:
2715 if status.message!=0 and not kw['exit_ignore']:
2666 show = True
2716 show = True
2667 else:
2717 else:
2668 if status.code and not kw['exit_ignore']:
2718 if status.code and not kw['exit_ignore']:
2669 show = True
2719 show = True
2670 if show:
2720 if show:
2671 self.showtraceback()
2721 self.showtraceback()
2672 warn('Failure executing file: <%s>' % fname)
2722 warn('Failure executing file: <%s>' % fname)
2673 except:
2723 except:
2674 self.showtraceback()
2724 self.showtraceback()
2675 warn('Failure executing file: <%s>' % fname)
2725 warn('Failure executing file: <%s>' % fname)
2676
2726
2677 syspath_cleanup()
2727 syspath_cleanup()
2678
2728
2679 #************************* end of file <iplib.py> *****************************
2729 #************************* end of file <iplib.py> *****************************
@@ -1,6 +1,26 b''
1 """Simple script to instantiate a class for testing %run"""
1 """Simple script to instantiate a class for testing %run"""
2
2
3 import sys
4
5 # An external test will check that calls to f() work after %run
3 class foo: pass
6 class foo: pass
4
7
5 def f():
8 def f():
6 foo()
9 return foo()
10
11 # We also want to ensure that while objects remain available for immediate
12 # access, objects from *previous* runs of the same script get collected, to
13 # avoid accumulating massive amounts of old references.
14 class C(object):
15 def __init__(self,name):
16 self.name = name
17
18 def __del__(self):
19 print 'Deleting object:',self.name
20
21 try:
22 name = sys.argv[1]
23 except IndexError:
24 pass
25 else:
26 c = C(name)
@@ -1,115 +1,127 b''
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5
5
6 # Standard library imports
6 # Standard library imports
7 import os
7 import os
8 import sys
8 import sys
9
9
10 # Third-party imports
10 # Third-party imports
11 import nose.tools as nt
11 import nose.tools as nt
12
12
13 # From our own code
13 # From our own code
14 from IPython.testing import decorators as dec
14 from IPython.testing import decorators as dec
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Test functions begin
17 # Test functions begin
18
18
19 def test_rehashx():
19 def test_rehashx():
20 # clear up everything
20 # clear up everything
21 _ip.IP.alias_table.clear()
21 _ip.IP.alias_table.clear()
22 del _ip.db['syscmdlist']
22 del _ip.db['syscmdlist']
23
23
24 _ip.magic('rehashx')
24 _ip.magic('rehashx')
25 # Practically ALL ipython development systems will have more than 10 aliases
25 # Practically ALL ipython development systems will have more than 10 aliases
26
26
27 assert len(_ip.IP.alias_table) > 10
27 assert len(_ip.IP.alias_table) > 10
28 for key, val in _ip.IP.alias_table.items():
28 for key, val in _ip.IP.alias_table.items():
29 # we must strip dots from alias names
29 # we must strip dots from alias names
30 assert '.' not in key
30 assert '.' not in key
31
31
32 # rehashx must fill up syscmdlist
32 # rehashx must fill up syscmdlist
33 scoms = _ip.db['syscmdlist']
33 scoms = _ip.db['syscmdlist']
34 assert len(scoms) > 10
34 assert len(scoms) > 10
35
35
36
36
37 def doctest_run_ns():
37 def doctest_run_ns():
38 """Classes declared %run scripts must be instantiable afterwards.
38 """Classes declared %run scripts must be instantiable afterwards.
39
39
40 In [11]: run tclass
41
42 In [12]: isinstance(f(),foo)
43 Out[12]: True
44 """
45
46
47 def doctest_run_ns2():
48 """Classes declared %run scripts must be instantiable afterwards.
49
40 In [3]: run tclass.py
50 In [3]: run tclass.py
41
51
42 In [4]: f()
52 In [4]: run tclass first_pass
53
54 In [5]: run tclass second_pass
55 Deleting object: first_pass
43 """
56 """
44 pass # doctest only
45
57
46
58
47 def doctest_hist_f():
59 def doctest_hist_f():
48 """Test %hist -f with temporary filename.
60 """Test %hist -f with temporary filename.
49
61
50 In [9]: import tempfile
62 In [9]: import tempfile
51
63
52 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
64 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
53
65
54 In [11]: %history -n -f $tfile 3
66 In [11]: %history -n -f $tfile 3
55 """
67 """
56
68
57
69
58 def doctest_hist_r():
70 def doctest_hist_r():
59 """Test %hist -r
71 """Test %hist -r
60
72
61 XXX - This test is not recording the output correctly. Not sure why...
73 XXX - This test is not recording the output correctly. Not sure why...
62
74
63 In [6]: x=1
75 In [6]: x=1
64
76
65 In [7]: hist -n -r 2
77 In [7]: hist -n -r 2
66 x=1 # random
78 x=1 # random
67 hist -n -r 2 # random
79 hist -n -r 2 # random
68 """
80 """
69
81
70
82
71 def test_shist():
83 def test_shist():
72 # Simple tests of ShadowHist class - test generator.
84 # Simple tests of ShadowHist class - test generator.
73 import os, shutil, tempfile
85 import os, shutil, tempfile
74
86
75 from IPython.Extensions import pickleshare
87 from IPython.Extensions import pickleshare
76 from IPython.history import ShadowHist
88 from IPython.history import ShadowHist
77
89
78 tfile = tempfile.mktemp('','tmp-ipython-')
90 tfile = tempfile.mktemp('','tmp-ipython-')
79
91
80 db = pickleshare.PickleShareDB(tfile)
92 db = pickleshare.PickleShareDB(tfile)
81 s = ShadowHist(db)
93 s = ShadowHist(db)
82 s.add('hello')
94 s.add('hello')
83 s.add('world')
95 s.add('world')
84 s.add('hello')
96 s.add('hello')
85 s.add('hello')
97 s.add('hello')
86 s.add('karhu')
98 s.add('karhu')
87
99
88 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
100 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
89
101
90 yield nt.assert_equal,s.get(2),'world'
102 yield nt.assert_equal,s.get(2),'world'
91
103
92 shutil.rmtree(tfile)
104 shutil.rmtree(tfile)
93
105
94 @dec.skipif_not_numpy
106 @dec.skipif_not_numpy
95 def test_numpy_clear_array_undec():
107 def test_numpy_clear_array_undec():
96 _ip.ex('import numpy as np')
108 _ip.ex('import numpy as np')
97 _ip.ex('a = np.empty(2)')
109 _ip.ex('a = np.empty(2)')
98
110
99 yield nt.assert_true,'a' in _ip.user_ns
111 yield nt.assert_true,'a' in _ip.user_ns
100 _ip.magic('clear array')
112 _ip.magic('clear array')
101 yield nt.assert_false,'a' in _ip.user_ns
113 yield nt.assert_false,'a' in _ip.user_ns
102
114
103
115
104 @dec.skip()
116 @dec.skip()
105 def test_fail_dec(*a,**k):
117 def test_fail_dec(*a,**k):
106 yield nt.assert_true, False
118 yield nt.assert_true, False
107
119
108 @dec.skip('This one shouldn not run')
120 @dec.skip('This one shouldn not run')
109 def test_fail_dec2(*a,**k):
121 def test_fail_dec2(*a,**k):
110 yield nt.assert_true, False
122 yield nt.assert_true, False
111
123
112 @dec.skipknownfailure
124 @dec.skipknownfailure
113 def test_fail_dec3(*a,**k):
125 def test_fail_dec3(*a,**k):
114 yield nt.assert_true, False
126 yield nt.assert_true, False
115
127
General Comments 0
You need to be logged in to leave comments. Login now