##// END OF EJS Templates
- More fixes for doctest support....
fperez -
Show More

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

@@ -1,3219 +1,3231 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 2754 2007-09-09 10:16:59Z fperez $"""
4 $Id: Magic.py 2763 2007-09-14 06:35:44Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt,GetoptError
36 from getopt import getopt,GetoptError
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38 from sets import Set
38 from sets import Set
39
39
40 # cProfile was added in Python2.5
40 # cProfile was added in Python2.5
41 try:
41 try:
42 import cProfile as profile
42 import cProfile as profile
43 import pstats
43 import pstats
44 except ImportError:
44 except ImportError:
45 # profile isn't bundled by default in Debian for license reasons
45 # profile isn't bundled by default in Debian for license reasons
46 try:
46 try:
47 import profile,pstats
47 import profile,pstats
48 except ImportError:
48 except ImportError:
49 profile = pstats = None
49 profile = pstats = None
50
50
51 # Homebrewed
51 # Homebrewed
52 import IPython
52 import IPython
53 from IPython import Debugger, OInspect, wildcard
53 from IPython import Debugger, OInspect, wildcard
54 from IPython.FakeModule import FakeModule
54 from IPython.FakeModule import FakeModule
55 from IPython.Itpl import Itpl, itpl, printpl,itplns
55 from IPython.Itpl import Itpl, itpl, printpl,itplns
56 from IPython.PyColorize import Parser
56 from IPython.PyColorize import Parser
57 from IPython.ipstruct import Struct
57 from IPython.ipstruct import Struct
58 from IPython.macro import Macro
58 from IPython.macro import Macro
59 from IPython.genutils import *
59 from IPython.genutils import *
60 from IPython import platutils
60 from IPython import platutils
61 import IPython.generics
61 import IPython.generics
62 import IPython.ipapi
62 import IPython.ipapi
63 from IPython.ipapi import UsageError
63 from IPython.ipapi import UsageError
64 #***************************************************************************
64 #***************************************************************************
65 # Utility functions
65 # Utility functions
66 def on_off(tag):
66 def on_off(tag):
67 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
67 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
68 return ['OFF','ON'][tag]
68 return ['OFF','ON'][tag]
69
69
70 class Bunch: pass
70 class Bunch: pass
71
71
72 def compress_dhist(dh):
72 def compress_dhist(dh):
73 head, tail = dh[:-10], dh[-10:]
73 head, tail = dh[:-10], dh[-10:]
74
74
75 newhead = []
75 newhead = []
76 done = Set()
76 done = Set()
77 for h in head:
77 for h in head:
78 if h in done:
78 if h in done:
79 continue
79 continue
80 newhead.append(h)
80 newhead.append(h)
81 done.add(h)
81 done.add(h)
82
82
83 return newhead + tail
83 return newhead + tail
84
84
85
85
86 #***************************************************************************
86 #***************************************************************************
87 # Main class implementing Magic functionality
87 # Main class implementing Magic functionality
88 class Magic:
88 class Magic:
89 """Magic functions for InteractiveShell.
89 """Magic functions for InteractiveShell.
90
90
91 Shell functions which can be reached as %function_name. All magic
91 Shell functions which can be reached as %function_name. All magic
92 functions should accept a string, which they can parse for their own
92 functions should accept a string, which they can parse for their own
93 needs. This can make some functions easier to type, eg `%cd ../`
93 needs. This can make some functions easier to type, eg `%cd ../`
94 vs. `%cd("../")`
94 vs. `%cd("../")`
95
95
96 ALL definitions MUST begin with the prefix magic_. The user won't need it
96 ALL definitions MUST begin with the prefix magic_. The user won't need it
97 at the command line, but it is is needed in the definition. """
97 at the command line, but it is is needed in the definition. """
98
98
99 # class globals
99 # class globals
100 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
100 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
101 'Automagic is ON, % prefix NOT needed for magic functions.']
101 'Automagic is ON, % prefix NOT needed for magic functions.']
102
102
103 #......................................................................
103 #......................................................................
104 # some utility functions
104 # some utility functions
105
105
106 def __init__(self,shell):
106 def __init__(self,shell):
107
107
108 self.options_table = {}
108 self.options_table = {}
109 if profile is None:
109 if profile is None:
110 self.magic_prun = self.profile_missing_notice
110 self.magic_prun = self.profile_missing_notice
111 self.shell = shell
111 self.shell = shell
112
112
113 # namespace for holding state we may need
113 # namespace for holding state we may need
114 self._magic_state = Bunch()
114 self._magic_state = Bunch()
115
115
116 def profile_missing_notice(self, *args, **kwargs):
116 def profile_missing_notice(self, *args, **kwargs):
117 error("""\
117 error("""\
118 The profile module could not be found. If you are a Debian user,
118 The profile module could not be found. If you are a Debian user,
119 it has been removed from the standard Debian package because of its non-free
119 it has been removed from the standard Debian package because of its non-free
120 license. To use profiling, please install"python2.3-profiler" from non-free.""")
120 license. To use profiling, please install"python2.3-profiler" from non-free.""")
121
121
122 def default_option(self,fn,optstr):
122 def default_option(self,fn,optstr):
123 """Make an entry in the options_table for fn, with value optstr"""
123 """Make an entry in the options_table for fn, with value optstr"""
124
124
125 if fn not in self.lsmagic():
125 if fn not in self.lsmagic():
126 error("%s is not a magic function" % fn)
126 error("%s is not a magic function" % fn)
127 self.options_table[fn] = optstr
127 self.options_table[fn] = optstr
128
128
129 def lsmagic(self):
129 def lsmagic(self):
130 """Return a list of currently available magic functions.
130 """Return a list of currently available magic functions.
131
131
132 Gives a list of the bare names after mangling (['ls','cd', ...], not
132 Gives a list of the bare names after mangling (['ls','cd', ...], not
133 ['magic_ls','magic_cd',...]"""
133 ['magic_ls','magic_cd',...]"""
134
134
135 # FIXME. This needs a cleanup, in the way the magics list is built.
135 # FIXME. This needs a cleanup, in the way the magics list is built.
136
136
137 # magics in class definition
137 # magics in class definition
138 class_magic = lambda fn: fn.startswith('magic_') and \
138 class_magic = lambda fn: fn.startswith('magic_') and \
139 callable(Magic.__dict__[fn])
139 callable(Magic.__dict__[fn])
140 # in instance namespace (run-time user additions)
140 # in instance namespace (run-time user additions)
141 inst_magic = lambda fn: fn.startswith('magic_') and \
141 inst_magic = lambda fn: fn.startswith('magic_') and \
142 callable(self.__dict__[fn])
142 callable(self.__dict__[fn])
143 # and bound magics by user (so they can access self):
143 # and bound magics by user (so they can access self):
144 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
144 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
145 callable(self.__class__.__dict__[fn])
145 callable(self.__class__.__dict__[fn])
146 magics = filter(class_magic,Magic.__dict__.keys()) + \
146 magics = filter(class_magic,Magic.__dict__.keys()) + \
147 filter(inst_magic,self.__dict__.keys()) + \
147 filter(inst_magic,self.__dict__.keys()) + \
148 filter(inst_bound_magic,self.__class__.__dict__.keys())
148 filter(inst_bound_magic,self.__class__.__dict__.keys())
149 out = []
149 out = []
150 for fn in magics:
150 for fn in magics:
151 out.append(fn.replace('magic_','',1))
151 out.append(fn.replace('magic_','',1))
152 out.sort()
152 out.sort()
153 return out
153 return out
154
154
155 def extract_input_slices(self,slices,raw=False):
155 def extract_input_slices(self,slices,raw=False):
156 """Return as a string a set of input history slices.
156 """Return as a string a set of input history slices.
157
157
158 Inputs:
158 Inputs:
159
159
160 - slices: the set of slices is given as a list of strings (like
160 - slices: the set of slices is given as a list of strings (like
161 ['1','4:8','9'], since this function is for use by magic functions
161 ['1','4:8','9'], since this function is for use by magic functions
162 which get their arguments as strings.
162 which get their arguments as strings.
163
163
164 Optional inputs:
164 Optional inputs:
165
165
166 - raw(False): by default, the processed input is used. If this is
166 - raw(False): by default, the processed input is used. If this is
167 true, the raw input history is used instead.
167 true, the raw input history is used instead.
168
168
169 Note that slices can be called with two notations:
169 Note that slices can be called with two notations:
170
170
171 N:M -> standard python form, means including items N...(M-1).
171 N:M -> standard python form, means including items N...(M-1).
172
172
173 N-M -> include items N..M (closed endpoint)."""
173 N-M -> include items N..M (closed endpoint)."""
174
174
175 if raw:
175 if raw:
176 hist = self.shell.input_hist_raw
176 hist = self.shell.input_hist_raw
177 else:
177 else:
178 hist = self.shell.input_hist
178 hist = self.shell.input_hist
179
179
180 cmds = []
180 cmds = []
181 for chunk in slices:
181 for chunk in slices:
182 if ':' in chunk:
182 if ':' in chunk:
183 ini,fin = map(int,chunk.split(':'))
183 ini,fin = map(int,chunk.split(':'))
184 elif '-' in chunk:
184 elif '-' in chunk:
185 ini,fin = map(int,chunk.split('-'))
185 ini,fin = map(int,chunk.split('-'))
186 fin += 1
186 fin += 1
187 else:
187 else:
188 ini = int(chunk)
188 ini = int(chunk)
189 fin = ini+1
189 fin = ini+1
190 cmds.append(hist[ini:fin])
190 cmds.append(hist[ini:fin])
191 return cmds
191 return cmds
192
192
193 def _ofind(self, oname, namespaces=None):
193 def _ofind(self, oname, namespaces=None):
194 """Find an object in the available namespaces.
194 """Find an object in the available namespaces.
195
195
196 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
196 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
197
197
198 Has special code to detect magic functions.
198 Has special code to detect magic functions.
199 """
199 """
200
200
201 oname = oname.strip()
201 oname = oname.strip()
202
202
203 alias_ns = None
203 alias_ns = None
204 if namespaces is None:
204 if namespaces is None:
205 # Namespaces to search in:
205 # Namespaces to search in:
206 # Put them in a list. The order is important so that we
206 # Put them in a list. The order is important so that we
207 # find things in the same order that Python finds them.
207 # find things in the same order that Python finds them.
208 namespaces = [ ('Interactive', self.shell.user_ns),
208 namespaces = [ ('Interactive', self.shell.user_ns),
209 ('IPython internal', self.shell.internal_ns),
209 ('IPython internal', self.shell.internal_ns),
210 ('Python builtin', __builtin__.__dict__),
210 ('Python builtin', __builtin__.__dict__),
211 ('Alias', self.shell.alias_table),
211 ('Alias', self.shell.alias_table),
212 ]
212 ]
213 alias_ns = self.shell.alias_table
213 alias_ns = self.shell.alias_table
214
214
215 # initialize results to 'null'
215 # initialize results to 'null'
216 found = 0; obj = None; ospace = None; ds = None;
216 found = 0; obj = None; ospace = None; ds = None;
217 ismagic = 0; isalias = 0; parent = None
217 ismagic = 0; isalias = 0; parent = None
218
218
219 # Look for the given name by splitting it in parts. If the head is
219 # Look for the given name by splitting it in parts. If the head is
220 # found, then we look for all the remaining parts as members, and only
220 # found, then we look for all the remaining parts as members, and only
221 # declare success if we can find them all.
221 # declare success if we can find them all.
222 oname_parts = oname.split('.')
222 oname_parts = oname.split('.')
223 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
223 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
224 for nsname,ns in namespaces:
224 for nsname,ns in namespaces:
225 try:
225 try:
226 obj = ns[oname_head]
226 obj = ns[oname_head]
227 except KeyError:
227 except KeyError:
228 continue
228 continue
229 else:
229 else:
230 #print 'oname_rest:', oname_rest # dbg
230 #print 'oname_rest:', oname_rest # dbg
231 for part in oname_rest:
231 for part in oname_rest:
232 try:
232 try:
233 parent = obj
233 parent = obj
234 obj = getattr(obj,part)
234 obj = getattr(obj,part)
235 except:
235 except:
236 # Blanket except b/c some badly implemented objects
236 # Blanket except b/c some badly implemented objects
237 # allow __getattr__ to raise exceptions other than
237 # allow __getattr__ to raise exceptions other than
238 # AttributeError, which then crashes IPython.
238 # AttributeError, which then crashes IPython.
239 break
239 break
240 else:
240 else:
241 # If we finish the for loop (no break), we got all members
241 # If we finish the for loop (no break), we got all members
242 found = 1
242 found = 1
243 ospace = nsname
243 ospace = nsname
244 if ns == alias_ns:
244 if ns == alias_ns:
245 isalias = 1
245 isalias = 1
246 break # namespace loop
246 break # namespace loop
247
247
248 # Try to see if it's magic
248 # Try to see if it's magic
249 if not found:
249 if not found:
250 if oname.startswith(self.shell.ESC_MAGIC):
250 if oname.startswith(self.shell.ESC_MAGIC):
251 oname = oname[1:]
251 oname = oname[1:]
252 obj = getattr(self,'magic_'+oname,None)
252 obj = getattr(self,'magic_'+oname,None)
253 if obj is not None:
253 if obj is not None:
254 found = 1
254 found = 1
255 ospace = 'IPython internal'
255 ospace = 'IPython internal'
256 ismagic = 1
256 ismagic = 1
257
257
258 # Last try: special-case some literals like '', [], {}, etc:
258 # Last try: special-case some literals like '', [], {}, etc:
259 if not found and oname_head in ["''",'""','[]','{}','()']:
259 if not found and oname_head in ["''",'""','[]','{}','()']:
260 obj = eval(oname_head)
260 obj = eval(oname_head)
261 found = 1
261 found = 1
262 ospace = 'Interactive'
262 ospace = 'Interactive'
263
263
264 return {'found':found, 'obj':obj, 'namespace':ospace,
264 return {'found':found, 'obj':obj, 'namespace':ospace,
265 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
265 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
266
266
267 def arg_err(self,func):
267 def arg_err(self,func):
268 """Print docstring if incorrect arguments were passed"""
268 """Print docstring if incorrect arguments were passed"""
269 print 'Error in arguments:'
269 print 'Error in arguments:'
270 print OInspect.getdoc(func)
270 print OInspect.getdoc(func)
271
271
272 def format_latex(self,strng):
272 def format_latex(self,strng):
273 """Format a string for latex inclusion."""
273 """Format a string for latex inclusion."""
274
274
275 # Characters that need to be escaped for latex:
275 # Characters that need to be escaped for latex:
276 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
276 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
277 # Magic command names as headers:
277 # Magic command names as headers:
278 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
278 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
279 re.MULTILINE)
279 re.MULTILINE)
280 # Magic commands
280 # Magic commands
281 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
281 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
282 re.MULTILINE)
282 re.MULTILINE)
283 # Paragraph continue
283 # Paragraph continue
284 par_re = re.compile(r'\\$',re.MULTILINE)
284 par_re = re.compile(r'\\$',re.MULTILINE)
285
285
286 # The "\n" symbol
286 # The "\n" symbol
287 newline_re = re.compile(r'\\n')
287 newline_re = re.compile(r'\\n')
288
288
289 # Now build the string for output:
289 # Now build the string for output:
290 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
290 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
291 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
291 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
292 strng)
292 strng)
293 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
293 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
294 strng = par_re.sub(r'\\\\',strng)
294 strng = par_re.sub(r'\\\\',strng)
295 strng = escape_re.sub(r'\\\1',strng)
295 strng = escape_re.sub(r'\\\1',strng)
296 strng = newline_re.sub(r'\\textbackslash{}n',strng)
296 strng = newline_re.sub(r'\\textbackslash{}n',strng)
297 return strng
297 return strng
298
298
299 def format_screen(self,strng):
299 def format_screen(self,strng):
300 """Format a string for screen printing.
300 """Format a string for screen printing.
301
301
302 This removes some latex-type format codes."""
302 This removes some latex-type format codes."""
303 # Paragraph continue
303 # Paragraph continue
304 par_re = re.compile(r'\\$',re.MULTILINE)
304 par_re = re.compile(r'\\$',re.MULTILINE)
305 strng = par_re.sub('',strng)
305 strng = par_re.sub('',strng)
306 return strng
306 return strng
307
307
308 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
308 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
309 """Parse options passed to an argument string.
309 """Parse options passed to an argument string.
310
310
311 The interface is similar to that of getopt(), but it returns back a
311 The interface is similar to that of getopt(), but it returns back a
312 Struct with the options as keys and the stripped argument string still
312 Struct with the options as keys and the stripped argument string still
313 as a string.
313 as a string.
314
314
315 arg_str is quoted as a true sys.argv vector by using shlex.split.
315 arg_str is quoted as a true sys.argv vector by using shlex.split.
316 This allows us to easily expand variables, glob files, quote
316 This allows us to easily expand variables, glob files, quote
317 arguments, etc.
317 arguments, etc.
318
318
319 Options:
319 Options:
320 -mode: default 'string'. If given as 'list', the argument string is
320 -mode: default 'string'. If given as 'list', the argument string is
321 returned as a list (split on whitespace) instead of a string.
321 returned as a list (split on whitespace) instead of a string.
322
322
323 -list_all: put all option values in lists. Normally only options
323 -list_all: put all option values in lists. Normally only options
324 appearing more than once are put in a list.
324 appearing more than once are put in a list.
325
325
326 -posix (True): whether to split the input line in POSIX mode or not,
326 -posix (True): whether to split the input line in POSIX mode or not,
327 as per the conventions outlined in the shlex module from the
327 as per the conventions outlined in the shlex module from the
328 standard library."""
328 standard library."""
329
329
330 # inject default options at the beginning of the input line
330 # inject default options at the beginning of the input line
331 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
331 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
332 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
332 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
333
333
334 mode = kw.get('mode','string')
334 mode = kw.get('mode','string')
335 if mode not in ['string','list']:
335 if mode not in ['string','list']:
336 raise ValueError,'incorrect mode given: %s' % mode
336 raise ValueError,'incorrect mode given: %s' % mode
337 # Get options
337 # Get options
338 list_all = kw.get('list_all',0)
338 list_all = kw.get('list_all',0)
339 posix = kw.get('posix',True)
339 posix = kw.get('posix',True)
340
340
341 # Check if we have more than one argument to warrant extra processing:
341 # Check if we have more than one argument to warrant extra processing:
342 odict = {} # Dictionary with options
342 odict = {} # Dictionary with options
343 args = arg_str.split()
343 args = arg_str.split()
344 if len(args) >= 1:
344 if len(args) >= 1:
345 # If the list of inputs only has 0 or 1 thing in it, there's no
345 # If the list of inputs only has 0 or 1 thing in it, there's no
346 # need to look for options
346 # need to look for options
347 argv = arg_split(arg_str,posix)
347 argv = arg_split(arg_str,posix)
348 # Do regular option processing
348 # Do regular option processing
349 try:
349 try:
350 opts,args = getopt(argv,opt_str,*long_opts)
350 opts,args = getopt(argv,opt_str,*long_opts)
351 except GetoptError,e:
351 except GetoptError,e:
352 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
352 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
353 " ".join(long_opts)))
353 " ".join(long_opts)))
354 for o,a in opts:
354 for o,a in opts:
355 if o.startswith('--'):
355 if o.startswith('--'):
356 o = o[2:]
356 o = o[2:]
357 else:
357 else:
358 o = o[1:]
358 o = o[1:]
359 try:
359 try:
360 odict[o].append(a)
360 odict[o].append(a)
361 except AttributeError:
361 except AttributeError:
362 odict[o] = [odict[o],a]
362 odict[o] = [odict[o],a]
363 except KeyError:
363 except KeyError:
364 if list_all:
364 if list_all:
365 odict[o] = [a]
365 odict[o] = [a]
366 else:
366 else:
367 odict[o] = a
367 odict[o] = a
368
368
369 # Prepare opts,args for return
369 # Prepare opts,args for return
370 opts = Struct(odict)
370 opts = Struct(odict)
371 if mode == 'string':
371 if mode == 'string':
372 args = ' '.join(args)
372 args = ' '.join(args)
373
373
374 return opts,args
374 return opts,args
375
375
376 #......................................................................
376 #......................................................................
377 # And now the actual magic functions
377 # And now the actual magic functions
378
378
379 # Functions for IPython shell work (vars,funcs, config, etc)
379 # Functions for IPython shell work (vars,funcs, config, etc)
380 def magic_lsmagic(self, parameter_s = ''):
380 def magic_lsmagic(self, parameter_s = ''):
381 """List currently available magic functions."""
381 """List currently available magic functions."""
382 mesc = self.shell.ESC_MAGIC
382 mesc = self.shell.ESC_MAGIC
383 print 'Available magic functions:\n'+mesc+\
383 print 'Available magic functions:\n'+mesc+\
384 (' '+mesc).join(self.lsmagic())
384 (' '+mesc).join(self.lsmagic())
385 print '\n' + Magic.auto_status[self.shell.rc.automagic]
385 print '\n' + Magic.auto_status[self.shell.rc.automagic]
386 return None
386 return None
387
387
388 def magic_magic(self, parameter_s = ''):
388 def magic_magic(self, parameter_s = ''):
389 """Print information about the magic function system."""
389 """Print information about the magic function system."""
390
390
391 mode = ''
391 mode = ''
392 try:
392 try:
393 if parameter_s.split()[0] == '-latex':
393 if parameter_s.split()[0] == '-latex':
394 mode = 'latex'
394 mode = 'latex'
395 if parameter_s.split()[0] == '-brief':
395 if parameter_s.split()[0] == '-brief':
396 mode = 'brief'
396 mode = 'brief'
397 except:
397 except:
398 pass
398 pass
399
399
400 magic_docs = []
400 magic_docs = []
401 for fname in self.lsmagic():
401 for fname in self.lsmagic():
402 mname = 'magic_' + fname
402 mname = 'magic_' + fname
403 for space in (Magic,self,self.__class__):
403 for space in (Magic,self,self.__class__):
404 try:
404 try:
405 fn = space.__dict__[mname]
405 fn = space.__dict__[mname]
406 except KeyError:
406 except KeyError:
407 pass
407 pass
408 else:
408 else:
409 break
409 break
410 if mode == 'brief':
410 if mode == 'brief':
411 # only first line
411 # only first line
412 fndoc = fn.__doc__.split('\n',1)[0]
412 fndoc = fn.__doc__.split('\n',1)[0]
413 else:
413 else:
414 fndoc = fn.__doc__
414 fndoc = fn.__doc__
415
415
416 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
416 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
417 fname,fndoc))
417 fname,fndoc))
418 magic_docs = ''.join(magic_docs)
418 magic_docs = ''.join(magic_docs)
419
419
420 if mode == 'latex':
420 if mode == 'latex':
421 print self.format_latex(magic_docs)
421 print self.format_latex(magic_docs)
422 return
422 return
423 else:
423 else:
424 magic_docs = self.format_screen(magic_docs)
424 magic_docs = self.format_screen(magic_docs)
425 if mode == 'brief':
425 if mode == 'brief':
426 return magic_docs
426 return magic_docs
427
427
428 outmsg = """
428 outmsg = """
429 IPython's 'magic' functions
429 IPython's 'magic' functions
430 ===========================
430 ===========================
431
431
432 The magic function system provides a series of functions which allow you to
432 The magic function system provides a series of functions which allow you to
433 control the behavior of IPython itself, plus a lot of system-type
433 control the behavior of IPython itself, plus a lot of system-type
434 features. All these functions are prefixed with a % character, but parameters
434 features. All these functions are prefixed with a % character, but parameters
435 are given without parentheses or quotes.
435 are given without parentheses or quotes.
436
436
437 NOTE: If you have 'automagic' enabled (via the command line option or with the
437 NOTE: If you have 'automagic' enabled (via the command line option or with the
438 %automagic function), you don't need to type in the % explicitly. By default,
438 %automagic function), you don't need to type in the % explicitly. By default,
439 IPython ships with automagic on, so you should only rarely need the % escape.
439 IPython ships with automagic on, so you should only rarely need the % escape.
440
440
441 Example: typing '%cd mydir' (without the quotes) changes you working directory
441 Example: typing '%cd mydir' (without the quotes) changes you working directory
442 to 'mydir', if it exists.
442 to 'mydir', if it exists.
443
443
444 You can define your own magic functions to extend the system. See the supplied
444 You can define your own magic functions to extend the system. See the supplied
445 ipythonrc and example-magic.py files for details (in your ipython
445 ipythonrc and example-magic.py files for details (in your ipython
446 configuration directory, typically $HOME/.ipython/).
446 configuration directory, typically $HOME/.ipython/).
447
447
448 You can also define your own aliased names for magic functions. In your
448 You can also define your own aliased names for magic functions. In your
449 ipythonrc file, placing a line like:
449 ipythonrc file, placing a line like:
450
450
451 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
451 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
452
452
453 will define %pf as a new name for %profile.
453 will define %pf as a new name for %profile.
454
454
455 You can also call magics in code using the ipmagic() function, which IPython
455 You can also call magics in code using the ipmagic() function, which IPython
456 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
456 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
457
457
458 For a list of the available magic functions, use %lsmagic. For a description
458 For a list of the available magic functions, use %lsmagic. For a description
459 of any of them, type %magic_name?, e.g. '%cd?'.
459 of any of them, type %magic_name?, e.g. '%cd?'.
460
460
461 Currently the magic system has the following functions:\n"""
461 Currently the magic system has the following functions:\n"""
462
462
463 mesc = self.shell.ESC_MAGIC
463 mesc = self.shell.ESC_MAGIC
464 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
464 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
465 "\n\n%s%s\n\n%s" % (outmsg,
465 "\n\n%s%s\n\n%s" % (outmsg,
466 magic_docs,mesc,mesc,
466 magic_docs,mesc,mesc,
467 (' '+mesc).join(self.lsmagic()),
467 (' '+mesc).join(self.lsmagic()),
468 Magic.auto_status[self.shell.rc.automagic] ) )
468 Magic.auto_status[self.shell.rc.automagic] ) )
469
469
470 page(outmsg,screen_lines=self.shell.rc.screen_length)
470 page(outmsg,screen_lines=self.shell.rc.screen_length)
471
471
472
472
473 def magic_autoindent(self, parameter_s = ''):
473 def magic_autoindent(self, parameter_s = ''):
474 """Toggle autoindent on/off (if available)."""
474 """Toggle autoindent on/off (if available)."""
475
475
476 self.shell.set_autoindent()
476 self.shell.set_autoindent()
477 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
477 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
478
478
479
479
480 def magic_automagic(self, parameter_s = ''):
480 def magic_automagic(self, parameter_s = ''):
481 """Make magic functions callable without having to type the initial %.
481 """Make magic functions callable without having to type the initial %.
482
482
483 Without argumentsl toggles on/off (when off, you must call it as
483 Without argumentsl toggles on/off (when off, you must call it as
484 %automagic, of course). With arguments it sets the value, and you can
484 %automagic, of course). With arguments it sets the value, and you can
485 use any of (case insensitive):
485 use any of (case insensitive):
486
486
487 - on,1,True: to activate
487 - on,1,True: to activate
488
488
489 - off,0,False: to deactivate.
489 - off,0,False: to deactivate.
490
490
491 Note that magic functions have lowest priority, so if there's a
491 Note that magic functions have lowest priority, so if there's a
492 variable whose name collides with that of a magic fn, automagic won't
492 variable whose name collides with that of a magic fn, automagic won't
493 work for that function (you get the variable instead). However, if you
493 work for that function (you get the variable instead). However, if you
494 delete the variable (del var), the previously shadowed magic function
494 delete the variable (del var), the previously shadowed magic function
495 becomes visible to automagic again."""
495 becomes visible to automagic again."""
496
496
497 rc = self.shell.rc
497 rc = self.shell.rc
498 arg = parameter_s.lower()
498 arg = parameter_s.lower()
499 if parameter_s in ('on','1','true'):
499 if parameter_s in ('on','1','true'):
500 rc.automagic = True
500 rc.automagic = True
501 elif parameter_s in ('off','0','false'):
501 elif parameter_s in ('off','0','false'):
502 rc.automagic = False
502 rc.automagic = False
503 else:
503 else:
504 rc.automagic = not rc.automagic
504 rc.automagic = not rc.automagic
505 print '\n' + Magic.auto_status[rc.automagic]
505 print '\n' + Magic.auto_status[rc.automagic]
506
506
507
507
508 def magic_autocall(self, parameter_s = ''):
508 def magic_autocall(self, parameter_s = ''):
509 """Make functions callable without having to type parentheses.
509 """Make functions callable without having to type parentheses.
510
510
511 Usage:
511 Usage:
512
512
513 %autocall [mode]
513 %autocall [mode]
514
514
515 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
515 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
516 value is toggled on and off (remembering the previous state).
516 value is toggled on and off (remembering the previous state).
517
517
518 In more detail, these values mean:
518 In more detail, these values mean:
519
519
520 0 -> fully disabled
520 0 -> fully disabled
521
521
522 1 -> active, but do not apply if there are no arguments on the line.
522 1 -> active, but do not apply if there are no arguments on the line.
523
523
524 In this mode, you get:
524 In this mode, you get:
525
525
526 In [1]: callable
526 In [1]: callable
527 Out[1]: <built-in function callable>
527 Out[1]: <built-in function callable>
528
528
529 In [2]: callable 'hello'
529 In [2]: callable 'hello'
530 ------> callable('hello')
530 ------> callable('hello')
531 Out[2]: False
531 Out[2]: False
532
532
533 2 -> Active always. Even if no arguments are present, the callable
533 2 -> Active always. Even if no arguments are present, the callable
534 object is called:
534 object is called:
535
535
536 In [4]: callable
536 In [4]: callable
537 ------> callable()
537 ------> callable()
538
538
539 Note that even with autocall off, you can still use '/' at the start of
539 Note that even with autocall off, you can still use '/' at the start of
540 a line to treat the first argument on the command line as a function
540 a line to treat the first argument on the command line as a function
541 and add parentheses to it:
541 and add parentheses to it:
542
542
543 In [8]: /str 43
543 In [8]: /str 43
544 ------> str(43)
544 ------> str(43)
545 Out[8]: '43'
545 Out[8]: '43'
546 """
546 """
547
547
548 rc = self.shell.rc
548 rc = self.shell.rc
549
549
550 if parameter_s:
550 if parameter_s:
551 arg = int(parameter_s)
551 arg = int(parameter_s)
552 else:
552 else:
553 arg = 'toggle'
553 arg = 'toggle'
554
554
555 if not arg in (0,1,2,'toggle'):
555 if not arg in (0,1,2,'toggle'):
556 error('Valid modes: (0->Off, 1->Smart, 2->Full')
556 error('Valid modes: (0->Off, 1->Smart, 2->Full')
557 return
557 return
558
558
559 if arg in (0,1,2):
559 if arg in (0,1,2):
560 rc.autocall = arg
560 rc.autocall = arg
561 else: # toggle
561 else: # toggle
562 if rc.autocall:
562 if rc.autocall:
563 self._magic_state.autocall_save = rc.autocall
563 self._magic_state.autocall_save = rc.autocall
564 rc.autocall = 0
564 rc.autocall = 0
565 else:
565 else:
566 try:
566 try:
567 rc.autocall = self._magic_state.autocall_save
567 rc.autocall = self._magic_state.autocall_save
568 except AttributeError:
568 except AttributeError:
569 rc.autocall = self._magic_state.autocall_save = 1
569 rc.autocall = self._magic_state.autocall_save = 1
570
570
571 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
571 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
572
572
573 def magic_system_verbose(self, parameter_s = ''):
573 def magic_system_verbose(self, parameter_s = ''):
574 """Set verbose printing of system calls.
574 """Set verbose printing of system calls.
575
575
576 If called without an argument, act as a toggle"""
576 If called without an argument, act as a toggle"""
577
577
578 if parameter_s:
578 if parameter_s:
579 val = bool(eval(parameter_s))
579 val = bool(eval(parameter_s))
580 else:
580 else:
581 val = None
581 val = None
582
582
583 self.shell.rc_set_toggle('system_verbose',val)
583 self.shell.rc_set_toggle('system_verbose',val)
584 print "System verbose printing is:",\
584 print "System verbose printing is:",\
585 ['OFF','ON'][self.shell.rc.system_verbose]
585 ['OFF','ON'][self.shell.rc.system_verbose]
586
586
587
587
588 def magic_page(self, parameter_s=''):
588 def magic_page(self, parameter_s=''):
589 """Pretty print the object and display it through a pager.
589 """Pretty print the object and display it through a pager.
590
590
591 %page [options] OBJECT
591 %page [options] OBJECT
592
592
593 If no object is given, use _ (last output).
593 If no object is given, use _ (last output).
594
594
595 Options:
595 Options:
596
596
597 -r: page str(object), don't pretty-print it."""
597 -r: page str(object), don't pretty-print it."""
598
598
599 # After a function contributed by Olivier Aubert, slightly modified.
599 # After a function contributed by Olivier Aubert, slightly modified.
600
600
601 # Process options/args
601 # Process options/args
602 opts,args = self.parse_options(parameter_s,'r')
602 opts,args = self.parse_options(parameter_s,'r')
603 raw = 'r' in opts
603 raw = 'r' in opts
604
604
605 oname = args and args or '_'
605 oname = args and args or '_'
606 info = self._ofind(oname)
606 info = self._ofind(oname)
607 if info['found']:
607 if info['found']:
608 txt = (raw and str or pformat)( info['obj'] )
608 txt = (raw and str or pformat)( info['obj'] )
609 page(txt)
609 page(txt)
610 else:
610 else:
611 print 'Object `%s` not found' % oname
611 print 'Object `%s` not found' % oname
612
612
613 def magic_profile(self, parameter_s=''):
613 def magic_profile(self, parameter_s=''):
614 """Print your currently active IPyhton profile."""
614 """Print your currently active IPyhton profile."""
615 if self.shell.rc.profile:
615 if self.shell.rc.profile:
616 printpl('Current IPython profile: $self.shell.rc.profile.')
616 printpl('Current IPython profile: $self.shell.rc.profile.')
617 else:
617 else:
618 print 'No profile active.'
618 print 'No profile active.'
619
619
620 def magic_pinfo(self, parameter_s='', namespaces=None):
620 def magic_pinfo(self, parameter_s='', namespaces=None):
621 """Provide detailed information about an object.
621 """Provide detailed information about an object.
622
622
623 '%pinfo object' is just a synonym for object? or ?object."""
623 '%pinfo object' is just a synonym for object? or ?object."""
624
624
625 #print 'pinfo par: <%s>' % parameter_s # dbg
625 #print 'pinfo par: <%s>' % parameter_s # dbg
626
626
627
627
628 # detail_level: 0 -> obj? , 1 -> obj??
628 # detail_level: 0 -> obj? , 1 -> obj??
629 detail_level = 0
629 detail_level = 0
630 # We need to detect if we got called as 'pinfo pinfo foo', which can
630 # We need to detect if we got called as 'pinfo pinfo foo', which can
631 # happen if the user types 'pinfo foo?' at the cmd line.
631 # happen if the user types 'pinfo foo?' at the cmd line.
632 pinfo,qmark1,oname,qmark2 = \
632 pinfo,qmark1,oname,qmark2 = \
633 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
633 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
634 if pinfo or qmark1 or qmark2:
634 if pinfo or qmark1 or qmark2:
635 detail_level = 1
635 detail_level = 1
636 if "*" in oname:
636 if "*" in oname:
637 self.magic_psearch(oname)
637 self.magic_psearch(oname)
638 else:
638 else:
639 self._inspect('pinfo', oname, detail_level=detail_level,
639 self._inspect('pinfo', oname, detail_level=detail_level,
640 namespaces=namespaces)
640 namespaces=namespaces)
641
641
642 def magic_pdef(self, parameter_s='', namespaces=None):
642 def magic_pdef(self, parameter_s='', namespaces=None):
643 """Print the definition header for any callable object.
643 """Print the definition header for any callable object.
644
644
645 If the object is a class, print the constructor information."""
645 If the object is a class, print the constructor information."""
646 self._inspect('pdef',parameter_s, namespaces)
646 self._inspect('pdef',parameter_s, namespaces)
647
647
648 def magic_pdoc(self, parameter_s='', namespaces=None):
648 def magic_pdoc(self, parameter_s='', namespaces=None):
649 """Print the docstring for an object.
649 """Print the docstring for an object.
650
650
651 If the given object is a class, it will print both the class and the
651 If the given object is a class, it will print both the class and the
652 constructor docstrings."""
652 constructor docstrings."""
653 self._inspect('pdoc',parameter_s, namespaces)
653 self._inspect('pdoc',parameter_s, namespaces)
654
654
655 def magic_psource(self, parameter_s='', namespaces=None):
655 def magic_psource(self, parameter_s='', namespaces=None):
656 """Print (or run through pager) the source code for an object."""
656 """Print (or run through pager) the source code for an object."""
657 self._inspect('psource',parameter_s, namespaces)
657 self._inspect('psource',parameter_s, namespaces)
658
658
659 def magic_pfile(self, parameter_s=''):
659 def magic_pfile(self, parameter_s=''):
660 """Print (or run through pager) the file where an object is defined.
660 """Print (or run through pager) the file where an object is defined.
661
661
662 The file opens at the line where the object definition begins. IPython
662 The file opens at the line where the object definition begins. IPython
663 will honor the environment variable PAGER if set, and otherwise will
663 will honor the environment variable PAGER if set, and otherwise will
664 do its best to print the file in a convenient form.
664 do its best to print the file in a convenient form.
665
665
666 If the given argument is not an object currently defined, IPython will
666 If the given argument is not an object currently defined, IPython will
667 try to interpret it as a filename (automatically adding a .py extension
667 try to interpret it as a filename (automatically adding a .py extension
668 if needed). You can thus use %pfile as a syntax highlighting code
668 if needed). You can thus use %pfile as a syntax highlighting code
669 viewer."""
669 viewer."""
670
670
671 # first interpret argument as an object name
671 # first interpret argument as an object name
672 out = self._inspect('pfile',parameter_s)
672 out = self._inspect('pfile',parameter_s)
673 # if not, try the input as a filename
673 # if not, try the input as a filename
674 if out == 'not found':
674 if out == 'not found':
675 try:
675 try:
676 filename = get_py_filename(parameter_s)
676 filename = get_py_filename(parameter_s)
677 except IOError,msg:
677 except IOError,msg:
678 print msg
678 print msg
679 return
679 return
680 page(self.shell.inspector.format(file(filename).read()))
680 page(self.shell.inspector.format(file(filename).read()))
681
681
682 def _inspect(self,meth,oname,namespaces=None,**kw):
682 def _inspect(self,meth,oname,namespaces=None,**kw):
683 """Generic interface to the inspector system.
683 """Generic interface to the inspector system.
684
684
685 This function is meant to be called by pdef, pdoc & friends."""
685 This function is meant to be called by pdef, pdoc & friends."""
686
686
687 #oname = oname.strip()
687 #oname = oname.strip()
688 #print '1- oname: <%r>' % oname # dbg
688 #print '1- oname: <%r>' % oname # dbg
689 try:
689 try:
690 oname = oname.strip().encode('ascii')
690 oname = oname.strip().encode('ascii')
691 #print '2- oname: <%r>' % oname # dbg
691 #print '2- oname: <%r>' % oname # dbg
692 except UnicodeEncodeError:
692 except UnicodeEncodeError:
693 print 'Python identifiers can only contain ascii characters.'
693 print 'Python identifiers can only contain ascii characters.'
694 return 'not found'
694 return 'not found'
695
695
696 info = Struct(self._ofind(oname, namespaces))
696 info = Struct(self._ofind(oname, namespaces))
697
697
698 if info.found:
698 if info.found:
699 try:
699 try:
700 IPython.generics.inspect_object(info.obj)
700 IPython.generics.inspect_object(info.obj)
701 return
701 return
702 except IPython.ipapi.TryNext:
702 except IPython.ipapi.TryNext:
703 pass
703 pass
704 # Get the docstring of the class property if it exists.
704 # Get the docstring of the class property if it exists.
705 path = oname.split('.')
705 path = oname.split('.')
706 root = '.'.join(path[:-1])
706 root = '.'.join(path[:-1])
707 if info.parent is not None:
707 if info.parent is not None:
708 try:
708 try:
709 target = getattr(info.parent, '__class__')
709 target = getattr(info.parent, '__class__')
710 # The object belongs to a class instance.
710 # The object belongs to a class instance.
711 try:
711 try:
712 target = getattr(target, path[-1])
712 target = getattr(target, path[-1])
713 # The class defines the object.
713 # The class defines the object.
714 if isinstance(target, property):
714 if isinstance(target, property):
715 oname = root + '.__class__.' + path[-1]
715 oname = root + '.__class__.' + path[-1]
716 info = Struct(self._ofind(oname))
716 info = Struct(self._ofind(oname))
717 except AttributeError: pass
717 except AttributeError: pass
718 except AttributeError: pass
718 except AttributeError: pass
719
719
720 pmethod = getattr(self.shell.inspector,meth)
720 pmethod = getattr(self.shell.inspector,meth)
721 formatter = info.ismagic and self.format_screen or None
721 formatter = info.ismagic and self.format_screen or None
722 if meth == 'pdoc':
722 if meth == 'pdoc':
723 pmethod(info.obj,oname,formatter)
723 pmethod(info.obj,oname,formatter)
724 elif meth == 'pinfo':
724 elif meth == 'pinfo':
725 pmethod(info.obj,oname,formatter,info,**kw)
725 pmethod(info.obj,oname,formatter,info,**kw)
726 else:
726 else:
727 pmethod(info.obj,oname)
727 pmethod(info.obj,oname)
728 else:
728 else:
729 print 'Object `%s` not found.' % oname
729 print 'Object `%s` not found.' % oname
730 return 'not found' # so callers can take other action
730 return 'not found' # so callers can take other action
731
731
732 def magic_psearch(self, parameter_s=''):
732 def magic_psearch(self, parameter_s=''):
733 """Search for object in namespaces by wildcard.
733 """Search for object in namespaces by wildcard.
734
734
735 %psearch [options] PATTERN [OBJECT TYPE]
735 %psearch [options] PATTERN [OBJECT TYPE]
736
736
737 Note: ? can be used as a synonym for %psearch, at the beginning or at
737 Note: ? can be used as a synonym for %psearch, at the beginning or at
738 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
738 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
739 rest of the command line must be unchanged (options come first), so
739 rest of the command line must be unchanged (options come first), so
740 for example the following forms are equivalent
740 for example the following forms are equivalent
741
741
742 %psearch -i a* function
742 %psearch -i a* function
743 -i a* function?
743 -i a* function?
744 ?-i a* function
744 ?-i a* function
745
745
746 Arguments:
746 Arguments:
747
747
748 PATTERN
748 PATTERN
749
749
750 where PATTERN is a string containing * as a wildcard similar to its
750 where PATTERN is a string containing * as a wildcard similar to its
751 use in a shell. The pattern is matched in all namespaces on the
751 use in a shell. The pattern is matched in all namespaces on the
752 search path. By default objects starting with a single _ are not
752 search path. By default objects starting with a single _ are not
753 matched, many IPython generated objects have a single
753 matched, many IPython generated objects have a single
754 underscore. The default is case insensitive matching. Matching is
754 underscore. The default is case insensitive matching. Matching is
755 also done on the attributes of objects and not only on the objects
755 also done on the attributes of objects and not only on the objects
756 in a module.
756 in a module.
757
757
758 [OBJECT TYPE]
758 [OBJECT TYPE]
759
759
760 Is the name of a python type from the types module. The name is
760 Is the name of a python type from the types module. The name is
761 given in lowercase without the ending type, ex. StringType is
761 given in lowercase without the ending type, ex. StringType is
762 written string. By adding a type here only objects matching the
762 written string. By adding a type here only objects matching the
763 given type are matched. Using all here makes the pattern match all
763 given type are matched. Using all here makes the pattern match all
764 types (this is the default).
764 types (this is the default).
765
765
766 Options:
766 Options:
767
767
768 -a: makes the pattern match even objects whose names start with a
768 -a: makes the pattern match even objects whose names start with a
769 single underscore. These names are normally ommitted from the
769 single underscore. These names are normally ommitted from the
770 search.
770 search.
771
771
772 -i/-c: make the pattern case insensitive/sensitive. If neither of
772 -i/-c: make the pattern case insensitive/sensitive. If neither of
773 these options is given, the default is read from your ipythonrc
773 these options is given, the default is read from your ipythonrc
774 file. The option name which sets this value is
774 file. The option name which sets this value is
775 'wildcards_case_sensitive'. If this option is not specified in your
775 'wildcards_case_sensitive'. If this option is not specified in your
776 ipythonrc file, IPython's internal default is to do a case sensitive
776 ipythonrc file, IPython's internal default is to do a case sensitive
777 search.
777 search.
778
778
779 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
779 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
780 specifiy can be searched in any of the following namespaces:
780 specifiy can be searched in any of the following namespaces:
781 'builtin', 'user', 'user_global','internal', 'alias', where
781 'builtin', 'user', 'user_global','internal', 'alias', where
782 'builtin' and 'user' are the search defaults. Note that you should
782 'builtin' and 'user' are the search defaults. Note that you should
783 not use quotes when specifying namespaces.
783 not use quotes when specifying namespaces.
784
784
785 'Builtin' contains the python module builtin, 'user' contains all
785 'Builtin' contains the python module builtin, 'user' contains all
786 user data, 'alias' only contain the shell aliases and no python
786 user data, 'alias' only contain the shell aliases and no python
787 objects, 'internal' contains objects used by IPython. The
787 objects, 'internal' contains objects used by IPython. The
788 'user_global' namespace is only used by embedded IPython instances,
788 'user_global' namespace is only used by embedded IPython instances,
789 and it contains module-level globals. You can add namespaces to the
789 and it contains module-level globals. You can add namespaces to the
790 search with -s or exclude them with -e (these options can be given
790 search with -s or exclude them with -e (these options can be given
791 more than once).
791 more than once).
792
792
793 Examples:
793 Examples:
794
794
795 %psearch a* -> objects beginning with an a
795 %psearch a* -> objects beginning with an a
796 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
796 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
797 %psearch a* function -> all functions beginning with an a
797 %psearch a* function -> all functions beginning with an a
798 %psearch re.e* -> objects beginning with an e in module re
798 %psearch re.e* -> objects beginning with an e in module re
799 %psearch r*.e* -> objects that start with e in modules starting in r
799 %psearch r*.e* -> objects that start with e in modules starting in r
800 %psearch r*.* string -> all strings in modules beginning with r
800 %psearch r*.* string -> all strings in modules beginning with r
801
801
802 Case sensitve search:
802 Case sensitve search:
803
803
804 %psearch -c a* list all object beginning with lower case a
804 %psearch -c a* list all object beginning with lower case a
805
805
806 Show objects beginning with a single _:
806 Show objects beginning with a single _:
807
807
808 %psearch -a _* list objects beginning with a single underscore"""
808 %psearch -a _* list objects beginning with a single underscore"""
809 try:
809 try:
810 parameter_s = parameter_s.encode('ascii')
810 parameter_s = parameter_s.encode('ascii')
811 except UnicodeEncodeError:
811 except UnicodeEncodeError:
812 print 'Python identifiers can only contain ascii characters.'
812 print 'Python identifiers can only contain ascii characters.'
813 return
813 return
814
814
815 # default namespaces to be searched
815 # default namespaces to be searched
816 def_search = ['user','builtin']
816 def_search = ['user','builtin']
817
817
818 # Process options/args
818 # Process options/args
819 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
819 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
820 opt = opts.get
820 opt = opts.get
821 shell = self.shell
821 shell = self.shell
822 psearch = shell.inspector.psearch
822 psearch = shell.inspector.psearch
823
823
824 # select case options
824 # select case options
825 if opts.has_key('i'):
825 if opts.has_key('i'):
826 ignore_case = True
826 ignore_case = True
827 elif opts.has_key('c'):
827 elif opts.has_key('c'):
828 ignore_case = False
828 ignore_case = False
829 else:
829 else:
830 ignore_case = not shell.rc.wildcards_case_sensitive
830 ignore_case = not shell.rc.wildcards_case_sensitive
831
831
832 # Build list of namespaces to search from user options
832 # Build list of namespaces to search from user options
833 def_search.extend(opt('s',[]))
833 def_search.extend(opt('s',[]))
834 ns_exclude = ns_exclude=opt('e',[])
834 ns_exclude = ns_exclude=opt('e',[])
835 ns_search = [nm for nm in def_search if nm not in ns_exclude]
835 ns_search = [nm for nm in def_search if nm not in ns_exclude]
836
836
837 # Call the actual search
837 # Call the actual search
838 try:
838 try:
839 psearch(args,shell.ns_table,ns_search,
839 psearch(args,shell.ns_table,ns_search,
840 show_all=opt('a'),ignore_case=ignore_case)
840 show_all=opt('a'),ignore_case=ignore_case)
841 except:
841 except:
842 shell.showtraceback()
842 shell.showtraceback()
843
843
844 def magic_who_ls(self, parameter_s=''):
844 def magic_who_ls(self, parameter_s=''):
845 """Return a sorted list of all interactive variables.
845 """Return a sorted list of all interactive variables.
846
846
847 If arguments are given, only variables of types matching these
847 If arguments are given, only variables of types matching these
848 arguments are returned."""
848 arguments are returned."""
849
849
850 user_ns = self.shell.user_ns
850 user_ns = self.shell.user_ns
851 internal_ns = self.shell.internal_ns
851 internal_ns = self.shell.internal_ns
852 user_config_ns = self.shell.user_config_ns
852 user_config_ns = self.shell.user_config_ns
853 out = []
853 out = []
854 typelist = parameter_s.split()
854 typelist = parameter_s.split()
855
855
856 for i in user_ns:
856 for i in user_ns:
857 if not (i.startswith('_') or i.startswith('_i')) \
857 if not (i.startswith('_') or i.startswith('_i')) \
858 and not (i in internal_ns or i in user_config_ns):
858 and not (i in internal_ns or i in user_config_ns):
859 if typelist:
859 if typelist:
860 if type(user_ns[i]).__name__ in typelist:
860 if type(user_ns[i]).__name__ in typelist:
861 out.append(i)
861 out.append(i)
862 else:
862 else:
863 out.append(i)
863 out.append(i)
864 out.sort()
864 out.sort()
865 return out
865 return out
866
866
867 def magic_who(self, parameter_s=''):
867 def magic_who(self, parameter_s=''):
868 """Print all interactive variables, with some minimal formatting.
868 """Print all interactive variables, with some minimal formatting.
869
869
870 If any arguments are given, only variables whose type matches one of
870 If any arguments are given, only variables whose type matches one of
871 these are printed. For example:
871 these are printed. For example:
872
872
873 %who function str
873 %who function str
874
874
875 will only list functions and strings, excluding all other types of
875 will only list functions and strings, excluding all other types of
876 variables. To find the proper type names, simply use type(var) at a
876 variables. To find the proper type names, simply use type(var) at a
877 command line to see how python prints type names. For example:
877 command line to see how python prints type names. For example:
878
878
879 In [1]: type('hello')\\
879 In [1]: type('hello')\\
880 Out[1]: <type 'str'>
880 Out[1]: <type 'str'>
881
881
882 indicates that the type name for strings is 'str'.
882 indicates that the type name for strings is 'str'.
883
883
884 %who always excludes executed names loaded through your configuration
884 %who always excludes executed names loaded through your configuration
885 file and things which are internal to IPython.
885 file and things which are internal to IPython.
886
886
887 This is deliberate, as typically you may load many modules and the
887 This is deliberate, as typically you may load many modules and the
888 purpose of %who is to show you only what you've manually defined."""
888 purpose of %who is to show you only what you've manually defined."""
889
889
890 varlist = self.magic_who_ls(parameter_s)
890 varlist = self.magic_who_ls(parameter_s)
891 if not varlist:
891 if not varlist:
892 if parameter_s:
892 if parameter_s:
893 print 'No variables match your requested type.'
893 print 'No variables match your requested type.'
894 else:
894 else:
895 print 'Interactive namespace is empty.'
895 print 'Interactive namespace is empty.'
896 return
896 return
897
897
898 # if we have variables, move on...
898 # if we have variables, move on...
899 count = 0
899 count = 0
900 for i in varlist:
900 for i in varlist:
901 print i+'\t',
901 print i+'\t',
902 count += 1
902 count += 1
903 if count > 8:
903 if count > 8:
904 count = 0
904 count = 0
905 print
905 print
906 print
906 print
907
907
908 def magic_whos(self, parameter_s=''):
908 def magic_whos(self, parameter_s=''):
909 """Like %who, but gives some extra information about each variable.
909 """Like %who, but gives some extra information about each variable.
910
910
911 The same type filtering of %who can be applied here.
911 The same type filtering of %who can be applied here.
912
912
913 For all variables, the type is printed. Additionally it prints:
913 For all variables, the type is printed. Additionally it prints:
914
914
915 - For {},[],(): their length.
915 - For {},[],(): their length.
916
916
917 - For numpy and Numeric arrays, a summary with shape, number of
917 - For numpy and Numeric arrays, a summary with shape, number of
918 elements, typecode and size in memory.
918 elements, typecode and size in memory.
919
919
920 - Everything else: a string representation, snipping their middle if
920 - Everything else: a string representation, snipping their middle if
921 too long."""
921 too long."""
922
922
923 varnames = self.magic_who_ls(parameter_s)
923 varnames = self.magic_who_ls(parameter_s)
924 if not varnames:
924 if not varnames:
925 if parameter_s:
925 if parameter_s:
926 print 'No variables match your requested type.'
926 print 'No variables match your requested type.'
927 else:
927 else:
928 print 'Interactive namespace is empty.'
928 print 'Interactive namespace is empty.'
929 return
929 return
930
930
931 # if we have variables, move on...
931 # if we have variables, move on...
932
932
933 # for these types, show len() instead of data:
933 # for these types, show len() instead of data:
934 seq_types = [types.DictType,types.ListType,types.TupleType]
934 seq_types = [types.DictType,types.ListType,types.TupleType]
935
935
936 # for numpy/Numeric arrays, display summary info
936 # for numpy/Numeric arrays, display summary info
937 try:
937 try:
938 import numpy
938 import numpy
939 except ImportError:
939 except ImportError:
940 ndarray_type = None
940 ndarray_type = None
941 else:
941 else:
942 ndarray_type = numpy.ndarray.__name__
942 ndarray_type = numpy.ndarray.__name__
943 try:
943 try:
944 import Numeric
944 import Numeric
945 except ImportError:
945 except ImportError:
946 array_type = None
946 array_type = None
947 else:
947 else:
948 array_type = Numeric.ArrayType.__name__
948 array_type = Numeric.ArrayType.__name__
949
949
950 # Find all variable names and types so we can figure out column sizes
950 # Find all variable names and types so we can figure out column sizes
951 def get_vars(i):
951 def get_vars(i):
952 return self.shell.user_ns[i]
952 return self.shell.user_ns[i]
953
953
954 # some types are well known and can be shorter
954 # some types are well known and can be shorter
955 abbrevs = {'IPython.macro.Macro' : 'Macro'}
955 abbrevs = {'IPython.macro.Macro' : 'Macro'}
956 def type_name(v):
956 def type_name(v):
957 tn = type(v).__name__
957 tn = type(v).__name__
958 return abbrevs.get(tn,tn)
958 return abbrevs.get(tn,tn)
959
959
960 varlist = map(get_vars,varnames)
960 varlist = map(get_vars,varnames)
961
961
962 typelist = []
962 typelist = []
963 for vv in varlist:
963 for vv in varlist:
964 tt = type_name(vv)
964 tt = type_name(vv)
965
965
966 if tt=='instance':
966 if tt=='instance':
967 typelist.append( abbrevs.get(str(vv.__class__),
967 typelist.append( abbrevs.get(str(vv.__class__),
968 str(vv.__class__)))
968 str(vv.__class__)))
969 else:
969 else:
970 typelist.append(tt)
970 typelist.append(tt)
971
971
972 # column labels and # of spaces as separator
972 # column labels and # of spaces as separator
973 varlabel = 'Variable'
973 varlabel = 'Variable'
974 typelabel = 'Type'
974 typelabel = 'Type'
975 datalabel = 'Data/Info'
975 datalabel = 'Data/Info'
976 colsep = 3
976 colsep = 3
977 # variable format strings
977 # variable format strings
978 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
978 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
979 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
979 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
980 aformat = "%s: %s elems, type `%s`, %s bytes"
980 aformat = "%s: %s elems, type `%s`, %s bytes"
981 # find the size of the columns to format the output nicely
981 # find the size of the columns to format the output nicely
982 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
982 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
983 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
983 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
984 # table header
984 # table header
985 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
985 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
986 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
986 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
987 # and the table itself
987 # and the table itself
988 kb = 1024
988 kb = 1024
989 Mb = 1048576 # kb**2
989 Mb = 1048576 # kb**2
990 for vname,var,vtype in zip(varnames,varlist,typelist):
990 for vname,var,vtype in zip(varnames,varlist,typelist):
991 print itpl(vformat),
991 print itpl(vformat),
992 if vtype in seq_types:
992 if vtype in seq_types:
993 print len(var)
993 print len(var)
994 elif vtype in [array_type,ndarray_type]:
994 elif vtype in [array_type,ndarray_type]:
995 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
995 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
996 if vtype==ndarray_type:
996 if vtype==ndarray_type:
997 # numpy
997 # numpy
998 vsize = var.size
998 vsize = var.size
999 vbytes = vsize*var.itemsize
999 vbytes = vsize*var.itemsize
1000 vdtype = var.dtype
1000 vdtype = var.dtype
1001 else:
1001 else:
1002 # Numeric
1002 # Numeric
1003 vsize = Numeric.size(var)
1003 vsize = Numeric.size(var)
1004 vbytes = vsize*var.itemsize()
1004 vbytes = vsize*var.itemsize()
1005 vdtype = var.typecode()
1005 vdtype = var.typecode()
1006
1006
1007 if vbytes < 100000:
1007 if vbytes < 100000:
1008 print aformat % (vshape,vsize,vdtype,vbytes)
1008 print aformat % (vshape,vsize,vdtype,vbytes)
1009 else:
1009 else:
1010 print aformat % (vshape,vsize,vdtype,vbytes),
1010 print aformat % (vshape,vsize,vdtype,vbytes),
1011 if vbytes < Mb:
1011 if vbytes < Mb:
1012 print '(%s kb)' % (vbytes/kb,)
1012 print '(%s kb)' % (vbytes/kb,)
1013 else:
1013 else:
1014 print '(%s Mb)' % (vbytes/Mb,)
1014 print '(%s Mb)' % (vbytes/Mb,)
1015 else:
1015 else:
1016 try:
1016 try:
1017 vstr = str(var)
1017 vstr = str(var)
1018 except UnicodeEncodeError:
1018 except UnicodeEncodeError:
1019 vstr = unicode(var).encode(sys.getdefaultencoding(),
1019 vstr = unicode(var).encode(sys.getdefaultencoding(),
1020 'backslashreplace')
1020 'backslashreplace')
1021 vstr = vstr.replace('\n','\\n')
1021 vstr = vstr.replace('\n','\\n')
1022 if len(vstr) < 50:
1022 if len(vstr) < 50:
1023 print vstr
1023 print vstr
1024 else:
1024 else:
1025 printpl(vfmt_short)
1025 printpl(vfmt_short)
1026
1026
1027 def magic_reset(self, parameter_s=''):
1027 def magic_reset(self, parameter_s=''):
1028 """Resets the namespace by removing all names defined by the user.
1028 """Resets the namespace by removing all names defined by the user.
1029
1029
1030 Input/Output history are left around in case you need them."""
1030 Input/Output history are left around in case you need them."""
1031
1031
1032 ans = self.shell.ask_yes_no(
1032 ans = self.shell.ask_yes_no(
1033 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1033 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1034 if not ans:
1034 if not ans:
1035 print 'Nothing done.'
1035 print 'Nothing done.'
1036 return
1036 return
1037 user_ns = self.shell.user_ns
1037 user_ns = self.shell.user_ns
1038 for i in self.magic_who_ls():
1038 for i in self.magic_who_ls():
1039 del(user_ns[i])
1039 del(user_ns[i])
1040
1041 # Also flush the private list of module references kept for script
1042 # execution protection
1043 self.shell._user_main_modules[:] = []
1040
1044
1041 def magic_logstart(self,parameter_s=''):
1045 def magic_logstart(self,parameter_s=''):
1042 """Start logging anywhere in a session.
1046 """Start logging anywhere in a session.
1043
1047
1044 %logstart [-o|-r|-t] [log_name [log_mode]]
1048 %logstart [-o|-r|-t] [log_name [log_mode]]
1045
1049
1046 If no name is given, it defaults to a file named 'ipython_log.py' in your
1050 If no name is given, it defaults to a file named 'ipython_log.py' in your
1047 current directory, in 'rotate' mode (see below).
1051 current directory, in 'rotate' mode (see below).
1048
1052
1049 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1053 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1050 history up to that point and then continues logging.
1054 history up to that point and then continues logging.
1051
1055
1052 %logstart takes a second optional parameter: logging mode. This can be one
1056 %logstart takes a second optional parameter: logging mode. This can be one
1053 of (note that the modes are given unquoted):\\
1057 of (note that the modes are given unquoted):\\
1054 append: well, that says it.\\
1058 append: well, that says it.\\
1055 backup: rename (if exists) to name~ and start name.\\
1059 backup: rename (if exists) to name~ and start name.\\
1056 global: single logfile in your home dir, appended to.\\
1060 global: single logfile in your home dir, appended to.\\
1057 over : overwrite existing log.\\
1061 over : overwrite existing log.\\
1058 rotate: create rotating logs name.1~, name.2~, etc.
1062 rotate: create rotating logs name.1~, name.2~, etc.
1059
1063
1060 Options:
1064 Options:
1061
1065
1062 -o: log also IPython's output. In this mode, all commands which
1066 -o: log also IPython's output. In this mode, all commands which
1063 generate an Out[NN] prompt are recorded to the logfile, right after
1067 generate an Out[NN] prompt are recorded to the logfile, right after
1064 their corresponding input line. The output lines are always
1068 their corresponding input line. The output lines are always
1065 prepended with a '#[Out]# ' marker, so that the log remains valid
1069 prepended with a '#[Out]# ' marker, so that the log remains valid
1066 Python code.
1070 Python code.
1067
1071
1068 Since this marker is always the same, filtering only the output from
1072 Since this marker is always the same, filtering only the output from
1069 a log is very easy, using for example a simple awk call:
1073 a log is very easy, using for example a simple awk call:
1070
1074
1071 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1075 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1072
1076
1073 -r: log 'raw' input. Normally, IPython's logs contain the processed
1077 -r: log 'raw' input. Normally, IPython's logs contain the processed
1074 input, so that user lines are logged in their final form, converted
1078 input, so that user lines are logged in their final form, converted
1075 into valid Python. For example, %Exit is logged as
1079 into valid Python. For example, %Exit is logged as
1076 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1080 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1077 exactly as typed, with no transformations applied.
1081 exactly as typed, with no transformations applied.
1078
1082
1079 -t: put timestamps before each input line logged (these are put in
1083 -t: put timestamps before each input line logged (these are put in
1080 comments)."""
1084 comments)."""
1081
1085
1082 opts,par = self.parse_options(parameter_s,'ort')
1086 opts,par = self.parse_options(parameter_s,'ort')
1083 log_output = 'o' in opts
1087 log_output = 'o' in opts
1084 log_raw_input = 'r' in opts
1088 log_raw_input = 'r' in opts
1085 timestamp = 't' in opts
1089 timestamp = 't' in opts
1086
1090
1087 rc = self.shell.rc
1091 rc = self.shell.rc
1088 logger = self.shell.logger
1092 logger = self.shell.logger
1089
1093
1090 # if no args are given, the defaults set in the logger constructor by
1094 # if no args are given, the defaults set in the logger constructor by
1091 # ipytohn remain valid
1095 # ipytohn remain valid
1092 if par:
1096 if par:
1093 try:
1097 try:
1094 logfname,logmode = par.split()
1098 logfname,logmode = par.split()
1095 except:
1099 except:
1096 logfname = par
1100 logfname = par
1097 logmode = 'backup'
1101 logmode = 'backup'
1098 else:
1102 else:
1099 logfname = logger.logfname
1103 logfname = logger.logfname
1100 logmode = logger.logmode
1104 logmode = logger.logmode
1101 # put logfname into rc struct as if it had been called on the command
1105 # put logfname into rc struct as if it had been called on the command
1102 # line, so it ends up saved in the log header Save it in case we need
1106 # line, so it ends up saved in the log header Save it in case we need
1103 # to restore it...
1107 # to restore it...
1104 old_logfile = rc.opts.get('logfile','')
1108 old_logfile = rc.opts.get('logfile','')
1105 if logfname:
1109 if logfname:
1106 logfname = os.path.expanduser(logfname)
1110 logfname = os.path.expanduser(logfname)
1107 rc.opts.logfile = logfname
1111 rc.opts.logfile = logfname
1108 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1112 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1109 try:
1113 try:
1110 started = logger.logstart(logfname,loghead,logmode,
1114 started = logger.logstart(logfname,loghead,logmode,
1111 log_output,timestamp,log_raw_input)
1115 log_output,timestamp,log_raw_input)
1112 except:
1116 except:
1113 rc.opts.logfile = old_logfile
1117 rc.opts.logfile = old_logfile
1114 warn("Couldn't start log: %s" % sys.exc_info()[1])
1118 warn("Couldn't start log: %s" % sys.exc_info()[1])
1115 else:
1119 else:
1116 # log input history up to this point, optionally interleaving
1120 # log input history up to this point, optionally interleaving
1117 # output if requested
1121 # output if requested
1118
1122
1119 if timestamp:
1123 if timestamp:
1120 # disable timestamping for the previous history, since we've
1124 # disable timestamping for the previous history, since we've
1121 # lost those already (no time machine here).
1125 # lost those already (no time machine here).
1122 logger.timestamp = False
1126 logger.timestamp = False
1123
1127
1124 if log_raw_input:
1128 if log_raw_input:
1125 input_hist = self.shell.input_hist_raw
1129 input_hist = self.shell.input_hist_raw
1126 else:
1130 else:
1127 input_hist = self.shell.input_hist
1131 input_hist = self.shell.input_hist
1128
1132
1129 if log_output:
1133 if log_output:
1130 log_write = logger.log_write
1134 log_write = logger.log_write
1131 output_hist = self.shell.output_hist
1135 output_hist = self.shell.output_hist
1132 for n in range(1,len(input_hist)-1):
1136 for n in range(1,len(input_hist)-1):
1133 log_write(input_hist[n].rstrip())
1137 log_write(input_hist[n].rstrip())
1134 if n in output_hist:
1138 if n in output_hist:
1135 log_write(repr(output_hist[n]),'output')
1139 log_write(repr(output_hist[n]),'output')
1136 else:
1140 else:
1137 logger.log_write(input_hist[1:])
1141 logger.log_write(input_hist[1:])
1138 if timestamp:
1142 if timestamp:
1139 # re-enable timestamping
1143 # re-enable timestamping
1140 logger.timestamp = True
1144 logger.timestamp = True
1141
1145
1142 print ('Activating auto-logging. '
1146 print ('Activating auto-logging. '
1143 'Current session state plus future input saved.')
1147 'Current session state plus future input saved.')
1144 logger.logstate()
1148 logger.logstate()
1145
1149
1146 def magic_logoff(self,parameter_s=''):
1150 def magic_logoff(self,parameter_s=''):
1147 """Temporarily stop logging.
1151 """Temporarily stop logging.
1148
1152
1149 You must have previously started logging."""
1153 You must have previously started logging."""
1150 self.shell.logger.switch_log(0)
1154 self.shell.logger.switch_log(0)
1151
1155
1152 def magic_logon(self,parameter_s=''):
1156 def magic_logon(self,parameter_s=''):
1153 """Restart logging.
1157 """Restart logging.
1154
1158
1155 This function is for restarting logging which you've temporarily
1159 This function is for restarting logging which you've temporarily
1156 stopped with %logoff. For starting logging for the first time, you
1160 stopped with %logoff. For starting logging for the first time, you
1157 must use the %logstart function, which allows you to specify an
1161 must use the %logstart function, which allows you to specify an
1158 optional log filename."""
1162 optional log filename."""
1159
1163
1160 self.shell.logger.switch_log(1)
1164 self.shell.logger.switch_log(1)
1161
1165
1162 def magic_logstate(self,parameter_s=''):
1166 def magic_logstate(self,parameter_s=''):
1163 """Print the status of the logging system."""
1167 """Print the status of the logging system."""
1164
1168
1165 self.shell.logger.logstate()
1169 self.shell.logger.logstate()
1166
1170
1167 def magic_pdb(self, parameter_s=''):
1171 def magic_pdb(self, parameter_s=''):
1168 """Control the automatic calling of the pdb interactive debugger.
1172 """Control the automatic calling of the pdb interactive debugger.
1169
1173
1170 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1174 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1171 argument it works as a toggle.
1175 argument it works as a toggle.
1172
1176
1173 When an exception is triggered, IPython can optionally call the
1177 When an exception is triggered, IPython can optionally call the
1174 interactive pdb debugger after the traceback printout. %pdb toggles
1178 interactive pdb debugger after the traceback printout. %pdb toggles
1175 this feature on and off.
1179 this feature on and off.
1176
1180
1177 The initial state of this feature is set in your ipythonrc
1181 The initial state of this feature is set in your ipythonrc
1178 configuration file (the variable is called 'pdb').
1182 configuration file (the variable is called 'pdb').
1179
1183
1180 If you want to just activate the debugger AFTER an exception has fired,
1184 If you want to just activate the debugger AFTER an exception has fired,
1181 without having to type '%pdb on' and rerunning your code, you can use
1185 without having to type '%pdb on' and rerunning your code, you can use
1182 the %debug magic."""
1186 the %debug magic."""
1183
1187
1184 par = parameter_s.strip().lower()
1188 par = parameter_s.strip().lower()
1185
1189
1186 if par:
1190 if par:
1187 try:
1191 try:
1188 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1192 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1189 except KeyError:
1193 except KeyError:
1190 print ('Incorrect argument. Use on/1, off/0, '
1194 print ('Incorrect argument. Use on/1, off/0, '
1191 'or nothing for a toggle.')
1195 'or nothing for a toggle.')
1192 return
1196 return
1193 else:
1197 else:
1194 # toggle
1198 # toggle
1195 new_pdb = not self.shell.call_pdb
1199 new_pdb = not self.shell.call_pdb
1196
1200
1197 # set on the shell
1201 # set on the shell
1198 self.shell.call_pdb = new_pdb
1202 self.shell.call_pdb = new_pdb
1199 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1203 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1200
1204
1201 def magic_debug(self, parameter_s=''):
1205 def magic_debug(self, parameter_s=''):
1202 """Activate the interactive debugger in post-mortem mode.
1206 """Activate the interactive debugger in post-mortem mode.
1203
1207
1204 If an exception has just occurred, this lets you inspect its stack
1208 If an exception has just occurred, this lets you inspect its stack
1205 frames interactively. Note that this will always work only on the last
1209 frames interactively. Note that this will always work only on the last
1206 traceback that occurred, so you must call this quickly after an
1210 traceback that occurred, so you must call this quickly after an
1207 exception that you wish to inspect has fired, because if another one
1211 exception that you wish to inspect has fired, because if another one
1208 occurs, it clobbers the previous one.
1212 occurs, it clobbers the previous one.
1209
1213
1210 If you want IPython to automatically do this on every exception, see
1214 If you want IPython to automatically do this on every exception, see
1211 the %pdb magic for more details.
1215 the %pdb magic for more details.
1212 """
1216 """
1213
1217
1214 self.shell.debugger(force=True)
1218 self.shell.debugger(force=True)
1215
1219
1216 def magic_prun(self, parameter_s ='',user_mode=1,
1220 def magic_prun(self, parameter_s ='',user_mode=1,
1217 opts=None,arg_lst=None,prog_ns=None):
1221 opts=None,arg_lst=None,prog_ns=None):
1218
1222
1219 """Run a statement through the python code profiler.
1223 """Run a statement through the python code profiler.
1220
1224
1221 Usage:\\
1225 Usage:\\
1222 %prun [options] statement
1226 %prun [options] statement
1223
1227
1224 The given statement (which doesn't require quote marks) is run via the
1228 The given statement (which doesn't require quote marks) is run via the
1225 python profiler in a manner similar to the profile.run() function.
1229 python profiler in a manner similar to the profile.run() function.
1226 Namespaces are internally managed to work correctly; profile.run
1230 Namespaces are internally managed to work correctly; profile.run
1227 cannot be used in IPython because it makes certain assumptions about
1231 cannot be used in IPython because it makes certain assumptions about
1228 namespaces which do not hold under IPython.
1232 namespaces which do not hold under IPython.
1229
1233
1230 Options:
1234 Options:
1231
1235
1232 -l <limit>: you can place restrictions on what or how much of the
1236 -l <limit>: you can place restrictions on what or how much of the
1233 profile gets printed. The limit value can be:
1237 profile gets printed. The limit value can be:
1234
1238
1235 * A string: only information for function names containing this string
1239 * A string: only information for function names containing this string
1236 is printed.
1240 is printed.
1237
1241
1238 * An integer: only these many lines are printed.
1242 * An integer: only these many lines are printed.
1239
1243
1240 * A float (between 0 and 1): this fraction of the report is printed
1244 * A float (between 0 and 1): this fraction of the report is printed
1241 (for example, use a limit of 0.4 to see the topmost 40% only).
1245 (for example, use a limit of 0.4 to see the topmost 40% only).
1242
1246
1243 You can combine several limits with repeated use of the option. For
1247 You can combine several limits with repeated use of the option. For
1244 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1248 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1245 information about class constructors.
1249 information about class constructors.
1246
1250
1247 -r: return the pstats.Stats object generated by the profiling. This
1251 -r: return the pstats.Stats object generated by the profiling. This
1248 object has all the information about the profile in it, and you can
1252 object has all the information about the profile in it, and you can
1249 later use it for further analysis or in other functions.
1253 later use it for further analysis or in other functions.
1250
1254
1251 -s <key>: sort profile by given key. You can provide more than one key
1255 -s <key>: sort profile by given key. You can provide more than one key
1252 by using the option several times: '-s key1 -s key2 -s key3...'. The
1256 by using the option several times: '-s key1 -s key2 -s key3...'. The
1253 default sorting key is 'time'.
1257 default sorting key is 'time'.
1254
1258
1255 The following is copied verbatim from the profile documentation
1259 The following is copied verbatim from the profile documentation
1256 referenced below:
1260 referenced below:
1257
1261
1258 When more than one key is provided, additional keys are used as
1262 When more than one key is provided, additional keys are used as
1259 secondary criteria when the there is equality in all keys selected
1263 secondary criteria when the there is equality in all keys selected
1260 before them.
1264 before them.
1261
1265
1262 Abbreviations can be used for any key names, as long as the
1266 Abbreviations can be used for any key names, as long as the
1263 abbreviation is unambiguous. The following are the keys currently
1267 abbreviation is unambiguous. The following are the keys currently
1264 defined:
1268 defined:
1265
1269
1266 Valid Arg Meaning\\
1270 Valid Arg Meaning\\
1267 "calls" call count\\
1271 "calls" call count\\
1268 "cumulative" cumulative time\\
1272 "cumulative" cumulative time\\
1269 "file" file name\\
1273 "file" file name\\
1270 "module" file name\\
1274 "module" file name\\
1271 "pcalls" primitive call count\\
1275 "pcalls" primitive call count\\
1272 "line" line number\\
1276 "line" line number\\
1273 "name" function name\\
1277 "name" function name\\
1274 "nfl" name/file/line\\
1278 "nfl" name/file/line\\
1275 "stdname" standard name\\
1279 "stdname" standard name\\
1276 "time" internal time
1280 "time" internal time
1277
1281
1278 Note that all sorts on statistics are in descending order (placing
1282 Note that all sorts on statistics are in descending order (placing
1279 most time consuming items first), where as name, file, and line number
1283 most time consuming items first), where as name, file, and line number
1280 searches are in ascending order (i.e., alphabetical). The subtle
1284 searches are in ascending order (i.e., alphabetical). The subtle
1281 distinction between "nfl" and "stdname" is that the standard name is a
1285 distinction between "nfl" and "stdname" is that the standard name is a
1282 sort of the name as printed, which means that the embedded line
1286 sort of the name as printed, which means that the embedded line
1283 numbers get compared in an odd way. For example, lines 3, 20, and 40
1287 numbers get compared in an odd way. For example, lines 3, 20, and 40
1284 would (if the file names were the same) appear in the string order
1288 would (if the file names were the same) appear in the string order
1285 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1289 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1286 line numbers. In fact, sort_stats("nfl") is the same as
1290 line numbers. In fact, sort_stats("nfl") is the same as
1287 sort_stats("name", "file", "line").
1291 sort_stats("name", "file", "line").
1288
1292
1289 -T <filename>: save profile results as shown on screen to a text
1293 -T <filename>: save profile results as shown on screen to a text
1290 file. The profile is still shown on screen.
1294 file. The profile is still shown on screen.
1291
1295
1292 -D <filename>: save (via dump_stats) profile statistics to given
1296 -D <filename>: save (via dump_stats) profile statistics to given
1293 filename. This data is in a format understod by the pstats module, and
1297 filename. This data is in a format understod by the pstats module, and
1294 is generated by a call to the dump_stats() method of profile
1298 is generated by a call to the dump_stats() method of profile
1295 objects. The profile is still shown on screen.
1299 objects. The profile is still shown on screen.
1296
1300
1297 If you want to run complete programs under the profiler's control, use
1301 If you want to run complete programs under the profiler's control, use
1298 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1302 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1299 contains profiler specific options as described here.
1303 contains profiler specific options as described here.
1300
1304
1301 You can read the complete documentation for the profile module with:\\
1305 You can read the complete documentation for the profile module with:\\
1302 In [1]: import profile; profile.help() """
1306 In [1]: import profile; profile.help() """
1303
1307
1304 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1308 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1305 # protect user quote marks
1309 # protect user quote marks
1306 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1310 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1307
1311
1308 if user_mode: # regular user call
1312 if user_mode: # regular user call
1309 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1313 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1310 list_all=1)
1314 list_all=1)
1311 namespace = self.shell.user_ns
1315 namespace = self.shell.user_ns
1312 else: # called to run a program by %run -p
1316 else: # called to run a program by %run -p
1313 try:
1317 try:
1314 filename = get_py_filename(arg_lst[0])
1318 filename = get_py_filename(arg_lst[0])
1315 except IOError,msg:
1319 except IOError,msg:
1316 error(msg)
1320 error(msg)
1317 return
1321 return
1318
1322
1319 arg_str = 'execfile(filename,prog_ns)'
1323 arg_str = 'execfile(filename,prog_ns)'
1320 namespace = locals()
1324 namespace = locals()
1321
1325
1322 opts.merge(opts_def)
1326 opts.merge(opts_def)
1323
1327
1324 prof = profile.Profile()
1328 prof = profile.Profile()
1325 try:
1329 try:
1326 prof = prof.runctx(arg_str,namespace,namespace)
1330 prof = prof.runctx(arg_str,namespace,namespace)
1327 sys_exit = ''
1331 sys_exit = ''
1328 except SystemExit:
1332 except SystemExit:
1329 sys_exit = """*** SystemExit exception caught in code being profiled."""
1333 sys_exit = """*** SystemExit exception caught in code being profiled."""
1330
1334
1331 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1335 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1332
1336
1333 lims = opts.l
1337 lims = opts.l
1334 if lims:
1338 if lims:
1335 lims = [] # rebuild lims with ints/floats/strings
1339 lims = [] # rebuild lims with ints/floats/strings
1336 for lim in opts.l:
1340 for lim in opts.l:
1337 try:
1341 try:
1338 lims.append(int(lim))
1342 lims.append(int(lim))
1339 except ValueError:
1343 except ValueError:
1340 try:
1344 try:
1341 lims.append(float(lim))
1345 lims.append(float(lim))
1342 except ValueError:
1346 except ValueError:
1343 lims.append(lim)
1347 lims.append(lim)
1344
1348
1345 # Trap output.
1349 # Trap output.
1346 stdout_trap = StringIO()
1350 stdout_trap = StringIO()
1347
1351
1348 if hasattr(stats,'stream'):
1352 if hasattr(stats,'stream'):
1349 # In newer versions of python, the stats object has a 'stream'
1353 # In newer versions of python, the stats object has a 'stream'
1350 # attribute to write into.
1354 # attribute to write into.
1351 stats.stream = stdout_trap
1355 stats.stream = stdout_trap
1352 stats.print_stats(*lims)
1356 stats.print_stats(*lims)
1353 else:
1357 else:
1354 # For older versions, we manually redirect stdout during printing
1358 # For older versions, we manually redirect stdout during printing
1355 sys_stdout = sys.stdout
1359 sys_stdout = sys.stdout
1356 try:
1360 try:
1357 sys.stdout = stdout_trap
1361 sys.stdout = stdout_trap
1358 stats.print_stats(*lims)
1362 stats.print_stats(*lims)
1359 finally:
1363 finally:
1360 sys.stdout = sys_stdout
1364 sys.stdout = sys_stdout
1361
1365
1362 output = stdout_trap.getvalue()
1366 output = stdout_trap.getvalue()
1363 output = output.rstrip()
1367 output = output.rstrip()
1364
1368
1365 page(output,screen_lines=self.shell.rc.screen_length)
1369 page(output,screen_lines=self.shell.rc.screen_length)
1366 print sys_exit,
1370 print sys_exit,
1367
1371
1368 dump_file = opts.D[0]
1372 dump_file = opts.D[0]
1369 text_file = opts.T[0]
1373 text_file = opts.T[0]
1370 if dump_file:
1374 if dump_file:
1371 prof.dump_stats(dump_file)
1375 prof.dump_stats(dump_file)
1372 print '\n*** Profile stats marshalled to file',\
1376 print '\n*** Profile stats marshalled to file',\
1373 `dump_file`+'.',sys_exit
1377 `dump_file`+'.',sys_exit
1374 if text_file:
1378 if text_file:
1375 pfile = file(text_file,'w')
1379 pfile = file(text_file,'w')
1376 pfile.write(output)
1380 pfile.write(output)
1377 pfile.close()
1381 pfile.close()
1378 print '\n*** Profile printout saved to text file',\
1382 print '\n*** Profile printout saved to text file',\
1379 `text_file`+'.',sys_exit
1383 `text_file`+'.',sys_exit
1380
1384
1381 if opts.has_key('r'):
1385 if opts.has_key('r'):
1382 return stats
1386 return stats
1383 else:
1387 else:
1384 return None
1388 return None
1385
1389
1386 def magic_run(self, parameter_s ='',runner=None):
1390 def magic_run(self, parameter_s ='',runner=None):
1387 """Run the named file inside IPython as a program.
1391 """Run the named file inside IPython as a program.
1388
1392
1389 Usage:\\
1393 Usage:\\
1390 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1394 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1391
1395
1392 Parameters after the filename are passed as command-line arguments to
1396 Parameters after the filename are passed as command-line arguments to
1393 the program (put in sys.argv). Then, control returns to IPython's
1397 the program (put in sys.argv). Then, control returns to IPython's
1394 prompt.
1398 prompt.
1395
1399
1396 This is similar to running at a system prompt:\\
1400 This is similar to running at a system prompt:\\
1397 $ python file args\\
1401 $ python file args\\
1398 but with the advantage of giving you IPython's tracebacks, and of
1402 but with the advantage of giving you IPython's tracebacks, and of
1399 loading all variables into your interactive namespace for further use
1403 loading all variables into your interactive namespace for further use
1400 (unless -p is used, see below).
1404 (unless -p is used, see below).
1401
1405
1402 The file is executed in a namespace initially consisting only of
1406 The file is executed in a namespace initially consisting only of
1403 __name__=='__main__' and sys.argv constructed as indicated. It thus
1407 __name__=='__main__' and sys.argv constructed as indicated. It thus
1404 sees its environment as if it were being run as a stand-alone
1408 sees its environment as if it were being run as a stand-alone
1405 program. But after execution, the IPython interactive namespace gets
1409 program. But after execution, the IPython interactive namespace gets
1406 updated with all variables defined in the program (except for __name__
1410 updated with all variables defined in the program (except for __name__
1407 and sys.argv). This allows for very convenient loading of code for
1411 and sys.argv). This allows for very convenient loading of code for
1408 interactive work, while giving each program a 'clean sheet' to run in.
1412 interactive work, while giving each program a 'clean sheet' to run in.
1409
1413
1410 Options:
1414 Options:
1411
1415
1412 -n: __name__ is NOT set to '__main__', but to the running file's name
1416 -n: __name__ is NOT set to '__main__', but to the running file's name
1413 without extension (as python does under import). This allows running
1417 without extension (as python does under import). This allows running
1414 scripts and reloading the definitions in them without calling code
1418 scripts and reloading the definitions in them without calling code
1415 protected by an ' if __name__ == "__main__" ' clause.
1419 protected by an ' if __name__ == "__main__" ' clause.
1416
1420
1417 -i: run the file in IPython's namespace instead of an empty one. This
1421 -i: run the file in IPython's namespace instead of an empty one. This
1418 is useful if you are experimenting with code written in a text editor
1422 is useful if you are experimenting with code written in a text editor
1419 which depends on variables defined interactively.
1423 which depends on variables defined interactively.
1420
1424
1421 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1425 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1422 being run. This is particularly useful if IPython is being used to
1426 being run. This is particularly useful if IPython is being used to
1423 run unittests, which always exit with a sys.exit() call. In such
1427 run unittests, which always exit with a sys.exit() call. In such
1424 cases you are interested in the output of the test results, not in
1428 cases you are interested in the output of the test results, not in
1425 seeing a traceback of the unittest module.
1429 seeing a traceback of the unittest module.
1426
1430
1427 -t: print timing information at the end of the run. IPython will give
1431 -t: print timing information at the end of the run. IPython will give
1428 you an estimated CPU time consumption for your script, which under
1432 you an estimated CPU time consumption for your script, which under
1429 Unix uses the resource module to avoid the wraparound problems of
1433 Unix uses the resource module to avoid the wraparound problems of
1430 time.clock(). Under Unix, an estimate of time spent on system tasks
1434 time.clock(). Under Unix, an estimate of time spent on system tasks
1431 is also given (for Windows platforms this is reported as 0.0).
1435 is also given (for Windows platforms this is reported as 0.0).
1432
1436
1433 If -t is given, an additional -N<N> option can be given, where <N>
1437 If -t is given, an additional -N<N> option can be given, where <N>
1434 must be an integer indicating how many times you want the script to
1438 must be an integer indicating how many times you want the script to
1435 run. The final timing report will include total and per run results.
1439 run. The final timing report will include total and per run results.
1436
1440
1437 For example (testing the script uniq_stable.py):
1441 For example (testing the script uniq_stable.py):
1438
1442
1439 In [1]: run -t uniq_stable
1443 In [1]: run -t uniq_stable
1440
1444
1441 IPython CPU timings (estimated):\\
1445 IPython CPU timings (estimated):\\
1442 User : 0.19597 s.\\
1446 User : 0.19597 s.\\
1443 System: 0.0 s.\\
1447 System: 0.0 s.\\
1444
1448
1445 In [2]: run -t -N5 uniq_stable
1449 In [2]: run -t -N5 uniq_stable
1446
1450
1447 IPython CPU timings (estimated):\\
1451 IPython CPU timings (estimated):\\
1448 Total runs performed: 5\\
1452 Total runs performed: 5\\
1449 Times : Total Per run\\
1453 Times : Total Per run\\
1450 User : 0.910862 s, 0.1821724 s.\\
1454 User : 0.910862 s, 0.1821724 s.\\
1451 System: 0.0 s, 0.0 s.
1455 System: 0.0 s, 0.0 s.
1452
1456
1453 -d: run your program under the control of pdb, the Python debugger.
1457 -d: run your program under the control of pdb, the Python debugger.
1454 This allows you to execute your program step by step, watch variables,
1458 This allows you to execute your program step by step, watch variables,
1455 etc. Internally, what IPython does is similar to calling:
1459 etc. Internally, what IPython does is similar to calling:
1456
1460
1457 pdb.run('execfile("YOURFILENAME")')
1461 pdb.run('execfile("YOURFILENAME")')
1458
1462
1459 with a breakpoint set on line 1 of your file. You can change the line
1463 with a breakpoint set on line 1 of your file. You can change the line
1460 number for this automatic breakpoint to be <N> by using the -bN option
1464 number for this automatic breakpoint to be <N> by using the -bN option
1461 (where N must be an integer). For example:
1465 (where N must be an integer). For example:
1462
1466
1463 %run -d -b40 myscript
1467 %run -d -b40 myscript
1464
1468
1465 will set the first breakpoint at line 40 in myscript.py. Note that
1469 will set the first breakpoint at line 40 in myscript.py. Note that
1466 the first breakpoint must be set on a line which actually does
1470 the first breakpoint must be set on a line which actually does
1467 something (not a comment or docstring) for it to stop execution.
1471 something (not a comment or docstring) for it to stop execution.
1468
1472
1469 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1473 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1470 first enter 'c' (without qoutes) to start execution up to the first
1474 first enter 'c' (without qoutes) to start execution up to the first
1471 breakpoint.
1475 breakpoint.
1472
1476
1473 Entering 'help' gives information about the use of the debugger. You
1477 Entering 'help' gives information about the use of the debugger. You
1474 can easily see pdb's full documentation with "import pdb;pdb.help()"
1478 can easily see pdb's full documentation with "import pdb;pdb.help()"
1475 at a prompt.
1479 at a prompt.
1476
1480
1477 -p: run program under the control of the Python profiler module (which
1481 -p: run program under the control of the Python profiler module (which
1478 prints a detailed report of execution times, function calls, etc).
1482 prints a detailed report of execution times, function calls, etc).
1479
1483
1480 You can pass other options after -p which affect the behavior of the
1484 You can pass other options after -p which affect the behavior of the
1481 profiler itself. See the docs for %prun for details.
1485 profiler itself. See the docs for %prun for details.
1482
1486
1483 In this mode, the program's variables do NOT propagate back to the
1487 In this mode, the program's variables do NOT propagate back to the
1484 IPython interactive namespace (because they remain in the namespace
1488 IPython interactive namespace (because they remain in the namespace
1485 where the profiler executes them).
1489 where the profiler executes them).
1486
1490
1487 Internally this triggers a call to %prun, see its documentation for
1491 Internally this triggers a call to %prun, see its documentation for
1488 details on the options available specifically for profiling.
1492 details on the options available specifically for profiling.
1489
1493
1490 There is one special usage for which the text above doesn't apply:
1494 There is one special usage for which the text above doesn't apply:
1491 if the filename ends with .ipy, the file is run as ipython script,
1495 if the filename ends with .ipy, the file is run as ipython script,
1492 just as if the commands were written on IPython prompt.
1496 just as if the commands were written on IPython prompt.
1493 """
1497 """
1494
1498
1495 # get arguments and set sys.argv for program to be run.
1499 # get arguments and set sys.argv for program to be run.
1496 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1500 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1497 mode='list',list_all=1)
1501 mode='list',list_all=1)
1498
1502
1499 try:
1503 try:
1500 filename = get_py_filename(arg_lst[0])
1504 filename = get_py_filename(arg_lst[0])
1501 except IndexError:
1505 except IndexError:
1502 warn('you must provide at least a filename.')
1506 warn('you must provide at least a filename.')
1503 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1507 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1504 return
1508 return
1505 except IOError,msg:
1509 except IOError,msg:
1506 error(msg)
1510 error(msg)
1507 return
1511 return
1508
1512
1509 if filename.lower().endswith('.ipy'):
1513 if filename.lower().endswith('.ipy'):
1510 self.api.runlines(open(filename).read())
1514 self.api.runlines(open(filename).read())
1511 return
1515 return
1512
1516
1513 # Control the response to exit() calls made by the script being run
1517 # Control the response to exit() calls made by the script being run
1514 exit_ignore = opts.has_key('e')
1518 exit_ignore = opts.has_key('e')
1515
1519
1516 # Make sure that the running script gets a proper sys.argv as if it
1520 # Make sure that the running script gets a proper sys.argv as if it
1517 # were run from a system shell.
1521 # were run from a system shell.
1518 save_argv = sys.argv # save it for later restoring
1522 save_argv = sys.argv # save it for later restoring
1519 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1523 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1520
1524
1521 if opts.has_key('i'):
1525 if opts.has_key('i'):
1526 # Run in user's interactive namespace
1522 prog_ns = self.shell.user_ns
1527 prog_ns = self.shell.user_ns
1523 __name__save = self.shell.user_ns['__name__']
1528 __name__save = self.shell.user_ns['__name__']
1524 prog_ns['__name__'] = '__main__'
1529 prog_ns['__name__'] = '__main__'
1525 main_mod = FakeModule(prog_ns)
1530 main_mod = FakeModule(prog_ns)
1526 else:
1531 else:
1532 # Run in a fresh, empty namespace
1527 if opts.has_key('n'):
1533 if opts.has_key('n'):
1528 name = os.path.splitext(os.path.basename(filename))[0]
1534 name = os.path.splitext(os.path.basename(filename))[0]
1529 else:
1535 else:
1530 name = '__main__'
1536 name = '__main__'
1531 main_mod = FakeModule()
1537 main_mod = FakeModule()
1532 prog_ns = main_mod.__dict__
1538 prog_ns = main_mod.__dict__
1533 prog_ns['__name__'] = name
1539 prog_ns['__name__'] = name
1540 # The shell MUST hold a reference to main_mod so after %run exits,
1541 # the python deletion mechanism doesn't zero it out (leaving
1542 # dangling references)
1543 self.shell._user_main_modules.append(main_mod)
1534
1544
1535 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1545 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1536 # set the __file__ global in the script's namespace
1546 # set the __file__ global in the script's namespace
1537 prog_ns['__file__'] = filename
1547 prog_ns['__file__'] = filename
1538
1548
1539 # pickle fix. See iplib for an explanation. But we need to make sure
1549 # pickle fix. See iplib for an explanation. But we need to make sure
1540 # that, if we overwrite __main__, we replace it at the end
1550 # that, if we overwrite __main__, we replace it at the end
1541 if prog_ns['__name__'] == '__main__':
1551 if prog_ns['__name__'] == '__main__':
1542 restore_main = sys.modules['__main__']
1552 restore_main = sys.modules['__main__']
1543 else:
1553 else:
1544 restore_main = False
1554 restore_main = False
1545
1555
1546 sys.modules[prog_ns['__name__']] = main_mod
1556 sys.modules[prog_ns['__name__']] = main_mod
1547
1557
1548 stats = None
1558 stats = None
1549 try:
1559 try:
1550 if self.shell.has_readline:
1560 if self.shell.has_readline:
1551 self.shell.savehist()
1561 self.shell.savehist()
1552
1562
1553 if opts.has_key('p'):
1563 if opts.has_key('p'):
1554 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1564 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1555 else:
1565 else:
1556 if opts.has_key('d'):
1566 if opts.has_key('d'):
1557 deb = Debugger.Pdb(self.shell.rc.colors)
1567 deb = Debugger.Pdb(self.shell.rc.colors)
1558 # reset Breakpoint state, which is moronically kept
1568 # reset Breakpoint state, which is moronically kept
1559 # in a class
1569 # in a class
1560 bdb.Breakpoint.next = 1
1570 bdb.Breakpoint.next = 1
1561 bdb.Breakpoint.bplist = {}
1571 bdb.Breakpoint.bplist = {}
1562 bdb.Breakpoint.bpbynumber = [None]
1572 bdb.Breakpoint.bpbynumber = [None]
1563 # Set an initial breakpoint to stop execution
1573 # Set an initial breakpoint to stop execution
1564 maxtries = 10
1574 maxtries = 10
1565 bp = int(opts.get('b',[1])[0])
1575 bp = int(opts.get('b',[1])[0])
1566 checkline = deb.checkline(filename,bp)
1576 checkline = deb.checkline(filename,bp)
1567 if not checkline:
1577 if not checkline:
1568 for bp in range(bp+1,bp+maxtries+1):
1578 for bp in range(bp+1,bp+maxtries+1):
1569 if deb.checkline(filename,bp):
1579 if deb.checkline(filename,bp):
1570 break
1580 break
1571 else:
1581 else:
1572 msg = ("\nI failed to find a valid line to set "
1582 msg = ("\nI failed to find a valid line to set "
1573 "a breakpoint\n"
1583 "a breakpoint\n"
1574 "after trying up to line: %s.\n"
1584 "after trying up to line: %s.\n"
1575 "Please set a valid breakpoint manually "
1585 "Please set a valid breakpoint manually "
1576 "with the -b option." % bp)
1586 "with the -b option." % bp)
1577 error(msg)
1587 error(msg)
1578 return
1588 return
1579 # if we find a good linenumber, set the breakpoint
1589 # if we find a good linenumber, set the breakpoint
1580 deb.do_break('%s:%s' % (filename,bp))
1590 deb.do_break('%s:%s' % (filename,bp))
1581 # Start file run
1591 # Start file run
1582 print "NOTE: Enter 'c' at the",
1592 print "NOTE: Enter 'c' at the",
1583 print "%s prompt to start your script." % deb.prompt
1593 print "%s prompt to start your script." % deb.prompt
1584 try:
1594 try:
1585 deb.run('execfile("%s")' % filename,prog_ns)
1595 deb.run('execfile("%s")' % filename,prog_ns)
1586
1596
1587 except:
1597 except:
1588 etype, value, tb = sys.exc_info()
1598 etype, value, tb = sys.exc_info()
1589 # Skip three frames in the traceback: the %run one,
1599 # Skip three frames in the traceback: the %run one,
1590 # one inside bdb.py, and the command-line typed by the
1600 # one inside bdb.py, and the command-line typed by the
1591 # user (run by exec in pdb itself).
1601 # user (run by exec in pdb itself).
1592 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1602 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1593 else:
1603 else:
1594 if runner is None:
1604 if runner is None:
1595 runner = self.shell.safe_execfile
1605 runner = self.shell.safe_execfile
1596 if opts.has_key('t'):
1606 if opts.has_key('t'):
1607 # timed execution
1597 try:
1608 try:
1598 nruns = int(opts['N'][0])
1609 nruns = int(opts['N'][0])
1599 if nruns < 1:
1610 if nruns < 1:
1600 error('Number of runs must be >=1')
1611 error('Number of runs must be >=1')
1601 return
1612 return
1602 except (KeyError):
1613 except (KeyError):
1603 nruns = 1
1614 nruns = 1
1604 if nruns == 1:
1615 if nruns == 1:
1605 t0 = clock2()
1616 t0 = clock2()
1606 runner(filename,prog_ns,prog_ns,
1617 runner(filename,prog_ns,prog_ns,
1607 exit_ignore=exit_ignore)
1618 exit_ignore=exit_ignore)
1608 t1 = clock2()
1619 t1 = clock2()
1609 t_usr = t1[0]-t0[0]
1620 t_usr = t1[0]-t0[0]
1610 t_sys = t1[1]-t1[1]
1621 t_sys = t1[1]-t1[1]
1611 print "\nIPython CPU timings (estimated):"
1622 print "\nIPython CPU timings (estimated):"
1612 print " User : %10s s." % t_usr
1623 print " User : %10s s." % t_usr
1613 print " System: %10s s." % t_sys
1624 print " System: %10s s." % t_sys
1614 else:
1625 else:
1615 runs = range(nruns)
1626 runs = range(nruns)
1616 t0 = clock2()
1627 t0 = clock2()
1617 for nr in runs:
1628 for nr in runs:
1618 runner(filename,prog_ns,prog_ns,
1629 runner(filename,prog_ns,prog_ns,
1619 exit_ignore=exit_ignore)
1630 exit_ignore=exit_ignore)
1620 t1 = clock2()
1631 t1 = clock2()
1621 t_usr = t1[0]-t0[0]
1632 t_usr = t1[0]-t0[0]
1622 t_sys = t1[1]-t1[1]
1633 t_sys = t1[1]-t1[1]
1623 print "\nIPython CPU timings (estimated):"
1634 print "\nIPython CPU timings (estimated):"
1624 print "Total runs performed:",nruns
1635 print "Total runs performed:",nruns
1625 print " Times : %10s %10s" % ('Total','Per run')
1636 print " Times : %10s %10s" % ('Total','Per run')
1626 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1637 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1627 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1638 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1628
1639
1629 else:
1640 else:
1641 # regular execution
1630 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1642 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1631 if opts.has_key('i'):
1643 if opts.has_key('i'):
1632 self.shell.user_ns['__name__'] = __name__save
1644 self.shell.user_ns['__name__'] = __name__save
1633 else:
1645 else:
1634 # update IPython interactive namespace
1646 # update IPython interactive namespace
1635 del prog_ns['__name__']
1647 del prog_ns['__name__']
1636 self.shell.user_ns.update(prog_ns)
1648 self.shell.user_ns.update(prog_ns)
1637 finally:
1649 finally:
1638 sys.argv = save_argv
1650 sys.argv = save_argv
1639 if restore_main:
1651 if restore_main:
1640 sys.modules['__main__'] = restore_main
1652 sys.modules['__main__'] = restore_main
1641 self.shell.reloadhist()
1653 self.shell.reloadhist()
1642
1654
1643 return stats
1655 return stats
1644
1656
1645 def magic_runlog(self, parameter_s =''):
1657 def magic_runlog(self, parameter_s =''):
1646 """Run files as logs.
1658 """Run files as logs.
1647
1659
1648 Usage:\\
1660 Usage:\\
1649 %runlog file1 file2 ...
1661 %runlog file1 file2 ...
1650
1662
1651 Run the named files (treating them as log files) in sequence inside
1663 Run the named files (treating them as log files) in sequence inside
1652 the interpreter, and return to the prompt. This is much slower than
1664 the interpreter, and return to the prompt. This is much slower than
1653 %run because each line is executed in a try/except block, but it
1665 %run because each line is executed in a try/except block, but it
1654 allows running files with syntax errors in them.
1666 allows running files with syntax errors in them.
1655
1667
1656 Normally IPython will guess when a file is one of its own logfiles, so
1668 Normally IPython will guess when a file is one of its own logfiles, so
1657 you can typically use %run even for logs. This shorthand allows you to
1669 you can typically use %run even for logs. This shorthand allows you to
1658 force any file to be treated as a log file."""
1670 force any file to be treated as a log file."""
1659
1671
1660 for f in parameter_s.split():
1672 for f in parameter_s.split():
1661 self.shell.safe_execfile(f,self.shell.user_ns,
1673 self.shell.safe_execfile(f,self.shell.user_ns,
1662 self.shell.user_ns,islog=1)
1674 self.shell.user_ns,islog=1)
1663
1675
1664 def magic_timeit(self, parameter_s =''):
1676 def magic_timeit(self, parameter_s =''):
1665 """Time execution of a Python statement or expression
1677 """Time execution of a Python statement or expression
1666
1678
1667 Usage:\\
1679 Usage:\\
1668 %timeit [-n<N> -r<R> [-t|-c]] statement
1680 %timeit [-n<N> -r<R> [-t|-c]] statement
1669
1681
1670 Time execution of a Python statement or expression using the timeit
1682 Time execution of a Python statement or expression using the timeit
1671 module.
1683 module.
1672
1684
1673 Options:
1685 Options:
1674 -n<N>: execute the given statement <N> times in a loop. If this value
1686 -n<N>: execute the given statement <N> times in a loop. If this value
1675 is not given, a fitting value is chosen.
1687 is not given, a fitting value is chosen.
1676
1688
1677 -r<R>: repeat the loop iteration <R> times and take the best result.
1689 -r<R>: repeat the loop iteration <R> times and take the best result.
1678 Default: 3
1690 Default: 3
1679
1691
1680 -t: use time.time to measure the time, which is the default on Unix.
1692 -t: use time.time to measure the time, which is the default on Unix.
1681 This function measures wall time.
1693 This function measures wall time.
1682
1694
1683 -c: use time.clock to measure the time, which is the default on
1695 -c: use time.clock to measure the time, which is the default on
1684 Windows and measures wall time. On Unix, resource.getrusage is used
1696 Windows and measures wall time. On Unix, resource.getrusage is used
1685 instead and returns the CPU user time.
1697 instead and returns the CPU user time.
1686
1698
1687 -p<P>: use a precision of <P> digits to display the timing result.
1699 -p<P>: use a precision of <P> digits to display the timing result.
1688 Default: 3
1700 Default: 3
1689
1701
1690
1702
1691 Examples:\\
1703 Examples:\\
1692 In [1]: %timeit pass
1704 In [1]: %timeit pass
1693 10000000 loops, best of 3: 53.3 ns per loop
1705 10000000 loops, best of 3: 53.3 ns per loop
1694
1706
1695 In [2]: u = None
1707 In [2]: u = None
1696
1708
1697 In [3]: %timeit u is None
1709 In [3]: %timeit u is None
1698 10000000 loops, best of 3: 184 ns per loop
1710 10000000 loops, best of 3: 184 ns per loop
1699
1711
1700 In [4]: %timeit -r 4 u == None
1712 In [4]: %timeit -r 4 u == None
1701 1000000 loops, best of 4: 242 ns per loop
1713 1000000 loops, best of 4: 242 ns per loop
1702
1714
1703 In [5]: import time
1715 In [5]: import time
1704
1716
1705 In [6]: %timeit -n1 time.sleep(2)
1717 In [6]: %timeit -n1 time.sleep(2)
1706 1 loops, best of 3: 2 s per loop
1718 1 loops, best of 3: 2 s per loop
1707
1719
1708
1720
1709 The times reported by %timeit will be slightly higher than those
1721 The times reported by %timeit will be slightly higher than those
1710 reported by the timeit.py script when variables are accessed. This is
1722 reported by the timeit.py script when variables are accessed. This is
1711 due to the fact that %timeit executes the statement in the namespace
1723 due to the fact that %timeit executes the statement in the namespace
1712 of the shell, compared with timeit.py, which uses a single setup
1724 of the shell, compared with timeit.py, which uses a single setup
1713 statement to import function or create variables. Generally, the bias
1725 statement to import function or create variables. Generally, the bias
1714 does not matter as long as results from timeit.py are not mixed with
1726 does not matter as long as results from timeit.py are not mixed with
1715 those from %timeit."""
1727 those from %timeit."""
1716
1728
1717 import timeit
1729 import timeit
1718 import math
1730 import math
1719
1731
1720 units = ["s", "ms", "\xc2\xb5s", "ns"]
1732 units = ["s", "ms", "\xc2\xb5s", "ns"]
1721 scaling = [1, 1e3, 1e6, 1e9]
1733 scaling = [1, 1e3, 1e6, 1e9]
1722
1734
1723 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1735 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1724 posix=False)
1736 posix=False)
1725 if stmt == "":
1737 if stmt == "":
1726 return
1738 return
1727 timefunc = timeit.default_timer
1739 timefunc = timeit.default_timer
1728 number = int(getattr(opts, "n", 0))
1740 number = int(getattr(opts, "n", 0))
1729 repeat = int(getattr(opts, "r", timeit.default_repeat))
1741 repeat = int(getattr(opts, "r", timeit.default_repeat))
1730 precision = int(getattr(opts, "p", 3))
1742 precision = int(getattr(opts, "p", 3))
1731 if hasattr(opts, "t"):
1743 if hasattr(opts, "t"):
1732 timefunc = time.time
1744 timefunc = time.time
1733 if hasattr(opts, "c"):
1745 if hasattr(opts, "c"):
1734 timefunc = clock
1746 timefunc = clock
1735
1747
1736 timer = timeit.Timer(timer=timefunc)
1748 timer = timeit.Timer(timer=timefunc)
1737 # this code has tight coupling to the inner workings of timeit.Timer,
1749 # this code has tight coupling to the inner workings of timeit.Timer,
1738 # but is there a better way to achieve that the code stmt has access
1750 # but is there a better way to achieve that the code stmt has access
1739 # to the shell namespace?
1751 # to the shell namespace?
1740
1752
1741 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1753 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1742 'setup': "pass"}
1754 'setup': "pass"}
1743 code = compile(src, "<magic-timeit>", "exec")
1755 code = compile(src, "<magic-timeit>", "exec")
1744 ns = {}
1756 ns = {}
1745 exec code in self.shell.user_ns, ns
1757 exec code in self.shell.user_ns, ns
1746 timer.inner = ns["inner"]
1758 timer.inner = ns["inner"]
1747
1759
1748 if number == 0:
1760 if number == 0:
1749 # determine number so that 0.2 <= total time < 2.0
1761 # determine number so that 0.2 <= total time < 2.0
1750 number = 1
1762 number = 1
1751 for i in range(1, 10):
1763 for i in range(1, 10):
1752 number *= 10
1764 number *= 10
1753 if timer.timeit(number) >= 0.2:
1765 if timer.timeit(number) >= 0.2:
1754 break
1766 break
1755
1767
1756 best = min(timer.repeat(repeat, number)) / number
1768 best = min(timer.repeat(repeat, number)) / number
1757
1769
1758 if best > 0.0:
1770 if best > 0.0:
1759 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1771 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1760 else:
1772 else:
1761 order = 3
1773 order = 3
1762 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1774 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1763 precision,
1775 precision,
1764 best * scaling[order],
1776 best * scaling[order],
1765 units[order])
1777 units[order])
1766
1778
1767 def magic_time(self,parameter_s = ''):
1779 def magic_time(self,parameter_s = ''):
1768 """Time execution of a Python statement or expression.
1780 """Time execution of a Python statement or expression.
1769
1781
1770 The CPU and wall clock times are printed, and the value of the
1782 The CPU and wall clock times are printed, and the value of the
1771 expression (if any) is returned. Note that under Win32, system time
1783 expression (if any) is returned. Note that under Win32, system time
1772 is always reported as 0, since it can not be measured.
1784 is always reported as 0, since it can not be measured.
1773
1785
1774 This function provides very basic timing functionality. In Python
1786 This function provides very basic timing functionality. In Python
1775 2.3, the timeit module offers more control and sophistication, so this
1787 2.3, the timeit module offers more control and sophistication, so this
1776 could be rewritten to use it (patches welcome).
1788 could be rewritten to use it (patches welcome).
1777
1789
1778 Some examples:
1790 Some examples:
1779
1791
1780 In [1]: time 2**128
1792 In [1]: time 2**128
1781 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1793 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1782 Wall time: 0.00
1794 Wall time: 0.00
1783 Out[1]: 340282366920938463463374607431768211456L
1795 Out[1]: 340282366920938463463374607431768211456L
1784
1796
1785 In [2]: n = 1000000
1797 In [2]: n = 1000000
1786
1798
1787 In [3]: time sum(range(n))
1799 In [3]: time sum(range(n))
1788 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1800 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1789 Wall time: 1.37
1801 Wall time: 1.37
1790 Out[3]: 499999500000L
1802 Out[3]: 499999500000L
1791
1803
1792 In [4]: time print 'hello world'
1804 In [4]: time print 'hello world'
1793 hello world
1805 hello world
1794 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1806 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1795 Wall time: 0.00
1807 Wall time: 0.00
1796 """
1808 """
1797
1809
1798 # fail immediately if the given expression can't be compiled
1810 # fail immediately if the given expression can't be compiled
1799
1811
1800 expr = self.shell.prefilter(parameter_s,False)
1812 expr = self.shell.prefilter(parameter_s,False)
1801
1813
1802 try:
1814 try:
1803 mode = 'eval'
1815 mode = 'eval'
1804 code = compile(expr,'<timed eval>',mode)
1816 code = compile(expr,'<timed eval>',mode)
1805 except SyntaxError:
1817 except SyntaxError:
1806 mode = 'exec'
1818 mode = 'exec'
1807 code = compile(expr,'<timed exec>',mode)
1819 code = compile(expr,'<timed exec>',mode)
1808 # skew measurement as little as possible
1820 # skew measurement as little as possible
1809 glob = self.shell.user_ns
1821 glob = self.shell.user_ns
1810 clk = clock2
1822 clk = clock2
1811 wtime = time.time
1823 wtime = time.time
1812 # time execution
1824 # time execution
1813 wall_st = wtime()
1825 wall_st = wtime()
1814 if mode=='eval':
1826 if mode=='eval':
1815 st = clk()
1827 st = clk()
1816 out = eval(code,glob)
1828 out = eval(code,glob)
1817 end = clk()
1829 end = clk()
1818 else:
1830 else:
1819 st = clk()
1831 st = clk()
1820 exec code in glob
1832 exec code in glob
1821 end = clk()
1833 end = clk()
1822 out = None
1834 out = None
1823 wall_end = wtime()
1835 wall_end = wtime()
1824 # Compute actual times and report
1836 # Compute actual times and report
1825 wall_time = wall_end-wall_st
1837 wall_time = wall_end-wall_st
1826 cpu_user = end[0]-st[0]
1838 cpu_user = end[0]-st[0]
1827 cpu_sys = end[1]-st[1]
1839 cpu_sys = end[1]-st[1]
1828 cpu_tot = cpu_user+cpu_sys
1840 cpu_tot = cpu_user+cpu_sys
1829 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1841 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1830 (cpu_user,cpu_sys,cpu_tot)
1842 (cpu_user,cpu_sys,cpu_tot)
1831 print "Wall time: %.2f" % wall_time
1843 print "Wall time: %.2f" % wall_time
1832 return out
1844 return out
1833
1845
1834 def magic_macro(self,parameter_s = ''):
1846 def magic_macro(self,parameter_s = ''):
1835 """Define a set of input lines as a macro for future re-execution.
1847 """Define a set of input lines as a macro for future re-execution.
1836
1848
1837 Usage:\\
1849 Usage:\\
1838 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1850 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1839
1851
1840 Options:
1852 Options:
1841
1853
1842 -r: use 'raw' input. By default, the 'processed' history is used,
1854 -r: use 'raw' input. By default, the 'processed' history is used,
1843 so that magics are loaded in their transformed version to valid
1855 so that magics are loaded in their transformed version to valid
1844 Python. If this option is given, the raw input as typed as the
1856 Python. If this option is given, the raw input as typed as the
1845 command line is used instead.
1857 command line is used instead.
1846
1858
1847 This will define a global variable called `name` which is a string
1859 This will define a global variable called `name` which is a string
1848 made of joining the slices and lines you specify (n1,n2,... numbers
1860 made of joining the slices and lines you specify (n1,n2,... numbers
1849 above) from your input history into a single string. This variable
1861 above) from your input history into a single string. This variable
1850 acts like an automatic function which re-executes those lines as if
1862 acts like an automatic function which re-executes those lines as if
1851 you had typed them. You just type 'name' at the prompt and the code
1863 you had typed them. You just type 'name' at the prompt and the code
1852 executes.
1864 executes.
1853
1865
1854 The notation for indicating number ranges is: n1-n2 means 'use line
1866 The notation for indicating number ranges is: n1-n2 means 'use line
1855 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1867 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1856 using the lines numbered 5,6 and 7.
1868 using the lines numbered 5,6 and 7.
1857
1869
1858 Note: as a 'hidden' feature, you can also use traditional python slice
1870 Note: as a 'hidden' feature, you can also use traditional python slice
1859 notation, where N:M means numbers N through M-1.
1871 notation, where N:M means numbers N through M-1.
1860
1872
1861 For example, if your history contains (%hist prints it):
1873 For example, if your history contains (%hist prints it):
1862
1874
1863 44: x=1\\
1875 44: x=1\\
1864 45: y=3\\
1876 45: y=3\\
1865 46: z=x+y\\
1877 46: z=x+y\\
1866 47: print x\\
1878 47: print x\\
1867 48: a=5\\
1879 48: a=5\\
1868 49: print 'x',x,'y',y\\
1880 49: print 'x',x,'y',y\\
1869
1881
1870 you can create a macro with lines 44 through 47 (included) and line 49
1882 you can create a macro with lines 44 through 47 (included) and line 49
1871 called my_macro with:
1883 called my_macro with:
1872
1884
1873 In [51]: %macro my_macro 44-47 49
1885 In [51]: %macro my_macro 44-47 49
1874
1886
1875 Now, typing `my_macro` (without quotes) will re-execute all this code
1887 Now, typing `my_macro` (without quotes) will re-execute all this code
1876 in one pass.
1888 in one pass.
1877
1889
1878 You don't need to give the line-numbers in order, and any given line
1890 You don't need to give the line-numbers in order, and any given line
1879 number can appear multiple times. You can assemble macros with any
1891 number can appear multiple times. You can assemble macros with any
1880 lines from your input history in any order.
1892 lines from your input history in any order.
1881
1893
1882 The macro is a simple object which holds its value in an attribute,
1894 The macro is a simple object which holds its value in an attribute,
1883 but IPython's display system checks for macros and executes them as
1895 but IPython's display system checks for macros and executes them as
1884 code instead of printing them when you type their name.
1896 code instead of printing them when you type their name.
1885
1897
1886 You can view a macro's contents by explicitly printing it with:
1898 You can view a macro's contents by explicitly printing it with:
1887
1899
1888 'print macro_name'.
1900 'print macro_name'.
1889
1901
1890 For one-off cases which DON'T contain magic function calls in them you
1902 For one-off cases which DON'T contain magic function calls in them you
1891 can obtain similar results by explicitly executing slices from your
1903 can obtain similar results by explicitly executing slices from your
1892 input history with:
1904 input history with:
1893
1905
1894 In [60]: exec In[44:48]+In[49]"""
1906 In [60]: exec In[44:48]+In[49]"""
1895
1907
1896 opts,args = self.parse_options(parameter_s,'r',mode='list')
1908 opts,args = self.parse_options(parameter_s,'r',mode='list')
1897 if not args:
1909 if not args:
1898 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1910 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1899 macs.sort()
1911 macs.sort()
1900 return macs
1912 return macs
1901 if len(args) == 1:
1913 if len(args) == 1:
1902 raise UsageError(
1914 raise UsageError(
1903 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1915 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1904 name,ranges = args[0], args[1:]
1916 name,ranges = args[0], args[1:]
1905
1917
1906 #print 'rng',ranges # dbg
1918 #print 'rng',ranges # dbg
1907 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1919 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1908 macro = Macro(lines)
1920 macro = Macro(lines)
1909 self.shell.user_ns.update({name:macro})
1921 self.shell.user_ns.update({name:macro})
1910 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1922 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1911 print 'Macro contents:'
1923 print 'Macro contents:'
1912 print macro,
1924 print macro,
1913
1925
1914 def magic_save(self,parameter_s = ''):
1926 def magic_save(self,parameter_s = ''):
1915 """Save a set of lines to a given filename.
1927 """Save a set of lines to a given filename.
1916
1928
1917 Usage:\\
1929 Usage:\\
1918 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1930 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1919
1931
1920 Options:
1932 Options:
1921
1933
1922 -r: use 'raw' input. By default, the 'processed' history is used,
1934 -r: use 'raw' input. By default, the 'processed' history is used,
1923 so that magics are loaded in their transformed version to valid
1935 so that magics are loaded in their transformed version to valid
1924 Python. If this option is given, the raw input as typed as the
1936 Python. If this option is given, the raw input as typed as the
1925 command line is used instead.
1937 command line is used instead.
1926
1938
1927 This function uses the same syntax as %macro for line extraction, but
1939 This function uses the same syntax as %macro for line extraction, but
1928 instead of creating a macro it saves the resulting string to the
1940 instead of creating a macro it saves the resulting string to the
1929 filename you specify.
1941 filename you specify.
1930
1942
1931 It adds a '.py' extension to the file if you don't do so yourself, and
1943 It adds a '.py' extension to the file if you don't do so yourself, and
1932 it asks for confirmation before overwriting existing files."""
1944 it asks for confirmation before overwriting existing files."""
1933
1945
1934 opts,args = self.parse_options(parameter_s,'r',mode='list')
1946 opts,args = self.parse_options(parameter_s,'r',mode='list')
1935 fname,ranges = args[0], args[1:]
1947 fname,ranges = args[0], args[1:]
1936 if not fname.endswith('.py'):
1948 if not fname.endswith('.py'):
1937 fname += '.py'
1949 fname += '.py'
1938 if os.path.isfile(fname):
1950 if os.path.isfile(fname):
1939 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1951 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1940 if ans.lower() not in ['y','yes']:
1952 if ans.lower() not in ['y','yes']:
1941 print 'Operation cancelled.'
1953 print 'Operation cancelled.'
1942 return
1954 return
1943 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1955 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1944 f = file(fname,'w')
1956 f = file(fname,'w')
1945 f.write(cmds)
1957 f.write(cmds)
1946 f.close()
1958 f.close()
1947 print 'The following commands were written to file `%s`:' % fname
1959 print 'The following commands were written to file `%s`:' % fname
1948 print cmds
1960 print cmds
1949
1961
1950 def _edit_macro(self,mname,macro):
1962 def _edit_macro(self,mname,macro):
1951 """open an editor with the macro data in a file"""
1963 """open an editor with the macro data in a file"""
1952 filename = self.shell.mktempfile(macro.value)
1964 filename = self.shell.mktempfile(macro.value)
1953 self.shell.hooks.editor(filename)
1965 self.shell.hooks.editor(filename)
1954
1966
1955 # and make a new macro object, to replace the old one
1967 # and make a new macro object, to replace the old one
1956 mfile = open(filename)
1968 mfile = open(filename)
1957 mvalue = mfile.read()
1969 mvalue = mfile.read()
1958 mfile.close()
1970 mfile.close()
1959 self.shell.user_ns[mname] = Macro(mvalue)
1971 self.shell.user_ns[mname] = Macro(mvalue)
1960
1972
1961 def magic_ed(self,parameter_s=''):
1973 def magic_ed(self,parameter_s=''):
1962 """Alias to %edit."""
1974 """Alias to %edit."""
1963 return self.magic_edit(parameter_s)
1975 return self.magic_edit(parameter_s)
1964
1976
1965 def magic_edit(self,parameter_s='',last_call=['','']):
1977 def magic_edit(self,parameter_s='',last_call=['','']):
1966 """Bring up an editor and execute the resulting code.
1978 """Bring up an editor and execute the resulting code.
1967
1979
1968 Usage:
1980 Usage:
1969 %edit [options] [args]
1981 %edit [options] [args]
1970
1982
1971 %edit runs IPython's editor hook. The default version of this hook is
1983 %edit runs IPython's editor hook. The default version of this hook is
1972 set to call the __IPYTHON__.rc.editor command. This is read from your
1984 set to call the __IPYTHON__.rc.editor command. This is read from your
1973 environment variable $EDITOR. If this isn't found, it will default to
1985 environment variable $EDITOR. If this isn't found, it will default to
1974 vi under Linux/Unix and to notepad under Windows. See the end of this
1986 vi under Linux/Unix and to notepad under Windows. See the end of this
1975 docstring for how to change the editor hook.
1987 docstring for how to change the editor hook.
1976
1988
1977 You can also set the value of this editor via the command line option
1989 You can also set the value of this editor via the command line option
1978 '-editor' or in your ipythonrc file. This is useful if you wish to use
1990 '-editor' or in your ipythonrc file. This is useful if you wish to use
1979 specifically for IPython an editor different from your typical default
1991 specifically for IPython an editor different from your typical default
1980 (and for Windows users who typically don't set environment variables).
1992 (and for Windows users who typically don't set environment variables).
1981
1993
1982 This command allows you to conveniently edit multi-line code right in
1994 This command allows you to conveniently edit multi-line code right in
1983 your IPython session.
1995 your IPython session.
1984
1996
1985 If called without arguments, %edit opens up an empty editor with a
1997 If called without arguments, %edit opens up an empty editor with a
1986 temporary file and will execute the contents of this file when you
1998 temporary file and will execute the contents of this file when you
1987 close it (don't forget to save it!).
1999 close it (don't forget to save it!).
1988
2000
1989
2001
1990 Options:
2002 Options:
1991
2003
1992 -n <number>: open the editor at a specified line number. By default,
2004 -n <number>: open the editor at a specified line number. By default,
1993 the IPython editor hook uses the unix syntax 'editor +N filename', but
2005 the IPython editor hook uses the unix syntax 'editor +N filename', but
1994 you can configure this by providing your own modified hook if your
2006 you can configure this by providing your own modified hook if your
1995 favorite editor supports line-number specifications with a different
2007 favorite editor supports line-number specifications with a different
1996 syntax.
2008 syntax.
1997
2009
1998 -p: this will call the editor with the same data as the previous time
2010 -p: this will call the editor with the same data as the previous time
1999 it was used, regardless of how long ago (in your current session) it
2011 it was used, regardless of how long ago (in your current session) it
2000 was.
2012 was.
2001
2013
2002 -r: use 'raw' input. This option only applies to input taken from the
2014 -r: use 'raw' input. This option only applies to input taken from the
2003 user's history. By default, the 'processed' history is used, so that
2015 user's history. By default, the 'processed' history is used, so that
2004 magics are loaded in their transformed version to valid Python. If
2016 magics are loaded in their transformed version to valid Python. If
2005 this option is given, the raw input as typed as the command line is
2017 this option is given, the raw input as typed as the command line is
2006 used instead. When you exit the editor, it will be executed by
2018 used instead. When you exit the editor, it will be executed by
2007 IPython's own processor.
2019 IPython's own processor.
2008
2020
2009 -x: do not execute the edited code immediately upon exit. This is
2021 -x: do not execute the edited code immediately upon exit. This is
2010 mainly useful if you are editing programs which need to be called with
2022 mainly useful if you are editing programs which need to be called with
2011 command line arguments, which you can then do using %run.
2023 command line arguments, which you can then do using %run.
2012
2024
2013
2025
2014 Arguments:
2026 Arguments:
2015
2027
2016 If arguments are given, the following possibilites exist:
2028 If arguments are given, the following possibilites exist:
2017
2029
2018 - The arguments are numbers or pairs of colon-separated numbers (like
2030 - The arguments are numbers or pairs of colon-separated numbers (like
2019 1 4:8 9). These are interpreted as lines of previous input to be
2031 1 4:8 9). These are interpreted as lines of previous input to be
2020 loaded into the editor. The syntax is the same of the %macro command.
2032 loaded into the editor. The syntax is the same of the %macro command.
2021
2033
2022 - If the argument doesn't start with a number, it is evaluated as a
2034 - If the argument doesn't start with a number, it is evaluated as a
2023 variable and its contents loaded into the editor. You can thus edit
2035 variable and its contents loaded into the editor. You can thus edit
2024 any string which contains python code (including the result of
2036 any string which contains python code (including the result of
2025 previous edits).
2037 previous edits).
2026
2038
2027 - If the argument is the name of an object (other than a string),
2039 - If the argument is the name of an object (other than a string),
2028 IPython will try to locate the file where it was defined and open the
2040 IPython will try to locate the file where it was defined and open the
2029 editor at the point where it is defined. You can use `%edit function`
2041 editor at the point where it is defined. You can use `%edit function`
2030 to load an editor exactly at the point where 'function' is defined,
2042 to load an editor exactly at the point where 'function' is defined,
2031 edit it and have the file be executed automatically.
2043 edit it and have the file be executed automatically.
2032
2044
2033 If the object is a macro (see %macro for details), this opens up your
2045 If the object is a macro (see %macro for details), this opens up your
2034 specified editor with a temporary file containing the macro's data.
2046 specified editor with a temporary file containing the macro's data.
2035 Upon exit, the macro is reloaded with the contents of the file.
2047 Upon exit, the macro is reloaded with the contents of the file.
2036
2048
2037 Note: opening at an exact line is only supported under Unix, and some
2049 Note: opening at an exact line is only supported under Unix, and some
2038 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2050 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2039 '+NUMBER' parameter necessary for this feature. Good editors like
2051 '+NUMBER' parameter necessary for this feature. Good editors like
2040 (X)Emacs, vi, jed, pico and joe all do.
2052 (X)Emacs, vi, jed, pico and joe all do.
2041
2053
2042 - If the argument is not found as a variable, IPython will look for a
2054 - If the argument is not found as a variable, IPython will look for a
2043 file with that name (adding .py if necessary) and load it into the
2055 file with that name (adding .py if necessary) and load it into the
2044 editor. It will execute its contents with execfile() when you exit,
2056 editor. It will execute its contents with execfile() when you exit,
2045 loading any code in the file into your interactive namespace.
2057 loading any code in the file into your interactive namespace.
2046
2058
2047 After executing your code, %edit will return as output the code you
2059 After executing your code, %edit will return as output the code you
2048 typed in the editor (except when it was an existing file). This way
2060 typed in the editor (except when it was an existing file). This way
2049 you can reload the code in further invocations of %edit as a variable,
2061 you can reload the code in further invocations of %edit as a variable,
2050 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2062 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2051 the output.
2063 the output.
2052
2064
2053 Note that %edit is also available through the alias %ed.
2065 Note that %edit is also available through the alias %ed.
2054
2066
2055 This is an example of creating a simple function inside the editor and
2067 This is an example of creating a simple function inside the editor and
2056 then modifying it. First, start up the editor:
2068 then modifying it. First, start up the editor:
2057
2069
2058 In [1]: ed\\
2070 In [1]: ed\\
2059 Editing... done. Executing edited code...\\
2071 Editing... done. Executing edited code...\\
2060 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
2072 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
2061
2073
2062 We can then call the function foo():
2074 We can then call the function foo():
2063
2075
2064 In [2]: foo()\\
2076 In [2]: foo()\\
2065 foo() was defined in an editing session
2077 foo() was defined in an editing session
2066
2078
2067 Now we edit foo. IPython automatically loads the editor with the
2079 Now we edit foo. IPython automatically loads the editor with the
2068 (temporary) file where foo() was previously defined:
2080 (temporary) file where foo() was previously defined:
2069
2081
2070 In [3]: ed foo\\
2082 In [3]: ed foo\\
2071 Editing... done. Executing edited code...
2083 Editing... done. Executing edited code...
2072
2084
2073 And if we call foo() again we get the modified version:
2085 And if we call foo() again we get the modified version:
2074
2086
2075 In [4]: foo()\\
2087 In [4]: foo()\\
2076 foo() has now been changed!
2088 foo() has now been changed!
2077
2089
2078 Here is an example of how to edit a code snippet successive
2090 Here is an example of how to edit a code snippet successive
2079 times. First we call the editor:
2091 times. First we call the editor:
2080
2092
2081 In [8]: ed\\
2093 In [8]: ed\\
2082 Editing... done. Executing edited code...\\
2094 Editing... done. Executing edited code...\\
2083 hello\\
2095 hello\\
2084 Out[8]: "print 'hello'\\n"
2096 Out[8]: "print 'hello'\\n"
2085
2097
2086 Now we call it again with the previous output (stored in _):
2098 Now we call it again with the previous output (stored in _):
2087
2099
2088 In [9]: ed _\\
2100 In [9]: ed _\\
2089 Editing... done. Executing edited code...\\
2101 Editing... done. Executing edited code...\\
2090 hello world\\
2102 hello world\\
2091 Out[9]: "print 'hello world'\\n"
2103 Out[9]: "print 'hello world'\\n"
2092
2104
2093 Now we call it with the output #8 (stored in _8, also as Out[8]):
2105 Now we call it with the output #8 (stored in _8, also as Out[8]):
2094
2106
2095 In [10]: ed _8\\
2107 In [10]: ed _8\\
2096 Editing... done. Executing edited code...\\
2108 Editing... done. Executing edited code...\\
2097 hello again\\
2109 hello again\\
2098 Out[10]: "print 'hello again'\\n"
2110 Out[10]: "print 'hello again'\\n"
2099
2111
2100
2112
2101 Changing the default editor hook:
2113 Changing the default editor hook:
2102
2114
2103 If you wish to write your own editor hook, you can put it in a
2115 If you wish to write your own editor hook, you can put it in a
2104 configuration file which you load at startup time. The default hook
2116 configuration file which you load at startup time. The default hook
2105 is defined in the IPython.hooks module, and you can use that as a
2117 is defined in the IPython.hooks module, and you can use that as a
2106 starting example for further modifications. That file also has
2118 starting example for further modifications. That file also has
2107 general instructions on how to set a new hook for use once you've
2119 general instructions on how to set a new hook for use once you've
2108 defined it."""
2120 defined it."""
2109
2121
2110 # FIXME: This function has become a convoluted mess. It needs a
2122 # FIXME: This function has become a convoluted mess. It needs a
2111 # ground-up rewrite with clean, simple logic.
2123 # ground-up rewrite with clean, simple logic.
2112
2124
2113 def make_filename(arg):
2125 def make_filename(arg):
2114 "Make a filename from the given args"
2126 "Make a filename from the given args"
2115 try:
2127 try:
2116 filename = get_py_filename(arg)
2128 filename = get_py_filename(arg)
2117 except IOError:
2129 except IOError:
2118 if args.endswith('.py'):
2130 if args.endswith('.py'):
2119 filename = arg
2131 filename = arg
2120 else:
2132 else:
2121 filename = None
2133 filename = None
2122 return filename
2134 return filename
2123
2135
2124 # custom exceptions
2136 # custom exceptions
2125 class DataIsObject(Exception): pass
2137 class DataIsObject(Exception): pass
2126
2138
2127 opts,args = self.parse_options(parameter_s,'prxn:')
2139 opts,args = self.parse_options(parameter_s,'prxn:')
2128 # Set a few locals from the options for convenience:
2140 # Set a few locals from the options for convenience:
2129 opts_p = opts.has_key('p')
2141 opts_p = opts.has_key('p')
2130 opts_r = opts.has_key('r')
2142 opts_r = opts.has_key('r')
2131
2143
2132 # Default line number value
2144 # Default line number value
2133 lineno = opts.get('n',None)
2145 lineno = opts.get('n',None)
2134
2146
2135 if opts_p:
2147 if opts_p:
2136 args = '_%s' % last_call[0]
2148 args = '_%s' % last_call[0]
2137 if not self.shell.user_ns.has_key(args):
2149 if not self.shell.user_ns.has_key(args):
2138 args = last_call[1]
2150 args = last_call[1]
2139
2151
2140 # use last_call to remember the state of the previous call, but don't
2152 # use last_call to remember the state of the previous call, but don't
2141 # let it be clobbered by successive '-p' calls.
2153 # let it be clobbered by successive '-p' calls.
2142 try:
2154 try:
2143 last_call[0] = self.shell.outputcache.prompt_count
2155 last_call[0] = self.shell.outputcache.prompt_count
2144 if not opts_p:
2156 if not opts_p:
2145 last_call[1] = parameter_s
2157 last_call[1] = parameter_s
2146 except:
2158 except:
2147 pass
2159 pass
2148
2160
2149 # by default this is done with temp files, except when the given
2161 # by default this is done with temp files, except when the given
2150 # arg is a filename
2162 # arg is a filename
2151 use_temp = 1
2163 use_temp = 1
2152
2164
2153 if re.match(r'\d',args):
2165 if re.match(r'\d',args):
2154 # Mode where user specifies ranges of lines, like in %macro.
2166 # Mode where user specifies ranges of lines, like in %macro.
2155 # This means that you can't edit files whose names begin with
2167 # This means that you can't edit files whose names begin with
2156 # numbers this way. Tough.
2168 # numbers this way. Tough.
2157 ranges = args.split()
2169 ranges = args.split()
2158 data = ''.join(self.extract_input_slices(ranges,opts_r))
2170 data = ''.join(self.extract_input_slices(ranges,opts_r))
2159 elif args.endswith('.py'):
2171 elif args.endswith('.py'):
2160 filename = make_filename(args)
2172 filename = make_filename(args)
2161 data = ''
2173 data = ''
2162 use_temp = 0
2174 use_temp = 0
2163 elif args:
2175 elif args:
2164 try:
2176 try:
2165 # Load the parameter given as a variable. If not a string,
2177 # Load the parameter given as a variable. If not a string,
2166 # process it as an object instead (below)
2178 # process it as an object instead (below)
2167
2179
2168 #print '*** args',args,'type',type(args) # dbg
2180 #print '*** args',args,'type',type(args) # dbg
2169 data = eval(args,self.shell.user_ns)
2181 data = eval(args,self.shell.user_ns)
2170 if not type(data) in StringTypes:
2182 if not type(data) in StringTypes:
2171 raise DataIsObject
2183 raise DataIsObject
2172
2184
2173 except (NameError,SyntaxError):
2185 except (NameError,SyntaxError):
2174 # given argument is not a variable, try as a filename
2186 # given argument is not a variable, try as a filename
2175 filename = make_filename(args)
2187 filename = make_filename(args)
2176 if filename is None:
2188 if filename is None:
2177 warn("Argument given (%s) can't be found as a variable "
2189 warn("Argument given (%s) can't be found as a variable "
2178 "or as a filename." % args)
2190 "or as a filename." % args)
2179 return
2191 return
2180
2192
2181 data = ''
2193 data = ''
2182 use_temp = 0
2194 use_temp = 0
2183 except DataIsObject:
2195 except DataIsObject:
2184
2196
2185 # macros have a special edit function
2197 # macros have a special edit function
2186 if isinstance(data,Macro):
2198 if isinstance(data,Macro):
2187 self._edit_macro(args,data)
2199 self._edit_macro(args,data)
2188 return
2200 return
2189
2201
2190 # For objects, try to edit the file where they are defined
2202 # For objects, try to edit the file where they are defined
2191 try:
2203 try:
2192 filename = inspect.getabsfile(data)
2204 filename = inspect.getabsfile(data)
2193 datafile = 1
2205 datafile = 1
2194 except TypeError:
2206 except TypeError:
2195 filename = make_filename(args)
2207 filename = make_filename(args)
2196 datafile = 1
2208 datafile = 1
2197 warn('Could not find file where `%s` is defined.\n'
2209 warn('Could not find file where `%s` is defined.\n'
2198 'Opening a file named `%s`' % (args,filename))
2210 'Opening a file named `%s`' % (args,filename))
2199 # Now, make sure we can actually read the source (if it was in
2211 # Now, make sure we can actually read the source (if it was in
2200 # a temp file it's gone by now).
2212 # a temp file it's gone by now).
2201 if datafile:
2213 if datafile:
2202 try:
2214 try:
2203 if lineno is None:
2215 if lineno is None:
2204 lineno = inspect.getsourcelines(data)[1]
2216 lineno = inspect.getsourcelines(data)[1]
2205 except IOError:
2217 except IOError:
2206 filename = make_filename(args)
2218 filename = make_filename(args)
2207 if filename is None:
2219 if filename is None:
2208 warn('The file `%s` where `%s` was defined cannot '
2220 warn('The file `%s` where `%s` was defined cannot '
2209 'be read.' % (filename,data))
2221 'be read.' % (filename,data))
2210 return
2222 return
2211 use_temp = 0
2223 use_temp = 0
2212 else:
2224 else:
2213 data = ''
2225 data = ''
2214
2226
2215 if use_temp:
2227 if use_temp:
2216 filename = self.shell.mktempfile(data)
2228 filename = self.shell.mktempfile(data)
2217 print 'IPython will make a temporary file named:',filename
2229 print 'IPython will make a temporary file named:',filename
2218
2230
2219 # do actual editing here
2231 # do actual editing here
2220 print 'Editing...',
2232 print 'Editing...',
2221 sys.stdout.flush()
2233 sys.stdout.flush()
2222 self.shell.hooks.editor(filename,lineno)
2234 self.shell.hooks.editor(filename,lineno)
2223 if opts.has_key('x'): # -x prevents actual execution
2235 if opts.has_key('x'): # -x prevents actual execution
2224 print
2236 print
2225 else:
2237 else:
2226 print 'done. Executing edited code...'
2238 print 'done. Executing edited code...'
2227 if opts_r:
2239 if opts_r:
2228 self.shell.runlines(file_read(filename))
2240 self.shell.runlines(file_read(filename))
2229 else:
2241 else:
2230 self.shell.safe_execfile(filename,self.shell.user_ns,
2242 self.shell.safe_execfile(filename,self.shell.user_ns,
2231 self.shell.user_ns)
2243 self.shell.user_ns)
2232 if use_temp:
2244 if use_temp:
2233 try:
2245 try:
2234 return open(filename).read()
2246 return open(filename).read()
2235 except IOError,msg:
2247 except IOError,msg:
2236 if msg.filename == filename:
2248 if msg.filename == filename:
2237 warn('File not found. Did you forget to save?')
2249 warn('File not found. Did you forget to save?')
2238 return
2250 return
2239 else:
2251 else:
2240 self.shell.showtraceback()
2252 self.shell.showtraceback()
2241
2253
2242 def magic_xmode(self,parameter_s = ''):
2254 def magic_xmode(self,parameter_s = ''):
2243 """Switch modes for the exception handlers.
2255 """Switch modes for the exception handlers.
2244
2256
2245 Valid modes: Plain, Context and Verbose.
2257 Valid modes: Plain, Context and Verbose.
2246
2258
2247 If called without arguments, acts as a toggle."""
2259 If called without arguments, acts as a toggle."""
2248
2260
2249 def xmode_switch_err(name):
2261 def xmode_switch_err(name):
2250 warn('Error changing %s exception modes.\n%s' %
2262 warn('Error changing %s exception modes.\n%s' %
2251 (name,sys.exc_info()[1]))
2263 (name,sys.exc_info()[1]))
2252
2264
2253 shell = self.shell
2265 shell = self.shell
2254 new_mode = parameter_s.strip().capitalize()
2266 new_mode = parameter_s.strip().capitalize()
2255 try:
2267 try:
2256 shell.InteractiveTB.set_mode(mode=new_mode)
2268 shell.InteractiveTB.set_mode(mode=new_mode)
2257 print 'Exception reporting mode:',shell.InteractiveTB.mode
2269 print 'Exception reporting mode:',shell.InteractiveTB.mode
2258 except:
2270 except:
2259 xmode_switch_err('user')
2271 xmode_switch_err('user')
2260
2272
2261 # threaded shells use a special handler in sys.excepthook
2273 # threaded shells use a special handler in sys.excepthook
2262 if shell.isthreaded:
2274 if shell.isthreaded:
2263 try:
2275 try:
2264 shell.sys_excepthook.set_mode(mode=new_mode)
2276 shell.sys_excepthook.set_mode(mode=new_mode)
2265 except:
2277 except:
2266 xmode_switch_err('threaded')
2278 xmode_switch_err('threaded')
2267
2279
2268 def magic_colors(self,parameter_s = ''):
2280 def magic_colors(self,parameter_s = ''):
2269 """Switch color scheme for prompts, info system and exception handlers.
2281 """Switch color scheme for prompts, info system and exception handlers.
2270
2282
2271 Currently implemented schemes: NoColor, Linux, LightBG.
2283 Currently implemented schemes: NoColor, Linux, LightBG.
2272
2284
2273 Color scheme names are not case-sensitive."""
2285 Color scheme names are not case-sensitive."""
2274
2286
2275 def color_switch_err(name):
2287 def color_switch_err(name):
2276 warn('Error changing %s color schemes.\n%s' %
2288 warn('Error changing %s color schemes.\n%s' %
2277 (name,sys.exc_info()[1]))
2289 (name,sys.exc_info()[1]))
2278
2290
2279
2291
2280 new_scheme = parameter_s.strip()
2292 new_scheme = parameter_s.strip()
2281 if not new_scheme:
2293 if not new_scheme:
2282 raise UsageError(
2294 raise UsageError(
2283 "%colors: you must specify a color scheme. See '%colors?'")
2295 "%colors: you must specify a color scheme. See '%colors?'")
2284 return
2296 return
2285 # local shortcut
2297 # local shortcut
2286 shell = self.shell
2298 shell = self.shell
2287
2299
2288 import IPython.rlineimpl as readline
2300 import IPython.rlineimpl as readline
2289
2301
2290 if not readline.have_readline and sys.platform == "win32":
2302 if not readline.have_readline and sys.platform == "win32":
2291 msg = """\
2303 msg = """\
2292 Proper color support under MS Windows requires the pyreadline library.
2304 Proper color support under MS Windows requires the pyreadline library.
2293 You can find it at:
2305 You can find it at:
2294 http://ipython.scipy.org/moin/PyReadline/Intro
2306 http://ipython.scipy.org/moin/PyReadline/Intro
2295 Gary's readline needs the ctypes module, from:
2307 Gary's readline needs the ctypes module, from:
2296 http://starship.python.net/crew/theller/ctypes
2308 http://starship.python.net/crew/theller/ctypes
2297 (Note that ctypes is already part of Python versions 2.5 and newer).
2309 (Note that ctypes is already part of Python versions 2.5 and newer).
2298
2310
2299 Defaulting color scheme to 'NoColor'"""
2311 Defaulting color scheme to 'NoColor'"""
2300 new_scheme = 'NoColor'
2312 new_scheme = 'NoColor'
2301 warn(msg)
2313 warn(msg)
2302
2314
2303 # readline option is 0
2315 # readline option is 0
2304 if not shell.has_readline:
2316 if not shell.has_readline:
2305 new_scheme = 'NoColor'
2317 new_scheme = 'NoColor'
2306
2318
2307 # Set prompt colors
2319 # Set prompt colors
2308 try:
2320 try:
2309 shell.outputcache.set_colors(new_scheme)
2321 shell.outputcache.set_colors(new_scheme)
2310 except:
2322 except:
2311 color_switch_err('prompt')
2323 color_switch_err('prompt')
2312 else:
2324 else:
2313 shell.rc.colors = \
2325 shell.rc.colors = \
2314 shell.outputcache.color_table.active_scheme_name
2326 shell.outputcache.color_table.active_scheme_name
2315 # Set exception colors
2327 # Set exception colors
2316 try:
2328 try:
2317 shell.InteractiveTB.set_colors(scheme = new_scheme)
2329 shell.InteractiveTB.set_colors(scheme = new_scheme)
2318 shell.SyntaxTB.set_colors(scheme = new_scheme)
2330 shell.SyntaxTB.set_colors(scheme = new_scheme)
2319 except:
2331 except:
2320 color_switch_err('exception')
2332 color_switch_err('exception')
2321
2333
2322 # threaded shells use a verbose traceback in sys.excepthook
2334 # threaded shells use a verbose traceback in sys.excepthook
2323 if shell.isthreaded:
2335 if shell.isthreaded:
2324 try:
2336 try:
2325 shell.sys_excepthook.set_colors(scheme=new_scheme)
2337 shell.sys_excepthook.set_colors(scheme=new_scheme)
2326 except:
2338 except:
2327 color_switch_err('system exception handler')
2339 color_switch_err('system exception handler')
2328
2340
2329 # Set info (for 'object?') colors
2341 # Set info (for 'object?') colors
2330 if shell.rc.color_info:
2342 if shell.rc.color_info:
2331 try:
2343 try:
2332 shell.inspector.set_active_scheme(new_scheme)
2344 shell.inspector.set_active_scheme(new_scheme)
2333 except:
2345 except:
2334 color_switch_err('object inspector')
2346 color_switch_err('object inspector')
2335 else:
2347 else:
2336 shell.inspector.set_active_scheme('NoColor')
2348 shell.inspector.set_active_scheme('NoColor')
2337
2349
2338 def magic_color_info(self,parameter_s = ''):
2350 def magic_color_info(self,parameter_s = ''):
2339 """Toggle color_info.
2351 """Toggle color_info.
2340
2352
2341 The color_info configuration parameter controls whether colors are
2353 The color_info configuration parameter controls whether colors are
2342 used for displaying object details (by things like %psource, %pfile or
2354 used for displaying object details (by things like %psource, %pfile or
2343 the '?' system). This function toggles this value with each call.
2355 the '?' system). This function toggles this value with each call.
2344
2356
2345 Note that unless you have a fairly recent pager (less works better
2357 Note that unless you have a fairly recent pager (less works better
2346 than more) in your system, using colored object information displays
2358 than more) in your system, using colored object information displays
2347 will not work properly. Test it and see."""
2359 will not work properly. Test it and see."""
2348
2360
2349 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2361 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2350 self.magic_colors(self.shell.rc.colors)
2362 self.magic_colors(self.shell.rc.colors)
2351 print 'Object introspection functions have now coloring:',
2363 print 'Object introspection functions have now coloring:',
2352 print ['OFF','ON'][self.shell.rc.color_info]
2364 print ['OFF','ON'][self.shell.rc.color_info]
2353
2365
2354 def magic_Pprint(self, parameter_s=''):
2366 def magic_Pprint(self, parameter_s=''):
2355 """Toggle pretty printing on/off."""
2367 """Toggle pretty printing on/off."""
2356
2368
2357 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2369 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2358 print 'Pretty printing has been turned', \
2370 print 'Pretty printing has been turned', \
2359 ['OFF','ON'][self.shell.rc.pprint]
2371 ['OFF','ON'][self.shell.rc.pprint]
2360
2372
2361 def magic_exit(self, parameter_s=''):
2373 def magic_exit(self, parameter_s=''):
2362 """Exit IPython, confirming if configured to do so.
2374 """Exit IPython, confirming if configured to do so.
2363
2375
2364 You can configure whether IPython asks for confirmation upon exit by
2376 You can configure whether IPython asks for confirmation upon exit by
2365 setting the confirm_exit flag in the ipythonrc file."""
2377 setting the confirm_exit flag in the ipythonrc file."""
2366
2378
2367 self.shell.exit()
2379 self.shell.exit()
2368
2380
2369 def magic_quit(self, parameter_s=''):
2381 def magic_quit(self, parameter_s=''):
2370 """Exit IPython, confirming if configured to do so (like %exit)"""
2382 """Exit IPython, confirming if configured to do so (like %exit)"""
2371
2383
2372 self.shell.exit()
2384 self.shell.exit()
2373
2385
2374 def magic_Exit(self, parameter_s=''):
2386 def magic_Exit(self, parameter_s=''):
2375 """Exit IPython without confirmation."""
2387 """Exit IPython without confirmation."""
2376
2388
2377 self.shell.exit_now = True
2389 self.shell.exit_now = True
2378
2390
2379 #......................................................................
2391 #......................................................................
2380 # Functions to implement unix shell-type things
2392 # Functions to implement unix shell-type things
2381
2393
2382 def magic_alias(self, parameter_s = ''):
2394 def magic_alias(self, parameter_s = ''):
2383 """Define an alias for a system command.
2395 """Define an alias for a system command.
2384
2396
2385 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2397 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2386
2398
2387 Then, typing 'alias_name params' will execute the system command 'cmd
2399 Then, typing 'alias_name params' will execute the system command 'cmd
2388 params' (from your underlying operating system).
2400 params' (from your underlying operating system).
2389
2401
2390 Aliases have lower precedence than magic functions and Python normal
2402 Aliases have lower precedence than magic functions and Python normal
2391 variables, so if 'foo' is both a Python variable and an alias, the
2403 variables, so if 'foo' is both a Python variable and an alias, the
2392 alias can not be executed until 'del foo' removes the Python variable.
2404 alias can not be executed until 'del foo' removes the Python variable.
2393
2405
2394 You can use the %l specifier in an alias definition to represent the
2406 You can use the %l specifier in an alias definition to represent the
2395 whole line when the alias is called. For example:
2407 whole line when the alias is called. For example:
2396
2408
2397 In [2]: alias all echo "Input in brackets: <%l>"\\
2409 In [2]: alias all echo "Input in brackets: <%l>"\\
2398 In [3]: all hello world\\
2410 In [3]: all hello world\\
2399 Input in brackets: <hello world>
2411 Input in brackets: <hello world>
2400
2412
2401 You can also define aliases with parameters using %s specifiers (one
2413 You can also define aliases with parameters using %s specifiers (one
2402 per parameter):
2414 per parameter):
2403
2415
2404 In [1]: alias parts echo first %s second %s\\
2416 In [1]: alias parts echo first %s second %s\\
2405 In [2]: %parts A B\\
2417 In [2]: %parts A B\\
2406 first A second B\\
2418 first A second B\\
2407 In [3]: %parts A\\
2419 In [3]: %parts A\\
2408 Incorrect number of arguments: 2 expected.\\
2420 Incorrect number of arguments: 2 expected.\\
2409 parts is an alias to: 'echo first %s second %s'
2421 parts is an alias to: 'echo first %s second %s'
2410
2422
2411 Note that %l and %s are mutually exclusive. You can only use one or
2423 Note that %l and %s are mutually exclusive. You can only use one or
2412 the other in your aliases.
2424 the other in your aliases.
2413
2425
2414 Aliases expand Python variables just like system calls using ! or !!
2426 Aliases expand Python variables just like system calls using ! or !!
2415 do: all expressions prefixed with '$' get expanded. For details of
2427 do: all expressions prefixed with '$' get expanded. For details of
2416 the semantic rules, see PEP-215:
2428 the semantic rules, see PEP-215:
2417 http://www.python.org/peps/pep-0215.html. This is the library used by
2429 http://www.python.org/peps/pep-0215.html. This is the library used by
2418 IPython for variable expansion. If you want to access a true shell
2430 IPython for variable expansion. If you want to access a true shell
2419 variable, an extra $ is necessary to prevent its expansion by IPython:
2431 variable, an extra $ is necessary to prevent its expansion by IPython:
2420
2432
2421 In [6]: alias show echo\\
2433 In [6]: alias show echo\\
2422 In [7]: PATH='A Python string'\\
2434 In [7]: PATH='A Python string'\\
2423 In [8]: show $PATH\\
2435 In [8]: show $PATH\\
2424 A Python string\\
2436 A Python string\\
2425 In [9]: show $$PATH\\
2437 In [9]: show $$PATH\\
2426 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2438 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2427
2439
2428 You can use the alias facility to acess all of $PATH. See the %rehash
2440 You can use the alias facility to acess all of $PATH. See the %rehash
2429 and %rehashx functions, which automatically create aliases for the
2441 and %rehashx functions, which automatically create aliases for the
2430 contents of your $PATH.
2442 contents of your $PATH.
2431
2443
2432 If called with no parameters, %alias prints the current alias table."""
2444 If called with no parameters, %alias prints the current alias table."""
2433
2445
2434 par = parameter_s.strip()
2446 par = parameter_s.strip()
2435 if not par:
2447 if not par:
2436 stored = self.db.get('stored_aliases', {} )
2448 stored = self.db.get('stored_aliases', {} )
2437 atab = self.shell.alias_table
2449 atab = self.shell.alias_table
2438 aliases = atab.keys()
2450 aliases = atab.keys()
2439 aliases.sort()
2451 aliases.sort()
2440 res = []
2452 res = []
2441 showlast = []
2453 showlast = []
2442 for alias in aliases:
2454 for alias in aliases:
2443 special = False
2455 special = False
2444 try:
2456 try:
2445 tgt = atab[alias][1]
2457 tgt = atab[alias][1]
2446 except (TypeError, AttributeError):
2458 except (TypeError, AttributeError):
2447 # unsubscriptable? probably a callable
2459 # unsubscriptable? probably a callable
2448 tgt = atab[alias]
2460 tgt = atab[alias]
2449 special = True
2461 special = True
2450 # 'interesting' aliases
2462 # 'interesting' aliases
2451 if (alias in stored or
2463 if (alias in stored or
2452 special or
2464 special or
2453 alias.lower() != os.path.splitext(tgt)[0].lower() or
2465 alias.lower() != os.path.splitext(tgt)[0].lower() or
2454 ' ' in tgt):
2466 ' ' in tgt):
2455 showlast.append((alias, tgt))
2467 showlast.append((alias, tgt))
2456 else:
2468 else:
2457 res.append((alias, tgt ))
2469 res.append((alias, tgt ))
2458
2470
2459 # show most interesting aliases last
2471 # show most interesting aliases last
2460 res.extend(showlast)
2472 res.extend(showlast)
2461 print "Total number of aliases:",len(aliases)
2473 print "Total number of aliases:",len(aliases)
2462 return res
2474 return res
2463 try:
2475 try:
2464 alias,cmd = par.split(None,1)
2476 alias,cmd = par.split(None,1)
2465 except:
2477 except:
2466 print OInspect.getdoc(self.magic_alias)
2478 print OInspect.getdoc(self.magic_alias)
2467 else:
2479 else:
2468 nargs = cmd.count('%s')
2480 nargs = cmd.count('%s')
2469 if nargs>0 and cmd.find('%l')>=0:
2481 if nargs>0 and cmd.find('%l')>=0:
2470 error('The %s and %l specifiers are mutually exclusive '
2482 error('The %s and %l specifiers are mutually exclusive '
2471 'in alias definitions.')
2483 'in alias definitions.')
2472 else: # all looks OK
2484 else: # all looks OK
2473 self.shell.alias_table[alias] = (nargs,cmd)
2485 self.shell.alias_table[alias] = (nargs,cmd)
2474 self.shell.alias_table_validate(verbose=0)
2486 self.shell.alias_table_validate(verbose=0)
2475 # end magic_alias
2487 # end magic_alias
2476
2488
2477 def magic_unalias(self, parameter_s = ''):
2489 def magic_unalias(self, parameter_s = ''):
2478 """Remove an alias"""
2490 """Remove an alias"""
2479
2491
2480 aname = parameter_s.strip()
2492 aname = parameter_s.strip()
2481 if aname in self.shell.alias_table:
2493 if aname in self.shell.alias_table:
2482 del self.shell.alias_table[aname]
2494 del self.shell.alias_table[aname]
2483 stored = self.db.get('stored_aliases', {} )
2495 stored = self.db.get('stored_aliases', {} )
2484 if aname in stored:
2496 if aname in stored:
2485 print "Removing %stored alias",aname
2497 print "Removing %stored alias",aname
2486 del stored[aname]
2498 del stored[aname]
2487 self.db['stored_aliases'] = stored
2499 self.db['stored_aliases'] = stored
2488
2500
2489
2501
2490 def magic_rehashx(self, parameter_s = ''):
2502 def magic_rehashx(self, parameter_s = ''):
2491 """Update the alias table with all executable files in $PATH.
2503 """Update the alias table with all executable files in $PATH.
2492
2504
2493 This version explicitly checks that every entry in $PATH is a file
2505 This version explicitly checks that every entry in $PATH is a file
2494 with execute access (os.X_OK), so it is much slower than %rehash.
2506 with execute access (os.X_OK), so it is much slower than %rehash.
2495
2507
2496 Under Windows, it checks executability as a match agains a
2508 Under Windows, it checks executability as a match agains a
2497 '|'-separated string of extensions, stored in the IPython config
2509 '|'-separated string of extensions, stored in the IPython config
2498 variable win_exec_ext. This defaults to 'exe|com|bat'.
2510 variable win_exec_ext. This defaults to 'exe|com|bat'.
2499
2511
2500 This function also resets the root module cache of module completer,
2512 This function also resets the root module cache of module completer,
2501 used on slow filesystems.
2513 used on slow filesystems.
2502 """
2514 """
2503
2515
2504
2516
2505 ip = self.api
2517 ip = self.api
2506
2518
2507 # for the benefit of module completer in ipy_completers.py
2519 # for the benefit of module completer in ipy_completers.py
2508 del ip.db['rootmodules']
2520 del ip.db['rootmodules']
2509
2521
2510 path = [os.path.abspath(os.path.expanduser(p)) for p in
2522 path = [os.path.abspath(os.path.expanduser(p)) for p in
2511 os.environ.get('PATH','').split(os.pathsep)]
2523 os.environ.get('PATH','').split(os.pathsep)]
2512 path = filter(os.path.isdir,path)
2524 path = filter(os.path.isdir,path)
2513
2525
2514 alias_table = self.shell.alias_table
2526 alias_table = self.shell.alias_table
2515 syscmdlist = []
2527 syscmdlist = []
2516 if os.name == 'posix':
2528 if os.name == 'posix':
2517 isexec = lambda fname:os.path.isfile(fname) and \
2529 isexec = lambda fname:os.path.isfile(fname) and \
2518 os.access(fname,os.X_OK)
2530 os.access(fname,os.X_OK)
2519 else:
2531 else:
2520
2532
2521 try:
2533 try:
2522 winext = os.environ['pathext'].replace(';','|').replace('.','')
2534 winext = os.environ['pathext'].replace(';','|').replace('.','')
2523 except KeyError:
2535 except KeyError:
2524 winext = 'exe|com|bat|py'
2536 winext = 'exe|com|bat|py'
2525 if 'py' not in winext:
2537 if 'py' not in winext:
2526 winext += '|py'
2538 winext += '|py'
2527 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2539 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2528 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2540 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2529 savedir = os.getcwd()
2541 savedir = os.getcwd()
2530 try:
2542 try:
2531 # write the whole loop for posix/Windows so we don't have an if in
2543 # write the whole loop for posix/Windows so we don't have an if in
2532 # the innermost part
2544 # the innermost part
2533 if os.name == 'posix':
2545 if os.name == 'posix':
2534 for pdir in path:
2546 for pdir in path:
2535 os.chdir(pdir)
2547 os.chdir(pdir)
2536 for ff in os.listdir(pdir):
2548 for ff in os.listdir(pdir):
2537 if isexec(ff) and ff not in self.shell.no_alias:
2549 if isexec(ff) and ff not in self.shell.no_alias:
2538 # each entry in the alias table must be (N,name),
2550 # each entry in the alias table must be (N,name),
2539 # where N is the number of positional arguments of the
2551 # where N is the number of positional arguments of the
2540 # alias.
2552 # alias.
2541 alias_table[ff] = (0,ff)
2553 alias_table[ff] = (0,ff)
2542 syscmdlist.append(ff)
2554 syscmdlist.append(ff)
2543 else:
2555 else:
2544 for pdir in path:
2556 for pdir in path:
2545 os.chdir(pdir)
2557 os.chdir(pdir)
2546 for ff in os.listdir(pdir):
2558 for ff in os.listdir(pdir):
2547 base, ext = os.path.splitext(ff)
2559 base, ext = os.path.splitext(ff)
2548 if isexec(ff) and base not in self.shell.no_alias:
2560 if isexec(ff) and base not in self.shell.no_alias:
2549 if ext.lower() == '.exe':
2561 if ext.lower() == '.exe':
2550 ff = base
2562 ff = base
2551 alias_table[base.lower()] = (0,ff)
2563 alias_table[base.lower()] = (0,ff)
2552 syscmdlist.append(ff)
2564 syscmdlist.append(ff)
2553 # Make sure the alias table doesn't contain keywords or builtins
2565 # Make sure the alias table doesn't contain keywords or builtins
2554 self.shell.alias_table_validate()
2566 self.shell.alias_table_validate()
2555 # Call again init_auto_alias() so we get 'rm -i' and other
2567 # Call again init_auto_alias() so we get 'rm -i' and other
2556 # modified aliases since %rehashx will probably clobber them
2568 # modified aliases since %rehashx will probably clobber them
2557
2569
2558 # no, we don't want them. if %rehashx clobbers them, good,
2570 # no, we don't want them. if %rehashx clobbers them, good,
2559 # we'll probably get better versions
2571 # we'll probably get better versions
2560 # self.shell.init_auto_alias()
2572 # self.shell.init_auto_alias()
2561 db = ip.db
2573 db = ip.db
2562 db['syscmdlist'] = syscmdlist
2574 db['syscmdlist'] = syscmdlist
2563 finally:
2575 finally:
2564 os.chdir(savedir)
2576 os.chdir(savedir)
2565
2577
2566 def magic_pwd(self, parameter_s = ''):
2578 def magic_pwd(self, parameter_s = ''):
2567 """Return the current working directory path."""
2579 """Return the current working directory path."""
2568 return os.getcwd()
2580 return os.getcwd()
2569
2581
2570 def magic_cd(self, parameter_s=''):
2582 def magic_cd(self, parameter_s=''):
2571 """Change the current working directory.
2583 """Change the current working directory.
2572
2584
2573 This command automatically maintains an internal list of directories
2585 This command automatically maintains an internal list of directories
2574 you visit during your IPython session, in the variable _dh. The
2586 you visit during your IPython session, in the variable _dh. The
2575 command %dhist shows this history nicely formatted. You can also
2587 command %dhist shows this history nicely formatted. You can also
2576 do 'cd -<tab>' to see directory history conveniently.
2588 do 'cd -<tab>' to see directory history conveniently.
2577
2589
2578 Usage:
2590 Usage:
2579
2591
2580 cd 'dir': changes to directory 'dir'.
2592 cd 'dir': changes to directory 'dir'.
2581
2593
2582 cd -: changes to the last visited directory.
2594 cd -: changes to the last visited directory.
2583
2595
2584 cd -<n>: changes to the n-th directory in the directory history.
2596 cd -<n>: changes to the n-th directory in the directory history.
2585
2597
2586 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2598 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2587 (note: cd <bookmark_name> is enough if there is no
2599 (note: cd <bookmark_name> is enough if there is no
2588 directory <bookmark_name>, but a bookmark with the name exists.)
2600 directory <bookmark_name>, but a bookmark with the name exists.)
2589 'cd -b <tab>' allows you to tab-complete bookmark names.
2601 'cd -b <tab>' allows you to tab-complete bookmark names.
2590
2602
2591 Options:
2603 Options:
2592
2604
2593 -q: quiet. Do not print the working directory after the cd command is
2605 -q: quiet. Do not print the working directory after the cd command is
2594 executed. By default IPython's cd command does print this directory,
2606 executed. By default IPython's cd command does print this directory,
2595 since the default prompts do not display path information.
2607 since the default prompts do not display path information.
2596
2608
2597 Note that !cd doesn't work for this purpose because the shell where
2609 Note that !cd doesn't work for this purpose because the shell where
2598 !command runs is immediately discarded after executing 'command'."""
2610 !command runs is immediately discarded after executing 'command'."""
2599
2611
2600 parameter_s = parameter_s.strip()
2612 parameter_s = parameter_s.strip()
2601 #bkms = self.shell.persist.get("bookmarks",{})
2613 #bkms = self.shell.persist.get("bookmarks",{})
2602
2614
2603 numcd = re.match(r'(-)(\d+)$',parameter_s)
2615 numcd = re.match(r'(-)(\d+)$',parameter_s)
2604 # jump in directory history by number
2616 # jump in directory history by number
2605 if numcd:
2617 if numcd:
2606 nn = int(numcd.group(2))
2618 nn = int(numcd.group(2))
2607 try:
2619 try:
2608 ps = self.shell.user_ns['_dh'][nn]
2620 ps = self.shell.user_ns['_dh'][nn]
2609 except IndexError:
2621 except IndexError:
2610 print 'The requested directory does not exist in history.'
2622 print 'The requested directory does not exist in history.'
2611 return
2623 return
2612 else:
2624 else:
2613 opts = {}
2625 opts = {}
2614 else:
2626 else:
2615 #turn all non-space-escaping backslashes to slashes,
2627 #turn all non-space-escaping backslashes to slashes,
2616 # for c:\windows\directory\names\
2628 # for c:\windows\directory\names\
2617 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2629 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2618 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2630 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2619 # jump to previous
2631 # jump to previous
2620 if ps == '-':
2632 if ps == '-':
2621 try:
2633 try:
2622 ps = self.shell.user_ns['_dh'][-2]
2634 ps = self.shell.user_ns['_dh'][-2]
2623 except IndexError:
2635 except IndexError:
2624 raise UsageError('%cd -: No previous directory to change to.')
2636 raise UsageError('%cd -: No previous directory to change to.')
2625 # jump to bookmark if needed
2637 # jump to bookmark if needed
2626 else:
2638 else:
2627 if not os.path.isdir(ps) or opts.has_key('b'):
2639 if not os.path.isdir(ps) or opts.has_key('b'):
2628 bkms = self.db.get('bookmarks', {})
2640 bkms = self.db.get('bookmarks', {})
2629
2641
2630 if bkms.has_key(ps):
2642 if bkms.has_key(ps):
2631 target = bkms[ps]
2643 target = bkms[ps]
2632 print '(bookmark:%s) -> %s' % (ps,target)
2644 print '(bookmark:%s) -> %s' % (ps,target)
2633 ps = target
2645 ps = target
2634 else:
2646 else:
2635 if opts.has_key('b'):
2647 if opts.has_key('b'):
2636 raise UsageError("Bookmark '%s' not found. "
2648 raise UsageError("Bookmark '%s' not found. "
2637 "Use '%%bookmark -l' to see your bookmarks." % ps)
2649 "Use '%%bookmark -l' to see your bookmarks." % ps)
2638
2650
2639 # at this point ps should point to the target dir
2651 # at this point ps should point to the target dir
2640 if ps:
2652 if ps:
2641 try:
2653 try:
2642 os.chdir(os.path.expanduser(ps))
2654 os.chdir(os.path.expanduser(ps))
2643 if self.shell.rc.term_title:
2655 if self.shell.rc.term_title:
2644 #print 'set term title:',self.shell.rc.term_title # dbg
2656 #print 'set term title:',self.shell.rc.term_title # dbg
2645 ttitle = 'IPy ' + abbrev_cwd()
2657 ttitle = 'IPy ' + abbrev_cwd()
2646 platutils.set_term_title(ttitle)
2658 platutils.set_term_title(ttitle)
2647 except OSError:
2659 except OSError:
2648 print sys.exc_info()[1]
2660 print sys.exc_info()[1]
2649 else:
2661 else:
2650 cwd = os.getcwd()
2662 cwd = os.getcwd()
2651 dhist = self.shell.user_ns['_dh']
2663 dhist = self.shell.user_ns['_dh']
2652 dhist.append(cwd)
2664 dhist.append(cwd)
2653 self.db['dhist'] = compress_dhist(dhist)[-100:]
2665 self.db['dhist'] = compress_dhist(dhist)[-100:]
2654
2666
2655 else:
2667 else:
2656 os.chdir(self.shell.home_dir)
2668 os.chdir(self.shell.home_dir)
2657 if self.shell.rc.term_title:
2669 if self.shell.rc.term_title:
2658 platutils.set_term_title("IPy ~")
2670 platutils.set_term_title("IPy ~")
2659 cwd = os.getcwd()
2671 cwd = os.getcwd()
2660 dhist = self.shell.user_ns['_dh']
2672 dhist = self.shell.user_ns['_dh']
2661 dhist.append(cwd)
2673 dhist.append(cwd)
2662 self.db['dhist'] = compress_dhist(dhist)[-100:]
2674 self.db['dhist'] = compress_dhist(dhist)[-100:]
2663 if not 'q' in opts and self.shell.user_ns['_dh']:
2675 if not 'q' in opts and self.shell.user_ns['_dh']:
2664 print self.shell.user_ns['_dh'][-1]
2676 print self.shell.user_ns['_dh'][-1]
2665
2677
2666
2678
2667 def magic_env(self, parameter_s=''):
2679 def magic_env(self, parameter_s=''):
2668 """List environment variables."""
2680 """List environment variables."""
2669
2681
2670 return os.environ.data
2682 return os.environ.data
2671
2683
2672 def magic_pushd(self, parameter_s=''):
2684 def magic_pushd(self, parameter_s=''):
2673 """Place the current dir on stack and change directory.
2685 """Place the current dir on stack and change directory.
2674
2686
2675 Usage:\\
2687 Usage:\\
2676 %pushd ['dirname']
2688 %pushd ['dirname']
2677 """
2689 """
2678
2690
2679 dir_s = self.shell.dir_stack
2691 dir_s = self.shell.dir_stack
2680 tgt = os.path.expanduser(parameter_s)
2692 tgt = os.path.expanduser(parameter_s)
2681 cwd = os.getcwd().replace(self.home_dir,'~')
2693 cwd = os.getcwd().replace(self.home_dir,'~')
2682 if tgt:
2694 if tgt:
2683 self.magic_cd(parameter_s)
2695 self.magic_cd(parameter_s)
2684 dir_s.insert(0,cwd)
2696 dir_s.insert(0,cwd)
2685 return self.magic_dirs()
2697 return self.magic_dirs()
2686
2698
2687 def magic_popd(self, parameter_s=''):
2699 def magic_popd(self, parameter_s=''):
2688 """Change to directory popped off the top of the stack.
2700 """Change to directory popped off the top of the stack.
2689 """
2701 """
2690 if not self.shell.dir_stack:
2702 if not self.shell.dir_stack:
2691 raise UsageError("%popd on empty stack")
2703 raise UsageError("%popd on empty stack")
2692 top = self.shell.dir_stack.pop(0)
2704 top = self.shell.dir_stack.pop(0)
2693 self.magic_cd(top)
2705 self.magic_cd(top)
2694 print "popd ->",top
2706 print "popd ->",top
2695
2707
2696 def magic_dirs(self, parameter_s=''):
2708 def magic_dirs(self, parameter_s=''):
2697 """Return the current directory stack."""
2709 """Return the current directory stack."""
2698
2710
2699 return self.shell.dir_stack
2711 return self.shell.dir_stack
2700
2712
2701 def magic_dhist(self, parameter_s=''):
2713 def magic_dhist(self, parameter_s=''):
2702 """Print your history of visited directories.
2714 """Print your history of visited directories.
2703
2715
2704 %dhist -> print full history\\
2716 %dhist -> print full history\\
2705 %dhist n -> print last n entries only\\
2717 %dhist n -> print last n entries only\\
2706 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2718 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2707
2719
2708 This history is automatically maintained by the %cd command, and
2720 This history is automatically maintained by the %cd command, and
2709 always available as the global list variable _dh. You can use %cd -<n>
2721 always available as the global list variable _dh. You can use %cd -<n>
2710 to go to directory number <n>.
2722 to go to directory number <n>.
2711
2723
2712 Note that most of time, you should view directory history by entering
2724 Note that most of time, you should view directory history by entering
2713 cd -<TAB>.
2725 cd -<TAB>.
2714
2726
2715 """
2727 """
2716
2728
2717 dh = self.shell.user_ns['_dh']
2729 dh = self.shell.user_ns['_dh']
2718 if parameter_s:
2730 if parameter_s:
2719 try:
2731 try:
2720 args = map(int,parameter_s.split())
2732 args = map(int,parameter_s.split())
2721 except:
2733 except:
2722 self.arg_err(Magic.magic_dhist)
2734 self.arg_err(Magic.magic_dhist)
2723 return
2735 return
2724 if len(args) == 1:
2736 if len(args) == 1:
2725 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2737 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2726 elif len(args) == 2:
2738 elif len(args) == 2:
2727 ini,fin = args
2739 ini,fin = args
2728 else:
2740 else:
2729 self.arg_err(Magic.magic_dhist)
2741 self.arg_err(Magic.magic_dhist)
2730 return
2742 return
2731 else:
2743 else:
2732 ini,fin = 0,len(dh)
2744 ini,fin = 0,len(dh)
2733 nlprint(dh,
2745 nlprint(dh,
2734 header = 'Directory history (kept in _dh)',
2746 header = 'Directory history (kept in _dh)',
2735 start=ini,stop=fin)
2747 start=ini,stop=fin)
2736
2748
2737
2749
2738 def magic_sc(self, parameter_s=''):
2750 def magic_sc(self, parameter_s=''):
2739 """Shell capture - execute a shell command and capture its output.
2751 """Shell capture - execute a shell command and capture its output.
2740
2752
2741 DEPRECATED. Suboptimal, retained for backwards compatibility.
2753 DEPRECATED. Suboptimal, retained for backwards compatibility.
2742
2754
2743 You should use the form 'var = !command' instead. Example:
2755 You should use the form 'var = !command' instead. Example:
2744
2756
2745 "%sc -l myfiles = ls ~" should now be written as
2757 "%sc -l myfiles = ls ~" should now be written as
2746
2758
2747 "myfiles = !ls ~"
2759 "myfiles = !ls ~"
2748
2760
2749 myfiles.s, myfiles.l and myfiles.n still apply as documented
2761 myfiles.s, myfiles.l and myfiles.n still apply as documented
2750 below.
2762 below.
2751
2763
2752 --
2764 --
2753 %sc [options] varname=command
2765 %sc [options] varname=command
2754
2766
2755 IPython will run the given command using commands.getoutput(), and
2767 IPython will run the given command using commands.getoutput(), and
2756 will then update the user's interactive namespace with a variable
2768 will then update the user's interactive namespace with a variable
2757 called varname, containing the value of the call. Your command can
2769 called varname, containing the value of the call. Your command can
2758 contain shell wildcards, pipes, etc.
2770 contain shell wildcards, pipes, etc.
2759
2771
2760 The '=' sign in the syntax is mandatory, and the variable name you
2772 The '=' sign in the syntax is mandatory, and the variable name you
2761 supply must follow Python's standard conventions for valid names.
2773 supply must follow Python's standard conventions for valid names.
2762
2774
2763 (A special format without variable name exists for internal use)
2775 (A special format without variable name exists for internal use)
2764
2776
2765 Options:
2777 Options:
2766
2778
2767 -l: list output. Split the output on newlines into a list before
2779 -l: list output. Split the output on newlines into a list before
2768 assigning it to the given variable. By default the output is stored
2780 assigning it to the given variable. By default the output is stored
2769 as a single string.
2781 as a single string.
2770
2782
2771 -v: verbose. Print the contents of the variable.
2783 -v: verbose. Print the contents of the variable.
2772
2784
2773 In most cases you should not need to split as a list, because the
2785 In most cases you should not need to split as a list, because the
2774 returned value is a special type of string which can automatically
2786 returned value is a special type of string which can automatically
2775 provide its contents either as a list (split on newlines) or as a
2787 provide its contents either as a list (split on newlines) or as a
2776 space-separated string. These are convenient, respectively, either
2788 space-separated string. These are convenient, respectively, either
2777 for sequential processing or to be passed to a shell command.
2789 for sequential processing or to be passed to a shell command.
2778
2790
2779 For example:
2791 For example:
2780
2792
2781 # Capture into variable a
2793 # Capture into variable a
2782 In [9]: sc a=ls *py
2794 In [9]: sc a=ls *py
2783
2795
2784 # a is a string with embedded newlines
2796 # a is a string with embedded newlines
2785 In [10]: a
2797 In [10]: a
2786 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2798 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2787
2799
2788 # which can be seen as a list:
2800 # which can be seen as a list:
2789 In [11]: a.l
2801 In [11]: a.l
2790 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2802 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2791
2803
2792 # or as a whitespace-separated string:
2804 # or as a whitespace-separated string:
2793 In [12]: a.s
2805 In [12]: a.s
2794 Out[12]: 'setup.py win32_manual_post_install.py'
2806 Out[12]: 'setup.py win32_manual_post_install.py'
2795
2807
2796 # a.s is useful to pass as a single command line:
2808 # a.s is useful to pass as a single command line:
2797 In [13]: !wc -l $a.s
2809 In [13]: !wc -l $a.s
2798 146 setup.py
2810 146 setup.py
2799 130 win32_manual_post_install.py
2811 130 win32_manual_post_install.py
2800 276 total
2812 276 total
2801
2813
2802 # while the list form is useful to loop over:
2814 # while the list form is useful to loop over:
2803 In [14]: for f in a.l:
2815 In [14]: for f in a.l:
2804 ....: !wc -l $f
2816 ....: !wc -l $f
2805 ....:
2817 ....:
2806 146 setup.py
2818 146 setup.py
2807 130 win32_manual_post_install.py
2819 130 win32_manual_post_install.py
2808
2820
2809 Similiarly, the lists returned by the -l option are also special, in
2821 Similiarly, the lists returned by the -l option are also special, in
2810 the sense that you can equally invoke the .s attribute on them to
2822 the sense that you can equally invoke the .s attribute on them to
2811 automatically get a whitespace-separated string from their contents:
2823 automatically get a whitespace-separated string from their contents:
2812
2824
2813 In [1]: sc -l b=ls *py
2825 In [1]: sc -l b=ls *py
2814
2826
2815 In [2]: b
2827 In [2]: b
2816 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2828 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2817
2829
2818 In [3]: b.s
2830 In [3]: b.s
2819 Out[3]: 'setup.py win32_manual_post_install.py'
2831 Out[3]: 'setup.py win32_manual_post_install.py'
2820
2832
2821 In summary, both the lists and strings used for ouptut capture have
2833 In summary, both the lists and strings used for ouptut capture have
2822 the following special attributes:
2834 the following special attributes:
2823
2835
2824 .l (or .list) : value as list.
2836 .l (or .list) : value as list.
2825 .n (or .nlstr): value as newline-separated string.
2837 .n (or .nlstr): value as newline-separated string.
2826 .s (or .spstr): value as space-separated string.
2838 .s (or .spstr): value as space-separated string.
2827 """
2839 """
2828
2840
2829 opts,args = self.parse_options(parameter_s,'lv')
2841 opts,args = self.parse_options(parameter_s,'lv')
2830 # Try to get a variable name and command to run
2842 # Try to get a variable name and command to run
2831 try:
2843 try:
2832 # the variable name must be obtained from the parse_options
2844 # the variable name must be obtained from the parse_options
2833 # output, which uses shlex.split to strip options out.
2845 # output, which uses shlex.split to strip options out.
2834 var,_ = args.split('=',1)
2846 var,_ = args.split('=',1)
2835 var = var.strip()
2847 var = var.strip()
2836 # But the the command has to be extracted from the original input
2848 # But the the command has to be extracted from the original input
2837 # parameter_s, not on what parse_options returns, to avoid the
2849 # parameter_s, not on what parse_options returns, to avoid the
2838 # quote stripping which shlex.split performs on it.
2850 # quote stripping which shlex.split performs on it.
2839 _,cmd = parameter_s.split('=',1)
2851 _,cmd = parameter_s.split('=',1)
2840 except ValueError:
2852 except ValueError:
2841 var,cmd = '',''
2853 var,cmd = '',''
2842 # If all looks ok, proceed
2854 # If all looks ok, proceed
2843 out,err = self.shell.getoutputerror(cmd)
2855 out,err = self.shell.getoutputerror(cmd)
2844 if err:
2856 if err:
2845 print >> Term.cerr,err
2857 print >> Term.cerr,err
2846 if opts.has_key('l'):
2858 if opts.has_key('l'):
2847 out = SList(out.split('\n'))
2859 out = SList(out.split('\n'))
2848 else:
2860 else:
2849 out = LSString(out)
2861 out = LSString(out)
2850 if opts.has_key('v'):
2862 if opts.has_key('v'):
2851 print '%s ==\n%s' % (var,pformat(out))
2863 print '%s ==\n%s' % (var,pformat(out))
2852 if var:
2864 if var:
2853 self.shell.user_ns.update({var:out})
2865 self.shell.user_ns.update({var:out})
2854 else:
2866 else:
2855 return out
2867 return out
2856
2868
2857 def magic_sx(self, parameter_s=''):
2869 def magic_sx(self, parameter_s=''):
2858 """Shell execute - run a shell command and capture its output.
2870 """Shell execute - run a shell command and capture its output.
2859
2871
2860 %sx command
2872 %sx command
2861
2873
2862 IPython will run the given command using commands.getoutput(), and
2874 IPython will run the given command using commands.getoutput(), and
2863 return the result formatted as a list (split on '\\n'). Since the
2875 return the result formatted as a list (split on '\\n'). Since the
2864 output is _returned_, it will be stored in ipython's regular output
2876 output is _returned_, it will be stored in ipython's regular output
2865 cache Out[N] and in the '_N' automatic variables.
2877 cache Out[N] and in the '_N' automatic variables.
2866
2878
2867 Notes:
2879 Notes:
2868
2880
2869 1) If an input line begins with '!!', then %sx is automatically
2881 1) If an input line begins with '!!', then %sx is automatically
2870 invoked. That is, while:
2882 invoked. That is, while:
2871 !ls
2883 !ls
2872 causes ipython to simply issue system('ls'), typing
2884 causes ipython to simply issue system('ls'), typing
2873 !!ls
2885 !!ls
2874 is a shorthand equivalent to:
2886 is a shorthand equivalent to:
2875 %sx ls
2887 %sx ls
2876
2888
2877 2) %sx differs from %sc in that %sx automatically splits into a list,
2889 2) %sx differs from %sc in that %sx automatically splits into a list,
2878 like '%sc -l'. The reason for this is to make it as easy as possible
2890 like '%sc -l'. The reason for this is to make it as easy as possible
2879 to process line-oriented shell output via further python commands.
2891 to process line-oriented shell output via further python commands.
2880 %sc is meant to provide much finer control, but requires more
2892 %sc is meant to provide much finer control, but requires more
2881 typing.
2893 typing.
2882
2894
2883 3) Just like %sc -l, this is a list with special attributes:
2895 3) Just like %sc -l, this is a list with special attributes:
2884
2896
2885 .l (or .list) : value as list.
2897 .l (or .list) : value as list.
2886 .n (or .nlstr): value as newline-separated string.
2898 .n (or .nlstr): value as newline-separated string.
2887 .s (or .spstr): value as whitespace-separated string.
2899 .s (or .spstr): value as whitespace-separated string.
2888
2900
2889 This is very useful when trying to use such lists as arguments to
2901 This is very useful when trying to use such lists as arguments to
2890 system commands."""
2902 system commands."""
2891
2903
2892 if parameter_s:
2904 if parameter_s:
2893 out,err = self.shell.getoutputerror(parameter_s)
2905 out,err = self.shell.getoutputerror(parameter_s)
2894 if err:
2906 if err:
2895 print >> Term.cerr,err
2907 print >> Term.cerr,err
2896 return SList(out.split('\n'))
2908 return SList(out.split('\n'))
2897
2909
2898 def magic_bg(self, parameter_s=''):
2910 def magic_bg(self, parameter_s=''):
2899 """Run a job in the background, in a separate thread.
2911 """Run a job in the background, in a separate thread.
2900
2912
2901 For example,
2913 For example,
2902
2914
2903 %bg myfunc(x,y,z=1)
2915 %bg myfunc(x,y,z=1)
2904
2916
2905 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2917 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2906 execution starts, a message will be printed indicating the job
2918 execution starts, a message will be printed indicating the job
2907 number. If your job number is 5, you can use
2919 number. If your job number is 5, you can use
2908
2920
2909 myvar = jobs.result(5) or myvar = jobs[5].result
2921 myvar = jobs.result(5) or myvar = jobs[5].result
2910
2922
2911 to assign this result to variable 'myvar'.
2923 to assign this result to variable 'myvar'.
2912
2924
2913 IPython has a job manager, accessible via the 'jobs' object. You can
2925 IPython has a job manager, accessible via the 'jobs' object. You can
2914 type jobs? to get more information about it, and use jobs.<TAB> to see
2926 type jobs? to get more information about it, and use jobs.<TAB> to see
2915 its attributes. All attributes not starting with an underscore are
2927 its attributes. All attributes not starting with an underscore are
2916 meant for public use.
2928 meant for public use.
2917
2929
2918 In particular, look at the jobs.new() method, which is used to create
2930 In particular, look at the jobs.new() method, which is used to create
2919 new jobs. This magic %bg function is just a convenience wrapper
2931 new jobs. This magic %bg function is just a convenience wrapper
2920 around jobs.new(), for expression-based jobs. If you want to create a
2932 around jobs.new(), for expression-based jobs. If you want to create a
2921 new job with an explicit function object and arguments, you must call
2933 new job with an explicit function object and arguments, you must call
2922 jobs.new() directly.
2934 jobs.new() directly.
2923
2935
2924 The jobs.new docstring also describes in detail several important
2936 The jobs.new docstring also describes in detail several important
2925 caveats associated with a thread-based model for background job
2937 caveats associated with a thread-based model for background job
2926 execution. Type jobs.new? for details.
2938 execution. Type jobs.new? for details.
2927
2939
2928 You can check the status of all jobs with jobs.status().
2940 You can check the status of all jobs with jobs.status().
2929
2941
2930 The jobs variable is set by IPython into the Python builtin namespace.
2942 The jobs variable is set by IPython into the Python builtin namespace.
2931 If you ever declare a variable named 'jobs', you will shadow this
2943 If you ever declare a variable named 'jobs', you will shadow this
2932 name. You can either delete your global jobs variable to regain
2944 name. You can either delete your global jobs variable to regain
2933 access to the job manager, or make a new name and assign it manually
2945 access to the job manager, or make a new name and assign it manually
2934 to the manager (stored in IPython's namespace). For example, to
2946 to the manager (stored in IPython's namespace). For example, to
2935 assign the job manager to the Jobs name, use:
2947 assign the job manager to the Jobs name, use:
2936
2948
2937 Jobs = __builtins__.jobs"""
2949 Jobs = __builtins__.jobs"""
2938
2950
2939 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2951 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2940
2952
2941 def magic_r(self, parameter_s=''):
2953 def magic_r(self, parameter_s=''):
2942 """Repeat previous input.
2954 """Repeat previous input.
2943
2955
2944 Note: Consider using the more powerfull %rep instead!
2956 Note: Consider using the more powerfull %rep instead!
2945
2957
2946 If given an argument, repeats the previous command which starts with
2958 If given an argument, repeats the previous command which starts with
2947 the same string, otherwise it just repeats the previous input.
2959 the same string, otherwise it just repeats the previous input.
2948
2960
2949 Shell escaped commands (with ! as first character) are not recognized
2961 Shell escaped commands (with ! as first character) are not recognized
2950 by this system, only pure python code and magic commands.
2962 by this system, only pure python code and magic commands.
2951 """
2963 """
2952
2964
2953 start = parameter_s.strip()
2965 start = parameter_s.strip()
2954 esc_magic = self.shell.ESC_MAGIC
2966 esc_magic = self.shell.ESC_MAGIC
2955 # Identify magic commands even if automagic is on (which means
2967 # Identify magic commands even if automagic is on (which means
2956 # the in-memory version is different from that typed by the user).
2968 # the in-memory version is different from that typed by the user).
2957 if self.shell.rc.automagic:
2969 if self.shell.rc.automagic:
2958 start_magic = esc_magic+start
2970 start_magic = esc_magic+start
2959 else:
2971 else:
2960 start_magic = start
2972 start_magic = start
2961 # Look through the input history in reverse
2973 # Look through the input history in reverse
2962 for n in range(len(self.shell.input_hist)-2,0,-1):
2974 for n in range(len(self.shell.input_hist)-2,0,-1):
2963 input = self.shell.input_hist[n]
2975 input = self.shell.input_hist[n]
2964 # skip plain 'r' lines so we don't recurse to infinity
2976 # skip plain 'r' lines so we don't recurse to infinity
2965 if input != '_ip.magic("r")\n' and \
2977 if input != '_ip.magic("r")\n' and \
2966 (input.startswith(start) or input.startswith(start_magic)):
2978 (input.startswith(start) or input.startswith(start_magic)):
2967 #print 'match',`input` # dbg
2979 #print 'match',`input` # dbg
2968 print 'Executing:',input,
2980 print 'Executing:',input,
2969 self.shell.runlines(input)
2981 self.shell.runlines(input)
2970 return
2982 return
2971 print 'No previous input matching `%s` found.' % start
2983 print 'No previous input matching `%s` found.' % start
2972
2984
2973
2985
2974 def magic_bookmark(self, parameter_s=''):
2986 def magic_bookmark(self, parameter_s=''):
2975 """Manage IPython's bookmark system.
2987 """Manage IPython's bookmark system.
2976
2988
2977 %bookmark <name> - set bookmark to current dir
2989 %bookmark <name> - set bookmark to current dir
2978 %bookmark <name> <dir> - set bookmark to <dir>
2990 %bookmark <name> <dir> - set bookmark to <dir>
2979 %bookmark -l - list all bookmarks
2991 %bookmark -l - list all bookmarks
2980 %bookmark -d <name> - remove bookmark
2992 %bookmark -d <name> - remove bookmark
2981 %bookmark -r - remove all bookmarks
2993 %bookmark -r - remove all bookmarks
2982
2994
2983 You can later on access a bookmarked folder with:
2995 You can later on access a bookmarked folder with:
2984 %cd -b <name>
2996 %cd -b <name>
2985 or simply '%cd <name>' if there is no directory called <name> AND
2997 or simply '%cd <name>' if there is no directory called <name> AND
2986 there is such a bookmark defined.
2998 there is such a bookmark defined.
2987
2999
2988 Your bookmarks persist through IPython sessions, but they are
3000 Your bookmarks persist through IPython sessions, but they are
2989 associated with each profile."""
3001 associated with each profile."""
2990
3002
2991 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3003 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2992 if len(args) > 2:
3004 if len(args) > 2:
2993 raise UsageError("%bookmark: too many arguments")
3005 raise UsageError("%bookmark: too many arguments")
2994
3006
2995 bkms = self.db.get('bookmarks',{})
3007 bkms = self.db.get('bookmarks',{})
2996
3008
2997 if opts.has_key('d'):
3009 if opts.has_key('d'):
2998 try:
3010 try:
2999 todel = args[0]
3011 todel = args[0]
3000 except IndexError:
3012 except IndexError:
3001 raise UsageError(
3013 raise UsageError(
3002 "%bookmark -d: must provide a bookmark to delete")
3014 "%bookmark -d: must provide a bookmark to delete")
3003 else:
3015 else:
3004 try:
3016 try:
3005 del bkms[todel]
3017 del bkms[todel]
3006 except KeyError:
3018 except KeyError:
3007 raise UsageError(
3019 raise UsageError(
3008 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3020 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3009
3021
3010 elif opts.has_key('r'):
3022 elif opts.has_key('r'):
3011 bkms = {}
3023 bkms = {}
3012 elif opts.has_key('l'):
3024 elif opts.has_key('l'):
3013 bks = bkms.keys()
3025 bks = bkms.keys()
3014 bks.sort()
3026 bks.sort()
3015 if bks:
3027 if bks:
3016 size = max(map(len,bks))
3028 size = max(map(len,bks))
3017 else:
3029 else:
3018 size = 0
3030 size = 0
3019 fmt = '%-'+str(size)+'s -> %s'
3031 fmt = '%-'+str(size)+'s -> %s'
3020 print 'Current bookmarks:'
3032 print 'Current bookmarks:'
3021 for bk in bks:
3033 for bk in bks:
3022 print fmt % (bk,bkms[bk])
3034 print fmt % (bk,bkms[bk])
3023 else:
3035 else:
3024 if not args:
3036 if not args:
3025 raise UsageError("%bookmark: You must specify the bookmark name")
3037 raise UsageError("%bookmark: You must specify the bookmark name")
3026 elif len(args)==1:
3038 elif len(args)==1:
3027 bkms[args[0]] = os.getcwd()
3039 bkms[args[0]] = os.getcwd()
3028 elif len(args)==2:
3040 elif len(args)==2:
3029 bkms[args[0]] = args[1]
3041 bkms[args[0]] = args[1]
3030 self.db['bookmarks'] = bkms
3042 self.db['bookmarks'] = bkms
3031
3043
3032 def magic_pycat(self, parameter_s=''):
3044 def magic_pycat(self, parameter_s=''):
3033 """Show a syntax-highlighted file through a pager.
3045 """Show a syntax-highlighted file through a pager.
3034
3046
3035 This magic is similar to the cat utility, but it will assume the file
3047 This magic is similar to the cat utility, but it will assume the file
3036 to be Python source and will show it with syntax highlighting. """
3048 to be Python source and will show it with syntax highlighting. """
3037
3049
3038 try:
3050 try:
3039 filename = get_py_filename(parameter_s)
3051 filename = get_py_filename(parameter_s)
3040 cont = file_read(filename)
3052 cont = file_read(filename)
3041 except IOError:
3053 except IOError:
3042 try:
3054 try:
3043 cont = eval(parameter_s,self.user_ns)
3055 cont = eval(parameter_s,self.user_ns)
3044 except NameError:
3056 except NameError:
3045 cont = None
3057 cont = None
3046 if cont is None:
3058 if cont is None:
3047 print "Error: no such file or variable"
3059 print "Error: no such file or variable"
3048 return
3060 return
3049
3061
3050 page(self.shell.pycolorize(cont),
3062 page(self.shell.pycolorize(cont),
3051 screen_lines=self.shell.rc.screen_length)
3063 screen_lines=self.shell.rc.screen_length)
3052
3064
3053 def magic_cpaste(self, parameter_s=''):
3065 def magic_cpaste(self, parameter_s=''):
3054 """Allows you to paste & execute a pre-formatted code block from clipboard
3066 """Allows you to paste & execute a pre-formatted code block from clipboard
3055
3067
3056 You must terminate the block with '--' (two minus-signs) alone on the
3068 You must terminate the block with '--' (two minus-signs) alone on the
3057 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3069 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3058 is the new sentinel for this operation)
3070 is the new sentinel for this operation)
3059
3071
3060 The block is dedented prior to execution to enable execution of method
3072 The block is dedented prior to execution to enable execution of method
3061 definitions. '>' and '+' characters at the beginning of a line are
3073 definitions. '>' and '+' characters at the beginning of a line are
3062 ignored, to allow pasting directly from e-mails or diff files. The
3074 ignored, to allow pasting directly from e-mails or diff files. The
3063 executed block is also assigned to variable named 'pasted_block' for
3075 executed block is also assigned to variable named 'pasted_block' for
3064 later editing with '%edit pasted_block'.
3076 later editing with '%edit pasted_block'.
3065
3077
3066 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3078 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3067 This assigns the pasted block to variable 'foo' as string, without
3079 This assigns the pasted block to variable 'foo' as string, without
3068 dedenting or executing it.
3080 dedenting or executing it.
3069
3081
3070 Do not be alarmed by garbled output on Windows (it's a readline bug).
3082 Do not be alarmed by garbled output on Windows (it's a readline bug).
3071 Just press enter and type -- (and press enter again) and the block
3083 Just press enter and type -- (and press enter again) and the block
3072 will be what was just pasted.
3084 will be what was just pasted.
3073
3085
3074 IPython statements (magics, shell escapes) are not supported (yet).
3086 IPython statements (magics, shell escapes) are not supported (yet).
3075 """
3087 """
3076 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3088 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3077 par = args.strip()
3089 par = args.strip()
3078 sentinel = opts.get('s','--')
3090 sentinel = opts.get('s','--')
3079
3091
3080 from IPython import iplib
3092 from IPython import iplib
3081 lines = []
3093 lines = []
3082 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3094 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3083 while 1:
3095 while 1:
3084 l = iplib.raw_input_original(':')
3096 l = iplib.raw_input_original(':')
3085 if l ==sentinel:
3097 if l ==sentinel:
3086 break
3098 break
3087 lines.append(l.lstrip('>').lstrip('+'))
3099 lines.append(l.lstrip('>').lstrip('+'))
3088 block = "\n".join(lines) + '\n'
3100 block = "\n".join(lines) + '\n'
3089 #print "block:\n",block
3101 #print "block:\n",block
3090 if not par:
3102 if not par:
3091 b = textwrap.dedent(block)
3103 b = textwrap.dedent(block)
3092 exec b in self.user_ns
3104 exec b in self.user_ns
3093 self.user_ns['pasted_block'] = b
3105 self.user_ns['pasted_block'] = b
3094 else:
3106 else:
3095 self.user_ns[par] = block
3107 self.user_ns[par] = block
3096 print "Block assigned to '%s'" % par
3108 print "Block assigned to '%s'" % par
3097
3109
3098 def magic_quickref(self,arg):
3110 def magic_quickref(self,arg):
3099 """ Show a quick reference sheet """
3111 """ Show a quick reference sheet """
3100 import IPython.usage
3112 import IPython.usage
3101 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3113 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3102
3114
3103 page(qr)
3115 page(qr)
3104
3116
3105 def magic_upgrade(self,arg):
3117 def magic_upgrade(self,arg):
3106 """ Upgrade your IPython installation
3118 """ Upgrade your IPython installation
3107
3119
3108 This will copy the config files that don't yet exist in your
3120 This will copy the config files that don't yet exist in your
3109 ipython dir from the system config dir. Use this after upgrading
3121 ipython dir from the system config dir. Use this after upgrading
3110 IPython if you don't wish to delete your .ipython dir.
3122 IPython if you don't wish to delete your .ipython dir.
3111
3123
3112 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3124 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3113 new users)
3125 new users)
3114
3126
3115 """
3127 """
3116 ip = self.getapi()
3128 ip = self.getapi()
3117 ipinstallation = path(IPython.__file__).dirname()
3129 ipinstallation = path(IPython.__file__).dirname()
3118 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3130 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3119 src_config = ipinstallation / 'UserConfig'
3131 src_config = ipinstallation / 'UserConfig'
3120 userdir = path(ip.options.ipythondir)
3132 userdir = path(ip.options.ipythondir)
3121 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3133 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3122 print ">",cmd
3134 print ">",cmd
3123 shell(cmd)
3135 shell(cmd)
3124 if arg == '-nolegacy':
3136 if arg == '-nolegacy':
3125 legacy = userdir.files('ipythonrc*')
3137 legacy = userdir.files('ipythonrc*')
3126 print "Nuking legacy files:",legacy
3138 print "Nuking legacy files:",legacy
3127
3139
3128 [p.remove() for p in legacy]
3140 [p.remove() for p in legacy]
3129 suffix = (sys.platform == 'win32' and '.ini' or '')
3141 suffix = (sys.platform == 'win32' and '.ini' or '')
3130 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3142 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3131
3143
3132
3144
3133 def magic_doctest_mode(self,parameter_s=''):
3145 def magic_doctest_mode(self,parameter_s=''):
3134 """Toggle doctest mode on and off.
3146 """Toggle doctest mode on and off.
3135
3147
3136 This mode allows you to toggle the prompt behavior between normal
3148 This mode allows you to toggle the prompt behavior between normal
3137 IPython prompts and ones that are as similar to the default IPython
3149 IPython prompts and ones that are as similar to the default IPython
3138 interpreter as possible.
3150 interpreter as possible.
3139
3151
3140 It also supports the pasting of code snippets that have leading '>>>'
3152 It also supports the pasting of code snippets that have leading '>>>'
3141 and '...' prompts in them. This means that you can paste doctests from
3153 and '...' prompts in them. This means that you can paste doctests from
3142 files or docstrings (even if they have leading whitespace), and the
3154 files or docstrings (even if they have leading whitespace), and the
3143 code will execute correctly. You can then use '%history -tn' to see
3155 code will execute correctly. You can then use '%history -tn' to see
3144 the translated history without line numbers; this will give you the
3156 the translated history without line numbers; this will give you the
3145 input after removal of all the leading prompts and whitespace, which
3157 input after removal of all the leading prompts and whitespace, which
3146 can be pasted back into an editor.
3158 can be pasted back into an editor.
3147
3159
3148 With these features, you can switch into this mode easily whenever you
3160 With these features, you can switch into this mode easily whenever you
3149 need to do testing and changes to doctests, without having to leave
3161 need to do testing and changes to doctests, without having to leave
3150 your existing IPython session.
3162 your existing IPython session.
3151 """
3163 """
3152
3164
3153 # XXX - Fix this to have cleaner activate/deactivate calls.
3165 # XXX - Fix this to have cleaner activate/deactivate calls.
3154 from IPython.Extensions import InterpreterPasteInput as ipaste
3166 from IPython.Extensions import InterpreterPasteInput as ipaste
3155 from IPython.ipstruct import Struct
3167 from IPython.ipstruct import Struct
3156
3168
3157 # Shorthands
3169 # Shorthands
3158 shell = self.shell
3170 shell = self.shell
3159 oc = shell.outputcache
3171 oc = shell.outputcache
3160 rc = shell.rc
3172 rc = shell.rc
3161 meta = shell.meta
3173 meta = shell.meta
3162 # dstore is a data store kept in the instance metadata bag to track any
3174 # dstore is a data store kept in the instance metadata bag to track any
3163 # changes we make, so we can undo them later.
3175 # changes we make, so we can undo them later.
3164 dstore = meta.setdefault('doctest_mode',Struct())
3176 dstore = meta.setdefault('doctest_mode',Struct())
3165 save_dstore = dstore.setdefault
3177 save_dstore = dstore.setdefault
3166
3178
3167 # save a few values we'll need to recover later
3179 # save a few values we'll need to recover later
3168 mode = save_dstore('mode',False)
3180 mode = save_dstore('mode',False)
3169 save_dstore('rc_pprint',rc.pprint)
3181 save_dstore('rc_pprint',rc.pprint)
3170 save_dstore('xmode',shell.InteractiveTB.mode)
3182 save_dstore('xmode',shell.InteractiveTB.mode)
3171 save_dstore('rc_separate_in',rc.separate_in)
3183 save_dstore('rc_separate_in',rc.separate_in)
3172 save_dstore('rc_separate_out',rc.separate_out)
3184 save_dstore('rc_separate_out',rc.separate_out)
3173 save_dstore('rc_separate_out2',rc.separate_out2)
3185 save_dstore('rc_separate_out2',rc.separate_out2)
3174 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3186 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3175
3187
3176 if mode == False:
3188 if mode == False:
3177 # turn on
3189 # turn on
3178 ipaste.activate_prefilter()
3190 ipaste.activate_prefilter()
3179
3191
3180 oc.prompt1.p_template = '>>> '
3192 oc.prompt1.p_template = '>>> '
3181 oc.prompt2.p_template = '... '
3193 oc.prompt2.p_template = '... '
3182 oc.prompt_out.p_template = ''
3194 oc.prompt_out.p_template = ''
3183
3195
3184 oc.prompt1.sep = '\n'
3196 oc.prompt1.sep = '\n'
3185 oc.output_sep = ''
3197 oc.output_sep = ''
3186 oc.output_sep2 = ''
3198 oc.output_sep2 = ''
3187
3199
3188 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3200 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3189 oc.prompt_out.pad_left = False
3201 oc.prompt_out.pad_left = False
3190
3202
3191 rc.pprint = False
3203 rc.pprint = False
3192
3204
3193 shell.magic_xmode('Plain')
3205 shell.magic_xmode('Plain')
3194
3206
3195 else:
3207 else:
3196 # turn off
3208 # turn off
3197 ipaste.deactivate_prefilter()
3209 ipaste.deactivate_prefilter()
3198
3210
3199 oc.prompt1.p_template = rc.prompt_in1
3211 oc.prompt1.p_template = rc.prompt_in1
3200 oc.prompt2.p_template = rc.prompt_in2
3212 oc.prompt2.p_template = rc.prompt_in2
3201 oc.prompt_out.p_template = rc.prompt_out
3213 oc.prompt_out.p_template = rc.prompt_out
3202
3214
3203 oc.prompt1.sep = dstore.rc_separate_in
3215 oc.prompt1.sep = dstore.rc_separate_in
3204 oc.output_sep = dstore.rc_separate_out
3216 oc.output_sep = dstore.rc_separate_out
3205 oc.output_sep2 = dstore.rc_separate_out2
3217 oc.output_sep2 = dstore.rc_separate_out2
3206
3218
3207 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3219 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3208 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3220 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3209
3221
3210 rc.pprint = dstore.rc_pprint
3222 rc.pprint = dstore.rc_pprint
3211
3223
3212 shell.magic_xmode(dstore.xmode)
3224 shell.magic_xmode(dstore.xmode)
3213
3225
3214 # Store new mode and inform
3226 # Store new mode and inform
3215 dstore.mode = bool(1-int(mode))
3227 dstore.mode = bool(1-int(mode))
3216 print 'Doctest mode is:',
3228 print 'Doctest mode is:',
3217 print ['OFF','ON'][dstore.mode]
3229 print ['OFF','ON'][dstore.mode]
3218
3230
3219 # end Magic
3231 # end Magic
@@ -1,1916 +1,1947 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 General purpose utilities.
3 General purpose utilities.
4
4
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 these things are also convenient when working at the command line.
6 these things are also convenient when working at the command line.
7
7
8 $Id: genutils.py 2727 2007-09-07 15:32:08Z vivainio $"""
8 $Id: genutils.py 2763 2007-09-14 06:35:44Z fperez $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __license__ = Release.license
19 __license__ = Release.license
20
20
21 #****************************************************************************
21 #****************************************************************************
22 # required modules from the Python standard library
22 # required modules from the Python standard library
23 import __main__
23 import __main__
24 import commands
24 import commands
25 import doctest
25 import os
26 import os
26 import re
27 import re
27 import shlex
28 import shlex
28 import shutil
29 import shutil
29 import sys
30 import sys
30 import tempfile
31 import tempfile
31 import time
32 import time
32 import types
33 import types
33 import warnings
34 import warnings
34
35
35 # Other IPython utilities
36 # Other IPython utilities
36 import IPython
37 import IPython
37 from IPython.Itpl import Itpl,itpl,printpl
38 from IPython.Itpl import Itpl,itpl,printpl
38 from IPython import DPyGetOpt, platutils
39 from IPython import DPyGetOpt, platutils
39 from IPython.generics import result_display
40 from IPython.generics import result_display
40 from path import path
41 from path import path
41 if os.name == "nt":
42 if os.name == "nt":
42 from IPython.winconsole import get_console_size
43 from IPython.winconsole import get_console_size
43
44
44 #****************************************************************************
45 #****************************************************************************
45 # Exceptions
46 # Exceptions
46 class Error(Exception):
47 class Error(Exception):
47 """Base class for exceptions in this module."""
48 """Base class for exceptions in this module."""
48 pass
49 pass
49
50
50 #----------------------------------------------------------------------------
51 #----------------------------------------------------------------------------
51 class IOStream:
52 class IOStream:
52 def __init__(self,stream,fallback):
53 def __init__(self,stream,fallback):
53 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
54 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
54 stream = fallback
55 stream = fallback
55 self.stream = stream
56 self.stream = stream
56 self._swrite = stream.write
57 self._swrite = stream.write
57 self.flush = stream.flush
58 self.flush = stream.flush
58
59
59 def write(self,data):
60 def write(self,data):
60 try:
61 try:
61 self._swrite(data)
62 self._swrite(data)
62 except:
63 except:
63 try:
64 try:
64 # print handles some unicode issues which may trip a plain
65 # print handles some unicode issues which may trip a plain
65 # write() call. Attempt to emulate write() by using a
66 # write() call. Attempt to emulate write() by using a
66 # trailing comma
67 # trailing comma
67 print >> self.stream, data,
68 print >> self.stream, data,
68 except:
69 except:
69 # if we get here, something is seriously broken.
70 # if we get here, something is seriously broken.
70 print >> sys.stderr, \
71 print >> sys.stderr, \
71 'ERROR - failed to write data to stream:', self.stream
72 'ERROR - failed to write data to stream:', self.stream
72
73
73 def close(self):
74 def close(self):
74 pass
75 pass
75
76
76
77
77 class IOTerm:
78 class IOTerm:
78 """ Term holds the file or file-like objects for handling I/O operations.
79 """ Term holds the file or file-like objects for handling I/O operations.
79
80
80 These are normally just sys.stdin, sys.stdout and sys.stderr but for
81 These are normally just sys.stdin, sys.stdout and sys.stderr but for
81 Windows they can can replaced to allow editing the strings before they are
82 Windows they can can replaced to allow editing the strings before they are
82 displayed."""
83 displayed."""
83
84
84 # In the future, having IPython channel all its I/O operations through
85 # In the future, having IPython channel all its I/O operations through
85 # this class will make it easier to embed it into other environments which
86 # this class will make it easier to embed it into other environments which
86 # are not a normal terminal (such as a GUI-based shell)
87 # are not a normal terminal (such as a GUI-based shell)
87 def __init__(self,cin=None,cout=None,cerr=None):
88 def __init__(self,cin=None,cout=None,cerr=None):
88 self.cin = IOStream(cin,sys.stdin)
89 self.cin = IOStream(cin,sys.stdin)
89 self.cout = IOStream(cout,sys.stdout)
90 self.cout = IOStream(cout,sys.stdout)
90 self.cerr = IOStream(cerr,sys.stderr)
91 self.cerr = IOStream(cerr,sys.stderr)
91
92
92 # Global variable to be used for all I/O
93 # Global variable to be used for all I/O
93 Term = IOTerm()
94 Term = IOTerm()
94
95
95 import IPython.rlineimpl as readline
96 import IPython.rlineimpl as readline
96 # Remake Term to use the readline i/o facilities
97 # Remake Term to use the readline i/o facilities
97 if sys.platform == 'win32' and readline.have_readline:
98 if sys.platform == 'win32' and readline.have_readline:
98
99
99 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
100 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
100
101
101
102
102 #****************************************************************************
103 #****************************************************************************
103 # Generic warning/error printer, used by everything else
104 # Generic warning/error printer, used by everything else
104 def warn(msg,level=2,exit_val=1):
105 def warn(msg,level=2,exit_val=1):
105 """Standard warning printer. Gives formatting consistency.
106 """Standard warning printer. Gives formatting consistency.
106
107
107 Output is sent to Term.cerr (sys.stderr by default).
108 Output is sent to Term.cerr (sys.stderr by default).
108
109
109 Options:
110 Options:
110
111
111 -level(2): allows finer control:
112 -level(2): allows finer control:
112 0 -> Do nothing, dummy function.
113 0 -> Do nothing, dummy function.
113 1 -> Print message.
114 1 -> Print message.
114 2 -> Print 'WARNING:' + message. (Default level).
115 2 -> Print 'WARNING:' + message. (Default level).
115 3 -> Print 'ERROR:' + message.
116 3 -> Print 'ERROR:' + message.
116 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
117 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
117
118
118 -exit_val (1): exit value returned by sys.exit() for a level 4
119 -exit_val (1): exit value returned by sys.exit() for a level 4
119 warning. Ignored for all other levels."""
120 warning. Ignored for all other levels."""
120
121
121 if level>0:
122 if level>0:
122 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
123 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
123 print >> Term.cerr, '%s%s' % (header[level],msg)
124 print >> Term.cerr, '%s%s' % (header[level],msg)
124 if level == 4:
125 if level == 4:
125 print >> Term.cerr,'Exiting.\n'
126 print >> Term.cerr,'Exiting.\n'
126 sys.exit(exit_val)
127 sys.exit(exit_val)
127
128
128 def info(msg):
129 def info(msg):
129 """Equivalent to warn(msg,level=1)."""
130 """Equivalent to warn(msg,level=1)."""
130
131
131 warn(msg,level=1)
132 warn(msg,level=1)
132
133
133 def error(msg):
134 def error(msg):
134 """Equivalent to warn(msg,level=3)."""
135 """Equivalent to warn(msg,level=3)."""
135
136
136 warn(msg,level=3)
137 warn(msg,level=3)
137
138
138 def fatal(msg,exit_val=1):
139 def fatal(msg,exit_val=1):
139 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
140 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
140
141
141 warn(msg,exit_val=exit_val,level=4)
142 warn(msg,exit_val=exit_val,level=4)
142
143
143 #---------------------------------------------------------------------------
144 #---------------------------------------------------------------------------
144 # Debugging routines
145 # Debugging routines
145 #
146 #
146 def debugx(expr,pre_msg=''):
147 def debugx(expr,pre_msg=''):
147 """Print the value of an expression from the caller's frame.
148 """Print the value of an expression from the caller's frame.
148
149
149 Takes an expression, evaluates it in the caller's frame and prints both
150 Takes an expression, evaluates it in the caller's frame and prints both
150 the given expression and the resulting value (as well as a debug mark
151 the given expression and the resulting value (as well as a debug mark
151 indicating the name of the calling function. The input must be of a form
152 indicating the name of the calling function. The input must be of a form
152 suitable for eval().
153 suitable for eval().
153
154
154 An optional message can be passed, which will be prepended to the printed
155 An optional message can be passed, which will be prepended to the printed
155 expr->value pair."""
156 expr->value pair."""
156
157
157 cf = sys._getframe(1)
158 cf = sys._getframe(1)
158 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
159 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
159 eval(expr,cf.f_globals,cf.f_locals))
160 eval(expr,cf.f_globals,cf.f_locals))
160
161
161 # deactivate it by uncommenting the following line, which makes it a no-op
162 # deactivate it by uncommenting the following line, which makes it a no-op
162 #def debugx(expr,pre_msg=''): pass
163 #def debugx(expr,pre_msg=''): pass
163
164
164 #----------------------------------------------------------------------------
165 #----------------------------------------------------------------------------
165 StringTypes = types.StringTypes
166 StringTypes = types.StringTypes
166
167
167 # Basic timing functionality
168 # Basic timing functionality
168
169
169 # If possible (Unix), use the resource module instead of time.clock()
170 # If possible (Unix), use the resource module instead of time.clock()
170 try:
171 try:
171 import resource
172 import resource
172 def clocku():
173 def clocku():
173 """clocku() -> floating point number
174 """clocku() -> floating point number
174
175
175 Return the *USER* CPU time in seconds since the start of the process.
176 Return the *USER* CPU time in seconds since the start of the process.
176 This is done via a call to resource.getrusage, so it avoids the
177 This is done via a call to resource.getrusage, so it avoids the
177 wraparound problems in time.clock()."""
178 wraparound problems in time.clock()."""
178
179
179 return resource.getrusage(resource.RUSAGE_SELF)[0]
180 return resource.getrusage(resource.RUSAGE_SELF)[0]
180
181
181 def clocks():
182 def clocks():
182 """clocks() -> floating point number
183 """clocks() -> floating point number
183
184
184 Return the *SYSTEM* CPU time in seconds since the start of the process.
185 Return the *SYSTEM* CPU time in seconds since the start of the process.
185 This is done via a call to resource.getrusage, so it avoids the
186 This is done via a call to resource.getrusage, so it avoids the
186 wraparound problems in time.clock()."""
187 wraparound problems in time.clock()."""
187
188
188 return resource.getrusage(resource.RUSAGE_SELF)[1]
189 return resource.getrusage(resource.RUSAGE_SELF)[1]
189
190
190 def clock():
191 def clock():
191 """clock() -> floating point number
192 """clock() -> floating point number
192
193
193 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
194 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
194 the process. This is done via a call to resource.getrusage, so it
195 the process. This is done via a call to resource.getrusage, so it
195 avoids the wraparound problems in time.clock()."""
196 avoids the wraparound problems in time.clock()."""
196
197
197 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
198 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
198 return u+s
199 return u+s
199
200
200 def clock2():
201 def clock2():
201 """clock2() -> (t_user,t_system)
202 """clock2() -> (t_user,t_system)
202
203
203 Similar to clock(), but return a tuple of user/system times."""
204 Similar to clock(), but return a tuple of user/system times."""
204 return resource.getrusage(resource.RUSAGE_SELF)[:2]
205 return resource.getrusage(resource.RUSAGE_SELF)[:2]
205
206
206 except ImportError:
207 except ImportError:
207 # There is no distinction of user/system time under windows, so we just use
208 # There is no distinction of user/system time under windows, so we just use
208 # time.clock() for everything...
209 # time.clock() for everything...
209 clocku = clocks = clock = time.clock
210 clocku = clocks = clock = time.clock
210 def clock2():
211 def clock2():
211 """Under windows, system CPU time can't be measured.
212 """Under windows, system CPU time can't be measured.
212
213
213 This just returns clock() and zero."""
214 This just returns clock() and zero."""
214 return time.clock(),0.0
215 return time.clock(),0.0
215
216
216 def timings_out(reps,func,*args,**kw):
217 def timings_out(reps,func,*args,**kw):
217 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
218 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
218
219
219 Execute a function reps times, return a tuple with the elapsed total
220 Execute a function reps times, return a tuple with the elapsed total
220 CPU time in seconds, the time per call and the function's output.
221 CPU time in seconds, the time per call and the function's output.
221
222
222 Under Unix, the return value is the sum of user+system time consumed by
223 Under Unix, the return value is the sum of user+system time consumed by
223 the process, computed via the resource module. This prevents problems
224 the process, computed via the resource module. This prevents problems
224 related to the wraparound effect which the time.clock() function has.
225 related to the wraparound effect which the time.clock() function has.
225
226
226 Under Windows the return value is in wall clock seconds. See the
227 Under Windows the return value is in wall clock seconds. See the
227 documentation for the time module for more details."""
228 documentation for the time module for more details."""
228
229
229 reps = int(reps)
230 reps = int(reps)
230 assert reps >=1, 'reps must be >= 1'
231 assert reps >=1, 'reps must be >= 1'
231 if reps==1:
232 if reps==1:
232 start = clock()
233 start = clock()
233 out = func(*args,**kw)
234 out = func(*args,**kw)
234 tot_time = clock()-start
235 tot_time = clock()-start
235 else:
236 else:
236 rng = xrange(reps-1) # the last time is executed separately to store output
237 rng = xrange(reps-1) # the last time is executed separately to store output
237 start = clock()
238 start = clock()
238 for dummy in rng: func(*args,**kw)
239 for dummy in rng: func(*args,**kw)
239 out = func(*args,**kw) # one last time
240 out = func(*args,**kw) # one last time
240 tot_time = clock()-start
241 tot_time = clock()-start
241 av_time = tot_time / reps
242 av_time = tot_time / reps
242 return tot_time,av_time,out
243 return tot_time,av_time,out
243
244
244 def timings(reps,func,*args,**kw):
245 def timings(reps,func,*args,**kw):
245 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
246 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
246
247
247 Execute a function reps times, return a tuple with the elapsed total CPU
248 Execute a function reps times, return a tuple with the elapsed total CPU
248 time in seconds and the time per call. These are just the first two values
249 time in seconds and the time per call. These are just the first two values
249 in timings_out()."""
250 in timings_out()."""
250
251
251 return timings_out(reps,func,*args,**kw)[0:2]
252 return timings_out(reps,func,*args,**kw)[0:2]
252
253
253 def timing(func,*args,**kw):
254 def timing(func,*args,**kw):
254 """timing(func,*args,**kw) -> t_total
255 """timing(func,*args,**kw) -> t_total
255
256
256 Execute a function once, return the elapsed total CPU time in
257 Execute a function once, return the elapsed total CPU time in
257 seconds. This is just the first value in timings_out()."""
258 seconds. This is just the first value in timings_out()."""
258
259
259 return timings_out(1,func,*args,**kw)[0]
260 return timings_out(1,func,*args,**kw)[0]
260
261
261 #****************************************************************************
262 #****************************************************************************
262 # file and system
263 # file and system
263
264
264 def arg_split(s,posix=False):
265 def arg_split(s,posix=False):
265 """Split a command line's arguments in a shell-like manner.
266 """Split a command line's arguments in a shell-like manner.
266
267
267 This is a modified version of the standard library's shlex.split()
268 This is a modified version of the standard library's shlex.split()
268 function, but with a default of posix=False for splitting, so that quotes
269 function, but with a default of posix=False for splitting, so that quotes
269 in inputs are respected."""
270 in inputs are respected."""
270
271
271 # XXX - there may be unicode-related problems here!!! I'm not sure that
272 # XXX - there may be unicode-related problems here!!! I'm not sure that
272 # shlex is truly unicode-safe, so it might be necessary to do
273 # shlex is truly unicode-safe, so it might be necessary to do
273 #
274 #
274 # s = s.encode(sys.stdin.encoding)
275 # s = s.encode(sys.stdin.encoding)
275 #
276 #
276 # first, to ensure that shlex gets a normal string. Input from anyone who
277 # first, to ensure that shlex gets a normal string. Input from anyone who
277 # knows more about unicode and shlex than I would be good to have here...
278 # knows more about unicode and shlex than I would be good to have here...
278 lex = shlex.shlex(s, posix=posix)
279 lex = shlex.shlex(s, posix=posix)
279 lex.whitespace_split = True
280 lex.whitespace_split = True
280 return list(lex)
281 return list(lex)
281
282
282 def system(cmd,verbose=0,debug=0,header=''):
283 def system(cmd,verbose=0,debug=0,header=''):
283 """Execute a system command, return its exit status.
284 """Execute a system command, return its exit status.
284
285
285 Options:
286 Options:
286
287
287 - verbose (0): print the command to be executed.
288 - verbose (0): print the command to be executed.
288
289
289 - debug (0): only print, do not actually execute.
290 - debug (0): only print, do not actually execute.
290
291
291 - header (''): Header to print on screen prior to the executed command (it
292 - header (''): Header to print on screen prior to the executed command (it
292 is only prepended to the command, no newlines are added).
293 is only prepended to the command, no newlines are added).
293
294
294 Note: a stateful version of this function is available through the
295 Note: a stateful version of this function is available through the
295 SystemExec class."""
296 SystemExec class."""
296
297
297 stat = 0
298 stat = 0
298 if verbose or debug: print header+cmd
299 if verbose or debug: print header+cmd
299 sys.stdout.flush()
300 sys.stdout.flush()
300 if not debug: stat = os.system(cmd)
301 if not debug: stat = os.system(cmd)
301 return stat
302 return stat
302
303
303 def abbrev_cwd():
304 def abbrev_cwd():
304 """ Return abbreviated version of cwd, e.g. d:mydir """
305 """ Return abbreviated version of cwd, e.g. d:mydir """
305 cwd = os.getcwd()
306 cwd = os.getcwd()
306 drivepart = ''
307 drivepart = ''
307 if sys.platform == 'win32':
308 if sys.platform == 'win32':
308 if len(cwd) < 4:
309 if len(cwd) < 4:
309 return cwd
310 return cwd
310 drivepart = os.path.splitdrive(cwd)[0]
311 drivepart = os.path.splitdrive(cwd)[0]
311 return (drivepart + (
312 return (drivepart + (
312 cwd == '/' and '/' or \
313 cwd == '/' and '/' or \
313 os.path.basename(cwd)))
314 os.path.basename(cwd)))
314
315
315
316
316 # This function is used by ipython in a lot of places to make system calls.
317 # This function is used by ipython in a lot of places to make system calls.
317 # We need it to be slightly different under win32, due to the vagaries of
318 # We need it to be slightly different under win32, due to the vagaries of
318 # 'network shares'. A win32 override is below.
319 # 'network shares'. A win32 override is below.
319
320
320 def shell(cmd,verbose=0,debug=0,header=''):
321 def shell(cmd,verbose=0,debug=0,header=''):
321 """Execute a command in the system shell, always return None.
322 """Execute a command in the system shell, always return None.
322
323
323 Options:
324 Options:
324
325
325 - verbose (0): print the command to be executed.
326 - verbose (0): print the command to be executed.
326
327
327 - debug (0): only print, do not actually execute.
328 - debug (0): only print, do not actually execute.
328
329
329 - header (''): Header to print on screen prior to the executed command (it
330 - header (''): Header to print on screen prior to the executed command (it
330 is only prepended to the command, no newlines are added).
331 is only prepended to the command, no newlines are added).
331
332
332 Note: this is similar to genutils.system(), but it returns None so it can
333 Note: this is similar to genutils.system(), but it returns None so it can
333 be conveniently used in interactive loops without getting the return value
334 be conveniently used in interactive loops without getting the return value
334 (typically 0) printed many times."""
335 (typically 0) printed many times."""
335
336
336 stat = 0
337 stat = 0
337 if verbose or debug: print header+cmd
338 if verbose or debug: print header+cmd
338 # flush stdout so we don't mangle python's buffering
339 # flush stdout so we don't mangle python's buffering
339 sys.stdout.flush()
340 sys.stdout.flush()
340
341
341 if not debug:
342 if not debug:
342 platutils.set_term_title("IPy " + cmd)
343 platutils.set_term_title("IPy " + cmd)
343 os.system(cmd)
344 os.system(cmd)
344 platutils.set_term_title("IPy " + abbrev_cwd())
345 platutils.set_term_title("IPy " + abbrev_cwd())
345
346
346 # override shell() for win32 to deal with network shares
347 # override shell() for win32 to deal with network shares
347 if os.name in ('nt','dos'):
348 if os.name in ('nt','dos'):
348
349
349 shell_ori = shell
350 shell_ori = shell
350
351
351 def shell(cmd,verbose=0,debug=0,header=''):
352 def shell(cmd,verbose=0,debug=0,header=''):
352 if os.getcwd().startswith(r"\\"):
353 if os.getcwd().startswith(r"\\"):
353 path = os.getcwd()
354 path = os.getcwd()
354 # change to c drive (cannot be on UNC-share when issuing os.system,
355 # change to c drive (cannot be on UNC-share when issuing os.system,
355 # as cmd.exe cannot handle UNC addresses)
356 # as cmd.exe cannot handle UNC addresses)
356 os.chdir("c:")
357 os.chdir("c:")
357 # issue pushd to the UNC-share and then run the command
358 # issue pushd to the UNC-share and then run the command
358 try:
359 try:
359 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
360 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
360 finally:
361 finally:
361 os.chdir(path)
362 os.chdir(path)
362 else:
363 else:
363 shell_ori(cmd,verbose,debug,header)
364 shell_ori(cmd,verbose,debug,header)
364
365
365 shell.__doc__ = shell_ori.__doc__
366 shell.__doc__ = shell_ori.__doc__
366
367
367 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
368 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
368 """Dummy substitute for perl's backquotes.
369 """Dummy substitute for perl's backquotes.
369
370
370 Executes a command and returns the output.
371 Executes a command and returns the output.
371
372
372 Accepts the same arguments as system(), plus:
373 Accepts the same arguments as system(), plus:
373
374
374 - split(0): if true, the output is returned as a list split on newlines.
375 - split(0): if true, the output is returned as a list split on newlines.
375
376
376 Note: a stateful version of this function is available through the
377 Note: a stateful version of this function is available through the
377 SystemExec class.
378 SystemExec class.
378
379
379 This is pretty much deprecated and rarely used,
380 This is pretty much deprecated and rarely used,
380 genutils.getoutputerror may be what you need.
381 genutils.getoutputerror may be what you need.
381
382
382 """
383 """
383
384
384 if verbose or debug: print header+cmd
385 if verbose or debug: print header+cmd
385 if not debug:
386 if not debug:
386 output = os.popen(cmd).read()
387 output = os.popen(cmd).read()
387 # stipping last \n is here for backwards compat.
388 # stipping last \n is here for backwards compat.
388 if output.endswith('\n'):
389 if output.endswith('\n'):
389 output = output[:-1]
390 output = output[:-1]
390 if split:
391 if split:
391 return output.split('\n')
392 return output.split('\n')
392 else:
393 else:
393 return output
394 return output
394
395
395 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
396 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
396 """Return (standard output,standard error) of executing cmd in a shell.
397 """Return (standard output,standard error) of executing cmd in a shell.
397
398
398 Accepts the same arguments as system(), plus:
399 Accepts the same arguments as system(), plus:
399
400
400 - split(0): if true, each of stdout/err is returned as a list split on
401 - split(0): if true, each of stdout/err is returned as a list split on
401 newlines.
402 newlines.
402
403
403 Note: a stateful version of this function is available through the
404 Note: a stateful version of this function is available through the
404 SystemExec class."""
405 SystemExec class."""
405
406
406 if verbose or debug: print header+cmd
407 if verbose or debug: print header+cmd
407 if not cmd:
408 if not cmd:
408 if split:
409 if split:
409 return [],[]
410 return [],[]
410 else:
411 else:
411 return '',''
412 return '',''
412 if not debug:
413 if not debug:
413 pin,pout,perr = os.popen3(cmd)
414 pin,pout,perr = os.popen3(cmd)
414 tout = pout.read().rstrip()
415 tout = pout.read().rstrip()
415 terr = perr.read().rstrip()
416 terr = perr.read().rstrip()
416 pin.close()
417 pin.close()
417 pout.close()
418 pout.close()
418 perr.close()
419 perr.close()
419 if split:
420 if split:
420 return tout.split('\n'),terr.split('\n')
421 return tout.split('\n'),terr.split('\n')
421 else:
422 else:
422 return tout,terr
423 return tout,terr
423
424
424 # for compatibility with older naming conventions
425 # for compatibility with older naming conventions
425 xsys = system
426 xsys = system
426 bq = getoutput
427 bq = getoutput
427
428
428 class SystemExec:
429 class SystemExec:
429 """Access the system and getoutput functions through a stateful interface.
430 """Access the system and getoutput functions through a stateful interface.
430
431
431 Note: here we refer to the system and getoutput functions from this
432 Note: here we refer to the system and getoutput functions from this
432 library, not the ones from the standard python library.
433 library, not the ones from the standard python library.
433
434
434 This class offers the system and getoutput functions as methods, but the
435 This class offers the system and getoutput functions as methods, but the
435 verbose, debug and header parameters can be set for the instance (at
436 verbose, debug and header parameters can be set for the instance (at
436 creation time or later) so that they don't need to be specified on each
437 creation time or later) so that they don't need to be specified on each
437 call.
438 call.
438
439
439 For efficiency reasons, there's no way to override the parameters on a
440 For efficiency reasons, there's no way to override the parameters on a
440 per-call basis other than by setting instance attributes. If you need
441 per-call basis other than by setting instance attributes. If you need
441 local overrides, it's best to directly call system() or getoutput().
442 local overrides, it's best to directly call system() or getoutput().
442
443
443 The following names are provided as alternate options:
444 The following names are provided as alternate options:
444 - xsys: alias to system
445 - xsys: alias to system
445 - bq: alias to getoutput
446 - bq: alias to getoutput
446
447
447 An instance can then be created as:
448 An instance can then be created as:
448 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
449 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
449
450
450 And used as:
451 And used as:
451 >>> sysexec.xsys('pwd')
452 >>> sysexec.xsys('pwd')
452 >>> dirlist = sysexec.bq('ls -l')
453 >>> dirlist = sysexec.bq('ls -l')
453 """
454 """
454
455
455 def __init__(self,verbose=0,debug=0,header='',split=0):
456 def __init__(self,verbose=0,debug=0,header='',split=0):
456 """Specify the instance's values for verbose, debug and header."""
457 """Specify the instance's values for verbose, debug and header."""
457 setattr_list(self,'verbose debug header split')
458 setattr_list(self,'verbose debug header split')
458
459
459 def system(self,cmd):
460 def system(self,cmd):
460 """Stateful interface to system(), with the same keyword parameters."""
461 """Stateful interface to system(), with the same keyword parameters."""
461
462
462 system(cmd,self.verbose,self.debug,self.header)
463 system(cmd,self.verbose,self.debug,self.header)
463
464
464 def shell(self,cmd):
465 def shell(self,cmd):
465 """Stateful interface to shell(), with the same keyword parameters."""
466 """Stateful interface to shell(), with the same keyword parameters."""
466
467
467 shell(cmd,self.verbose,self.debug,self.header)
468 shell(cmd,self.verbose,self.debug,self.header)
468
469
469 xsys = system # alias
470 xsys = system # alias
470
471
471 def getoutput(self,cmd):
472 def getoutput(self,cmd):
472 """Stateful interface to getoutput()."""
473 """Stateful interface to getoutput()."""
473
474
474 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
475 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
475
476
476 def getoutputerror(self,cmd):
477 def getoutputerror(self,cmd):
477 """Stateful interface to getoutputerror()."""
478 """Stateful interface to getoutputerror()."""
478
479
479 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
480 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
480
481
481 bq = getoutput # alias
482 bq = getoutput # alias
482
483
483 #-----------------------------------------------------------------------------
484 #-----------------------------------------------------------------------------
484 def mutex_opts(dict,ex_op):
485 def mutex_opts(dict,ex_op):
485 """Check for presence of mutually exclusive keys in a dict.
486 """Check for presence of mutually exclusive keys in a dict.
486
487
487 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
488 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
488 for op1,op2 in ex_op:
489 for op1,op2 in ex_op:
489 if op1 in dict and op2 in dict:
490 if op1 in dict and op2 in dict:
490 raise ValueError,'\n*** ERROR in Arguments *** '\
491 raise ValueError,'\n*** ERROR in Arguments *** '\
491 'Options '+op1+' and '+op2+' are mutually exclusive.'
492 'Options '+op1+' and '+op2+' are mutually exclusive.'
492
493
493 #-----------------------------------------------------------------------------
494 #-----------------------------------------------------------------------------
494 def get_py_filename(name):
495 def get_py_filename(name):
495 """Return a valid python filename in the current directory.
496 """Return a valid python filename in the current directory.
496
497
497 If the given name is not a file, it adds '.py' and searches again.
498 If the given name is not a file, it adds '.py' and searches again.
498 Raises IOError with an informative message if the file isn't found."""
499 Raises IOError with an informative message if the file isn't found."""
499
500
500 name = os.path.expanduser(name)
501 name = os.path.expanduser(name)
501 if not os.path.isfile(name) and not name.endswith('.py'):
502 if not os.path.isfile(name) and not name.endswith('.py'):
502 name += '.py'
503 name += '.py'
503 if os.path.isfile(name):
504 if os.path.isfile(name):
504 return name
505 return name
505 else:
506 else:
506 raise IOError,'File `%s` not found.' % name
507 raise IOError,'File `%s` not found.' % name
507
508
508 #-----------------------------------------------------------------------------
509 #-----------------------------------------------------------------------------
509 def filefind(fname,alt_dirs = None):
510 def filefind(fname,alt_dirs = None):
510 """Return the given filename either in the current directory, if it
511 """Return the given filename either in the current directory, if it
511 exists, or in a specified list of directories.
512 exists, or in a specified list of directories.
512
513
513 ~ expansion is done on all file and directory names.
514 ~ expansion is done on all file and directory names.
514
515
515 Upon an unsuccessful search, raise an IOError exception."""
516 Upon an unsuccessful search, raise an IOError exception."""
516
517
517 if alt_dirs is None:
518 if alt_dirs is None:
518 try:
519 try:
519 alt_dirs = get_home_dir()
520 alt_dirs = get_home_dir()
520 except HomeDirError:
521 except HomeDirError:
521 alt_dirs = os.getcwd()
522 alt_dirs = os.getcwd()
522 search = [fname] + list_strings(alt_dirs)
523 search = [fname] + list_strings(alt_dirs)
523 search = map(os.path.expanduser,search)
524 search = map(os.path.expanduser,search)
524 #print 'search list for',fname,'list:',search # dbg
525 #print 'search list for',fname,'list:',search # dbg
525 fname = search[0]
526 fname = search[0]
526 if os.path.isfile(fname):
527 if os.path.isfile(fname):
527 return fname
528 return fname
528 for direc in search[1:]:
529 for direc in search[1:]:
529 testname = os.path.join(direc,fname)
530 testname = os.path.join(direc,fname)
530 #print 'testname',testname # dbg
531 #print 'testname',testname # dbg
531 if os.path.isfile(testname):
532 if os.path.isfile(testname):
532 return testname
533 return testname
533 raise IOError,'File' + `fname` + \
534 raise IOError,'File' + `fname` + \
534 ' not found in current or supplied directories:' + `alt_dirs`
535 ' not found in current or supplied directories:' + `alt_dirs`
535
536
536 #----------------------------------------------------------------------------
537 #----------------------------------------------------------------------------
537 def file_read(filename):
538 def file_read(filename):
538 """Read a file and close it. Returns the file source."""
539 """Read a file and close it. Returns the file source."""
539 fobj = open(filename,'r');
540 fobj = open(filename,'r');
540 source = fobj.read();
541 source = fobj.read();
541 fobj.close()
542 fobj.close()
542 return source
543 return source
543
544
544 def file_readlines(filename):
545 def file_readlines(filename):
545 """Read a file and close it. Returns the file source using readlines()."""
546 """Read a file and close it. Returns the file source using readlines()."""
546 fobj = open(filename,'r');
547 fobj = open(filename,'r');
547 lines = fobj.readlines();
548 lines = fobj.readlines();
548 fobj.close()
549 fobj.close()
549 return lines
550 return lines
550
551
551 #----------------------------------------------------------------------------
552 #----------------------------------------------------------------------------
552 def target_outdated(target,deps):
553 def target_outdated(target,deps):
553 """Determine whether a target is out of date.
554 """Determine whether a target is out of date.
554
555
555 target_outdated(target,deps) -> 1/0
556 target_outdated(target,deps) -> 1/0
556
557
557 deps: list of filenames which MUST exist.
558 deps: list of filenames which MUST exist.
558 target: single filename which may or may not exist.
559 target: single filename which may or may not exist.
559
560
560 If target doesn't exist or is older than any file listed in deps, return
561 If target doesn't exist or is older than any file listed in deps, return
561 true, otherwise return false.
562 true, otherwise return false.
562 """
563 """
563 try:
564 try:
564 target_time = os.path.getmtime(target)
565 target_time = os.path.getmtime(target)
565 except os.error:
566 except os.error:
566 return 1
567 return 1
567 for dep in deps:
568 for dep in deps:
568 dep_time = os.path.getmtime(dep)
569 dep_time = os.path.getmtime(dep)
569 if dep_time > target_time:
570 if dep_time > target_time:
570 #print "For target",target,"Dep failed:",dep # dbg
571 #print "For target",target,"Dep failed:",dep # dbg
571 #print "times (dep,tar):",dep_time,target_time # dbg
572 #print "times (dep,tar):",dep_time,target_time # dbg
572 return 1
573 return 1
573 return 0
574 return 0
574
575
575 #-----------------------------------------------------------------------------
576 #-----------------------------------------------------------------------------
576 def target_update(target,deps,cmd):
577 def target_update(target,deps,cmd):
577 """Update a target with a given command given a list of dependencies.
578 """Update a target with a given command given a list of dependencies.
578
579
579 target_update(target,deps,cmd) -> runs cmd if target is outdated.
580 target_update(target,deps,cmd) -> runs cmd if target is outdated.
580
581
581 This is just a wrapper around target_outdated() which calls the given
582 This is just a wrapper around target_outdated() which calls the given
582 command if target is outdated."""
583 command if target is outdated."""
583
584
584 if target_outdated(target,deps):
585 if target_outdated(target,deps):
585 xsys(cmd)
586 xsys(cmd)
586
587
587 #----------------------------------------------------------------------------
588 #----------------------------------------------------------------------------
588 def unquote_ends(istr):
589 def unquote_ends(istr):
589 """Remove a single pair of quotes from the endpoints of a string."""
590 """Remove a single pair of quotes from the endpoints of a string."""
590
591
591 if not istr:
592 if not istr:
592 return istr
593 return istr
593 if (istr[0]=="'" and istr[-1]=="'") or \
594 if (istr[0]=="'" and istr[-1]=="'") or \
594 (istr[0]=='"' and istr[-1]=='"'):
595 (istr[0]=='"' and istr[-1]=='"'):
595 return istr[1:-1]
596 return istr[1:-1]
596 else:
597 else:
597 return istr
598 return istr
598
599
599 #----------------------------------------------------------------------------
600 #----------------------------------------------------------------------------
600 def process_cmdline(argv,names=[],defaults={},usage=''):
601 def process_cmdline(argv,names=[],defaults={},usage=''):
601 """ Process command-line options and arguments.
602 """ Process command-line options and arguments.
602
603
603 Arguments:
604 Arguments:
604
605
605 - argv: list of arguments, typically sys.argv.
606 - argv: list of arguments, typically sys.argv.
606
607
607 - names: list of option names. See DPyGetOpt docs for details on options
608 - names: list of option names. See DPyGetOpt docs for details on options
608 syntax.
609 syntax.
609
610
610 - defaults: dict of default values.
611 - defaults: dict of default values.
611
612
612 - usage: optional usage notice to print if a wrong argument is passed.
613 - usage: optional usage notice to print if a wrong argument is passed.
613
614
614 Return a dict of options and a list of free arguments."""
615 Return a dict of options and a list of free arguments."""
615
616
616 getopt = DPyGetOpt.DPyGetOpt()
617 getopt = DPyGetOpt.DPyGetOpt()
617 getopt.setIgnoreCase(0)
618 getopt.setIgnoreCase(0)
618 getopt.parseConfiguration(names)
619 getopt.parseConfiguration(names)
619
620
620 try:
621 try:
621 getopt.processArguments(argv)
622 getopt.processArguments(argv)
622 except:
623 except:
623 print usage
624 print usage
624 warn(`sys.exc_value`,level=4)
625 warn(`sys.exc_value`,level=4)
625
626
626 defaults.update(getopt.optionValues)
627 defaults.update(getopt.optionValues)
627 args = getopt.freeValues
628 args = getopt.freeValues
628
629
629 return defaults,args
630 return defaults,args
630
631
631 #----------------------------------------------------------------------------
632 #----------------------------------------------------------------------------
632 def optstr2types(ostr):
633 def optstr2types(ostr):
633 """Convert a string of option names to a dict of type mappings.
634 """Convert a string of option names to a dict of type mappings.
634
635
635 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
636 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
636
637
637 This is used to get the types of all the options in a string formatted
638 This is used to get the types of all the options in a string formatted
638 with the conventions of DPyGetOpt. The 'type' None is used for options
639 with the conventions of DPyGetOpt. The 'type' None is used for options
639 which are strings (they need no further conversion). This function's main
640 which are strings (they need no further conversion). This function's main
640 use is to get a typemap for use with read_dict().
641 use is to get a typemap for use with read_dict().
641 """
642 """
642
643
643 typeconv = {None:'',int:'',float:''}
644 typeconv = {None:'',int:'',float:''}
644 typemap = {'s':None,'i':int,'f':float}
645 typemap = {'s':None,'i':int,'f':float}
645 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
646 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
646
647
647 for w in ostr.split():
648 for w in ostr.split():
648 oname,alias,otype = opt_re.match(w).groups()
649 oname,alias,otype = opt_re.match(w).groups()
649 if otype == '' or alias == '!': # simple switches are integers too
650 if otype == '' or alias == '!': # simple switches are integers too
650 otype = 'i'
651 otype = 'i'
651 typeconv[typemap[otype]] += oname + ' '
652 typeconv[typemap[otype]] += oname + ' '
652 return typeconv
653 return typeconv
653
654
654 #----------------------------------------------------------------------------
655 #----------------------------------------------------------------------------
655 def read_dict(filename,type_conv=None,**opt):
656 def read_dict(filename,type_conv=None,**opt):
656
657
657 """Read a dictionary of key=value pairs from an input file, optionally
658 """Read a dictionary of key=value pairs from an input file, optionally
658 performing conversions on the resulting values.
659 performing conversions on the resulting values.
659
660
660 read_dict(filename,type_conv,**opt) -> dict
661 read_dict(filename,type_conv,**opt) -> dict
661
662
662 Only one value per line is accepted, the format should be
663 Only one value per line is accepted, the format should be
663 # optional comments are ignored
664 # optional comments are ignored
664 key value\n
665 key value\n
665
666
666 Args:
667 Args:
667
668
668 - type_conv: A dictionary specifying which keys need to be converted to
669 - type_conv: A dictionary specifying which keys need to be converted to
669 which types. By default all keys are read as strings. This dictionary
670 which types. By default all keys are read as strings. This dictionary
670 should have as its keys valid conversion functions for strings
671 should have as its keys valid conversion functions for strings
671 (int,long,float,complex, or your own). The value for each key
672 (int,long,float,complex, or your own). The value for each key
672 (converter) should be a whitespace separated string containing the names
673 (converter) should be a whitespace separated string containing the names
673 of all the entries in the file to be converted using that function. For
674 of all the entries in the file to be converted using that function. For
674 keys to be left alone, use None as the conversion function (only needed
675 keys to be left alone, use None as the conversion function (only needed
675 with purge=1, see below).
676 with purge=1, see below).
676
677
677 - opt: dictionary with extra options as below (default in parens)
678 - opt: dictionary with extra options as below (default in parens)
678
679
679 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
680 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
680 of the dictionary to be returned. If purge is going to be used, the
681 of the dictionary to be returned. If purge is going to be used, the
681 set of keys to be left as strings also has to be explicitly specified
682 set of keys to be left as strings also has to be explicitly specified
682 using the (non-existent) conversion function None.
683 using the (non-existent) conversion function None.
683
684
684 fs(None): field separator. This is the key/value separator to be used
685 fs(None): field separator. This is the key/value separator to be used
685 when parsing the file. The None default means any whitespace [behavior
686 when parsing the file. The None default means any whitespace [behavior
686 of string.split()].
687 of string.split()].
687
688
688 strip(0): if 1, strip string values of leading/trailinig whitespace.
689 strip(0): if 1, strip string values of leading/trailinig whitespace.
689
690
690 warn(1): warning level if requested keys are not found in file.
691 warn(1): warning level if requested keys are not found in file.
691 - 0: silently ignore.
692 - 0: silently ignore.
692 - 1: inform but proceed.
693 - 1: inform but proceed.
693 - 2: raise KeyError exception.
694 - 2: raise KeyError exception.
694
695
695 no_empty(0): if 1, remove keys with whitespace strings as a value.
696 no_empty(0): if 1, remove keys with whitespace strings as a value.
696
697
697 unique([]): list of keys (or space separated string) which can't be
698 unique([]): list of keys (or space separated string) which can't be
698 repeated. If one such key is found in the file, each new instance
699 repeated. If one such key is found in the file, each new instance
699 overwrites the previous one. For keys not listed here, the behavior is
700 overwrites the previous one. For keys not listed here, the behavior is
700 to make a list of all appearances.
701 to make a list of all appearances.
701
702
702 Example:
703 Example:
703 If the input file test.ini has:
704 If the input file test.ini has:
704 i 3
705 i 3
705 x 4.5
706 x 4.5
706 y 5.5
707 y 5.5
707 s hi ho
708 s hi ho
708 Then:
709 Then:
709
710
710 >>> type_conv={int:'i',float:'x',None:'s'}
711 >>> type_conv={int:'i',float:'x',None:'s'}
711 >>> read_dict('test.ini')
712 >>> read_dict('test.ini')
712 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
713 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
713 >>> read_dict('test.ini',type_conv)
714 >>> read_dict('test.ini',type_conv)
714 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
715 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
715 >>> read_dict('test.ini',type_conv,purge=1)
716 >>> read_dict('test.ini',type_conv,purge=1)
716 {'i': 3, 's': 'hi ho', 'x': 4.5}
717 {'i': 3, 's': 'hi ho', 'x': 4.5}
717 """
718 """
718
719
719 # starting config
720 # starting config
720 opt.setdefault('purge',0)
721 opt.setdefault('purge',0)
721 opt.setdefault('fs',None) # field sep defaults to any whitespace
722 opt.setdefault('fs',None) # field sep defaults to any whitespace
722 opt.setdefault('strip',0)
723 opt.setdefault('strip',0)
723 opt.setdefault('warn',1)
724 opt.setdefault('warn',1)
724 opt.setdefault('no_empty',0)
725 opt.setdefault('no_empty',0)
725 opt.setdefault('unique','')
726 opt.setdefault('unique','')
726 if type(opt['unique']) in StringTypes:
727 if type(opt['unique']) in StringTypes:
727 unique_keys = qw(opt['unique'])
728 unique_keys = qw(opt['unique'])
728 elif type(opt['unique']) in (types.TupleType,types.ListType):
729 elif type(opt['unique']) in (types.TupleType,types.ListType):
729 unique_keys = opt['unique']
730 unique_keys = opt['unique']
730 else:
731 else:
731 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
732 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
732
733
733 dict = {}
734 dict = {}
734 # first read in table of values as strings
735 # first read in table of values as strings
735 file = open(filename,'r')
736 file = open(filename,'r')
736 for line in file.readlines():
737 for line in file.readlines():
737 line = line.strip()
738 line = line.strip()
738 if len(line) and line[0]=='#': continue
739 if len(line) and line[0]=='#': continue
739 if len(line)>0:
740 if len(line)>0:
740 lsplit = line.split(opt['fs'],1)
741 lsplit = line.split(opt['fs'],1)
741 try:
742 try:
742 key,val = lsplit
743 key,val = lsplit
743 except ValueError:
744 except ValueError:
744 key,val = lsplit[0],''
745 key,val = lsplit[0],''
745 key = key.strip()
746 key = key.strip()
746 if opt['strip']: val = val.strip()
747 if opt['strip']: val = val.strip()
747 if val == "''" or val == '""': val = ''
748 if val == "''" or val == '""': val = ''
748 if opt['no_empty'] and (val=='' or val.isspace()):
749 if opt['no_empty'] and (val=='' or val.isspace()):
749 continue
750 continue
750 # if a key is found more than once in the file, build a list
751 # if a key is found more than once in the file, build a list
751 # unless it's in the 'unique' list. In that case, last found in file
752 # unless it's in the 'unique' list. In that case, last found in file
752 # takes precedence. User beware.
753 # takes precedence. User beware.
753 try:
754 try:
754 if dict[key] and key in unique_keys:
755 if dict[key] and key in unique_keys:
755 dict[key] = val
756 dict[key] = val
756 elif type(dict[key]) is types.ListType:
757 elif type(dict[key]) is types.ListType:
757 dict[key].append(val)
758 dict[key].append(val)
758 else:
759 else:
759 dict[key] = [dict[key],val]
760 dict[key] = [dict[key],val]
760 except KeyError:
761 except KeyError:
761 dict[key] = val
762 dict[key] = val
762 # purge if requested
763 # purge if requested
763 if opt['purge']:
764 if opt['purge']:
764 accepted_keys = qwflat(type_conv.values())
765 accepted_keys = qwflat(type_conv.values())
765 for key in dict.keys():
766 for key in dict.keys():
766 if key in accepted_keys: continue
767 if key in accepted_keys: continue
767 del(dict[key])
768 del(dict[key])
768 # now convert if requested
769 # now convert if requested
769 if type_conv==None: return dict
770 if type_conv==None: return dict
770 conversions = type_conv.keys()
771 conversions = type_conv.keys()
771 try: conversions.remove(None)
772 try: conversions.remove(None)
772 except: pass
773 except: pass
773 for convert in conversions:
774 for convert in conversions:
774 for val in qw(type_conv[convert]):
775 for val in qw(type_conv[convert]):
775 try:
776 try:
776 dict[val] = convert(dict[val])
777 dict[val] = convert(dict[val])
777 except KeyError,e:
778 except KeyError,e:
778 if opt['warn'] == 0:
779 if opt['warn'] == 0:
779 pass
780 pass
780 elif opt['warn'] == 1:
781 elif opt['warn'] == 1:
781 print >>sys.stderr, 'Warning: key',val,\
782 print >>sys.stderr, 'Warning: key',val,\
782 'not found in file',filename
783 'not found in file',filename
783 elif opt['warn'] == 2:
784 elif opt['warn'] == 2:
784 raise KeyError,e
785 raise KeyError,e
785 else:
786 else:
786 raise ValueError,'Warning level must be 0,1 or 2'
787 raise ValueError,'Warning level must be 0,1 or 2'
787
788
788 return dict
789 return dict
789
790
790 #----------------------------------------------------------------------------
791 #----------------------------------------------------------------------------
791 def flag_calls(func):
792 def flag_calls(func):
792 """Wrap a function to detect and flag when it gets called.
793 """Wrap a function to detect and flag when it gets called.
793
794
794 This is a decorator which takes a function and wraps it in a function with
795 This is a decorator which takes a function and wraps it in a function with
795 a 'called' attribute. wrapper.called is initialized to False.
796 a 'called' attribute. wrapper.called is initialized to False.
796
797
797 The wrapper.called attribute is set to False right before each call to the
798 The wrapper.called attribute is set to False right before each call to the
798 wrapped function, so if the call fails it remains False. After the call
799 wrapped function, so if the call fails it remains False. After the call
799 completes, wrapper.called is set to True and the output is returned.
800 completes, wrapper.called is set to True and the output is returned.
800
801
801 Testing for truth in wrapper.called allows you to determine if a call to
802 Testing for truth in wrapper.called allows you to determine if a call to
802 func() was attempted and succeeded."""
803 func() was attempted and succeeded."""
803
804
804 def wrapper(*args,**kw):
805 def wrapper(*args,**kw):
805 wrapper.called = False
806 wrapper.called = False
806 out = func(*args,**kw)
807 out = func(*args,**kw)
807 wrapper.called = True
808 wrapper.called = True
808 return out
809 return out
809
810
810 wrapper.called = False
811 wrapper.called = False
811 wrapper.__doc__ = func.__doc__
812 wrapper.__doc__ = func.__doc__
812 return wrapper
813 return wrapper
813
814
814 #----------------------------------------------------------------------------
815 #----------------------------------------------------------------------------
815 def dhook_wrap(func,*a,**k):
816 def dhook_wrap(func,*a,**k):
816 """Wrap a function call in a sys.displayhook controller.
817 """Wrap a function call in a sys.displayhook controller.
817
818
818 Returns a wrapper around func which calls func, with all its arguments and
819 Returns a wrapper around func which calls func, with all its arguments and
819 keywords unmodified, using the default sys.displayhook. Since IPython
820 keywords unmodified, using the default sys.displayhook. Since IPython
820 modifies sys.displayhook, it breaks the behavior of certain systems that
821 modifies sys.displayhook, it breaks the behavior of certain systems that
821 rely on the default behavior, notably doctest.
822 rely on the default behavior, notably doctest.
822 """
823 """
823
824
824 def f(*a,**k):
825 def f(*a,**k):
825
826
826 dhook_s = sys.displayhook
827 dhook_s = sys.displayhook
827 sys.displayhook = sys.__displayhook__
828 sys.displayhook = sys.__displayhook__
828 try:
829 try:
829 out = func(*a,**k)
830 out = func(*a,**k)
830 finally:
831 finally:
831 sys.displayhook = dhook_s
832 sys.displayhook = dhook_s
832
833
833 return out
834 return out
834
835
835 f.__doc__ = func.__doc__
836 f.__doc__ = func.__doc__
836 return f
837 return f
837
838
838 #----------------------------------------------------------------------------
839 #----------------------------------------------------------------------------
840 def doctest_reload():
841 """Properly reload doctest to reuse it interactively.
842
843 This routine:
844
845 - reloads doctest
846
847 - resets its global 'master' attribute to None, so that multiple uses of
848 the module interactively don't produce cumulative reports.
849
850 - Monkeypatches its core test runner method to protect it from IPython's
851 modified displayhook. Doctest expects the default displayhook behavior
852 deep down, so our modification breaks it completely. For this reason, a
853 hard monkeypatch seems like a reasonable solution rather than asking
854 users to manually use a different doctest runner when under IPython."""
855
856 import doctest
857 reload(doctest)
858 doctest.master=None
859
860 try:
861 doctest.DocTestRunner
862 except AttributeError:
863 # This is only for python 2.3 compatibility, remove once we move to
864 # 2.4 only.
865 pass
866 else:
867 doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run)
868
869 #----------------------------------------------------------------------------
839 class HomeDirError(Error):
870 class HomeDirError(Error):
840 pass
871 pass
841
872
842 def get_home_dir():
873 def get_home_dir():
843 """Return the closest possible equivalent to a 'home' directory.
874 """Return the closest possible equivalent to a 'home' directory.
844
875
845 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
876 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
846
877
847 Currently only Posix and NT are implemented, a HomeDirError exception is
878 Currently only Posix and NT are implemented, a HomeDirError exception is
848 raised for all other OSes. """
879 raised for all other OSes. """
849
880
850 isdir = os.path.isdir
881 isdir = os.path.isdir
851 env = os.environ
882 env = os.environ
852
883
853 # first, check py2exe distribution root directory for _ipython.
884 # first, check py2exe distribution root directory for _ipython.
854 # This overrides all. Normally does not exist.
885 # This overrides all. Normally does not exist.
855
886
856 if '\\library.zip\\' in IPython.__file__.lower():
887 if '\\library.zip\\' in IPython.__file__.lower():
857 root, rest = IPython.__file__.lower().split('library.zip')
888 root, rest = IPython.__file__.lower().split('library.zip')
858 if isdir(root + '_ipython'):
889 if isdir(root + '_ipython'):
859 os.environ["IPYKITROOT"] = root.rstrip('\\')
890 os.environ["IPYKITROOT"] = root.rstrip('\\')
860 return root
891 return root
861
892
862 try:
893 try:
863 homedir = env['HOME']
894 homedir = env['HOME']
864 if not isdir(homedir):
895 if not isdir(homedir):
865 # in case a user stuck some string which does NOT resolve to a
896 # in case a user stuck some string which does NOT resolve to a
866 # valid path, it's as good as if we hadn't foud it
897 # valid path, it's as good as if we hadn't foud it
867 raise KeyError
898 raise KeyError
868 return homedir
899 return homedir
869 except KeyError:
900 except KeyError:
870 if os.name == 'posix':
901 if os.name == 'posix':
871 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
902 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
872 elif os.name == 'nt':
903 elif os.name == 'nt':
873 # For some strange reason, win9x returns 'nt' for os.name.
904 # For some strange reason, win9x returns 'nt' for os.name.
874 try:
905 try:
875 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
906 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
876 if not isdir(homedir):
907 if not isdir(homedir):
877 homedir = os.path.join(env['USERPROFILE'])
908 homedir = os.path.join(env['USERPROFILE'])
878 if not isdir(homedir):
909 if not isdir(homedir):
879 raise HomeDirError
910 raise HomeDirError
880 return homedir
911 return homedir
881 except:
912 except:
882 try:
913 try:
883 # Use the registry to get the 'My Documents' folder.
914 # Use the registry to get the 'My Documents' folder.
884 import _winreg as wreg
915 import _winreg as wreg
885 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
916 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
886 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
917 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
887 homedir = wreg.QueryValueEx(key,'Personal')[0]
918 homedir = wreg.QueryValueEx(key,'Personal')[0]
888 key.Close()
919 key.Close()
889 if not isdir(homedir):
920 if not isdir(homedir):
890 e = ('Invalid "Personal" folder registry key '
921 e = ('Invalid "Personal" folder registry key '
891 'typically "My Documents".\n'
922 'typically "My Documents".\n'
892 'Value: %s\n'
923 'Value: %s\n'
893 'This is not a valid directory on your system.' %
924 'This is not a valid directory on your system.' %
894 homedir)
925 homedir)
895 raise HomeDirError(e)
926 raise HomeDirError(e)
896 return homedir
927 return homedir
897 except HomeDirError:
928 except HomeDirError:
898 raise
929 raise
899 except:
930 except:
900 return 'C:\\'
931 return 'C:\\'
901 elif os.name == 'dos':
932 elif os.name == 'dos':
902 # Desperate, may do absurd things in classic MacOS. May work under DOS.
933 # Desperate, may do absurd things in classic MacOS. May work under DOS.
903 return 'C:\\'
934 return 'C:\\'
904 else:
935 else:
905 raise HomeDirError,'support for your operating system not implemented.'
936 raise HomeDirError,'support for your operating system not implemented.'
906
937
907 #****************************************************************************
938 #****************************************************************************
908 # strings and text
939 # strings and text
909
940
910 class LSString(str):
941 class LSString(str):
911 """String derivative with a special access attributes.
942 """String derivative with a special access attributes.
912
943
913 These are normal strings, but with the special attributes:
944 These are normal strings, but with the special attributes:
914
945
915 .l (or .list) : value as list (split on newlines).
946 .l (or .list) : value as list (split on newlines).
916 .n (or .nlstr): original value (the string itself).
947 .n (or .nlstr): original value (the string itself).
917 .s (or .spstr): value as whitespace-separated string.
948 .s (or .spstr): value as whitespace-separated string.
918 .p (or .paths): list of path objects
949 .p (or .paths): list of path objects
919
950
920 Any values which require transformations are computed only once and
951 Any values which require transformations are computed only once and
921 cached.
952 cached.
922
953
923 Such strings are very useful to efficiently interact with the shell, which
954 Such strings are very useful to efficiently interact with the shell, which
924 typically only understands whitespace-separated options for commands."""
955 typically only understands whitespace-separated options for commands."""
925
956
926 def get_list(self):
957 def get_list(self):
927 try:
958 try:
928 return self.__list
959 return self.__list
929 except AttributeError:
960 except AttributeError:
930 self.__list = self.split('\n')
961 self.__list = self.split('\n')
931 return self.__list
962 return self.__list
932
963
933 l = list = property(get_list)
964 l = list = property(get_list)
934
965
935 def get_spstr(self):
966 def get_spstr(self):
936 try:
967 try:
937 return self.__spstr
968 return self.__spstr
938 except AttributeError:
969 except AttributeError:
939 self.__spstr = self.replace('\n',' ')
970 self.__spstr = self.replace('\n',' ')
940 return self.__spstr
971 return self.__spstr
941
972
942 s = spstr = property(get_spstr)
973 s = spstr = property(get_spstr)
943
974
944 def get_nlstr(self):
975 def get_nlstr(self):
945 return self
976 return self
946
977
947 n = nlstr = property(get_nlstr)
978 n = nlstr = property(get_nlstr)
948
979
949 def get_paths(self):
980 def get_paths(self):
950 try:
981 try:
951 return self.__paths
982 return self.__paths
952 except AttributeError:
983 except AttributeError:
953 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
984 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
954 return self.__paths
985 return self.__paths
955
986
956 p = paths = property(get_paths)
987 p = paths = property(get_paths)
957
988
958 def print_lsstring(arg):
989 def print_lsstring(arg):
959 """ Prettier (non-repr-like) and more informative printer for LSString """
990 """ Prettier (non-repr-like) and more informative printer for LSString """
960 print "LSString (.p, .n, .l, .s available). Value:"
991 print "LSString (.p, .n, .l, .s available). Value:"
961 print arg
992 print arg
962
993
963 print_lsstring = result_display.when_type(LSString)(print_lsstring)
994 print_lsstring = result_display.when_type(LSString)(print_lsstring)
964
995
965 #----------------------------------------------------------------------------
996 #----------------------------------------------------------------------------
966 class SList(list):
997 class SList(list):
967 """List derivative with a special access attributes.
998 """List derivative with a special access attributes.
968
999
969 These are normal lists, but with the special attributes:
1000 These are normal lists, but with the special attributes:
970
1001
971 .l (or .list) : value as list (the list itself).
1002 .l (or .list) : value as list (the list itself).
972 .n (or .nlstr): value as a string, joined on newlines.
1003 .n (or .nlstr): value as a string, joined on newlines.
973 .s (or .spstr): value as a string, joined on spaces.
1004 .s (or .spstr): value as a string, joined on spaces.
974 .p (or .paths): list of path objects
1005 .p (or .paths): list of path objects
975
1006
976 Any values which require transformations are computed only once and
1007 Any values which require transformations are computed only once and
977 cached."""
1008 cached."""
978
1009
979 def get_list(self):
1010 def get_list(self):
980 return self
1011 return self
981
1012
982 l = list = property(get_list)
1013 l = list = property(get_list)
983
1014
984 def get_spstr(self):
1015 def get_spstr(self):
985 try:
1016 try:
986 return self.__spstr
1017 return self.__spstr
987 except AttributeError:
1018 except AttributeError:
988 self.__spstr = ' '.join(self)
1019 self.__spstr = ' '.join(self)
989 return self.__spstr
1020 return self.__spstr
990
1021
991 s = spstr = property(get_spstr)
1022 s = spstr = property(get_spstr)
992
1023
993 def get_nlstr(self):
1024 def get_nlstr(self):
994 try:
1025 try:
995 return self.__nlstr
1026 return self.__nlstr
996 except AttributeError:
1027 except AttributeError:
997 self.__nlstr = '\n'.join(self)
1028 self.__nlstr = '\n'.join(self)
998 return self.__nlstr
1029 return self.__nlstr
999
1030
1000 n = nlstr = property(get_nlstr)
1031 n = nlstr = property(get_nlstr)
1001
1032
1002 def get_paths(self):
1033 def get_paths(self):
1003 try:
1034 try:
1004 return self.__paths
1035 return self.__paths
1005 except AttributeError:
1036 except AttributeError:
1006 self.__paths = [path(p) for p in self if os.path.exists(p)]
1037 self.__paths = [path(p) for p in self if os.path.exists(p)]
1007 return self.__paths
1038 return self.__paths
1008
1039
1009 p = paths = property(get_paths)
1040 p = paths = property(get_paths)
1010
1041
1011 def grep(self, pattern, prune = False):
1042 def grep(self, pattern, prune = False):
1012 """ Return all strings matching 'pattern' (a regex or callable)
1043 """ Return all strings matching 'pattern' (a regex or callable)
1013
1044
1014 This is case-insensitive. If prune is true, return all items
1045 This is case-insensitive. If prune is true, return all items
1015 NOT matching the pattern.
1046 NOT matching the pattern.
1016
1047
1017 Examples::
1048 Examples::
1018
1049
1019 a.grep( lambda x: x.startswith('C') )
1050 a.grep( lambda x: x.startswith('C') )
1020 a.grep('Cha.*log', prune=1)
1051 a.grep('Cha.*log', prune=1)
1021 """
1052 """
1022 if isinstance(pattern, basestring):
1053 if isinstance(pattern, basestring):
1023 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
1054 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
1024 else:
1055 else:
1025 pred = pattern
1056 pred = pattern
1026 if not prune:
1057 if not prune:
1027 return SList([el for el in self if pred(el)])
1058 return SList([el for el in self if pred(el)])
1028 else:
1059 else:
1029 return SList([el for el in self if not pred(el)])
1060 return SList([el for el in self if not pred(el)])
1030
1061
1031 def print_slist(arg):
1062 def print_slist(arg):
1032 """ Prettier (non-repr-like) and more informative printer for SList """
1063 """ Prettier (non-repr-like) and more informative printer for SList """
1033 print "SList (.p, .n, .l, .s, .grep() available). Value:"
1064 print "SList (.p, .n, .l, .s, .grep() available). Value:"
1034 nlprint(arg)
1065 nlprint(arg)
1035
1066
1036 print_slist = result_display.when_type(SList)(print_slist)
1067 print_slist = result_display.when_type(SList)(print_slist)
1037
1068
1038
1069
1039
1070
1040 #----------------------------------------------------------------------------
1071 #----------------------------------------------------------------------------
1041 def esc_quotes(strng):
1072 def esc_quotes(strng):
1042 """Return the input string with single and double quotes escaped out"""
1073 """Return the input string with single and double quotes escaped out"""
1043
1074
1044 return strng.replace('"','\\"').replace("'","\\'")
1075 return strng.replace('"','\\"').replace("'","\\'")
1045
1076
1046 #----------------------------------------------------------------------------
1077 #----------------------------------------------------------------------------
1047 def make_quoted_expr(s):
1078 def make_quoted_expr(s):
1048 """Return string s in appropriate quotes, using raw string if possible.
1079 """Return string s in appropriate quotes, using raw string if possible.
1049
1080
1050 Effectively this turns string: cd \ao\ao\
1081 Effectively this turns string: cd \ao\ao\
1051 to: r"cd \ao\ao\_"[:-1]
1082 to: r"cd \ao\ao\_"[:-1]
1052
1083
1053 Note the use of raw string and padding at the end to allow trailing backslash.
1084 Note the use of raw string and padding at the end to allow trailing backslash.
1054
1085
1055 """
1086 """
1056
1087
1057 tail = ''
1088 tail = ''
1058 tailpadding = ''
1089 tailpadding = ''
1059 raw = ''
1090 raw = ''
1060 if "\\" in s:
1091 if "\\" in s:
1061 raw = 'r'
1092 raw = 'r'
1062 if s.endswith('\\'):
1093 if s.endswith('\\'):
1063 tail = '[:-1]'
1094 tail = '[:-1]'
1064 tailpadding = '_'
1095 tailpadding = '_'
1065 if '"' not in s:
1096 if '"' not in s:
1066 quote = '"'
1097 quote = '"'
1067 elif "'" not in s:
1098 elif "'" not in s:
1068 quote = "'"
1099 quote = "'"
1069 elif '"""' not in s and not s.endswith('"'):
1100 elif '"""' not in s and not s.endswith('"'):
1070 quote = '"""'
1101 quote = '"""'
1071 elif "'''" not in s and not s.endswith("'"):
1102 elif "'''" not in s and not s.endswith("'"):
1072 quote = "'''"
1103 quote = "'''"
1073 else:
1104 else:
1074 # give up, backslash-escaped string will do
1105 # give up, backslash-escaped string will do
1075 return '"%s"' % esc_quotes(s)
1106 return '"%s"' % esc_quotes(s)
1076 res = itpl("$raw$quote$s$tailpadding$quote$tail")
1107 res = itpl("$raw$quote$s$tailpadding$quote$tail")
1077 return res
1108 return res
1078
1109
1079
1110
1080 #----------------------------------------------------------------------------
1111 #----------------------------------------------------------------------------
1081 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1112 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1082 """Take multiple lines of input.
1113 """Take multiple lines of input.
1083
1114
1084 A list with each line of input as a separate element is returned when a
1115 A list with each line of input as a separate element is returned when a
1085 termination string is entered (defaults to a single '.'). Input can also
1116 termination string is entered (defaults to a single '.'). Input can also
1086 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1117 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1087
1118
1088 Lines of input which end in \\ are joined into single entries (and a
1119 Lines of input which end in \\ are joined into single entries (and a
1089 secondary continuation prompt is issued as long as the user terminates
1120 secondary continuation prompt is issued as long as the user terminates
1090 lines with \\). This allows entering very long strings which are still
1121 lines with \\). This allows entering very long strings which are still
1091 meant to be treated as single entities.
1122 meant to be treated as single entities.
1092 """
1123 """
1093
1124
1094 try:
1125 try:
1095 if header:
1126 if header:
1096 header += '\n'
1127 header += '\n'
1097 lines = [raw_input(header + ps1)]
1128 lines = [raw_input(header + ps1)]
1098 except EOFError:
1129 except EOFError:
1099 return []
1130 return []
1100 terminate = [terminate_str]
1131 terminate = [terminate_str]
1101 try:
1132 try:
1102 while lines[-1:] != terminate:
1133 while lines[-1:] != terminate:
1103 new_line = raw_input(ps1)
1134 new_line = raw_input(ps1)
1104 while new_line.endswith('\\'):
1135 while new_line.endswith('\\'):
1105 new_line = new_line[:-1] + raw_input(ps2)
1136 new_line = new_line[:-1] + raw_input(ps2)
1106 lines.append(new_line)
1137 lines.append(new_line)
1107
1138
1108 return lines[:-1] # don't return the termination command
1139 return lines[:-1] # don't return the termination command
1109 except EOFError:
1140 except EOFError:
1110 print
1141 print
1111 return lines
1142 return lines
1112
1143
1113 #----------------------------------------------------------------------------
1144 #----------------------------------------------------------------------------
1114 def raw_input_ext(prompt='', ps2='... '):
1145 def raw_input_ext(prompt='', ps2='... '):
1115 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1146 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1116
1147
1117 line = raw_input(prompt)
1148 line = raw_input(prompt)
1118 while line.endswith('\\'):
1149 while line.endswith('\\'):
1119 line = line[:-1] + raw_input(ps2)
1150 line = line[:-1] + raw_input(ps2)
1120 return line
1151 return line
1121
1152
1122 #----------------------------------------------------------------------------
1153 #----------------------------------------------------------------------------
1123 def ask_yes_no(prompt,default=None):
1154 def ask_yes_no(prompt,default=None):
1124 """Asks a question and returns a boolean (y/n) answer.
1155 """Asks a question and returns a boolean (y/n) answer.
1125
1156
1126 If default is given (one of 'y','n'), it is used if the user input is
1157 If default is given (one of 'y','n'), it is used if the user input is
1127 empty. Otherwise the question is repeated until an answer is given.
1158 empty. Otherwise the question is repeated until an answer is given.
1128
1159
1129 An EOF is treated as the default answer. If there is no default, an
1160 An EOF is treated as the default answer. If there is no default, an
1130 exception is raised to prevent infinite loops.
1161 exception is raised to prevent infinite loops.
1131
1162
1132 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1163 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1133
1164
1134 answers = {'y':True,'n':False,'yes':True,'no':False}
1165 answers = {'y':True,'n':False,'yes':True,'no':False}
1135 ans = None
1166 ans = None
1136 while ans not in answers.keys():
1167 while ans not in answers.keys():
1137 try:
1168 try:
1138 ans = raw_input(prompt+' ').lower()
1169 ans = raw_input(prompt+' ').lower()
1139 if not ans: # response was an empty string
1170 if not ans: # response was an empty string
1140 ans = default
1171 ans = default
1141 except KeyboardInterrupt:
1172 except KeyboardInterrupt:
1142 pass
1173 pass
1143 except EOFError:
1174 except EOFError:
1144 if default in answers.keys():
1175 if default in answers.keys():
1145 ans = default
1176 ans = default
1146 print
1177 print
1147 else:
1178 else:
1148 raise
1179 raise
1149
1180
1150 return answers[ans]
1181 return answers[ans]
1151
1182
1152 #----------------------------------------------------------------------------
1183 #----------------------------------------------------------------------------
1153 def marquee(txt='',width=78,mark='*'):
1184 def marquee(txt='',width=78,mark='*'):
1154 """Return the input string centered in a 'marquee'."""
1185 """Return the input string centered in a 'marquee'."""
1155 if not txt:
1186 if not txt:
1156 return (mark*width)[:width]
1187 return (mark*width)[:width]
1157 nmark = (width-len(txt)-2)/len(mark)/2
1188 nmark = (width-len(txt)-2)/len(mark)/2
1158 if nmark < 0: nmark =0
1189 if nmark < 0: nmark =0
1159 marks = mark*nmark
1190 marks = mark*nmark
1160 return '%s %s %s' % (marks,txt,marks)
1191 return '%s %s %s' % (marks,txt,marks)
1161
1192
1162 #----------------------------------------------------------------------------
1193 #----------------------------------------------------------------------------
1163 class EvalDict:
1194 class EvalDict:
1164 """
1195 """
1165 Emulate a dict which evaluates its contents in the caller's frame.
1196 Emulate a dict which evaluates its contents in the caller's frame.
1166
1197
1167 Usage:
1198 Usage:
1168 >>>number = 19
1199 >>>number = 19
1169 >>>text = "python"
1200 >>>text = "python"
1170 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1201 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1171 """
1202 """
1172
1203
1173 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1204 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1174 # modified (shorter) version of:
1205 # modified (shorter) version of:
1175 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1206 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1176 # Skip Montanaro (skip@pobox.com).
1207 # Skip Montanaro (skip@pobox.com).
1177
1208
1178 def __getitem__(self, name):
1209 def __getitem__(self, name):
1179 frame = sys._getframe(1)
1210 frame = sys._getframe(1)
1180 return eval(name, frame.f_globals, frame.f_locals)
1211 return eval(name, frame.f_globals, frame.f_locals)
1181
1212
1182 EvalString = EvalDict # for backwards compatibility
1213 EvalString = EvalDict # for backwards compatibility
1183 #----------------------------------------------------------------------------
1214 #----------------------------------------------------------------------------
1184 def qw(words,flat=0,sep=None,maxsplit=-1):
1215 def qw(words,flat=0,sep=None,maxsplit=-1):
1185 """Similar to Perl's qw() operator, but with some more options.
1216 """Similar to Perl's qw() operator, but with some more options.
1186
1217
1187 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1218 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1188
1219
1189 words can also be a list itself, and with flat=1, the output will be
1220 words can also be a list itself, and with flat=1, the output will be
1190 recursively flattened. Examples:
1221 recursively flattened. Examples:
1191
1222
1192 >>> qw('1 2')
1223 >>> qw('1 2')
1193 ['1', '2']
1224 ['1', '2']
1194 >>> qw(['a b','1 2',['m n','p q']])
1225 >>> qw(['a b','1 2',['m n','p q']])
1195 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1226 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1196 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1227 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1197 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1228 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1198
1229
1199 if type(words) in StringTypes:
1230 if type(words) in StringTypes:
1200 return [word.strip() for word in words.split(sep,maxsplit)
1231 return [word.strip() for word in words.split(sep,maxsplit)
1201 if word and not word.isspace() ]
1232 if word and not word.isspace() ]
1202 if flat:
1233 if flat:
1203 return flatten(map(qw,words,[1]*len(words)))
1234 return flatten(map(qw,words,[1]*len(words)))
1204 return map(qw,words)
1235 return map(qw,words)
1205
1236
1206 #----------------------------------------------------------------------------
1237 #----------------------------------------------------------------------------
1207 def qwflat(words,sep=None,maxsplit=-1):
1238 def qwflat(words,sep=None,maxsplit=-1):
1208 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1239 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1209 return qw(words,1,sep,maxsplit)
1240 return qw(words,1,sep,maxsplit)
1210
1241
1211 #----------------------------------------------------------------------------
1242 #----------------------------------------------------------------------------
1212 def qw_lol(indata):
1243 def qw_lol(indata):
1213 """qw_lol('a b') -> [['a','b']],
1244 """qw_lol('a b') -> [['a','b']],
1214 otherwise it's just a call to qw().
1245 otherwise it's just a call to qw().
1215
1246
1216 We need this to make sure the modules_some keys *always* end up as a
1247 We need this to make sure the modules_some keys *always* end up as a
1217 list of lists."""
1248 list of lists."""
1218
1249
1219 if type(indata) in StringTypes:
1250 if type(indata) in StringTypes:
1220 return [qw(indata)]
1251 return [qw(indata)]
1221 else:
1252 else:
1222 return qw(indata)
1253 return qw(indata)
1223
1254
1224 #-----------------------------------------------------------------------------
1255 #-----------------------------------------------------------------------------
1225 def list_strings(arg):
1256 def list_strings(arg):
1226 """Always return a list of strings, given a string or list of strings
1257 """Always return a list of strings, given a string or list of strings
1227 as input."""
1258 as input."""
1228
1259
1229 if type(arg) in StringTypes: return [arg]
1260 if type(arg) in StringTypes: return [arg]
1230 else: return arg
1261 else: return arg
1231
1262
1232 #----------------------------------------------------------------------------
1263 #----------------------------------------------------------------------------
1233 def grep(pat,list,case=1):
1264 def grep(pat,list,case=1):
1234 """Simple minded grep-like function.
1265 """Simple minded grep-like function.
1235 grep(pat,list) returns occurrences of pat in list, None on failure.
1266 grep(pat,list) returns occurrences of pat in list, None on failure.
1236
1267
1237 It only does simple string matching, with no support for regexps. Use the
1268 It only does simple string matching, with no support for regexps. Use the
1238 option case=0 for case-insensitive matching."""
1269 option case=0 for case-insensitive matching."""
1239
1270
1240 # This is pretty crude. At least it should implement copying only references
1271 # This is pretty crude. At least it should implement copying only references
1241 # to the original data in case it's big. Now it copies the data for output.
1272 # to the original data in case it's big. Now it copies the data for output.
1242 out=[]
1273 out=[]
1243 if case:
1274 if case:
1244 for term in list:
1275 for term in list:
1245 if term.find(pat)>-1: out.append(term)
1276 if term.find(pat)>-1: out.append(term)
1246 else:
1277 else:
1247 lpat=pat.lower()
1278 lpat=pat.lower()
1248 for term in list:
1279 for term in list:
1249 if term.lower().find(lpat)>-1: out.append(term)
1280 if term.lower().find(lpat)>-1: out.append(term)
1250
1281
1251 if len(out): return out
1282 if len(out): return out
1252 else: return None
1283 else: return None
1253
1284
1254 #----------------------------------------------------------------------------
1285 #----------------------------------------------------------------------------
1255 def dgrep(pat,*opts):
1286 def dgrep(pat,*opts):
1256 """Return grep() on dir()+dir(__builtins__).
1287 """Return grep() on dir()+dir(__builtins__).
1257
1288
1258 A very common use of grep() when working interactively."""
1289 A very common use of grep() when working interactively."""
1259
1290
1260 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1291 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1261
1292
1262 #----------------------------------------------------------------------------
1293 #----------------------------------------------------------------------------
1263 def idgrep(pat):
1294 def idgrep(pat):
1264 """Case-insensitive dgrep()"""
1295 """Case-insensitive dgrep()"""
1265
1296
1266 return dgrep(pat,0)
1297 return dgrep(pat,0)
1267
1298
1268 #----------------------------------------------------------------------------
1299 #----------------------------------------------------------------------------
1269 def igrep(pat,list):
1300 def igrep(pat,list):
1270 """Synonym for case-insensitive grep."""
1301 """Synonym for case-insensitive grep."""
1271
1302
1272 return grep(pat,list,case=0)
1303 return grep(pat,list,case=0)
1273
1304
1274 #----------------------------------------------------------------------------
1305 #----------------------------------------------------------------------------
1275 def indent(str,nspaces=4,ntabs=0):
1306 def indent(str,nspaces=4,ntabs=0):
1276 """Indent a string a given number of spaces or tabstops.
1307 """Indent a string a given number of spaces or tabstops.
1277
1308
1278 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1309 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1279 """
1310 """
1280 if str is None:
1311 if str is None:
1281 return
1312 return
1282 ind = '\t'*ntabs+' '*nspaces
1313 ind = '\t'*ntabs+' '*nspaces
1283 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1314 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1284 if outstr.endswith(os.linesep+ind):
1315 if outstr.endswith(os.linesep+ind):
1285 return outstr[:-len(ind)]
1316 return outstr[:-len(ind)]
1286 else:
1317 else:
1287 return outstr
1318 return outstr
1288
1319
1289 #-----------------------------------------------------------------------------
1320 #-----------------------------------------------------------------------------
1290 def native_line_ends(filename,backup=1):
1321 def native_line_ends(filename,backup=1):
1291 """Convert (in-place) a file to line-ends native to the current OS.
1322 """Convert (in-place) a file to line-ends native to the current OS.
1292
1323
1293 If the optional backup argument is given as false, no backup of the
1324 If the optional backup argument is given as false, no backup of the
1294 original file is left. """
1325 original file is left. """
1295
1326
1296 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1327 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1297
1328
1298 bak_filename = filename + backup_suffixes[os.name]
1329 bak_filename = filename + backup_suffixes[os.name]
1299
1330
1300 original = open(filename).read()
1331 original = open(filename).read()
1301 shutil.copy2(filename,bak_filename)
1332 shutil.copy2(filename,bak_filename)
1302 try:
1333 try:
1303 new = open(filename,'wb')
1334 new = open(filename,'wb')
1304 new.write(os.linesep.join(original.splitlines()))
1335 new.write(os.linesep.join(original.splitlines()))
1305 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1336 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1306 new.close()
1337 new.close()
1307 except:
1338 except:
1308 os.rename(bak_filename,filename)
1339 os.rename(bak_filename,filename)
1309 if not backup:
1340 if not backup:
1310 try:
1341 try:
1311 os.remove(bak_filename)
1342 os.remove(bak_filename)
1312 except:
1343 except:
1313 pass
1344 pass
1314
1345
1315 #----------------------------------------------------------------------------
1346 #----------------------------------------------------------------------------
1316 def get_pager_cmd(pager_cmd = None):
1347 def get_pager_cmd(pager_cmd = None):
1317 """Return a pager command.
1348 """Return a pager command.
1318
1349
1319 Makes some attempts at finding an OS-correct one."""
1350 Makes some attempts at finding an OS-correct one."""
1320
1351
1321 if os.name == 'posix':
1352 if os.name == 'posix':
1322 default_pager_cmd = 'less -r' # -r for color control sequences
1353 default_pager_cmd = 'less -r' # -r for color control sequences
1323 elif os.name in ['nt','dos']:
1354 elif os.name in ['nt','dos']:
1324 default_pager_cmd = 'type'
1355 default_pager_cmd = 'type'
1325
1356
1326 if pager_cmd is None:
1357 if pager_cmd is None:
1327 try:
1358 try:
1328 pager_cmd = os.environ['PAGER']
1359 pager_cmd = os.environ['PAGER']
1329 except:
1360 except:
1330 pager_cmd = default_pager_cmd
1361 pager_cmd = default_pager_cmd
1331 return pager_cmd
1362 return pager_cmd
1332
1363
1333 #-----------------------------------------------------------------------------
1364 #-----------------------------------------------------------------------------
1334 def get_pager_start(pager,start):
1365 def get_pager_start(pager,start):
1335 """Return the string for paging files with an offset.
1366 """Return the string for paging files with an offset.
1336
1367
1337 This is the '+N' argument which less and more (under Unix) accept.
1368 This is the '+N' argument which less and more (under Unix) accept.
1338 """
1369 """
1339
1370
1340 if pager in ['less','more']:
1371 if pager in ['less','more']:
1341 if start:
1372 if start:
1342 start_string = '+' + str(start)
1373 start_string = '+' + str(start)
1343 else:
1374 else:
1344 start_string = ''
1375 start_string = ''
1345 else:
1376 else:
1346 start_string = ''
1377 start_string = ''
1347 return start_string
1378 return start_string
1348
1379
1349 #----------------------------------------------------------------------------
1380 #----------------------------------------------------------------------------
1350 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1381 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1351 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1382 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1352 import msvcrt
1383 import msvcrt
1353 def page_more():
1384 def page_more():
1354 """ Smart pausing between pages
1385 """ Smart pausing between pages
1355
1386
1356 @return: True if need print more lines, False if quit
1387 @return: True if need print more lines, False if quit
1357 """
1388 """
1358 Term.cout.write('---Return to continue, q to quit--- ')
1389 Term.cout.write('---Return to continue, q to quit--- ')
1359 ans = msvcrt.getch()
1390 ans = msvcrt.getch()
1360 if ans in ("q", "Q"):
1391 if ans in ("q", "Q"):
1361 result = False
1392 result = False
1362 else:
1393 else:
1363 result = True
1394 result = True
1364 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1395 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1365 return result
1396 return result
1366 else:
1397 else:
1367 def page_more():
1398 def page_more():
1368 ans = raw_input('---Return to continue, q to quit--- ')
1399 ans = raw_input('---Return to continue, q to quit--- ')
1369 if ans.lower().startswith('q'):
1400 if ans.lower().startswith('q'):
1370 return False
1401 return False
1371 else:
1402 else:
1372 return True
1403 return True
1373
1404
1374 esc_re = re.compile(r"(\x1b[^m]+m)")
1405 esc_re = re.compile(r"(\x1b[^m]+m)")
1375
1406
1376 def page_dumb(strng,start=0,screen_lines=25):
1407 def page_dumb(strng,start=0,screen_lines=25):
1377 """Very dumb 'pager' in Python, for when nothing else works.
1408 """Very dumb 'pager' in Python, for when nothing else works.
1378
1409
1379 Only moves forward, same interface as page(), except for pager_cmd and
1410 Only moves forward, same interface as page(), except for pager_cmd and
1380 mode."""
1411 mode."""
1381
1412
1382 out_ln = strng.splitlines()[start:]
1413 out_ln = strng.splitlines()[start:]
1383 screens = chop(out_ln,screen_lines-1)
1414 screens = chop(out_ln,screen_lines-1)
1384 if len(screens) == 1:
1415 if len(screens) == 1:
1385 print >>Term.cout, os.linesep.join(screens[0])
1416 print >>Term.cout, os.linesep.join(screens[0])
1386 else:
1417 else:
1387 last_escape = ""
1418 last_escape = ""
1388 for scr in screens[0:-1]:
1419 for scr in screens[0:-1]:
1389 hunk = os.linesep.join(scr)
1420 hunk = os.linesep.join(scr)
1390 print >>Term.cout, last_escape + hunk
1421 print >>Term.cout, last_escape + hunk
1391 if not page_more():
1422 if not page_more():
1392 return
1423 return
1393 esc_list = esc_re.findall(hunk)
1424 esc_list = esc_re.findall(hunk)
1394 if len(esc_list) > 0:
1425 if len(esc_list) > 0:
1395 last_escape = esc_list[-1]
1426 last_escape = esc_list[-1]
1396 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1427 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1397
1428
1398 #----------------------------------------------------------------------------
1429 #----------------------------------------------------------------------------
1399 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1430 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1400 """Print a string, piping through a pager after a certain length.
1431 """Print a string, piping through a pager after a certain length.
1401
1432
1402 The screen_lines parameter specifies the number of *usable* lines of your
1433 The screen_lines parameter specifies the number of *usable* lines of your
1403 terminal screen (total lines minus lines you need to reserve to show other
1434 terminal screen (total lines minus lines you need to reserve to show other
1404 information).
1435 information).
1405
1436
1406 If you set screen_lines to a number <=0, page() will try to auto-determine
1437 If you set screen_lines to a number <=0, page() will try to auto-determine
1407 your screen size and will only use up to (screen_size+screen_lines) for
1438 your screen size and will only use up to (screen_size+screen_lines) for
1408 printing, paging after that. That is, if you want auto-detection but need
1439 printing, paging after that. That is, if you want auto-detection but need
1409 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1440 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1410 auto-detection without any lines reserved simply use screen_lines = 0.
1441 auto-detection without any lines reserved simply use screen_lines = 0.
1411
1442
1412 If a string won't fit in the allowed lines, it is sent through the
1443 If a string won't fit in the allowed lines, it is sent through the
1413 specified pager command. If none given, look for PAGER in the environment,
1444 specified pager command. If none given, look for PAGER in the environment,
1414 and ultimately default to less.
1445 and ultimately default to less.
1415
1446
1416 If no system pager works, the string is sent through a 'dumb pager'
1447 If no system pager works, the string is sent through a 'dumb pager'
1417 written in python, very simplistic.
1448 written in python, very simplistic.
1418 """
1449 """
1419
1450
1420 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1451 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1421 TERM = os.environ.get('TERM','dumb')
1452 TERM = os.environ.get('TERM','dumb')
1422 if TERM in ['dumb','emacs'] and os.name != 'nt':
1453 if TERM in ['dumb','emacs'] and os.name != 'nt':
1423 print strng
1454 print strng
1424 return
1455 return
1425 # chop off the topmost part of the string we don't want to see
1456 # chop off the topmost part of the string we don't want to see
1426 str_lines = strng.split(os.linesep)[start:]
1457 str_lines = strng.split(os.linesep)[start:]
1427 str_toprint = os.linesep.join(str_lines)
1458 str_toprint = os.linesep.join(str_lines)
1428 num_newlines = len(str_lines)
1459 num_newlines = len(str_lines)
1429 len_str = len(str_toprint)
1460 len_str = len(str_toprint)
1430
1461
1431 # Dumb heuristics to guesstimate number of on-screen lines the string
1462 # Dumb heuristics to guesstimate number of on-screen lines the string
1432 # takes. Very basic, but good enough for docstrings in reasonable
1463 # takes. Very basic, but good enough for docstrings in reasonable
1433 # terminals. If someone later feels like refining it, it's not hard.
1464 # terminals. If someone later feels like refining it, it's not hard.
1434 numlines = max(num_newlines,int(len_str/80)+1)
1465 numlines = max(num_newlines,int(len_str/80)+1)
1435
1466
1436 if os.name == "nt":
1467 if os.name == "nt":
1437 screen_lines_def = get_console_size(defaulty=25)[1]
1468 screen_lines_def = get_console_size(defaulty=25)[1]
1438 else:
1469 else:
1439 screen_lines_def = 25 # default value if we can't auto-determine
1470 screen_lines_def = 25 # default value if we can't auto-determine
1440
1471
1441 # auto-determine screen size
1472 # auto-determine screen size
1442 if screen_lines <= 0:
1473 if screen_lines <= 0:
1443 if TERM=='xterm':
1474 if TERM=='xterm':
1444 try:
1475 try:
1445 import curses
1476 import curses
1446 if hasattr(curses,'initscr'):
1477 if hasattr(curses,'initscr'):
1447 use_curses = 1
1478 use_curses = 1
1448 else:
1479 else:
1449 use_curses = 0
1480 use_curses = 0
1450 except ImportError:
1481 except ImportError:
1451 use_curses = 0
1482 use_curses = 0
1452 else:
1483 else:
1453 # curses causes problems on many terminals other than xterm.
1484 # curses causes problems on many terminals other than xterm.
1454 use_curses = 0
1485 use_curses = 0
1455 if use_curses:
1486 if use_curses:
1456 scr = curses.initscr()
1487 scr = curses.initscr()
1457 screen_lines_real,screen_cols = scr.getmaxyx()
1488 screen_lines_real,screen_cols = scr.getmaxyx()
1458 curses.endwin()
1489 curses.endwin()
1459 screen_lines += screen_lines_real
1490 screen_lines += screen_lines_real
1460 #print '***Screen size:',screen_lines_real,'lines x',\
1491 #print '***Screen size:',screen_lines_real,'lines x',\
1461 #screen_cols,'columns.' # dbg
1492 #screen_cols,'columns.' # dbg
1462 else:
1493 else:
1463 screen_lines += screen_lines_def
1494 screen_lines += screen_lines_def
1464
1495
1465 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1496 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1466 if numlines <= screen_lines :
1497 if numlines <= screen_lines :
1467 #print '*** normal print' # dbg
1498 #print '*** normal print' # dbg
1468 print >>Term.cout, str_toprint
1499 print >>Term.cout, str_toprint
1469 else:
1500 else:
1470 # Try to open pager and default to internal one if that fails.
1501 # Try to open pager and default to internal one if that fails.
1471 # All failure modes are tagged as 'retval=1', to match the return
1502 # All failure modes are tagged as 'retval=1', to match the return
1472 # value of a failed system command. If any intermediate attempt
1503 # value of a failed system command. If any intermediate attempt
1473 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1504 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1474 pager_cmd = get_pager_cmd(pager_cmd)
1505 pager_cmd = get_pager_cmd(pager_cmd)
1475 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1506 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1476 if os.name == 'nt':
1507 if os.name == 'nt':
1477 if pager_cmd.startswith('type'):
1508 if pager_cmd.startswith('type'):
1478 # The default WinXP 'type' command is failing on complex strings.
1509 # The default WinXP 'type' command is failing on complex strings.
1479 retval = 1
1510 retval = 1
1480 else:
1511 else:
1481 tmpname = tempfile.mktemp('.txt')
1512 tmpname = tempfile.mktemp('.txt')
1482 tmpfile = file(tmpname,'wt')
1513 tmpfile = file(tmpname,'wt')
1483 tmpfile.write(strng)
1514 tmpfile.write(strng)
1484 tmpfile.close()
1515 tmpfile.close()
1485 cmd = "%s < %s" % (pager_cmd,tmpname)
1516 cmd = "%s < %s" % (pager_cmd,tmpname)
1486 if os.system(cmd):
1517 if os.system(cmd):
1487 retval = 1
1518 retval = 1
1488 else:
1519 else:
1489 retval = None
1520 retval = None
1490 os.remove(tmpname)
1521 os.remove(tmpname)
1491 else:
1522 else:
1492 try:
1523 try:
1493 retval = None
1524 retval = None
1494 # if I use popen4, things hang. No idea why.
1525 # if I use popen4, things hang. No idea why.
1495 #pager,shell_out = os.popen4(pager_cmd)
1526 #pager,shell_out = os.popen4(pager_cmd)
1496 pager = os.popen(pager_cmd,'w')
1527 pager = os.popen(pager_cmd,'w')
1497 pager.write(strng)
1528 pager.write(strng)
1498 pager.close()
1529 pager.close()
1499 retval = pager.close() # success returns None
1530 retval = pager.close() # success returns None
1500 except IOError,msg: # broken pipe when user quits
1531 except IOError,msg: # broken pipe when user quits
1501 if msg.args == (32,'Broken pipe'):
1532 if msg.args == (32,'Broken pipe'):
1502 retval = None
1533 retval = None
1503 else:
1534 else:
1504 retval = 1
1535 retval = 1
1505 except OSError:
1536 except OSError:
1506 # Other strange problems, sometimes seen in Win2k/cygwin
1537 # Other strange problems, sometimes seen in Win2k/cygwin
1507 retval = 1
1538 retval = 1
1508 if retval is not None:
1539 if retval is not None:
1509 page_dumb(strng,screen_lines=screen_lines)
1540 page_dumb(strng,screen_lines=screen_lines)
1510
1541
1511 #----------------------------------------------------------------------------
1542 #----------------------------------------------------------------------------
1512 def page_file(fname,start = 0, pager_cmd = None):
1543 def page_file(fname,start = 0, pager_cmd = None):
1513 """Page a file, using an optional pager command and starting line.
1544 """Page a file, using an optional pager command and starting line.
1514 """
1545 """
1515
1546
1516 pager_cmd = get_pager_cmd(pager_cmd)
1547 pager_cmd = get_pager_cmd(pager_cmd)
1517 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1548 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1518
1549
1519 try:
1550 try:
1520 if os.environ['TERM'] in ['emacs','dumb']:
1551 if os.environ['TERM'] in ['emacs','dumb']:
1521 raise EnvironmentError
1552 raise EnvironmentError
1522 xsys(pager_cmd + ' ' + fname)
1553 xsys(pager_cmd + ' ' + fname)
1523 except:
1554 except:
1524 try:
1555 try:
1525 if start > 0:
1556 if start > 0:
1526 start -= 1
1557 start -= 1
1527 page(open(fname).read(),start)
1558 page(open(fname).read(),start)
1528 except:
1559 except:
1529 print 'Unable to show file',`fname`
1560 print 'Unable to show file',`fname`
1530
1561
1531 #----------------------------------------------------------------------------
1562 #----------------------------------------------------------------------------
1532 def snip_print(str,width = 75,print_full = 0,header = ''):
1563 def snip_print(str,width = 75,print_full = 0,header = ''):
1533 """Print a string snipping the midsection to fit in width.
1564 """Print a string snipping the midsection to fit in width.
1534
1565
1535 print_full: mode control:
1566 print_full: mode control:
1536 - 0: only snip long strings
1567 - 0: only snip long strings
1537 - 1: send to page() directly.
1568 - 1: send to page() directly.
1538 - 2: snip long strings and ask for full length viewing with page()
1569 - 2: snip long strings and ask for full length viewing with page()
1539 Return 1 if snipping was necessary, 0 otherwise."""
1570 Return 1 if snipping was necessary, 0 otherwise."""
1540
1571
1541 if print_full == 1:
1572 if print_full == 1:
1542 page(header+str)
1573 page(header+str)
1543 return 0
1574 return 0
1544
1575
1545 print header,
1576 print header,
1546 if len(str) < width:
1577 if len(str) < width:
1547 print str
1578 print str
1548 snip = 0
1579 snip = 0
1549 else:
1580 else:
1550 whalf = int((width -5)/2)
1581 whalf = int((width -5)/2)
1551 print str[:whalf] + ' <...> ' + str[-whalf:]
1582 print str[:whalf] + ' <...> ' + str[-whalf:]
1552 snip = 1
1583 snip = 1
1553 if snip and print_full == 2:
1584 if snip and print_full == 2:
1554 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1585 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1555 page(str)
1586 page(str)
1556 return snip
1587 return snip
1557
1588
1558 #****************************************************************************
1589 #****************************************************************************
1559 # lists, dicts and structures
1590 # lists, dicts and structures
1560
1591
1561 def belong(candidates,checklist):
1592 def belong(candidates,checklist):
1562 """Check whether a list of items appear in a given list of options.
1593 """Check whether a list of items appear in a given list of options.
1563
1594
1564 Returns a list of 1 and 0, one for each candidate given."""
1595 Returns a list of 1 and 0, one for each candidate given."""
1565
1596
1566 return [x in checklist for x in candidates]
1597 return [x in checklist for x in candidates]
1567
1598
1568 #----------------------------------------------------------------------------
1599 #----------------------------------------------------------------------------
1569 def uniq_stable(elems):
1600 def uniq_stable(elems):
1570 """uniq_stable(elems) -> list
1601 """uniq_stable(elems) -> list
1571
1602
1572 Return from an iterable, a list of all the unique elements in the input,
1603 Return from an iterable, a list of all the unique elements in the input,
1573 but maintaining the order in which they first appear.
1604 but maintaining the order in which they first appear.
1574
1605
1575 A naive solution to this problem which just makes a dictionary with the
1606 A naive solution to this problem which just makes a dictionary with the
1576 elements as keys fails to respect the stability condition, since
1607 elements as keys fails to respect the stability condition, since
1577 dictionaries are unsorted by nature.
1608 dictionaries are unsorted by nature.
1578
1609
1579 Note: All elements in the input must be valid dictionary keys for this
1610 Note: All elements in the input must be valid dictionary keys for this
1580 routine to work, as it internally uses a dictionary for efficiency
1611 routine to work, as it internally uses a dictionary for efficiency
1581 reasons."""
1612 reasons."""
1582
1613
1583 unique = []
1614 unique = []
1584 unique_dict = {}
1615 unique_dict = {}
1585 for nn in elems:
1616 for nn in elems:
1586 if nn not in unique_dict:
1617 if nn not in unique_dict:
1587 unique.append(nn)
1618 unique.append(nn)
1588 unique_dict[nn] = None
1619 unique_dict[nn] = None
1589 return unique
1620 return unique
1590
1621
1591 #----------------------------------------------------------------------------
1622 #----------------------------------------------------------------------------
1592 class NLprinter:
1623 class NLprinter:
1593 """Print an arbitrarily nested list, indicating index numbers.
1624 """Print an arbitrarily nested list, indicating index numbers.
1594
1625
1595 An instance of this class called nlprint is available and callable as a
1626 An instance of this class called nlprint is available and callable as a
1596 function.
1627 function.
1597
1628
1598 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1629 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1599 and using 'sep' to separate the index from the value. """
1630 and using 'sep' to separate the index from the value. """
1600
1631
1601 def __init__(self):
1632 def __init__(self):
1602 self.depth = 0
1633 self.depth = 0
1603
1634
1604 def __call__(self,lst,pos='',**kw):
1635 def __call__(self,lst,pos='',**kw):
1605 """Prints the nested list numbering levels."""
1636 """Prints the nested list numbering levels."""
1606 kw.setdefault('indent',' ')
1637 kw.setdefault('indent',' ')
1607 kw.setdefault('sep',': ')
1638 kw.setdefault('sep',': ')
1608 kw.setdefault('start',0)
1639 kw.setdefault('start',0)
1609 kw.setdefault('stop',len(lst))
1640 kw.setdefault('stop',len(lst))
1610 # we need to remove start and stop from kw so they don't propagate
1641 # we need to remove start and stop from kw so they don't propagate
1611 # into a recursive call for a nested list.
1642 # into a recursive call for a nested list.
1612 start = kw['start']; del kw['start']
1643 start = kw['start']; del kw['start']
1613 stop = kw['stop']; del kw['stop']
1644 stop = kw['stop']; del kw['stop']
1614 if self.depth == 0 and 'header' in kw.keys():
1645 if self.depth == 0 and 'header' in kw.keys():
1615 print kw['header']
1646 print kw['header']
1616
1647
1617 for idx in range(start,stop):
1648 for idx in range(start,stop):
1618 elem = lst[idx]
1649 elem = lst[idx]
1619 if type(elem)==type([]):
1650 if type(elem)==type([]):
1620 self.depth += 1
1651 self.depth += 1
1621 self.__call__(elem,itpl('$pos$idx,'),**kw)
1652 self.__call__(elem,itpl('$pos$idx,'),**kw)
1622 self.depth -= 1
1653 self.depth -= 1
1623 else:
1654 else:
1624 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1655 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1625
1656
1626 nlprint = NLprinter()
1657 nlprint = NLprinter()
1627 #----------------------------------------------------------------------------
1658 #----------------------------------------------------------------------------
1628 def all_belong(candidates,checklist):
1659 def all_belong(candidates,checklist):
1629 """Check whether a list of items ALL appear in a given list of options.
1660 """Check whether a list of items ALL appear in a given list of options.
1630
1661
1631 Returns a single 1 or 0 value."""
1662 Returns a single 1 or 0 value."""
1632
1663
1633 return 1-(0 in [x in checklist for x in candidates])
1664 return 1-(0 in [x in checklist for x in candidates])
1634
1665
1635 #----------------------------------------------------------------------------
1666 #----------------------------------------------------------------------------
1636 def sort_compare(lst1,lst2,inplace = 1):
1667 def sort_compare(lst1,lst2,inplace = 1):
1637 """Sort and compare two lists.
1668 """Sort and compare two lists.
1638
1669
1639 By default it does it in place, thus modifying the lists. Use inplace = 0
1670 By default it does it in place, thus modifying the lists. Use inplace = 0
1640 to avoid that (at the cost of temporary copy creation)."""
1671 to avoid that (at the cost of temporary copy creation)."""
1641 if not inplace:
1672 if not inplace:
1642 lst1 = lst1[:]
1673 lst1 = lst1[:]
1643 lst2 = lst2[:]
1674 lst2 = lst2[:]
1644 lst1.sort(); lst2.sort()
1675 lst1.sort(); lst2.sort()
1645 return lst1 == lst2
1676 return lst1 == lst2
1646
1677
1647 #----------------------------------------------------------------------------
1678 #----------------------------------------------------------------------------
1648 def mkdict(**kwargs):
1679 def mkdict(**kwargs):
1649 """Return a dict from a keyword list.
1680 """Return a dict from a keyword list.
1650
1681
1651 It's just syntactic sugar for making ditcionary creation more convenient:
1682 It's just syntactic sugar for making ditcionary creation more convenient:
1652 # the standard way
1683 # the standard way
1653 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1684 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1654 # a cleaner way
1685 # a cleaner way
1655 >>>data = dict(red=1, green=2, blue=3)
1686 >>>data = dict(red=1, green=2, blue=3)
1656
1687
1657 If you need more than this, look at the Struct() class."""
1688 If you need more than this, look at the Struct() class."""
1658
1689
1659 return kwargs
1690 return kwargs
1660
1691
1661 #----------------------------------------------------------------------------
1692 #----------------------------------------------------------------------------
1662 def list2dict(lst):
1693 def list2dict(lst):
1663 """Takes a list of (key,value) pairs and turns it into a dict."""
1694 """Takes a list of (key,value) pairs and turns it into a dict."""
1664
1695
1665 dic = {}
1696 dic = {}
1666 for k,v in lst: dic[k] = v
1697 for k,v in lst: dic[k] = v
1667 return dic
1698 return dic
1668
1699
1669 #----------------------------------------------------------------------------
1700 #----------------------------------------------------------------------------
1670 def list2dict2(lst,default=''):
1701 def list2dict2(lst,default=''):
1671 """Takes a list and turns it into a dict.
1702 """Takes a list and turns it into a dict.
1672 Much slower than list2dict, but more versatile. This version can take
1703 Much slower than list2dict, but more versatile. This version can take
1673 lists with sublists of arbitrary length (including sclars)."""
1704 lists with sublists of arbitrary length (including sclars)."""
1674
1705
1675 dic = {}
1706 dic = {}
1676 for elem in lst:
1707 for elem in lst:
1677 if type(elem) in (types.ListType,types.TupleType):
1708 if type(elem) in (types.ListType,types.TupleType):
1678 size = len(elem)
1709 size = len(elem)
1679 if size == 0:
1710 if size == 0:
1680 pass
1711 pass
1681 elif size == 1:
1712 elif size == 1:
1682 dic[elem] = default
1713 dic[elem] = default
1683 else:
1714 else:
1684 k,v = elem[0], elem[1:]
1715 k,v = elem[0], elem[1:]
1685 if len(v) == 1: v = v[0]
1716 if len(v) == 1: v = v[0]
1686 dic[k] = v
1717 dic[k] = v
1687 else:
1718 else:
1688 dic[elem] = default
1719 dic[elem] = default
1689 return dic
1720 return dic
1690
1721
1691 #----------------------------------------------------------------------------
1722 #----------------------------------------------------------------------------
1692 def flatten(seq):
1723 def flatten(seq):
1693 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1724 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1694
1725
1695 return [x for subseq in seq for x in subseq]
1726 return [x for subseq in seq for x in subseq]
1696
1727
1697 #----------------------------------------------------------------------------
1728 #----------------------------------------------------------------------------
1698 def get_slice(seq,start=0,stop=None,step=1):
1729 def get_slice(seq,start=0,stop=None,step=1):
1699 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1730 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1700 if stop == None:
1731 if stop == None:
1701 stop = len(seq)
1732 stop = len(seq)
1702 item = lambda i: seq[i]
1733 item = lambda i: seq[i]
1703 return map(item,xrange(start,stop,step))
1734 return map(item,xrange(start,stop,step))
1704
1735
1705 #----------------------------------------------------------------------------
1736 #----------------------------------------------------------------------------
1706 def chop(seq,size):
1737 def chop(seq,size):
1707 """Chop a sequence into chunks of the given size."""
1738 """Chop a sequence into chunks of the given size."""
1708 chunk = lambda i: seq[i:i+size]
1739 chunk = lambda i: seq[i:i+size]
1709 return map(chunk,xrange(0,len(seq),size))
1740 return map(chunk,xrange(0,len(seq),size))
1710
1741
1711 #----------------------------------------------------------------------------
1742 #----------------------------------------------------------------------------
1712 # with is a keyword as of python 2.5, so this function is renamed to withobj
1743 # with is a keyword as of python 2.5, so this function is renamed to withobj
1713 # from its old 'with' name.
1744 # from its old 'with' name.
1714 def with_obj(object, **args):
1745 def with_obj(object, **args):
1715 """Set multiple attributes for an object, similar to Pascal's with.
1746 """Set multiple attributes for an object, similar to Pascal's with.
1716
1747
1717 Example:
1748 Example:
1718 with_obj(jim,
1749 with_obj(jim,
1719 born = 1960,
1750 born = 1960,
1720 haircolour = 'Brown',
1751 haircolour = 'Brown',
1721 eyecolour = 'Green')
1752 eyecolour = 'Green')
1722
1753
1723 Credit: Greg Ewing, in
1754 Credit: Greg Ewing, in
1724 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1755 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1725
1756
1726 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1757 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1727 has become a keyword for Python 2.5, so we had to rename it."""
1758 has become a keyword for Python 2.5, so we had to rename it."""
1728
1759
1729 object.__dict__.update(args)
1760 object.__dict__.update(args)
1730
1761
1731 #----------------------------------------------------------------------------
1762 #----------------------------------------------------------------------------
1732 def setattr_list(obj,alist,nspace = None):
1763 def setattr_list(obj,alist,nspace = None):
1733 """Set a list of attributes for an object taken from a namespace.
1764 """Set a list of attributes for an object taken from a namespace.
1734
1765
1735 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1766 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1736 alist with their values taken from nspace, which must be a dict (something
1767 alist with their values taken from nspace, which must be a dict (something
1737 like locals() will often do) If nspace isn't given, locals() of the
1768 like locals() will often do) If nspace isn't given, locals() of the
1738 *caller* is used, so in most cases you can omit it.
1769 *caller* is used, so in most cases you can omit it.
1739
1770
1740 Note that alist can be given as a string, which will be automatically
1771 Note that alist can be given as a string, which will be automatically
1741 split into a list on whitespace. If given as a list, it must be a list of
1772 split into a list on whitespace. If given as a list, it must be a list of
1742 *strings* (the variable names themselves), not of variables."""
1773 *strings* (the variable names themselves), not of variables."""
1743
1774
1744 # this grabs the local variables from the *previous* call frame -- that is
1775 # this grabs the local variables from the *previous* call frame -- that is
1745 # the locals from the function that called setattr_list().
1776 # the locals from the function that called setattr_list().
1746 # - snipped from weave.inline()
1777 # - snipped from weave.inline()
1747 if nspace is None:
1778 if nspace is None:
1748 call_frame = sys._getframe().f_back
1779 call_frame = sys._getframe().f_back
1749 nspace = call_frame.f_locals
1780 nspace = call_frame.f_locals
1750
1781
1751 if type(alist) in StringTypes:
1782 if type(alist) in StringTypes:
1752 alist = alist.split()
1783 alist = alist.split()
1753 for attr in alist:
1784 for attr in alist:
1754 val = eval(attr,nspace)
1785 val = eval(attr,nspace)
1755 setattr(obj,attr,val)
1786 setattr(obj,attr,val)
1756
1787
1757 #----------------------------------------------------------------------------
1788 #----------------------------------------------------------------------------
1758 def getattr_list(obj,alist,*args):
1789 def getattr_list(obj,alist,*args):
1759 """getattr_list(obj,alist[, default]) -> attribute list.
1790 """getattr_list(obj,alist[, default]) -> attribute list.
1760
1791
1761 Get a list of named attributes for an object. When a default argument is
1792 Get a list of named attributes for an object. When a default argument is
1762 given, it is returned when the attribute doesn't exist; without it, an
1793 given, it is returned when the attribute doesn't exist; without it, an
1763 exception is raised in that case.
1794 exception is raised in that case.
1764
1795
1765 Note that alist can be given as a string, which will be automatically
1796 Note that alist can be given as a string, which will be automatically
1766 split into a list on whitespace. If given as a list, it must be a list of
1797 split into a list on whitespace. If given as a list, it must be a list of
1767 *strings* (the variable names themselves), not of variables."""
1798 *strings* (the variable names themselves), not of variables."""
1768
1799
1769 if type(alist) in StringTypes:
1800 if type(alist) in StringTypes:
1770 alist = alist.split()
1801 alist = alist.split()
1771 if args:
1802 if args:
1772 if len(args)==1:
1803 if len(args)==1:
1773 default = args[0]
1804 default = args[0]
1774 return map(lambda attr: getattr(obj,attr,default),alist)
1805 return map(lambda attr: getattr(obj,attr,default),alist)
1775 else:
1806 else:
1776 raise ValueError,'getattr_list() takes only one optional argument'
1807 raise ValueError,'getattr_list() takes only one optional argument'
1777 else:
1808 else:
1778 return map(lambda attr: getattr(obj,attr),alist)
1809 return map(lambda attr: getattr(obj,attr),alist)
1779
1810
1780 #----------------------------------------------------------------------------
1811 #----------------------------------------------------------------------------
1781 def map_method(method,object_list,*argseq,**kw):
1812 def map_method(method,object_list,*argseq,**kw):
1782 """map_method(method,object_list,*args,**kw) -> list
1813 """map_method(method,object_list,*args,**kw) -> list
1783
1814
1784 Return a list of the results of applying the methods to the items of the
1815 Return a list of the results of applying the methods to the items of the
1785 argument sequence(s). If more than one sequence is given, the method is
1816 argument sequence(s). If more than one sequence is given, the method is
1786 called with an argument list consisting of the corresponding item of each
1817 called with an argument list consisting of the corresponding item of each
1787 sequence. All sequences must be of the same length.
1818 sequence. All sequences must be of the same length.
1788
1819
1789 Keyword arguments are passed verbatim to all objects called.
1820 Keyword arguments are passed verbatim to all objects called.
1790
1821
1791 This is Python code, so it's not nearly as fast as the builtin map()."""
1822 This is Python code, so it's not nearly as fast as the builtin map()."""
1792
1823
1793 out_list = []
1824 out_list = []
1794 idx = 0
1825 idx = 0
1795 for object in object_list:
1826 for object in object_list:
1796 try:
1827 try:
1797 handler = getattr(object, method)
1828 handler = getattr(object, method)
1798 except AttributeError:
1829 except AttributeError:
1799 out_list.append(None)
1830 out_list.append(None)
1800 else:
1831 else:
1801 if argseq:
1832 if argseq:
1802 args = map(lambda lst:lst[idx],argseq)
1833 args = map(lambda lst:lst[idx],argseq)
1803 #print 'ob',object,'hand',handler,'ar',args # dbg
1834 #print 'ob',object,'hand',handler,'ar',args # dbg
1804 out_list.append(handler(args,**kw))
1835 out_list.append(handler(args,**kw))
1805 else:
1836 else:
1806 out_list.append(handler(**kw))
1837 out_list.append(handler(**kw))
1807 idx += 1
1838 idx += 1
1808 return out_list
1839 return out_list
1809
1840
1810 #----------------------------------------------------------------------------
1841 #----------------------------------------------------------------------------
1811 def get_class_members(cls):
1842 def get_class_members(cls):
1812 ret = dir(cls)
1843 ret = dir(cls)
1813 if hasattr(cls,'__bases__'):
1844 if hasattr(cls,'__bases__'):
1814 for base in cls.__bases__:
1845 for base in cls.__bases__:
1815 ret.extend(get_class_members(base))
1846 ret.extend(get_class_members(base))
1816 return ret
1847 return ret
1817
1848
1818 #----------------------------------------------------------------------------
1849 #----------------------------------------------------------------------------
1819 def dir2(obj):
1850 def dir2(obj):
1820 """dir2(obj) -> list of strings
1851 """dir2(obj) -> list of strings
1821
1852
1822 Extended version of the Python builtin dir(), which does a few extra
1853 Extended version of the Python builtin dir(), which does a few extra
1823 checks, and supports common objects with unusual internals that confuse
1854 checks, and supports common objects with unusual internals that confuse
1824 dir(), such as Traits and PyCrust.
1855 dir(), such as Traits and PyCrust.
1825
1856
1826 This version is guaranteed to return only a list of true strings, whereas
1857 This version is guaranteed to return only a list of true strings, whereas
1827 dir() returns anything that objects inject into themselves, even if they
1858 dir() returns anything that objects inject into themselves, even if they
1828 are later not really valid for attribute access (many extension libraries
1859 are later not really valid for attribute access (many extension libraries
1829 have such bugs).
1860 have such bugs).
1830 """
1861 """
1831
1862
1832 # Start building the attribute list via dir(), and then complete it
1863 # Start building the attribute list via dir(), and then complete it
1833 # with a few extra special-purpose calls.
1864 # with a few extra special-purpose calls.
1834 words = dir(obj)
1865 words = dir(obj)
1835
1866
1836 if hasattr(obj,'__class__'):
1867 if hasattr(obj,'__class__'):
1837 words.append('__class__')
1868 words.append('__class__')
1838 words.extend(get_class_members(obj.__class__))
1869 words.extend(get_class_members(obj.__class__))
1839 #if '__base__' in words: 1/0
1870 #if '__base__' in words: 1/0
1840
1871
1841 # Some libraries (such as traits) may introduce duplicates, we want to
1872 # Some libraries (such as traits) may introduce duplicates, we want to
1842 # track and clean this up if it happens
1873 # track and clean this up if it happens
1843 may_have_dupes = False
1874 may_have_dupes = False
1844
1875
1845 # this is the 'dir' function for objects with Enthought's traits
1876 # this is the 'dir' function for objects with Enthought's traits
1846 if hasattr(obj, 'trait_names'):
1877 if hasattr(obj, 'trait_names'):
1847 try:
1878 try:
1848 words.extend(obj.trait_names())
1879 words.extend(obj.trait_names())
1849 may_have_dupes = True
1880 may_have_dupes = True
1850 except TypeError:
1881 except TypeError:
1851 # This will happen if `obj` is a class and not an instance.
1882 # This will happen if `obj` is a class and not an instance.
1852 pass
1883 pass
1853
1884
1854 # Support for PyCrust-style _getAttributeNames magic method.
1885 # Support for PyCrust-style _getAttributeNames magic method.
1855 if hasattr(obj, '_getAttributeNames'):
1886 if hasattr(obj, '_getAttributeNames'):
1856 try:
1887 try:
1857 words.extend(obj._getAttributeNames())
1888 words.extend(obj._getAttributeNames())
1858 may_have_dupes = True
1889 may_have_dupes = True
1859 except TypeError:
1890 except TypeError:
1860 # `obj` is a class and not an instance. Ignore
1891 # `obj` is a class and not an instance. Ignore
1861 # this error.
1892 # this error.
1862 pass
1893 pass
1863
1894
1864 if may_have_dupes:
1895 if may_have_dupes:
1865 # eliminate possible duplicates, as some traits may also
1896 # eliminate possible duplicates, as some traits may also
1866 # appear as normal attributes in the dir() call.
1897 # appear as normal attributes in the dir() call.
1867 words = list(set(words))
1898 words = list(set(words))
1868 words.sort()
1899 words.sort()
1869
1900
1870 # filter out non-string attributes which may be stuffed by dir() calls
1901 # filter out non-string attributes which may be stuffed by dir() calls
1871 # and poor coding in third-party modules
1902 # and poor coding in third-party modules
1872 return [w for w in words if isinstance(w, basestring)]
1903 return [w for w in words if isinstance(w, basestring)]
1873
1904
1874 #----------------------------------------------------------------------------
1905 #----------------------------------------------------------------------------
1875 def import_fail_info(mod_name,fns=None):
1906 def import_fail_info(mod_name,fns=None):
1876 """Inform load failure for a module."""
1907 """Inform load failure for a module."""
1877
1908
1878 if fns == None:
1909 if fns == None:
1879 warn("Loading of %s failed.\n" % (mod_name,))
1910 warn("Loading of %s failed.\n" % (mod_name,))
1880 else:
1911 else:
1881 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1912 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1882
1913
1883 #----------------------------------------------------------------------------
1914 #----------------------------------------------------------------------------
1884 # Proposed popitem() extension, written as a method
1915 # Proposed popitem() extension, written as a method
1885
1916
1886
1917
1887 class NotGiven: pass
1918 class NotGiven: pass
1888
1919
1889 def popkey(dct,key,default=NotGiven):
1920 def popkey(dct,key,default=NotGiven):
1890 """Return dct[key] and delete dct[key].
1921 """Return dct[key] and delete dct[key].
1891
1922
1892 If default is given, return it if dct[key] doesn't exist, otherwise raise
1923 If default is given, return it if dct[key] doesn't exist, otherwise raise
1893 KeyError. """
1924 KeyError. """
1894
1925
1895 try:
1926 try:
1896 val = dct[key]
1927 val = dct[key]
1897 except KeyError:
1928 except KeyError:
1898 if default is NotGiven:
1929 if default is NotGiven:
1899 raise
1930 raise
1900 else:
1931 else:
1901 return default
1932 return default
1902 else:
1933 else:
1903 del dct[key]
1934 del dct[key]
1904 return val
1935 return val
1905
1936
1906 def wrap_deprecated(func, suggest = '<nothing>'):
1937 def wrap_deprecated(func, suggest = '<nothing>'):
1907 def newFunc(*args, **kwargs):
1938 def newFunc(*args, **kwargs):
1908 warnings.warn("Call to deprecated function %s, use %s instead" %
1939 warnings.warn("Call to deprecated function %s, use %s instead" %
1909 ( func.__name__, suggest),
1940 ( func.__name__, suggest),
1910 category=DeprecationWarning,
1941 category=DeprecationWarning,
1911 stacklevel = 2)
1942 stacklevel = 2)
1912 return func(*args, **kwargs)
1943 return func(*args, **kwargs)
1913 return newFunc
1944 return newFunc
1914
1945
1915 #*************************** end of file <genutils.py> **********************
1946 #*************************** end of file <genutils.py> **********************
1916
1947
@@ -1,2555 +1,2557 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.3 or newer.
5 Requires Python 2.3 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 2754 2007-09-09 10:16:59Z fperez $
9 $Id: iplib.py 2763 2007-09-14 06:35:44Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import StringIO
40 import StringIO
41 import bdb
41 import bdb
42 import cPickle as pickle
42 import cPickle as pickle
43 import codeop
43 import codeop
44 import doctest
45 import exceptions
44 import exceptions
46 import glob
45 import glob
47 import inspect
46 import inspect
48 import keyword
47 import keyword
49 import new
48 import new
50 import os
49 import os
51 import pydoc
50 import pydoc
52 import re
51 import re
53 import shutil
52 import shutil
54 import string
53 import string
55 import sys
54 import sys
56 import tempfile
55 import tempfile
57 import traceback
56 import traceback
58 import types
57 import types
59 import pickleshare
58 import pickleshare
60 from sets import Set
59 from sets import Set
61 from pprint import pprint, pformat
60 from pprint import pprint, pformat
62
61
63 # IPython's own modules
62 # IPython's own modules
64 #import IPython
63 #import IPython
65 from IPython import Debugger,OInspect,PyColorize,ultraTB
64 from IPython import Debugger,OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
66 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
67 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
68 from IPython.Logger import Logger
70 from IPython.Magic import Magic
69 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
70 from IPython.Prompts import CachedOutput
72 from IPython.ipstruct import Struct
71 from IPython.ipstruct import Struct
73 from IPython.background_jobs import BackgroundJobManager
72 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
73 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
74 from IPython.genutils import *
76 from IPython.strdispatch import StrDispatch
75 from IPython.strdispatch import StrDispatch
77 import IPython.ipapi
76 import IPython.ipapi
78 import IPython.history
77 import IPython.history
79 import IPython.prefilter as prefilter
78 import IPython.prefilter as prefilter
80 import IPython.shadowns
79 import IPython.shadowns
81 # Globals
80 # Globals
82
81
83 # store the builtin raw_input globally, and use this always, in case user code
82 # store the builtin raw_input globally, and use this always, in case user code
84 # overwrites it (like wx.py.PyShell does)
83 # overwrites it (like wx.py.PyShell does)
85 raw_input_original = raw_input
84 raw_input_original = raw_input
86
85
87 # compiled regexps for autoindent management
86 # compiled regexps for autoindent management
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89
88
90
89
91 #****************************************************************************
90 #****************************************************************************
92 # Some utility function definitions
91 # Some utility function definitions
93
92
94 ini_spaces_re = re.compile(r'^(\s+)')
93 ini_spaces_re = re.compile(r'^(\s+)')
95
94
96 def num_ini_spaces(strng):
95 def num_ini_spaces(strng):
97 """Return the number of initial spaces in a string"""
96 """Return the number of initial spaces in a string"""
98
97
99 ini_spaces = ini_spaces_re.match(strng)
98 ini_spaces = ini_spaces_re.match(strng)
100 if ini_spaces:
99 if ini_spaces:
101 return ini_spaces.end()
100 return ini_spaces.end()
102 else:
101 else:
103 return 0
102 return 0
104
103
105 def softspace(file, newvalue):
104 def softspace(file, newvalue):
106 """Copied from code.py, to remove the dependency"""
105 """Copied from code.py, to remove the dependency"""
107
106
108 oldvalue = 0
107 oldvalue = 0
109 try:
108 try:
110 oldvalue = file.softspace
109 oldvalue = file.softspace
111 except AttributeError:
110 except AttributeError:
112 pass
111 pass
113 try:
112 try:
114 file.softspace = newvalue
113 file.softspace = newvalue
115 except (AttributeError, TypeError):
114 except (AttributeError, TypeError):
116 # "attribute-less object" or "read-only attributes"
115 # "attribute-less object" or "read-only attributes"
117 pass
116 pass
118 return oldvalue
117 return oldvalue
119
118
120
119
121 #****************************************************************************
120 #****************************************************************************
122 # Local use exceptions
121 # Local use exceptions
123 class SpaceInInput(exceptions.Exception): pass
122 class SpaceInInput(exceptions.Exception): pass
124
123
125
124
126 #****************************************************************************
125 #****************************************************************************
127 # Local use classes
126 # Local use classes
128 class Bunch: pass
127 class Bunch: pass
129
128
130 class Undefined: pass
129 class Undefined: pass
131
130
132 class Quitter(object):
131 class Quitter(object):
133 """Simple class to handle exit, similar to Python 2.5's.
132 """Simple class to handle exit, similar to Python 2.5's.
134
133
135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
134 It handles exiting in an ipython-safe manner, which the one in Python 2.5
136 doesn't do (obviously, since it doesn't know about ipython)."""
135 doesn't do (obviously, since it doesn't know about ipython)."""
137
136
138 def __init__(self,shell,name):
137 def __init__(self,shell,name):
139 self.shell = shell
138 self.shell = shell
140 self.name = name
139 self.name = name
141
140
142 def __repr__(self):
141 def __repr__(self):
143 return 'Type %s() to exit.' % self.name
142 return 'Type %s() to exit.' % self.name
144 __str__ = __repr__
143 __str__ = __repr__
145
144
146 def __call__(self):
145 def __call__(self):
147 self.shell.exit()
146 self.shell.exit()
148
147
149 class InputList(list):
148 class InputList(list):
150 """Class to store user input.
149 """Class to store user input.
151
150
152 It's basically a list, but slices return a string instead of a list, thus
151 It's basically a list, but slices return a string instead of a list, thus
153 allowing things like (assuming 'In' is an instance):
152 allowing things like (assuming 'In' is an instance):
154
153
155 exec In[4:7]
154 exec In[4:7]
156
155
157 or
156 or
158
157
159 exec In[5:9] + In[14] + In[21:25]"""
158 exec In[5:9] + In[14] + In[21:25]"""
160
159
161 def __getslice__(self,i,j):
160 def __getslice__(self,i,j):
162 return ''.join(list.__getslice__(self,i,j))
161 return ''.join(list.__getslice__(self,i,j))
163
162
164 class SyntaxTB(ultraTB.ListTB):
163 class SyntaxTB(ultraTB.ListTB):
165 """Extension which holds some state: the last exception value"""
164 """Extension which holds some state: the last exception value"""
166
165
167 def __init__(self,color_scheme = 'NoColor'):
166 def __init__(self,color_scheme = 'NoColor'):
168 ultraTB.ListTB.__init__(self,color_scheme)
167 ultraTB.ListTB.__init__(self,color_scheme)
169 self.last_syntax_error = None
168 self.last_syntax_error = None
170
169
171 def __call__(self, etype, value, elist):
170 def __call__(self, etype, value, elist):
172 self.last_syntax_error = value
171 self.last_syntax_error = value
173 ultraTB.ListTB.__call__(self,etype,value,elist)
172 ultraTB.ListTB.__call__(self,etype,value,elist)
174
173
175 def clear_err_state(self):
174 def clear_err_state(self):
176 """Return the current error state and clear it"""
175 """Return the current error state and clear it"""
177 e = self.last_syntax_error
176 e = self.last_syntax_error
178 self.last_syntax_error = None
177 self.last_syntax_error = None
179 return e
178 return e
180
179
181 #****************************************************************************
180 #****************************************************************************
182 # Main IPython class
181 # Main IPython class
183
182
184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
183 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
185 # until a full rewrite is made. I've cleaned all cross-class uses of
184 # until a full rewrite is made. I've cleaned all cross-class uses of
186 # attributes and methods, but too much user code out there relies on the
185 # attributes and methods, but too much user code out there relies on the
187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
186 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
188 #
187 #
189 # But at least now, all the pieces have been separated and we could, in
188 # But at least now, all the pieces have been separated and we could, in
190 # principle, stop using the mixin. This will ease the transition to the
189 # principle, stop using the mixin. This will ease the transition to the
191 # chainsaw branch.
190 # chainsaw branch.
192
191
193 # For reference, the following is the list of 'self.foo' uses in the Magic
192 # For reference, the following is the list of 'self.foo' uses in the Magic
194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
193 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
195 # class, to prevent clashes.
194 # class, to prevent clashes.
196
195
197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
196 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
197 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
198 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
200 # 'self.value']
199 # 'self.value']
201
200
202 class InteractiveShell(object,Magic):
201 class InteractiveShell(object,Magic):
203 """An enhanced console for Python."""
202 """An enhanced console for Python."""
204
203
205 # class attribute to indicate whether the class supports threads or not.
204 # class attribute to indicate whether the class supports threads or not.
206 # Subclasses with thread support should override this as needed.
205 # Subclasses with thread support should override this as needed.
207 isthreaded = False
206 isthreaded = False
208
207
209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
208 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
210 user_ns = None,user_global_ns=None,banner2='',
209 user_ns = None,user_global_ns=None,banner2='',
211 custom_exceptions=((),None),embedded=False):
210 custom_exceptions=((),None),embedded=False):
212
211
213 # log system
212 # log system
214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
213 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
215
214
216 # some minimal strict typechecks. For some core data structures, I
215 # some minimal strict typechecks. For some core data structures, I
217 # want actual basic python types, not just anything that looks like
216 # want actual basic python types, not just anything that looks like
218 # one. This is especially true for namespaces.
217 # one. This is especially true for namespaces.
219 for ns in (user_ns,user_global_ns):
218 for ns in (user_ns,user_global_ns):
220 if ns is not None and type(ns) != types.DictType:
219 if ns is not None and type(ns) != types.DictType:
221 raise TypeError,'namespace must be a dictionary'
220 raise TypeError,'namespace must be a dictionary'
222
221
223 # Job manager (for jobs run as background threads)
222 # Job manager (for jobs run as background threads)
224 self.jobs = BackgroundJobManager()
223 self.jobs = BackgroundJobManager()
225
224
226 # Store the actual shell's name
225 # Store the actual shell's name
227 self.name = name
226 self.name = name
228
227
229 # We need to know whether the instance is meant for embedding, since
228 # We need to know whether the instance is meant for embedding, since
230 # global/local namespaces need to be handled differently in that case
229 # global/local namespaces need to be handled differently in that case
231 self.embedded = embedded
230 self.embedded = embedded
232 if embedded:
231 if embedded:
233 # Control variable so users can, from within the embedded instance,
232 # Control variable so users can, from within the embedded instance,
234 # permanently deactivate it.
233 # permanently deactivate it.
235 self.embedded_active = True
234 self.embedded_active = True
236
235
237 # command compiler
236 # command compiler
238 self.compile = codeop.CommandCompiler()
237 self.compile = codeop.CommandCompiler()
239
238
240 # User input buffer
239 # User input buffer
241 self.buffer = []
240 self.buffer = []
242
241
243 # Default name given in compilation of code
242 # Default name given in compilation of code
244 self.filename = '<ipython console>'
243 self.filename = '<ipython console>'
245
244
246 # Install our own quitter instead of the builtins. For python2.3-2.4,
245 # Install our own quitter instead of the builtins. For python2.3-2.4,
247 # this brings in behavior like 2.5, and for 2.5 it's identical.
246 # this brings in behavior like 2.5, and for 2.5 it's identical.
248 __builtin__.exit = Quitter(self,'exit')
247 __builtin__.exit = Quitter(self,'exit')
249 __builtin__.quit = Quitter(self,'quit')
248 __builtin__.quit = Quitter(self,'quit')
250
249
251 # Make an empty namespace, which extension writers can rely on both
250 # Make an empty namespace, which extension writers can rely on both
252 # existing and NEVER being used by ipython itself. This gives them a
251 # existing and NEVER being used by ipython itself. This gives them a
253 # convenient location for storing additional information and state
252 # convenient location for storing additional information and state
254 # their extensions may require, without fear of collisions with other
253 # their extensions may require, without fear of collisions with other
255 # ipython names that may develop later.
254 # ipython names that may develop later.
256 self.meta = Struct()
255 self.meta = Struct()
257
256
258 # Create the namespace where the user will operate. user_ns is
257 # Create the namespace where the user will operate. user_ns is
259 # normally the only one used, and it is passed to the exec calls as
258 # normally the only one used, and it is passed to the exec calls as
260 # the locals argument. But we do carry a user_global_ns namespace
259 # the locals argument. But we do carry a user_global_ns namespace
261 # given as the exec 'globals' argument, This is useful in embedding
260 # given as the exec 'globals' argument, This is useful in embedding
262 # situations where the ipython shell opens in a context where the
261 # situations where the ipython shell opens in a context where the
263 # distinction between locals and globals is meaningful.
262 # distinction between locals and globals is meaningful.
264
263
265 # FIXME. For some strange reason, __builtins__ is showing up at user
264 # FIXME. For some strange reason, __builtins__ is showing up at user
266 # level as a dict instead of a module. This is a manual fix, but I
265 # level as a dict instead of a module. This is a manual fix, but I
267 # should really track down where the problem is coming from. Alex
266 # should really track down where the problem is coming from. Alex
268 # Schmolck reported this problem first.
267 # Schmolck reported this problem first.
269
268
270 # A useful post by Alex Martelli on this topic:
269 # A useful post by Alex Martelli on this topic:
271 # Re: inconsistent value from __builtins__
270 # Re: inconsistent value from __builtins__
272 # Von: Alex Martelli <aleaxit@yahoo.com>
271 # Von: Alex Martelli <aleaxit@yahoo.com>
273 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
272 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
274 # Gruppen: comp.lang.python
273 # Gruppen: comp.lang.python
275
274
276 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
275 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
277 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
276 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
278 # > <type 'dict'>
277 # > <type 'dict'>
279 # > >>> print type(__builtins__)
278 # > >>> print type(__builtins__)
280 # > <type 'module'>
279 # > <type 'module'>
281 # > Is this difference in return value intentional?
280 # > Is this difference in return value intentional?
282
281
283 # Well, it's documented that '__builtins__' can be either a dictionary
282 # Well, it's documented that '__builtins__' can be either a dictionary
284 # or a module, and it's been that way for a long time. Whether it's
283 # or a module, and it's been that way for a long time. Whether it's
285 # intentional (or sensible), I don't know. In any case, the idea is
284 # intentional (or sensible), I don't know. In any case, the idea is
286 # that if you need to access the built-in namespace directly, you
285 # that if you need to access the built-in namespace directly, you
287 # should start with "import __builtin__" (note, no 's') which will
286 # should start with "import __builtin__" (note, no 's') which will
288 # definitely give you a module. Yeah, it's somewhat confusing:-(.
287 # definitely give you a module. Yeah, it's somewhat confusing:-(.
289
288
290 # These routines return properly built dicts as needed by the rest of
289 # These routines return properly built dicts as needed by the rest of
291 # the code, and can also be used by extension writers to generate
290 # the code, and can also be used by extension writers to generate
292 # properly initialized namespaces.
291 # properly initialized namespaces.
293 user_ns = IPython.ipapi.make_user_ns(user_ns)
292 user_ns = IPython.ipapi.make_user_ns(user_ns)
294 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
293 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
295
294
296 # Assign namespaces
295 # Assign namespaces
297 # This is the namespace where all normal user variables live
296 # This is the namespace where all normal user variables live
298 self.user_ns = user_ns
297 self.user_ns = user_ns
299 # Embedded instances require a separate namespace for globals.
298 # Embedded instances require a separate namespace for globals.
300 # Normally this one is unused by non-embedded instances.
299 # Normally this one is unused by non-embedded instances.
301 self.user_global_ns = user_global_ns
300 self.user_global_ns = user_global_ns
302 # A namespace to keep track of internal data structures to prevent
301 # A namespace to keep track of internal data structures to prevent
303 # them from cluttering user-visible stuff. Will be updated later
302 # them from cluttering user-visible stuff. Will be updated later
304 self.internal_ns = {}
303 self.internal_ns = {}
305
304
306 # Namespace of system aliases. Each entry in the alias
305 # Namespace of system aliases. Each entry in the alias
307 # table must be a 2-tuple of the form (N,name), where N is the number
306 # table must be a 2-tuple of the form (N,name), where N is the number
308 # of positional arguments of the alias.
307 # of positional arguments of the alias.
309 self.alias_table = {}
308 self.alias_table = {}
310
309
311 # A table holding all the namespaces IPython deals with, so that
310 # A table holding all the namespaces IPython deals with, so that
312 # introspection facilities can search easily.
311 # introspection facilities can search easily.
313 self.ns_table = {'user':user_ns,
312 self.ns_table = {'user':user_ns,
314 'user_global':user_global_ns,
313 'user_global':user_global_ns,
315 'alias':self.alias_table,
314 'alias':self.alias_table,
316 'internal':self.internal_ns,
315 'internal':self.internal_ns,
317 'builtin':__builtin__.__dict__
316 'builtin':__builtin__.__dict__
318 }
317 }
319 # The user namespace MUST have a pointer to the shell itself.
318 # The user namespace MUST have a pointer to the shell itself.
320 self.user_ns[name] = self
319 self.user_ns[name] = self
321
320
322 # We need to insert into sys.modules something that looks like a
321 # We need to insert into sys.modules something that looks like a
323 # module but which accesses the IPython namespace, for shelve and
322 # module but which accesses the IPython namespace, for shelve and
324 # pickle to work interactively. Normally they rely on getting
323 # pickle to work interactively. Normally they rely on getting
325 # everything out of __main__, but for embedding purposes each IPython
324 # everything out of __main__, but for embedding purposes each IPython
326 # instance has its own private namespace, so we can't go shoving
325 # instance has its own private namespace, so we can't go shoving
327 # everything into __main__.
326 # everything into __main__.
328
327
329 # note, however, that we should only do this for non-embedded
328 # note, however, that we should only do this for non-embedded
330 # ipythons, which really mimic the __main__.__dict__ with their own
329 # ipythons, which really mimic the __main__.__dict__ with their own
331 # namespace. Embedded instances, on the other hand, should not do
330 # namespace. Embedded instances, on the other hand, should not do
332 # this because they need to manage the user local/global namespaces
331 # this because they need to manage the user local/global namespaces
333 # only, but they live within a 'normal' __main__ (meaning, they
332 # only, but they live within a 'normal' __main__ (meaning, they
334 # shouldn't overtake the execution environment of the script they're
333 # shouldn't overtake the execution environment of the script they're
335 # embedded in).
334 # embedded in).
336
335
337 if not embedded:
336 if not embedded:
338 try:
337 try:
339 main_name = self.user_ns['__name__']
338 main_name = self.user_ns['__name__']
340 except KeyError:
339 except KeyError:
341 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
340 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
342 else:
341 else:
343 #print "pickle hack in place" # dbg
342 #print "pickle hack in place" # dbg
344 #print 'main_name:',main_name # dbg
343 #print 'main_name:',main_name # dbg
345 sys.modules[main_name] = FakeModule(self.user_ns)
344 sys.modules[main_name] = FakeModule(self.user_ns)
346
345
346 # Now that FakeModule produces a real module, we've run into a nasty
347 # problem: after script execution (via %run), the module where the user
348 # code ran is deleted. Now that this object is a true module (needed
349 # so docetst and other tools work correctly), the Python module
350 # teardown mechanism runs over it, and sets to None every variable
351 # present in that module. This means that later calls to functions
352 # defined in the script (which have become interactively visible after
353 # script exit) fail, because they hold references to objects that have
354 # become overwritten into None. The only solution I see right now is
355 # to protect every FakeModule used by %run by holding an internal
356 # reference to it. This private list will be used for that. The
357 # %reset command will flush it as well.
358 self._user_main_modules = []
359
347 # List of input with multi-line handling.
360 # List of input with multi-line handling.
348 # Fill its zero entry, user counter starts at 1
361 # Fill its zero entry, user counter starts at 1
349 self.input_hist = InputList(['\n'])
362 self.input_hist = InputList(['\n'])
350 # This one will hold the 'raw' input history, without any
363 # This one will hold the 'raw' input history, without any
351 # pre-processing. This will allow users to retrieve the input just as
364 # pre-processing. This will allow users to retrieve the input just as
352 # it was exactly typed in by the user, with %hist -r.
365 # it was exactly typed in by the user, with %hist -r.
353 self.input_hist_raw = InputList(['\n'])
366 self.input_hist_raw = InputList(['\n'])
354
367
355 # list of visited directories
368 # list of visited directories
356 try:
369 try:
357 self.dir_hist = [os.getcwd()]
370 self.dir_hist = [os.getcwd()]
358 except OSError:
371 except OSError:
359 self.dir_hist = []
372 self.dir_hist = []
360
373
361 # dict of output history
374 # dict of output history
362 self.output_hist = {}
375 self.output_hist = {}
363
376
364 # Get system encoding at startup time. Certain terminals (like Emacs
377 # 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
378 # under Win32 have it set to None, and we need to have a known valid
366 # encoding to use in the raw_input() method
379 # encoding to use in the raw_input() method
367 self.stdin_encoding = sys.stdin.encoding or 'ascii'
380 self.stdin_encoding = sys.stdin.encoding or 'ascii'
368
381
369 # dict of things NOT to alias (keywords, builtins and some magics)
382 # dict of things NOT to alias (keywords, builtins and some magics)
370 no_alias = {}
383 no_alias = {}
371 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
384 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
372 for key in keyword.kwlist + no_alias_magics:
385 for key in keyword.kwlist + no_alias_magics:
373 no_alias[key] = 1
386 no_alias[key] = 1
374 no_alias.update(__builtin__.__dict__)
387 no_alias.update(__builtin__.__dict__)
375 self.no_alias = no_alias
388 self.no_alias = no_alias
376
389
377 # make global variables for user access to these
390 # make global variables for user access to these
378 self.user_ns['_ih'] = self.input_hist
391 self.user_ns['_ih'] = self.input_hist
379 self.user_ns['_oh'] = self.output_hist
392 self.user_ns['_oh'] = self.output_hist
380 self.user_ns['_dh'] = self.dir_hist
393 self.user_ns['_dh'] = self.dir_hist
381
394
382 # user aliases to input and output histories
395 # user aliases to input and output histories
383 self.user_ns['In'] = self.input_hist
396 self.user_ns['In'] = self.input_hist
384 self.user_ns['Out'] = self.output_hist
397 self.user_ns['Out'] = self.output_hist
385
398
386 self.user_ns['_sh'] = IPython.shadowns
399 self.user_ns['_sh'] = IPython.shadowns
387 # Object variable to store code object waiting execution. This is
400 # Object variable to store code object waiting execution. This is
388 # used mainly by the multithreaded shells, but it can come in handy in
401 # used mainly by the multithreaded shells, but it can come in handy in
389 # other situations. No need to use a Queue here, since it's a single
402 # other situations. No need to use a Queue here, since it's a single
390 # item which gets cleared once run.
403 # item which gets cleared once run.
391 self.code_to_run = None
404 self.code_to_run = None
392
405
393 # escapes for automatic behavior on the command line
406 # escapes for automatic behavior on the command line
394 self.ESC_SHELL = '!'
407 self.ESC_SHELL = '!'
395 self.ESC_SH_CAP = '!!'
408 self.ESC_SH_CAP = '!!'
396 self.ESC_HELP = '?'
409 self.ESC_HELP = '?'
397 self.ESC_MAGIC = '%'
410 self.ESC_MAGIC = '%'
398 self.ESC_QUOTE = ','
411 self.ESC_QUOTE = ','
399 self.ESC_QUOTE2 = ';'
412 self.ESC_QUOTE2 = ';'
400 self.ESC_PAREN = '/'
413 self.ESC_PAREN = '/'
401
414
402 # And their associated handlers
415 # And their associated handlers
403 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
416 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
404 self.ESC_QUOTE : self.handle_auto,
417 self.ESC_QUOTE : self.handle_auto,
405 self.ESC_QUOTE2 : self.handle_auto,
418 self.ESC_QUOTE2 : self.handle_auto,
406 self.ESC_MAGIC : self.handle_magic,
419 self.ESC_MAGIC : self.handle_magic,
407 self.ESC_HELP : self.handle_help,
420 self.ESC_HELP : self.handle_help,
408 self.ESC_SHELL : self.handle_shell_escape,
421 self.ESC_SHELL : self.handle_shell_escape,
409 self.ESC_SH_CAP : self.handle_shell_escape,
422 self.ESC_SH_CAP : self.handle_shell_escape,
410 }
423 }
411
424
412 # class initializations
425 # class initializations
413 Magic.__init__(self,self)
426 Magic.__init__(self,self)
414
427
415 # Python source parser/formatter for syntax highlighting
428 # Python source parser/formatter for syntax highlighting
416 pyformat = PyColorize.Parser().format
429 pyformat = PyColorize.Parser().format
417 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
430 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
418
431
419 # hooks holds pointers used for user-side customizations
432 # hooks holds pointers used for user-side customizations
420 self.hooks = Struct()
433 self.hooks = Struct()
421
434
422 self.strdispatchers = {}
435 self.strdispatchers = {}
423
436
424 # Set all default hooks, defined in the IPython.hooks module.
437 # Set all default hooks, defined in the IPython.hooks module.
425 hooks = IPython.hooks
438 hooks = IPython.hooks
426 for hook_name in hooks.__all__:
439 for hook_name in hooks.__all__:
427 # default hooks have priority 100, i.e. low; user hooks should have
440 # default hooks have priority 100, i.e. low; user hooks should have
428 # 0-100 priority
441 # 0-100 priority
429 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
442 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
430 #print "bound hook",hook_name
443 #print "bound hook",hook_name
431
444
432 # Flag to mark unconditional exit
445 # Flag to mark unconditional exit
433 self.exit_now = False
446 self.exit_now = False
434
447
435 self.usage_min = """\
448 self.usage_min = """\
436 An enhanced console for Python.
449 An enhanced console for Python.
437 Some of its features are:
450 Some of its features are:
438 - Readline support if the readline library is present.
451 - Readline support if the readline library is present.
439 - Tab completion in the local namespace.
452 - Tab completion in the local namespace.
440 - Logging of input, see command-line options.
453 - Logging of input, see command-line options.
441 - System shell escape via ! , eg !ls.
454 - System shell escape via ! , eg !ls.
442 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
455 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
443 - Keeps track of locally defined variables via %who, %whos.
456 - Keeps track of locally defined variables via %who, %whos.
444 - Show object information with a ? eg ?x or x? (use ?? for more info).
457 - Show object information with a ? eg ?x or x? (use ?? for more info).
445 """
458 """
446 if usage: self.usage = usage
459 if usage: self.usage = usage
447 else: self.usage = self.usage_min
460 else: self.usage = self.usage_min
448
461
449 # Storage
462 # Storage
450 self.rc = rc # This will hold all configuration information
463 self.rc = rc # This will hold all configuration information
451 self.pager = 'less'
464 self.pager = 'less'
452 # temporary files used for various purposes. Deleted at exit.
465 # temporary files used for various purposes. Deleted at exit.
453 self.tempfiles = []
466 self.tempfiles = []
454
467
455 # Keep track of readline usage (later set by init_readline)
468 # Keep track of readline usage (later set by init_readline)
456 self.has_readline = False
469 self.has_readline = False
457
470
458 # template for logfile headers. It gets resolved at runtime by the
471 # template for logfile headers. It gets resolved at runtime by the
459 # logstart method.
472 # logstart method.
460 self.loghead_tpl = \
473 self.loghead_tpl = \
461 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
474 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
462 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
475 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
463 #log# opts = %s
476 #log# opts = %s
464 #log# args = %s
477 #log# args = %s
465 #log# It is safe to make manual edits below here.
478 #log# It is safe to make manual edits below here.
466 #log#-----------------------------------------------------------------------
479 #log#-----------------------------------------------------------------------
467 """
480 """
468 # for pushd/popd management
481 # for pushd/popd management
469 try:
482 try:
470 self.home_dir = get_home_dir()
483 self.home_dir = get_home_dir()
471 except HomeDirError,msg:
484 except HomeDirError,msg:
472 fatal(msg)
485 fatal(msg)
473
486
474 self.dir_stack = []
487 self.dir_stack = []
475
488
476 # Functions to call the underlying shell.
489 # Functions to call the underlying shell.
477
490
478 # The first is similar to os.system, but it doesn't return a value,
491 # The first is similar to os.system, but it doesn't return a value,
479 # and it allows interpolation of variables in the user's namespace.
492 # and it allows interpolation of variables in the user's namespace.
480 self.system = lambda cmd: \
493 self.system = lambda cmd: \
481 shell(self.var_expand(cmd,depth=2),
494 shell(self.var_expand(cmd,depth=2),
482 header=self.rc.system_header,
495 header=self.rc.system_header,
483 verbose=self.rc.system_verbose)
496 verbose=self.rc.system_verbose)
484
497
485 # These are for getoutput and getoutputerror:
498 # These are for getoutput and getoutputerror:
486 self.getoutput = lambda cmd: \
499 self.getoutput = lambda cmd: \
487 getoutput(self.var_expand(cmd,depth=2),
500 getoutput(self.var_expand(cmd,depth=2),
488 header=self.rc.system_header,
501 header=self.rc.system_header,
489 verbose=self.rc.system_verbose)
502 verbose=self.rc.system_verbose)
490
503
491 self.getoutputerror = lambda cmd: \
504 self.getoutputerror = lambda cmd: \
492 getoutputerror(self.var_expand(cmd,depth=2),
505 getoutputerror(self.var_expand(cmd,depth=2),
493 header=self.rc.system_header,
506 header=self.rc.system_header,
494 verbose=self.rc.system_verbose)
507 verbose=self.rc.system_verbose)
495
508
496
509
497 # keep track of where we started running (mainly for crash post-mortem)
510 # keep track of where we started running (mainly for crash post-mortem)
498 self.starting_dir = os.getcwd()
511 self.starting_dir = os.getcwd()
499
512
500 # Various switches which can be set
513 # Various switches which can be set
501 self.CACHELENGTH = 5000 # this is cheap, it's just text
514 self.CACHELENGTH = 5000 # this is cheap, it's just text
502 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
515 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
503 self.banner2 = banner2
516 self.banner2 = banner2
504
517
505 # TraceBack handlers:
518 # TraceBack handlers:
506
519
507 # Syntax error handler.
520 # Syntax error handler.
508 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
521 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
509
522
510 # The interactive one is initialized with an offset, meaning we always
523 # The interactive one is initialized with an offset, meaning we always
511 # want to remove the topmost item in the traceback, which is our own
524 # want to remove the topmost item in the traceback, which is our own
512 # internal code. Valid modes: ['Plain','Context','Verbose']
525 # internal code. Valid modes: ['Plain','Context','Verbose']
513 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
526 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
514 color_scheme='NoColor',
527 color_scheme='NoColor',
515 tb_offset = 1)
528 tb_offset = 1)
516
529
517 # IPython itself shouldn't crash. This will produce a detailed
530 # IPython itself shouldn't crash. This will produce a detailed
518 # post-mortem if it does. But we only install the crash handler for
531 # post-mortem if it does. But we only install the crash handler for
519 # non-threaded shells, the threaded ones use a normal verbose reporter
532 # non-threaded shells, the threaded ones use a normal verbose reporter
520 # and lose the crash handler. This is because exceptions in the main
533 # and lose the crash handler. This is because exceptions in the main
521 # thread (such as in GUI code) propagate directly to sys.excepthook,
534 # thread (such as in GUI code) propagate directly to sys.excepthook,
522 # and there's no point in printing crash dumps for every user exception.
535 # and there's no point in printing crash dumps for every user exception.
523 if self.isthreaded:
536 if self.isthreaded:
524 ipCrashHandler = ultraTB.FormattedTB()
537 ipCrashHandler = ultraTB.FormattedTB()
525 else:
538 else:
526 from IPython import CrashHandler
539 from IPython import CrashHandler
527 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
540 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
528 self.set_crash_handler(ipCrashHandler)
541 self.set_crash_handler(ipCrashHandler)
529
542
530 # and add any custom exception handlers the user may have specified
543 # and add any custom exception handlers the user may have specified
531 self.set_custom_exc(*custom_exceptions)
544 self.set_custom_exc(*custom_exceptions)
532
545
533 # indentation management
546 # indentation management
534 self.autoindent = False
547 self.autoindent = False
535 self.indent_current_nsp = 0
548 self.indent_current_nsp = 0
536
549
537 # Make some aliases automatically
550 # Make some aliases automatically
538 # Prepare list of shell aliases to auto-define
551 # Prepare list of shell aliases to auto-define
539 if os.name == 'posix':
552 if os.name == 'posix':
540 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
553 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
541 'mv mv -i','rm rm -i','cp cp -i',
554 'mv mv -i','rm rm -i','cp cp -i',
542 'cat cat','less less','clear clear',
555 'cat cat','less less','clear clear',
543 # a better ls
556 # a better ls
544 'ls ls -F',
557 'ls ls -F',
545 # long ls
558 # long ls
546 'll ls -lF')
559 'll ls -lF')
547 # Extra ls aliases with color, which need special treatment on BSD
560 # Extra ls aliases with color, which need special treatment on BSD
548 # variants
561 # variants
549 ls_extra = ( # color ls
562 ls_extra = ( # color ls
550 'lc ls -F -o --color',
563 'lc ls -F -o --color',
551 # ls normal files only
564 # ls normal files only
552 'lf ls -F -o --color %l | grep ^-',
565 'lf ls -F -o --color %l | grep ^-',
553 # ls symbolic links
566 # ls symbolic links
554 'lk ls -F -o --color %l | grep ^l',
567 'lk ls -F -o --color %l | grep ^l',
555 # directories or links to directories,
568 # directories or links to directories,
556 'ldir ls -F -o --color %l | grep /$',
569 'ldir ls -F -o --color %l | grep /$',
557 # things which are executable
570 # things which are executable
558 'lx ls -F -o --color %l | grep ^-..x',
571 'lx ls -F -o --color %l | grep ^-..x',
559 )
572 )
560 # The BSDs don't ship GNU ls, so they don't understand the
573 # The BSDs don't ship GNU ls, so they don't understand the
561 # --color switch out of the box
574 # --color switch out of the box
562 if 'bsd' in sys.platform:
575 if 'bsd' in sys.platform:
563 ls_extra = ( # ls normal files only
576 ls_extra = ( # ls normal files only
564 'lf ls -lF | grep ^-',
577 'lf ls -lF | grep ^-',
565 # ls symbolic links
578 # ls symbolic links
566 'lk ls -lF | grep ^l',
579 'lk ls -lF | grep ^l',
567 # directories or links to directories,
580 # directories or links to directories,
568 'ldir ls -lF | grep /$',
581 'ldir ls -lF | grep /$',
569 # things which are executable
582 # things which are executable
570 'lx ls -lF | grep ^-..x',
583 'lx ls -lF | grep ^-..x',
571 )
584 )
572 auto_alias = auto_alias + ls_extra
585 auto_alias = auto_alias + ls_extra
573 elif os.name in ['nt','dos']:
586 elif os.name in ['nt','dos']:
574 auto_alias = ('ls dir /on',
587 auto_alias = ('ls dir /on',
575 'ddir dir /ad /on', 'ldir dir /ad /on',
588 'ddir dir /ad /on', 'ldir dir /ad /on',
576 'mkdir mkdir','rmdir rmdir','echo echo',
589 'mkdir mkdir','rmdir rmdir','echo echo',
577 'ren ren','cls cls','copy copy')
590 'ren ren','cls cls','copy copy')
578 else:
591 else:
579 auto_alias = ()
592 auto_alias = ()
580 self.auto_alias = [s.split(None,1) for s in auto_alias]
593 self.auto_alias = [s.split(None,1) for s in auto_alias]
581
594
582 # Produce a public API instance
595 # Produce a public API instance
583 self.api = IPython.ipapi.IPApi(self)
596 self.api = IPython.ipapi.IPApi(self)
584
597
585 # Call the actual (public) initializer
598 # Call the actual (public) initializer
586 self.init_auto_alias()
599 self.init_auto_alias()
587
600
588 # track which builtins we add, so we can clean up later
601 # track which builtins we add, so we can clean up later
589 self.builtins_added = {}
602 self.builtins_added = {}
590 # This method will add the necessary builtins for operation, but
603 # This method will add the necessary builtins for operation, but
591 # tracking what it did via the builtins_added dict.
604 # tracking what it did via the builtins_added dict.
592 self.add_builtins()
605 self.add_builtins()
593
606
594
607
595
608
596 # end __init__
609 # end __init__
597
610
598 def var_expand(self,cmd,depth=0):
611 def var_expand(self,cmd,depth=0):
599 """Expand python variables in a string.
612 """Expand python variables in a string.
600
613
601 The depth argument indicates how many frames above the caller should
614 The depth argument indicates how many frames above the caller should
602 be walked to look for the local namespace where to expand variables.
615 be walked to look for the local namespace where to expand variables.
603
616
604 The global namespace for expansion is always the user's interactive
617 The global namespace for expansion is always the user's interactive
605 namespace.
618 namespace.
606 """
619 """
607
620
608 return str(ItplNS(cmd.replace('#','\#'),
621 return str(ItplNS(cmd.replace('#','\#'),
609 self.user_ns, # globals
622 self.user_ns, # globals
610 # Skip our own frame in searching for locals:
623 # Skip our own frame in searching for locals:
611 sys._getframe(depth+1).f_locals # locals
624 sys._getframe(depth+1).f_locals # locals
612 ))
625 ))
613
626
614 def pre_config_initialization(self):
627 def pre_config_initialization(self):
615 """Pre-configuration init method
628 """Pre-configuration init method
616
629
617 This is called before the configuration files are processed to
630 This is called before the configuration files are processed to
618 prepare the services the config files might need.
631 prepare the services the config files might need.
619
632
620 self.rc already has reasonable default values at this point.
633 self.rc already has reasonable default values at this point.
621 """
634 """
622 rc = self.rc
635 rc = self.rc
623 try:
636 try:
624 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
637 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
625 except exceptions.UnicodeDecodeError:
638 except exceptions.UnicodeDecodeError:
626 print "Your ipythondir can't be decoded to unicode!"
639 print "Your ipythondir can't be decoded to unicode!"
627 print "Please set HOME environment variable to something that"
640 print "Please set HOME environment variable to something that"
628 print r"only has ASCII characters, e.g. c:\home"
641 print r"only has ASCII characters, e.g. c:\home"
629 print "Now it is",rc.ipythondir
642 print "Now it is",rc.ipythondir
630 sys.exit()
643 sys.exit()
631 self.shadowhist = IPython.history.ShadowHist(self.db)
644 self.shadowhist = IPython.history.ShadowHist(self.db)
632
645
633
646
634 def post_config_initialization(self):
647 def post_config_initialization(self):
635 """Post configuration init method
648 """Post configuration init method
636
649
637 This is called after the configuration files have been processed to
650 This is called after the configuration files have been processed to
638 'finalize' the initialization."""
651 'finalize' the initialization."""
639
652
640 rc = self.rc
653 rc = self.rc
641
654
642 # Object inspector
655 # Object inspector
643 self.inspector = OInspect.Inspector(OInspect.InspectColors,
656 self.inspector = OInspect.Inspector(OInspect.InspectColors,
644 PyColorize.ANSICodeColors,
657 PyColorize.ANSICodeColors,
645 'NoColor',
658 'NoColor',
646 rc.object_info_string_level)
659 rc.object_info_string_level)
647
660
648 self.rl_next_input = None
661 self.rl_next_input = None
649 self.rl_do_indent = False
662 self.rl_do_indent = False
650 # Load readline proper
663 # Load readline proper
651 if rc.readline:
664 if rc.readline:
652 self.init_readline()
665 self.init_readline()
653
666
654
667
655 # local shortcut, this is used a LOT
668 # local shortcut, this is used a LOT
656 self.log = self.logger.log
669 self.log = self.logger.log
657
670
658 # Initialize cache, set in/out prompts and printing system
671 # Initialize cache, set in/out prompts and printing system
659 self.outputcache = CachedOutput(self,
672 self.outputcache = CachedOutput(self,
660 rc.cache_size,
673 rc.cache_size,
661 rc.pprint,
674 rc.pprint,
662 input_sep = rc.separate_in,
675 input_sep = rc.separate_in,
663 output_sep = rc.separate_out,
676 output_sep = rc.separate_out,
664 output_sep2 = rc.separate_out2,
677 output_sep2 = rc.separate_out2,
665 ps1 = rc.prompt_in1,
678 ps1 = rc.prompt_in1,
666 ps2 = rc.prompt_in2,
679 ps2 = rc.prompt_in2,
667 ps_out = rc.prompt_out,
680 ps_out = rc.prompt_out,
668 pad_left = rc.prompts_pad_left)
681 pad_left = rc.prompts_pad_left)
669
682
670 # user may have over-ridden the default print hook:
683 # user may have over-ridden the default print hook:
671 try:
684 try:
672 self.outputcache.__class__.display = self.hooks.display
685 self.outputcache.__class__.display = self.hooks.display
673 except AttributeError:
686 except AttributeError:
674 pass
687 pass
675
688
676 # I don't like assigning globally to sys, because it means when
689 # I don't like assigning globally to sys, because it means when
677 # embedding instances, each embedded instance overrides the previous
690 # embedding instances, each embedded instance overrides the previous
678 # choice. But sys.displayhook seems to be called internally by exec,
691 # choice. But sys.displayhook seems to be called internally by exec,
679 # so I don't see a way around it. We first save the original and then
692 # so I don't see a way around it. We first save the original and then
680 # overwrite it.
693 # overwrite it.
681 self.sys_displayhook = sys.displayhook
694 self.sys_displayhook = sys.displayhook
682 sys.displayhook = self.outputcache
695 sys.displayhook = self.outputcache
683
696
684 # Monkeypatch doctest so that its core test runner method is protected
697 # Do a proper resetting of doctest, including the necessary displayhook
685 # from IPython's modified displayhook. Doctest expects the default
698 # monkeypatching
686 # displayhook behavior deep down, so our modification breaks it
699 doctest_reload()
687 # completely. For this reason, a hard monkeypatch seems like a
700
688 # reasonable solution rather than asking users to manually use a
689 # different doctest runner when under IPython.
690 try:
691 doctest.DocTestRunner
692 except AttributeError:
693 # This is only for python 2.3 compatibility, remove once we move to
694 # 2.4 only.
695 pass
696 else:
697 doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run)
698
699 # Set user colors (don't do it in the constructor above so that it
701 # Set user colors (don't do it in the constructor above so that it
700 # doesn't crash if colors option is invalid)
702 # doesn't crash if colors option is invalid)
701 self.magic_colors(rc.colors)
703 self.magic_colors(rc.colors)
702
704
703 # Set calling of pdb on exceptions
705 # Set calling of pdb on exceptions
704 self.call_pdb = rc.pdb
706 self.call_pdb = rc.pdb
705
707
706 # Load user aliases
708 # Load user aliases
707 for alias in rc.alias:
709 for alias in rc.alias:
708 self.magic_alias(alias)
710 self.magic_alias(alias)
709
711
710 self.hooks.late_startup_hook()
712 self.hooks.late_startup_hook()
711
713
712 batchrun = False
714 batchrun = False
713 for batchfile in [path(arg) for arg in self.rc.args
715 for batchfile in [path(arg) for arg in self.rc.args
714 if arg.lower().endswith('.ipy')]:
716 if arg.lower().endswith('.ipy')]:
715 if not batchfile.isfile():
717 if not batchfile.isfile():
716 print "No such batch file:", batchfile
718 print "No such batch file:", batchfile
717 continue
719 continue
718 self.api.runlines(batchfile.text())
720 self.api.runlines(batchfile.text())
719 batchrun = True
721 batchrun = True
720 # without -i option, exit after running the batch file
722 # without -i option, exit after running the batch file
721 if batchrun and not self.rc.interact:
723 if batchrun and not self.rc.interact:
722 self.exit_now = True
724 self.exit_now = True
723
725
724 def add_builtins(self):
726 def add_builtins(self):
725 """Store ipython references into the builtin namespace.
727 """Store ipython references into the builtin namespace.
726
728
727 Some parts of ipython operate via builtins injected here, which hold a
729 Some parts of ipython operate via builtins injected here, which hold a
728 reference to IPython itself."""
730 reference to IPython itself."""
729
731
730 # TODO: deprecate all except _ip; 'jobs' should be installed
732 # TODO: deprecate all except _ip; 'jobs' should be installed
731 # by an extension and the rest are under _ip, ipalias is redundant
733 # by an extension and the rest are under _ip, ipalias is redundant
732 builtins_new = dict(__IPYTHON__ = self,
734 builtins_new = dict(__IPYTHON__ = self,
733 ip_set_hook = self.set_hook,
735 ip_set_hook = self.set_hook,
734 jobs = self.jobs,
736 jobs = self.jobs,
735 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
737 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
736 ipalias = wrap_deprecated(self.ipalias),
738 ipalias = wrap_deprecated(self.ipalias),
737 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
739 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
738 _ip = self.api
740 _ip = self.api
739 )
741 )
740 for biname,bival in builtins_new.items():
742 for biname,bival in builtins_new.items():
741 try:
743 try:
742 # store the orignal value so we can restore it
744 # store the orignal value so we can restore it
743 self.builtins_added[biname] = __builtin__.__dict__[biname]
745 self.builtins_added[biname] = __builtin__.__dict__[biname]
744 except KeyError:
746 except KeyError:
745 # or mark that it wasn't defined, and we'll just delete it at
747 # or mark that it wasn't defined, and we'll just delete it at
746 # cleanup
748 # cleanup
747 self.builtins_added[biname] = Undefined
749 self.builtins_added[biname] = Undefined
748 __builtin__.__dict__[biname] = bival
750 __builtin__.__dict__[biname] = bival
749
751
750 # Keep in the builtins a flag for when IPython is active. We set it
752 # 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
753 # with setdefault so that multiple nested IPythons don't clobber one
752 # another. Each will increase its value by one upon being activated,
754 # another. Each will increase its value by one upon being activated,
753 # which also gives us a way to determine the nesting level.
755 # which also gives us a way to determine the nesting level.
754 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
756 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
755
757
756 def clean_builtins(self):
758 def clean_builtins(self):
757 """Remove any builtins which might have been added by add_builtins, or
759 """Remove any builtins which might have been added by add_builtins, or
758 restore overwritten ones to their previous values."""
760 restore overwritten ones to their previous values."""
759 for biname,bival in self.builtins_added.items():
761 for biname,bival in self.builtins_added.items():
760 if bival is Undefined:
762 if bival is Undefined:
761 del __builtin__.__dict__[biname]
763 del __builtin__.__dict__[biname]
762 else:
764 else:
763 __builtin__.__dict__[biname] = bival
765 __builtin__.__dict__[biname] = bival
764 self.builtins_added.clear()
766 self.builtins_added.clear()
765
767
766 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
768 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
767 """set_hook(name,hook) -> sets an internal IPython hook.
769 """set_hook(name,hook) -> sets an internal IPython hook.
768
770
769 IPython exposes some of its internal API as user-modifiable hooks. By
771 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
772 adding your function to one of these hooks, you can modify IPython's
771 behavior to call at runtime your own routines."""
773 behavior to call at runtime your own routines."""
772
774
773 # At some point in the future, this should validate the hook before it
775 # 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
776 # accepts it. Probably at least check that the hook takes the number
775 # of args it's supposed to.
777 # of args it's supposed to.
776
778
777 f = new.instancemethod(hook,self,self.__class__)
779 f = new.instancemethod(hook,self,self.__class__)
778
780
779 # check if the hook is for strdispatcher first
781 # check if the hook is for strdispatcher first
780 if str_key is not None:
782 if str_key is not None:
781 sdp = self.strdispatchers.get(name, StrDispatch())
783 sdp = self.strdispatchers.get(name, StrDispatch())
782 sdp.add_s(str_key, f, priority )
784 sdp.add_s(str_key, f, priority )
783 self.strdispatchers[name] = sdp
785 self.strdispatchers[name] = sdp
784 return
786 return
785 if re_key is not None:
787 if re_key is not None:
786 sdp = self.strdispatchers.get(name, StrDispatch())
788 sdp = self.strdispatchers.get(name, StrDispatch())
787 sdp.add_re(re.compile(re_key), f, priority )
789 sdp.add_re(re.compile(re_key), f, priority )
788 self.strdispatchers[name] = sdp
790 self.strdispatchers[name] = sdp
789 return
791 return
790
792
791 dp = getattr(self.hooks, name, None)
793 dp = getattr(self.hooks, name, None)
792 if name not in IPython.hooks.__all__:
794 if name not in IPython.hooks.__all__:
793 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
795 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
794 if not dp:
796 if not dp:
795 dp = IPython.hooks.CommandChainDispatcher()
797 dp = IPython.hooks.CommandChainDispatcher()
796
798
797 try:
799 try:
798 dp.add(f,priority)
800 dp.add(f,priority)
799 except AttributeError:
801 except AttributeError:
800 # it was not commandchain, plain old func - replace
802 # it was not commandchain, plain old func - replace
801 dp = f
803 dp = f
802
804
803 setattr(self.hooks,name, dp)
805 setattr(self.hooks,name, dp)
804
806
805
807
806 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
808 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
807
809
808 def set_crash_handler(self,crashHandler):
810 def set_crash_handler(self,crashHandler):
809 """Set the IPython crash handler.
811 """Set the IPython crash handler.
810
812
811 This must be a callable with a signature suitable for use as
813 This must be a callable with a signature suitable for use as
812 sys.excepthook."""
814 sys.excepthook."""
813
815
814 # Install the given crash handler as the Python exception hook
816 # Install the given crash handler as the Python exception hook
815 sys.excepthook = crashHandler
817 sys.excepthook = crashHandler
816
818
817 # The instance will store a pointer to this, so that runtime code
819 # The instance will store a pointer to this, so that runtime code
818 # (such as magics) can access it. This is because during the
820 # (such as magics) can access it. This is because during the
819 # read-eval loop, it gets temporarily overwritten (to deal with GUI
821 # read-eval loop, it gets temporarily overwritten (to deal with GUI
820 # frameworks).
822 # frameworks).
821 self.sys_excepthook = sys.excepthook
823 self.sys_excepthook = sys.excepthook
822
824
823
825
824 def set_custom_exc(self,exc_tuple,handler):
826 def set_custom_exc(self,exc_tuple,handler):
825 """set_custom_exc(exc_tuple,handler)
827 """set_custom_exc(exc_tuple,handler)
826
828
827 Set a custom exception handler, which will be called if any of the
829 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
830 exceptions in exc_tuple occur in the mainloop (specifically, in the
829 runcode() method.
831 runcode() method.
830
832
831 Inputs:
833 Inputs:
832
834
833 - exc_tuple: a *tuple* of valid exceptions to call the defined
835 - 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
836 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
837 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:
838 you only want to trap a single exception, use a singleton tuple:
837
839
838 exc_tuple == (MyCustomException,)
840 exc_tuple == (MyCustomException,)
839
841
840 - handler: this must be defined as a function with the following
842 - handler: this must be defined as a function with the following
841 basic interface: def my_handler(self,etype,value,tb).
843 basic interface: def my_handler(self,etype,value,tb).
842
844
843 This will be made into an instance method (via new.instancemethod)
845 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
846 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
847 listed in the exc_tuple are caught. If the handler is None, an
846 internal basic one is used, which just prints basic info.
848 internal basic one is used, which just prints basic info.
847
849
848 WARNING: by putting in your own exception handler into IPython's main
850 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
851 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."""
852 facility should only be used if you really know what you are doing."""
851
853
852 assert type(exc_tuple)==type(()) , \
854 assert type(exc_tuple)==type(()) , \
853 "The custom exceptions must be given AS A TUPLE."
855 "The custom exceptions must be given AS A TUPLE."
854
856
855 def dummy_handler(self,etype,value,tb):
857 def dummy_handler(self,etype,value,tb):
856 print '*** Simple custom exception handler ***'
858 print '*** Simple custom exception handler ***'
857 print 'Exception type :',etype
859 print 'Exception type :',etype
858 print 'Exception value:',value
860 print 'Exception value:',value
859 print 'Traceback :',tb
861 print 'Traceback :',tb
860 print 'Source code :','\n'.join(self.buffer)
862 print 'Source code :','\n'.join(self.buffer)
861
863
862 if handler is None: handler = dummy_handler
864 if handler is None: handler = dummy_handler
863
865
864 self.CustomTB = new.instancemethod(handler,self,self.__class__)
866 self.CustomTB = new.instancemethod(handler,self,self.__class__)
865 self.custom_exceptions = exc_tuple
867 self.custom_exceptions = exc_tuple
866
868
867 def set_custom_completer(self,completer,pos=0):
869 def set_custom_completer(self,completer,pos=0):
868 """set_custom_completer(completer,pos=0)
870 """set_custom_completer(completer,pos=0)
869
871
870 Adds a new custom completer function.
872 Adds a new custom completer function.
871
873
872 The position argument (defaults to 0) is the index in the completers
874 The position argument (defaults to 0) is the index in the completers
873 list where you want the completer to be inserted."""
875 list where you want the completer to be inserted."""
874
876
875 newcomp = new.instancemethod(completer,self.Completer,
877 newcomp = new.instancemethod(completer,self.Completer,
876 self.Completer.__class__)
878 self.Completer.__class__)
877 self.Completer.matchers.insert(pos,newcomp)
879 self.Completer.matchers.insert(pos,newcomp)
878
880
879 def set_completer(self):
881 def set_completer(self):
880 """reset readline's completer to be our own."""
882 """reset readline's completer to be our own."""
881 self.readline.set_completer(self.Completer.complete)
883 self.readline.set_completer(self.Completer.complete)
882
884
883 def _get_call_pdb(self):
885 def _get_call_pdb(self):
884 return self._call_pdb
886 return self._call_pdb
885
887
886 def _set_call_pdb(self,val):
888 def _set_call_pdb(self,val):
887
889
888 if val not in (0,1,False,True):
890 if val not in (0,1,False,True):
889 raise ValueError,'new call_pdb value must be boolean'
891 raise ValueError,'new call_pdb value must be boolean'
890
892
891 # store value in instance
893 # store value in instance
892 self._call_pdb = val
894 self._call_pdb = val
893
895
894 # notify the actual exception handlers
896 # notify the actual exception handlers
895 self.InteractiveTB.call_pdb = val
897 self.InteractiveTB.call_pdb = val
896 if self.isthreaded:
898 if self.isthreaded:
897 try:
899 try:
898 self.sys_excepthook.call_pdb = val
900 self.sys_excepthook.call_pdb = val
899 except:
901 except:
900 warn('Failed to activate pdb for threaded exception handler')
902 warn('Failed to activate pdb for threaded exception handler')
901
903
902 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
904 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
903 'Control auto-activation of pdb at exceptions')
905 'Control auto-activation of pdb at exceptions')
904
906
905
907
906 # These special functions get installed in the builtin namespace, to
908 # These special functions get installed in the builtin namespace, to
907 # provide programmatic (pure python) access to magics, aliases and system
909 # provide programmatic (pure python) access to magics, aliases and system
908 # calls. This is important for logging, user scripting, and more.
910 # calls. This is important for logging, user scripting, and more.
909
911
910 # We are basically exposing, via normal python functions, the three
912 # We are basically exposing, via normal python functions, the three
911 # mechanisms in which ipython offers special call modes (magics for
913 # mechanisms in which ipython offers special call modes (magics for
912 # internal control, aliases for direct system access via pre-selected
914 # internal control, aliases for direct system access via pre-selected
913 # names, and !cmd for calling arbitrary system commands).
915 # names, and !cmd for calling arbitrary system commands).
914
916
915 def ipmagic(self,arg_s):
917 def ipmagic(self,arg_s):
916 """Call a magic function by name.
918 """Call a magic function by name.
917
919
918 Input: a string containing the name of the magic function to call and any
920 Input: a string containing the name of the magic function to call and any
919 additional arguments to be passed to the magic.
921 additional arguments to be passed to the magic.
920
922
921 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
923 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
922 prompt:
924 prompt:
923
925
924 In[1]: %name -opt foo bar
926 In[1]: %name -opt foo bar
925
927
926 To call a magic without arguments, simply use ipmagic('name').
928 To call a magic without arguments, simply use ipmagic('name').
927
929
928 This provides a proper Python function to call IPython's magics in any
930 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
931 valid Python code you can type at the interpreter, including loops and
930 compound statements. It is added by IPython to the Python builtin
932 compound statements. It is added by IPython to the Python builtin
931 namespace upon initialization."""
933 namespace upon initialization."""
932
934
933 args = arg_s.split(' ',1)
935 args = arg_s.split(' ',1)
934 magic_name = args[0]
936 magic_name = args[0]
935 magic_name = magic_name.lstrip(self.ESC_MAGIC)
937 magic_name = magic_name.lstrip(self.ESC_MAGIC)
936
938
937 try:
939 try:
938 magic_args = args[1]
940 magic_args = args[1]
939 except IndexError:
941 except IndexError:
940 magic_args = ''
942 magic_args = ''
941 fn = getattr(self,'magic_'+magic_name,None)
943 fn = getattr(self,'magic_'+magic_name,None)
942 if fn is None:
944 if fn is None:
943 error("Magic function `%s` not found." % magic_name)
945 error("Magic function `%s` not found." % magic_name)
944 else:
946 else:
945 magic_args = self.var_expand(magic_args,1)
947 magic_args = self.var_expand(magic_args,1)
946 return fn(magic_args)
948 return fn(magic_args)
947
949
948 def ipalias(self,arg_s):
950 def ipalias(self,arg_s):
949 """Call an alias by name.
951 """Call an alias by name.
950
952
951 Input: a string containing the name of the alias to call and any
953 Input: a string containing the name of the alias to call and any
952 additional arguments to be passed to the magic.
954 additional arguments to be passed to the magic.
953
955
954 ipalias('name -opt foo bar') is equivalent to typing at the ipython
956 ipalias('name -opt foo bar') is equivalent to typing at the ipython
955 prompt:
957 prompt:
956
958
957 In[1]: name -opt foo bar
959 In[1]: name -opt foo bar
958
960
959 To call an alias without arguments, simply use ipalias('name').
961 To call an alias without arguments, simply use ipalias('name').
960
962
961 This provides a proper Python function to call IPython's aliases in any
963 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
964 valid Python code you can type at the interpreter, including loops and
963 compound statements. It is added by IPython to the Python builtin
965 compound statements. It is added by IPython to the Python builtin
964 namespace upon initialization."""
966 namespace upon initialization."""
965
967
966 args = arg_s.split(' ',1)
968 args = arg_s.split(' ',1)
967 alias_name = args[0]
969 alias_name = args[0]
968 try:
970 try:
969 alias_args = args[1]
971 alias_args = args[1]
970 except IndexError:
972 except IndexError:
971 alias_args = ''
973 alias_args = ''
972 if alias_name in self.alias_table:
974 if alias_name in self.alias_table:
973 self.call_alias(alias_name,alias_args)
975 self.call_alias(alias_name,alias_args)
974 else:
976 else:
975 error("Alias `%s` not found." % alias_name)
977 error("Alias `%s` not found." % alias_name)
976
978
977 def ipsystem(self,arg_s):
979 def ipsystem(self,arg_s):
978 """Make a system call, using IPython."""
980 """Make a system call, using IPython."""
979
981
980 self.system(arg_s)
982 self.system(arg_s)
981
983
982 def complete(self,text):
984 def complete(self,text):
983 """Return a sorted list of all possible completions on text.
985 """Return a sorted list of all possible completions on text.
984
986
985 Inputs:
987 Inputs:
986
988
987 - text: a string of text to be completed on.
989 - text: a string of text to be completed on.
988
990
989 This is a wrapper around the completion mechanism, similar to what
991 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
992 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
993 exposing it as a method, it can be used by other non-readline
992 environments (such as GUIs) for text completion.
994 environments (such as GUIs) for text completion.
993
995
994 Simple usage example:
996 Simple usage example:
995
997
996 In [1]: x = 'hello'
998 In [1]: x = 'hello'
997
999
998 In [2]: __IP.complete('x.l')
1000 In [2]: __IP.complete('x.l')
999 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
1001 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
1000
1002
1001 complete = self.Completer.complete
1003 complete = self.Completer.complete
1002 state = 0
1004 state = 0
1003 # use a dict so we get unique keys, since ipyhton's multiple
1005 # use a dict so we get unique keys, since ipyhton's multiple
1004 # completers can return duplicates. When we make 2.4 a requirement,
1006 # completers can return duplicates. When we make 2.4 a requirement,
1005 # start using sets instead, which are faster.
1007 # start using sets instead, which are faster.
1006 comps = {}
1008 comps = {}
1007 while True:
1009 while True:
1008 newcomp = complete(text,state,line_buffer=text)
1010 newcomp = complete(text,state,line_buffer=text)
1009 if newcomp is None:
1011 if newcomp is None:
1010 break
1012 break
1011 comps[newcomp] = 1
1013 comps[newcomp] = 1
1012 state += 1
1014 state += 1
1013 outcomps = comps.keys()
1015 outcomps = comps.keys()
1014 outcomps.sort()
1016 outcomps.sort()
1015 return outcomps
1017 return outcomps
1016
1018
1017 def set_completer_frame(self, frame=None):
1019 def set_completer_frame(self, frame=None):
1018 if frame:
1020 if frame:
1019 self.Completer.namespace = frame.f_locals
1021 self.Completer.namespace = frame.f_locals
1020 self.Completer.global_namespace = frame.f_globals
1022 self.Completer.global_namespace = frame.f_globals
1021 else:
1023 else:
1022 self.Completer.namespace = self.user_ns
1024 self.Completer.namespace = self.user_ns
1023 self.Completer.global_namespace = self.user_global_ns
1025 self.Completer.global_namespace = self.user_global_ns
1024
1026
1025 def init_auto_alias(self):
1027 def init_auto_alias(self):
1026 """Define some aliases automatically.
1028 """Define some aliases automatically.
1027
1029
1028 These are ALL parameter-less aliases"""
1030 These are ALL parameter-less aliases"""
1029
1031
1030 for alias,cmd in self.auto_alias:
1032 for alias,cmd in self.auto_alias:
1031 self.getapi().defalias(alias,cmd)
1033 self.getapi().defalias(alias,cmd)
1032
1034
1033
1035
1034 def alias_table_validate(self,verbose=0):
1036 def alias_table_validate(self,verbose=0):
1035 """Update information about the alias table.
1037 """Update information about the alias table.
1036
1038
1037 In particular, make sure no Python keywords/builtins are in it."""
1039 In particular, make sure no Python keywords/builtins are in it."""
1038
1040
1039 no_alias = self.no_alias
1041 no_alias = self.no_alias
1040 for k in self.alias_table.keys():
1042 for k in self.alias_table.keys():
1041 if k in no_alias:
1043 if k in no_alias:
1042 del self.alias_table[k]
1044 del self.alias_table[k]
1043 if verbose:
1045 if verbose:
1044 print ("Deleting alias <%s>, it's a Python "
1046 print ("Deleting alias <%s>, it's a Python "
1045 "keyword or builtin." % k)
1047 "keyword or builtin." % k)
1046
1048
1047 def set_autoindent(self,value=None):
1049 def set_autoindent(self,value=None):
1048 """Set the autoindent flag, checking for readline support.
1050 """Set the autoindent flag, checking for readline support.
1049
1051
1050 If called with no arguments, it acts as a toggle."""
1052 If called with no arguments, it acts as a toggle."""
1051
1053
1052 if not self.has_readline:
1054 if not self.has_readline:
1053 if os.name == 'posix':
1055 if os.name == 'posix':
1054 warn("The auto-indent feature requires the readline library")
1056 warn("The auto-indent feature requires the readline library")
1055 self.autoindent = 0
1057 self.autoindent = 0
1056 return
1058 return
1057 if value is None:
1059 if value is None:
1058 self.autoindent = not self.autoindent
1060 self.autoindent = not self.autoindent
1059 else:
1061 else:
1060 self.autoindent = value
1062 self.autoindent = value
1061
1063
1062 def rc_set_toggle(self,rc_field,value=None):
1064 def rc_set_toggle(self,rc_field,value=None):
1063 """Set or toggle a field in IPython's rc config. structure.
1065 """Set or toggle a field in IPython's rc config. structure.
1064
1066
1065 If called with no arguments, it acts as a toggle.
1067 If called with no arguments, it acts as a toggle.
1066
1068
1067 If called with a non-existent field, the resulting AttributeError
1069 If called with a non-existent field, the resulting AttributeError
1068 exception will propagate out."""
1070 exception will propagate out."""
1069
1071
1070 rc_val = getattr(self.rc,rc_field)
1072 rc_val = getattr(self.rc,rc_field)
1071 if value is None:
1073 if value is None:
1072 value = not rc_val
1074 value = not rc_val
1073 setattr(self.rc,rc_field,value)
1075 setattr(self.rc,rc_field,value)
1074
1076
1075 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1077 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1076 """Install the user configuration directory.
1078 """Install the user configuration directory.
1077
1079
1078 Can be called when running for the first time or to upgrade the user's
1080 Can be called when running for the first time or to upgrade the user's
1079 .ipython/ directory with the mode parameter. Valid modes are 'install'
1081 .ipython/ directory with the mode parameter. Valid modes are 'install'
1080 and 'upgrade'."""
1082 and 'upgrade'."""
1081
1083
1082 def wait():
1084 def wait():
1083 try:
1085 try:
1084 raw_input("Please press <RETURN> to start IPython.")
1086 raw_input("Please press <RETURN> to start IPython.")
1085 except EOFError:
1087 except EOFError:
1086 print >> Term.cout
1088 print >> Term.cout
1087 print '*'*70
1089 print '*'*70
1088
1090
1089 cwd = os.getcwd() # remember where we started
1091 cwd = os.getcwd() # remember where we started
1090 glb = glob.glob
1092 glb = glob.glob
1091 print '*'*70
1093 print '*'*70
1092 if mode == 'install':
1094 if mode == 'install':
1093 print \
1095 print \
1094 """Welcome to IPython. I will try to create a personal configuration directory
1096 """Welcome to IPython. I will try to create a personal configuration directory
1095 where you can customize many aspects of IPython's functionality in:\n"""
1097 where you can customize many aspects of IPython's functionality in:\n"""
1096 else:
1098 else:
1097 print 'I am going to upgrade your configuration in:'
1099 print 'I am going to upgrade your configuration in:'
1098
1100
1099 print ipythondir
1101 print ipythondir
1100
1102
1101 rcdirend = os.path.join('IPython','UserConfig')
1103 rcdirend = os.path.join('IPython','UserConfig')
1102 cfg = lambda d: os.path.join(d,rcdirend)
1104 cfg = lambda d: os.path.join(d,rcdirend)
1103 try:
1105 try:
1104 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1106 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1105 except IOError:
1107 except IOError:
1106 warning = """
1108 warning = """
1107 Installation error. IPython's directory was not found.
1109 Installation error. IPython's directory was not found.
1108
1110
1109 Check the following:
1111 Check the following:
1110
1112
1111 The ipython/IPython directory should be in a directory belonging to your
1113 The ipython/IPython directory should be in a directory belonging to your
1112 PYTHONPATH environment variable (that is, it should be in a directory
1114 PYTHONPATH environment variable (that is, it should be in a directory
1113 belonging to sys.path). You can copy it explicitly there or just link to it.
1115 belonging to sys.path). You can copy it explicitly there or just link to it.
1114
1116
1115 IPython will proceed with builtin defaults.
1117 IPython will proceed with builtin defaults.
1116 """
1118 """
1117 warn(warning)
1119 warn(warning)
1118 wait()
1120 wait()
1119 return
1121 return
1120
1122
1121 if mode == 'install':
1123 if mode == 'install':
1122 try:
1124 try:
1123 shutil.copytree(rcdir,ipythondir)
1125 shutil.copytree(rcdir,ipythondir)
1124 os.chdir(ipythondir)
1126 os.chdir(ipythondir)
1125 rc_files = glb("ipythonrc*")
1127 rc_files = glb("ipythonrc*")
1126 for rc_file in rc_files:
1128 for rc_file in rc_files:
1127 os.rename(rc_file,rc_file+rc_suffix)
1129 os.rename(rc_file,rc_file+rc_suffix)
1128 except:
1130 except:
1129 warning = """
1131 warning = """
1130
1132
1131 There was a problem with the installation:
1133 There was a problem with the installation:
1132 %s
1134 %s
1133 Try to correct it or contact the developers if you think it's a bug.
1135 Try to correct it or contact the developers if you think it's a bug.
1134 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1136 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1135 warn(warning)
1137 warn(warning)
1136 wait()
1138 wait()
1137 return
1139 return
1138
1140
1139 elif mode == 'upgrade':
1141 elif mode == 'upgrade':
1140 try:
1142 try:
1141 os.chdir(ipythondir)
1143 os.chdir(ipythondir)
1142 except:
1144 except:
1143 print """
1145 print """
1144 Can not upgrade: changing to directory %s failed. Details:
1146 Can not upgrade: changing to directory %s failed. Details:
1145 %s
1147 %s
1146 """ % (ipythondir,sys.exc_info()[1])
1148 """ % (ipythondir,sys.exc_info()[1])
1147 wait()
1149 wait()
1148 return
1150 return
1149 else:
1151 else:
1150 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1152 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1151 for new_full_path in sources:
1153 for new_full_path in sources:
1152 new_filename = os.path.basename(new_full_path)
1154 new_filename = os.path.basename(new_full_path)
1153 if new_filename.startswith('ipythonrc'):
1155 if new_filename.startswith('ipythonrc'):
1154 new_filename = new_filename + rc_suffix
1156 new_filename = new_filename + rc_suffix
1155 # The config directory should only contain files, skip any
1157 # The config directory should only contain files, skip any
1156 # directories which may be there (like CVS)
1158 # directories which may be there (like CVS)
1157 if os.path.isdir(new_full_path):
1159 if os.path.isdir(new_full_path):
1158 continue
1160 continue
1159 if os.path.exists(new_filename):
1161 if os.path.exists(new_filename):
1160 old_file = new_filename+'.old'
1162 old_file = new_filename+'.old'
1161 if os.path.exists(old_file):
1163 if os.path.exists(old_file):
1162 os.remove(old_file)
1164 os.remove(old_file)
1163 os.rename(new_filename,old_file)
1165 os.rename(new_filename,old_file)
1164 shutil.copy(new_full_path,new_filename)
1166 shutil.copy(new_full_path,new_filename)
1165 else:
1167 else:
1166 raise ValueError,'unrecognized mode for install:',`mode`
1168 raise ValueError,'unrecognized mode for install:',`mode`
1167
1169
1168 # Fix line-endings to those native to each platform in the config
1170 # Fix line-endings to those native to each platform in the config
1169 # directory.
1171 # directory.
1170 try:
1172 try:
1171 os.chdir(ipythondir)
1173 os.chdir(ipythondir)
1172 except:
1174 except:
1173 print """
1175 print """
1174 Problem: changing to directory %s failed.
1176 Problem: changing to directory %s failed.
1175 Details:
1177 Details:
1176 %s
1178 %s
1177
1179
1178 Some configuration files may have incorrect line endings. This should not
1180 Some configuration files may have incorrect line endings. This should not
1179 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1181 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1180 wait()
1182 wait()
1181 else:
1183 else:
1182 for fname in glb('ipythonrc*'):
1184 for fname in glb('ipythonrc*'):
1183 try:
1185 try:
1184 native_line_ends(fname,backup=0)
1186 native_line_ends(fname,backup=0)
1185 except IOError:
1187 except IOError:
1186 pass
1188 pass
1187
1189
1188 if mode == 'install':
1190 if mode == 'install':
1189 print """
1191 print """
1190 Successful installation!
1192 Successful installation!
1191
1193
1192 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1194 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1193 IPython manual (there are both HTML and PDF versions supplied with the
1195 IPython manual (there are both HTML and PDF versions supplied with the
1194 distribution) to make sure that your system environment is properly configured
1196 distribution) to make sure that your system environment is properly configured
1195 to take advantage of IPython's features.
1197 to take advantage of IPython's features.
1196
1198
1197 Important note: the configuration system has changed! The old system is
1199 Important note: the configuration system has changed! The old system is
1198 still in place, but its setting may be partly overridden by the settings in
1200 still in place, but its setting may be partly overridden by the settings in
1199 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1201 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1200 if some of the new settings bother you.
1202 if some of the new settings bother you.
1201
1203
1202 """
1204 """
1203 else:
1205 else:
1204 print """
1206 print """
1205 Successful upgrade!
1207 Successful upgrade!
1206
1208
1207 All files in your directory:
1209 All files in your directory:
1208 %(ipythondir)s
1210 %(ipythondir)s
1209 which would have been overwritten by the upgrade were backed up with a .old
1211 which would have been overwritten by the upgrade were backed up with a .old
1210 extension. If you had made particular customizations in those files you may
1212 extension. If you had made particular customizations in those files you may
1211 want to merge them back into the new files.""" % locals()
1213 want to merge them back into the new files.""" % locals()
1212 wait()
1214 wait()
1213 os.chdir(cwd)
1215 os.chdir(cwd)
1214 # end user_setup()
1216 # end user_setup()
1215
1217
1216 def atexit_operations(self):
1218 def atexit_operations(self):
1217 """This will be executed at the time of exit.
1219 """This will be executed at the time of exit.
1218
1220
1219 Saving of persistent data should be performed here. """
1221 Saving of persistent data should be performed here. """
1220
1222
1221 #print '*** IPython exit cleanup ***' # dbg
1223 #print '*** IPython exit cleanup ***' # dbg
1222 # input history
1224 # input history
1223 self.savehist()
1225 self.savehist()
1224
1226
1225 # Cleanup all tempfiles left around
1227 # Cleanup all tempfiles left around
1226 for tfile in self.tempfiles:
1228 for tfile in self.tempfiles:
1227 try:
1229 try:
1228 os.unlink(tfile)
1230 os.unlink(tfile)
1229 except OSError:
1231 except OSError:
1230 pass
1232 pass
1231
1233
1232 self.hooks.shutdown_hook()
1234 self.hooks.shutdown_hook()
1233
1235
1234 def savehist(self):
1236 def savehist(self):
1235 """Save input history to a file (via readline library)."""
1237 """Save input history to a file (via readline library)."""
1236 try:
1238 try:
1237 self.readline.write_history_file(self.histfile)
1239 self.readline.write_history_file(self.histfile)
1238 except:
1240 except:
1239 print 'Unable to save IPython command history to file: ' + \
1241 print 'Unable to save IPython command history to file: ' + \
1240 `self.histfile`
1242 `self.histfile`
1241
1243
1242 def reloadhist(self):
1244 def reloadhist(self):
1243 """Reload the input history from disk file."""
1245 """Reload the input history from disk file."""
1244
1246
1245 if self.has_readline:
1247 if self.has_readline:
1246 self.readline.clear_history()
1248 self.readline.clear_history()
1247 self.readline.read_history_file(self.shell.histfile)
1249 self.readline.read_history_file(self.shell.histfile)
1248
1250
1249 def history_saving_wrapper(self, func):
1251 def history_saving_wrapper(self, func):
1250 """ Wrap func for readline history saving
1252 """ Wrap func for readline history saving
1251
1253
1252 Convert func into callable that saves & restores
1254 Convert func into callable that saves & restores
1253 history around the call """
1255 history around the call """
1254
1256
1255 if not self.has_readline:
1257 if not self.has_readline:
1256 return func
1258 return func
1257
1259
1258 def wrapper():
1260 def wrapper():
1259 self.savehist()
1261 self.savehist()
1260 try:
1262 try:
1261 func()
1263 func()
1262 finally:
1264 finally:
1263 readline.read_history_file(self.histfile)
1265 readline.read_history_file(self.histfile)
1264 return wrapper
1266 return wrapper
1265
1267
1266
1268
1267 def pre_readline(self):
1269 def pre_readline(self):
1268 """readline hook to be used at the start of each line.
1270 """readline hook to be used at the start of each line.
1269
1271
1270 Currently it handles auto-indent only."""
1272 Currently it handles auto-indent only."""
1271
1273
1272 #debugx('self.indent_current_nsp','pre_readline:')
1274 #debugx('self.indent_current_nsp','pre_readline:')
1273
1275
1274 if self.rl_do_indent:
1276 if self.rl_do_indent:
1275 self.readline.insert_text(self.indent_current_str())
1277 self.readline.insert_text(self.indent_current_str())
1276 if self.rl_next_input is not None:
1278 if self.rl_next_input is not None:
1277 self.readline.insert_text(self.rl_next_input)
1279 self.readline.insert_text(self.rl_next_input)
1278 self.rl_next_input = None
1280 self.rl_next_input = None
1279
1281
1280 def init_readline(self):
1282 def init_readline(self):
1281 """Command history completion/saving/reloading."""
1283 """Command history completion/saving/reloading."""
1282
1284
1283
1285
1284 import IPython.rlineimpl as readline
1286 import IPython.rlineimpl as readline
1285
1287
1286 if not readline.have_readline:
1288 if not readline.have_readline:
1287 self.has_readline = 0
1289 self.has_readline = 0
1288 self.readline = None
1290 self.readline = None
1289 # no point in bugging windows users with this every time:
1291 # no point in bugging windows users with this every time:
1290 warn('Readline services not available on this platform.')
1292 warn('Readline services not available on this platform.')
1291 else:
1293 else:
1292 sys.modules['readline'] = readline
1294 sys.modules['readline'] = readline
1293 import atexit
1295 import atexit
1294 from IPython.completer import IPCompleter
1296 from IPython.completer import IPCompleter
1295 self.Completer = IPCompleter(self,
1297 self.Completer = IPCompleter(self,
1296 self.user_ns,
1298 self.user_ns,
1297 self.user_global_ns,
1299 self.user_global_ns,
1298 self.rc.readline_omit__names,
1300 self.rc.readline_omit__names,
1299 self.alias_table)
1301 self.alias_table)
1300 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1302 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1301 self.strdispatchers['complete_command'] = sdisp
1303 self.strdispatchers['complete_command'] = sdisp
1302 self.Completer.custom_completers = sdisp
1304 self.Completer.custom_completers = sdisp
1303 # Platform-specific configuration
1305 # Platform-specific configuration
1304 if os.name == 'nt':
1306 if os.name == 'nt':
1305 self.readline_startup_hook = readline.set_pre_input_hook
1307 self.readline_startup_hook = readline.set_pre_input_hook
1306 else:
1308 else:
1307 self.readline_startup_hook = readline.set_startup_hook
1309 self.readline_startup_hook = readline.set_startup_hook
1308
1310
1309 # Load user's initrc file (readline config)
1311 # Load user's initrc file (readline config)
1310 inputrc_name = os.environ.get('INPUTRC')
1312 inputrc_name = os.environ.get('INPUTRC')
1311 if inputrc_name is None:
1313 if inputrc_name is None:
1312 home_dir = get_home_dir()
1314 home_dir = get_home_dir()
1313 if home_dir is not None:
1315 if home_dir is not None:
1314 inputrc_name = os.path.join(home_dir,'.inputrc')
1316 inputrc_name = os.path.join(home_dir,'.inputrc')
1315 if os.path.isfile(inputrc_name):
1317 if os.path.isfile(inputrc_name):
1316 try:
1318 try:
1317 readline.read_init_file(inputrc_name)
1319 readline.read_init_file(inputrc_name)
1318 except:
1320 except:
1319 warn('Problems reading readline initialization file <%s>'
1321 warn('Problems reading readline initialization file <%s>'
1320 % inputrc_name)
1322 % inputrc_name)
1321
1323
1322 self.has_readline = 1
1324 self.has_readline = 1
1323 self.readline = readline
1325 self.readline = readline
1324 # save this in sys so embedded copies can restore it properly
1326 # save this in sys so embedded copies can restore it properly
1325 sys.ipcompleter = self.Completer.complete
1327 sys.ipcompleter = self.Completer.complete
1326 self.set_completer()
1328 self.set_completer()
1327
1329
1328 # Configure readline according to user's prefs
1330 # Configure readline according to user's prefs
1329 for rlcommand in self.rc.readline_parse_and_bind:
1331 for rlcommand in self.rc.readline_parse_and_bind:
1330 readline.parse_and_bind(rlcommand)
1332 readline.parse_and_bind(rlcommand)
1331
1333
1332 # remove some chars from the delimiters list
1334 # remove some chars from the delimiters list
1333 delims = readline.get_completer_delims()
1335 delims = readline.get_completer_delims()
1334 delims = delims.translate(string._idmap,
1336 delims = delims.translate(string._idmap,
1335 self.rc.readline_remove_delims)
1337 self.rc.readline_remove_delims)
1336 readline.set_completer_delims(delims)
1338 readline.set_completer_delims(delims)
1337 # otherwise we end up with a monster history after a while:
1339 # otherwise we end up with a monster history after a while:
1338 readline.set_history_length(1000)
1340 readline.set_history_length(1000)
1339 try:
1341 try:
1340 #print '*** Reading readline history' # dbg
1342 #print '*** Reading readline history' # dbg
1341 readline.read_history_file(self.histfile)
1343 readline.read_history_file(self.histfile)
1342 except IOError:
1344 except IOError:
1343 pass # It doesn't exist yet.
1345 pass # It doesn't exist yet.
1344
1346
1345 atexit.register(self.atexit_operations)
1347 atexit.register(self.atexit_operations)
1346 del atexit
1348 del atexit
1347
1349
1348 # Configure auto-indent for all platforms
1350 # Configure auto-indent for all platforms
1349 self.set_autoindent(self.rc.autoindent)
1351 self.set_autoindent(self.rc.autoindent)
1350
1352
1351 def ask_yes_no(self,prompt,default=True):
1353 def ask_yes_no(self,prompt,default=True):
1352 if self.rc.quiet:
1354 if self.rc.quiet:
1353 return True
1355 return True
1354 return ask_yes_no(prompt,default)
1356 return ask_yes_no(prompt,default)
1355
1357
1356 def _should_recompile(self,e):
1358 def _should_recompile(self,e):
1357 """Utility routine for edit_syntax_error"""
1359 """Utility routine for edit_syntax_error"""
1358
1360
1359 if e.filename in ('<ipython console>','<input>','<string>',
1361 if e.filename in ('<ipython console>','<input>','<string>',
1360 '<console>','<BackgroundJob compilation>',
1362 '<console>','<BackgroundJob compilation>',
1361 None):
1363 None):
1362
1364
1363 return False
1365 return False
1364 try:
1366 try:
1365 if (self.rc.autoedit_syntax and
1367 if (self.rc.autoedit_syntax and
1366 not self.ask_yes_no('Return to editor to correct syntax error? '
1368 not self.ask_yes_no('Return to editor to correct syntax error? '
1367 '[Y/n] ','y')):
1369 '[Y/n] ','y')):
1368 return False
1370 return False
1369 except EOFError:
1371 except EOFError:
1370 return False
1372 return False
1371
1373
1372 def int0(x):
1374 def int0(x):
1373 try:
1375 try:
1374 return int(x)
1376 return int(x)
1375 except TypeError:
1377 except TypeError:
1376 return 0
1378 return 0
1377 # always pass integer line and offset values to editor hook
1379 # always pass integer line and offset values to editor hook
1378 self.hooks.fix_error_editor(e.filename,
1380 self.hooks.fix_error_editor(e.filename,
1379 int0(e.lineno),int0(e.offset),e.msg)
1381 int0(e.lineno),int0(e.offset),e.msg)
1380 return True
1382 return True
1381
1383
1382 def edit_syntax_error(self):
1384 def edit_syntax_error(self):
1383 """The bottom half of the syntax error handler called in the main loop.
1385 """The bottom half of the syntax error handler called in the main loop.
1384
1386
1385 Loop until syntax error is fixed or user cancels.
1387 Loop until syntax error is fixed or user cancels.
1386 """
1388 """
1387
1389
1388 while self.SyntaxTB.last_syntax_error:
1390 while self.SyntaxTB.last_syntax_error:
1389 # copy and clear last_syntax_error
1391 # copy and clear last_syntax_error
1390 err = self.SyntaxTB.clear_err_state()
1392 err = self.SyntaxTB.clear_err_state()
1391 if not self._should_recompile(err):
1393 if not self._should_recompile(err):
1392 return
1394 return
1393 try:
1395 try:
1394 # may set last_syntax_error again if a SyntaxError is raised
1396 # may set last_syntax_error again if a SyntaxError is raised
1395 self.safe_execfile(err.filename,self.user_ns)
1397 self.safe_execfile(err.filename,self.user_ns)
1396 except:
1398 except:
1397 self.showtraceback()
1399 self.showtraceback()
1398 else:
1400 else:
1399 try:
1401 try:
1400 f = file(err.filename)
1402 f = file(err.filename)
1401 try:
1403 try:
1402 sys.displayhook(f.read())
1404 sys.displayhook(f.read())
1403 finally:
1405 finally:
1404 f.close()
1406 f.close()
1405 except:
1407 except:
1406 self.showtraceback()
1408 self.showtraceback()
1407
1409
1408 def showsyntaxerror(self, filename=None):
1410 def showsyntaxerror(self, filename=None):
1409 """Display the syntax error that just occurred.
1411 """Display the syntax error that just occurred.
1410
1412
1411 This doesn't display a stack trace because there isn't one.
1413 This doesn't display a stack trace because there isn't one.
1412
1414
1413 If a filename is given, it is stuffed in the exception instead
1415 If a filename is given, it is stuffed in the exception instead
1414 of what was there before (because Python's parser always uses
1416 of what was there before (because Python's parser always uses
1415 "<string>" when reading from a string).
1417 "<string>" when reading from a string).
1416 """
1418 """
1417 etype, value, last_traceback = sys.exc_info()
1419 etype, value, last_traceback = sys.exc_info()
1418
1420
1419 # See note about these variables in showtraceback() below
1421 # See note about these variables in showtraceback() below
1420 sys.last_type = etype
1422 sys.last_type = etype
1421 sys.last_value = value
1423 sys.last_value = value
1422 sys.last_traceback = last_traceback
1424 sys.last_traceback = last_traceback
1423
1425
1424 if filename and etype is SyntaxError:
1426 if filename and etype is SyntaxError:
1425 # Work hard to stuff the correct filename in the exception
1427 # Work hard to stuff the correct filename in the exception
1426 try:
1428 try:
1427 msg, (dummy_filename, lineno, offset, line) = value
1429 msg, (dummy_filename, lineno, offset, line) = value
1428 except:
1430 except:
1429 # Not the format we expect; leave it alone
1431 # Not the format we expect; leave it alone
1430 pass
1432 pass
1431 else:
1433 else:
1432 # Stuff in the right filename
1434 # Stuff in the right filename
1433 try:
1435 try:
1434 # Assume SyntaxError is a class exception
1436 # Assume SyntaxError is a class exception
1435 value = SyntaxError(msg, (filename, lineno, offset, line))
1437 value = SyntaxError(msg, (filename, lineno, offset, line))
1436 except:
1438 except:
1437 # If that failed, assume SyntaxError is a string
1439 # If that failed, assume SyntaxError is a string
1438 value = msg, (filename, lineno, offset, line)
1440 value = msg, (filename, lineno, offset, line)
1439 self.SyntaxTB(etype,value,[])
1441 self.SyntaxTB(etype,value,[])
1440
1442
1441 def debugger(self,force=False):
1443 def debugger(self,force=False):
1442 """Call the pydb/pdb debugger.
1444 """Call the pydb/pdb debugger.
1443
1445
1444 Keywords:
1446 Keywords:
1445
1447
1446 - force(False): by default, this routine checks the instance call_pdb
1448 - force(False): by default, this routine checks the instance call_pdb
1447 flag and does not actually invoke the debugger if the flag is false.
1449 flag and does not actually invoke the debugger if the flag is false.
1448 The 'force' option forces the debugger to activate even if the flag
1450 The 'force' option forces the debugger to activate even if the flag
1449 is false.
1451 is false.
1450 """
1452 """
1451
1453
1452 if not (force or self.call_pdb):
1454 if not (force or self.call_pdb):
1453 return
1455 return
1454
1456
1455 if not hasattr(sys,'last_traceback'):
1457 if not hasattr(sys,'last_traceback'):
1456 error('No traceback has been produced, nothing to debug.')
1458 error('No traceback has been produced, nothing to debug.')
1457 return
1459 return
1458
1460
1459 # use pydb if available
1461 # use pydb if available
1460 if Debugger.has_pydb:
1462 if Debugger.has_pydb:
1461 from pydb import pm
1463 from pydb import pm
1462 else:
1464 else:
1463 # fallback to our internal debugger
1465 # fallback to our internal debugger
1464 pm = lambda : self.InteractiveTB.debugger(force=True)
1466 pm = lambda : self.InteractiveTB.debugger(force=True)
1465 self.history_saving_wrapper(pm)()
1467 self.history_saving_wrapper(pm)()
1466
1468
1467 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1469 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1468 """Display the exception that just occurred.
1470 """Display the exception that just occurred.
1469
1471
1470 If nothing is known about the exception, this is the method which
1472 If nothing is known about the exception, this is the method which
1471 should be used throughout the code for presenting user tracebacks,
1473 should be used throughout the code for presenting user tracebacks,
1472 rather than directly invoking the InteractiveTB object.
1474 rather than directly invoking the InteractiveTB object.
1473
1475
1474 A specific showsyntaxerror() also exists, but this method can take
1476 A specific showsyntaxerror() also exists, but this method can take
1475 care of calling it if needed, so unless you are explicitly catching a
1477 care of calling it if needed, so unless you are explicitly catching a
1476 SyntaxError exception, don't try to analyze the stack manually and
1478 SyntaxError exception, don't try to analyze the stack manually and
1477 simply call this method."""
1479 simply call this method."""
1478
1480
1479
1481
1480 # Though this won't be called by syntax errors in the input line,
1482 # Though this won't be called by syntax errors in the input line,
1481 # there may be SyntaxError cases whith imported code.
1483 # there may be SyntaxError cases whith imported code.
1482
1484
1483
1485
1484 if exc_tuple is None:
1486 if exc_tuple is None:
1485 etype, value, tb = sys.exc_info()
1487 etype, value, tb = sys.exc_info()
1486 else:
1488 else:
1487 etype, value, tb = exc_tuple
1489 etype, value, tb = exc_tuple
1488
1490
1489 if etype is SyntaxError:
1491 if etype is SyntaxError:
1490 self.showsyntaxerror(filename)
1492 self.showsyntaxerror(filename)
1491 elif etype is IPython.ipapi.UsageError:
1493 elif etype is IPython.ipapi.UsageError:
1492 print "UsageError:", value
1494 print "UsageError:", value
1493 else:
1495 else:
1494 # WARNING: these variables are somewhat deprecated and not
1496 # WARNING: these variables are somewhat deprecated and not
1495 # necessarily safe to use in a threaded environment, but tools
1497 # necessarily safe to use in a threaded environment, but tools
1496 # like pdb depend on their existence, so let's set them. If we
1498 # like pdb depend on their existence, so let's set them. If we
1497 # find problems in the field, we'll need to revisit their use.
1499 # find problems in the field, we'll need to revisit their use.
1498 sys.last_type = etype
1500 sys.last_type = etype
1499 sys.last_value = value
1501 sys.last_value = value
1500 sys.last_traceback = tb
1502 sys.last_traceback = tb
1501
1503
1502 if etype in self.custom_exceptions:
1504 if etype in self.custom_exceptions:
1503 self.CustomTB(etype,value,tb)
1505 self.CustomTB(etype,value,tb)
1504 else:
1506 else:
1505 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1507 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1506 if self.InteractiveTB.call_pdb and self.has_readline:
1508 if self.InteractiveTB.call_pdb and self.has_readline:
1507 # pdb mucks up readline, fix it back
1509 # pdb mucks up readline, fix it back
1508 self.set_completer()
1510 self.set_completer()
1509
1511
1510
1512
1511 def mainloop(self,banner=None):
1513 def mainloop(self,banner=None):
1512 """Creates the local namespace and starts the mainloop.
1514 """Creates the local namespace and starts the mainloop.
1513
1515
1514 If an optional banner argument is given, it will override the
1516 If an optional banner argument is given, it will override the
1515 internally created default banner."""
1517 internally created default banner."""
1516
1518
1517 if self.rc.c: # Emulate Python's -c option
1519 if self.rc.c: # Emulate Python's -c option
1518 self.exec_init_cmd()
1520 self.exec_init_cmd()
1519 if banner is None:
1521 if banner is None:
1520 if not self.rc.banner:
1522 if not self.rc.banner:
1521 banner = ''
1523 banner = ''
1522 # banner is string? Use it directly!
1524 # banner is string? Use it directly!
1523 elif isinstance(self.rc.banner,basestring):
1525 elif isinstance(self.rc.banner,basestring):
1524 banner = self.rc.banner
1526 banner = self.rc.banner
1525 else:
1527 else:
1526 banner = self.BANNER+self.banner2
1528 banner = self.BANNER+self.banner2
1527
1529
1528 self.interact(banner)
1530 self.interact(banner)
1529
1531
1530 def exec_init_cmd(self):
1532 def exec_init_cmd(self):
1531 """Execute a command given at the command line.
1533 """Execute a command given at the command line.
1532
1534
1533 This emulates Python's -c option."""
1535 This emulates Python's -c option."""
1534
1536
1535 #sys.argv = ['-c']
1537 #sys.argv = ['-c']
1536 self.push(self.prefilter(self.rc.c, False))
1538 self.push(self.prefilter(self.rc.c, False))
1537 if not self.rc.interact:
1539 if not self.rc.interact:
1538 self.exit_now = True
1540 self.exit_now = True
1539
1541
1540 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1542 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1541 """Embeds IPython into a running python program.
1543 """Embeds IPython into a running python program.
1542
1544
1543 Input:
1545 Input:
1544
1546
1545 - header: An optional header message can be specified.
1547 - header: An optional header message can be specified.
1546
1548
1547 - local_ns, global_ns: working namespaces. If given as None, the
1549 - local_ns, global_ns: working namespaces. If given as None, the
1548 IPython-initialized one is updated with __main__.__dict__, so that
1550 IPython-initialized one is updated with __main__.__dict__, so that
1549 program variables become visible but user-specific configuration
1551 program variables become visible but user-specific configuration
1550 remains possible.
1552 remains possible.
1551
1553
1552 - stack_depth: specifies how many levels in the stack to go to
1554 - stack_depth: specifies how many levels in the stack to go to
1553 looking for namespaces (when local_ns and global_ns are None). This
1555 looking for namespaces (when local_ns and global_ns are None). This
1554 allows an intermediate caller to make sure that this function gets
1556 allows an intermediate caller to make sure that this function gets
1555 the namespace from the intended level in the stack. By default (0)
1557 the namespace from the intended level in the stack. By default (0)
1556 it will get its locals and globals from the immediate caller.
1558 it will get its locals and globals from the immediate caller.
1557
1559
1558 Warning: it's possible to use this in a program which is being run by
1560 Warning: it's possible to use this in a program which is being run by
1559 IPython itself (via %run), but some funny things will happen (a few
1561 IPython itself (via %run), but some funny things will happen (a few
1560 globals get overwritten). In the future this will be cleaned up, as
1562 globals get overwritten). In the future this will be cleaned up, as
1561 there is no fundamental reason why it can't work perfectly."""
1563 there is no fundamental reason why it can't work perfectly."""
1562
1564
1563 # Get locals and globals from caller
1565 # Get locals and globals from caller
1564 if local_ns is None or global_ns is None:
1566 if local_ns is None or global_ns is None:
1565 call_frame = sys._getframe(stack_depth).f_back
1567 call_frame = sys._getframe(stack_depth).f_back
1566
1568
1567 if local_ns is None:
1569 if local_ns is None:
1568 local_ns = call_frame.f_locals
1570 local_ns = call_frame.f_locals
1569 if global_ns is None:
1571 if global_ns is None:
1570 global_ns = call_frame.f_globals
1572 global_ns = call_frame.f_globals
1571
1573
1572 # Update namespaces and fire up interpreter
1574 # Update namespaces and fire up interpreter
1573
1575
1574 # The global one is easy, we can just throw it in
1576 # The global one is easy, we can just throw it in
1575 self.user_global_ns = global_ns
1577 self.user_global_ns = global_ns
1576
1578
1577 # but the user/local one is tricky: ipython needs it to store internal
1579 # but the user/local one is tricky: ipython needs it to store internal
1578 # data, but we also need the locals. We'll copy locals in the user
1580 # data, but we also need the locals. We'll copy locals in the user
1579 # one, but will track what got copied so we can delete them at exit.
1581 # one, but will track what got copied so we can delete them at exit.
1580 # This is so that a later embedded call doesn't see locals from a
1582 # This is so that a later embedded call doesn't see locals from a
1581 # previous call (which most likely existed in a separate scope).
1583 # previous call (which most likely existed in a separate scope).
1582 local_varnames = local_ns.keys()
1584 local_varnames = local_ns.keys()
1583 self.user_ns.update(local_ns)
1585 self.user_ns.update(local_ns)
1584
1586
1585 # Patch for global embedding to make sure that things don't overwrite
1587 # Patch for global embedding to make sure that things don't overwrite
1586 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1588 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1587 # FIXME. Test this a bit more carefully (the if.. is new)
1589 # FIXME. Test this a bit more carefully (the if.. is new)
1588 if local_ns is None and global_ns is None:
1590 if local_ns is None and global_ns is None:
1589 self.user_global_ns.update(__main__.__dict__)
1591 self.user_global_ns.update(__main__.__dict__)
1590
1592
1591 # make sure the tab-completer has the correct frame information, so it
1593 # make sure the tab-completer has the correct frame information, so it
1592 # actually completes using the frame's locals/globals
1594 # actually completes using the frame's locals/globals
1593 self.set_completer_frame()
1595 self.set_completer_frame()
1594
1596
1595 # before activating the interactive mode, we need to make sure that
1597 # before activating the interactive mode, we need to make sure that
1596 # all names in the builtin namespace needed by ipython point to
1598 # all names in the builtin namespace needed by ipython point to
1597 # ourselves, and not to other instances.
1599 # ourselves, and not to other instances.
1598 self.add_builtins()
1600 self.add_builtins()
1599
1601
1600 self.interact(header)
1602 self.interact(header)
1601
1603
1602 # now, purge out the user namespace from anything we might have added
1604 # now, purge out the user namespace from anything we might have added
1603 # from the caller's local namespace
1605 # from the caller's local namespace
1604 delvar = self.user_ns.pop
1606 delvar = self.user_ns.pop
1605 for var in local_varnames:
1607 for var in local_varnames:
1606 delvar(var,None)
1608 delvar(var,None)
1607 # and clean builtins we may have overridden
1609 # and clean builtins we may have overridden
1608 self.clean_builtins()
1610 self.clean_builtins()
1609
1611
1610 def interact(self, banner=None):
1612 def interact(self, banner=None):
1611 """Closely emulate the interactive Python console.
1613 """Closely emulate the interactive Python console.
1612
1614
1613 The optional banner argument specify the banner to print
1615 The optional banner argument specify the banner to print
1614 before the first interaction; by default it prints a banner
1616 before the first interaction; by default it prints a banner
1615 similar to the one printed by the real Python interpreter,
1617 similar to the one printed by the real Python interpreter,
1616 followed by the current class name in parentheses (so as not
1618 followed by the current class name in parentheses (so as not
1617 to confuse this with the real interpreter -- since it's so
1619 to confuse this with the real interpreter -- since it's so
1618 close!).
1620 close!).
1619
1621
1620 """
1622 """
1621
1623
1622 if self.exit_now:
1624 if self.exit_now:
1623 # batch run -> do not interact
1625 # batch run -> do not interact
1624 return
1626 return
1625 cprt = 'Type "copyright", "credits" or "license" for more information.'
1627 cprt = 'Type "copyright", "credits" or "license" for more information.'
1626 if banner is None:
1628 if banner is None:
1627 self.write("Python %s on %s\n%s\n(%s)\n" %
1629 self.write("Python %s on %s\n%s\n(%s)\n" %
1628 (sys.version, sys.platform, cprt,
1630 (sys.version, sys.platform, cprt,
1629 self.__class__.__name__))
1631 self.__class__.__name__))
1630 else:
1632 else:
1631 self.write(banner)
1633 self.write(banner)
1632
1634
1633 more = 0
1635 more = 0
1634
1636
1635 # Mark activity in the builtins
1637 # Mark activity in the builtins
1636 __builtin__.__dict__['__IPYTHON__active'] += 1
1638 __builtin__.__dict__['__IPYTHON__active'] += 1
1637
1639
1638 if self.has_readline:
1640 if self.has_readline:
1639 self.readline_startup_hook(self.pre_readline)
1641 self.readline_startup_hook(self.pre_readline)
1640 # exit_now is set by a call to %Exit or %Quit
1642 # exit_now is set by a call to %Exit or %Quit
1641
1643
1642 while not self.exit_now:
1644 while not self.exit_now:
1643 if more:
1645 if more:
1644 prompt = self.hooks.generate_prompt(True)
1646 prompt = self.hooks.generate_prompt(True)
1645 if self.autoindent:
1647 if self.autoindent:
1646 self.rl_do_indent = True
1648 self.rl_do_indent = True
1647
1649
1648 else:
1650 else:
1649 prompt = self.hooks.generate_prompt(False)
1651 prompt = self.hooks.generate_prompt(False)
1650 try:
1652 try:
1651 line = self.raw_input(prompt,more)
1653 line = self.raw_input(prompt,more)
1652 if self.exit_now:
1654 if self.exit_now:
1653 # quick exit on sys.std[in|out] close
1655 # quick exit on sys.std[in|out] close
1654 break
1656 break
1655 if self.autoindent:
1657 if self.autoindent:
1656 self.rl_do_indent = False
1658 self.rl_do_indent = False
1657
1659
1658 except KeyboardInterrupt:
1660 except KeyboardInterrupt:
1659 self.write('\nKeyboardInterrupt\n')
1661 self.write('\nKeyboardInterrupt\n')
1660 self.resetbuffer()
1662 self.resetbuffer()
1661 # keep cache in sync with the prompt counter:
1663 # keep cache in sync with the prompt counter:
1662 self.outputcache.prompt_count -= 1
1664 self.outputcache.prompt_count -= 1
1663
1665
1664 if self.autoindent:
1666 if self.autoindent:
1665 self.indent_current_nsp = 0
1667 self.indent_current_nsp = 0
1666 more = 0
1668 more = 0
1667 except EOFError:
1669 except EOFError:
1668 if self.autoindent:
1670 if self.autoindent:
1669 self.rl_do_indent = False
1671 self.rl_do_indent = False
1670 self.readline_startup_hook(None)
1672 self.readline_startup_hook(None)
1671 self.write('\n')
1673 self.write('\n')
1672 self.exit()
1674 self.exit()
1673 except bdb.BdbQuit:
1675 except bdb.BdbQuit:
1674 warn('The Python debugger has exited with a BdbQuit exception.\n'
1676 warn('The Python debugger has exited with a BdbQuit exception.\n'
1675 'Because of how pdb handles the stack, it is impossible\n'
1677 'Because of how pdb handles the stack, it is impossible\n'
1676 'for IPython to properly format this particular exception.\n'
1678 'for IPython to properly format this particular exception.\n'
1677 'IPython will resume normal operation.')
1679 'IPython will resume normal operation.')
1678 except:
1680 except:
1679 # exceptions here are VERY RARE, but they can be triggered
1681 # exceptions here are VERY RARE, but they can be triggered
1680 # asynchronously by signal handlers, for example.
1682 # asynchronously by signal handlers, for example.
1681 self.showtraceback()
1683 self.showtraceback()
1682 else:
1684 else:
1683 more = self.push(line)
1685 more = self.push(line)
1684 if (self.SyntaxTB.last_syntax_error and
1686 if (self.SyntaxTB.last_syntax_error and
1685 self.rc.autoedit_syntax):
1687 self.rc.autoedit_syntax):
1686 self.edit_syntax_error()
1688 self.edit_syntax_error()
1687
1689
1688 # We are off again...
1690 # We are off again...
1689 __builtin__.__dict__['__IPYTHON__active'] -= 1
1691 __builtin__.__dict__['__IPYTHON__active'] -= 1
1690
1692
1691 def excepthook(self, etype, value, tb):
1693 def excepthook(self, etype, value, tb):
1692 """One more defense for GUI apps that call sys.excepthook.
1694 """One more defense for GUI apps that call sys.excepthook.
1693
1695
1694 GUI frameworks like wxPython trap exceptions and call
1696 GUI frameworks like wxPython trap exceptions and call
1695 sys.excepthook themselves. I guess this is a feature that
1697 sys.excepthook themselves. I guess this is a feature that
1696 enables them to keep running after exceptions that would
1698 enables them to keep running after exceptions that would
1697 otherwise kill their mainloop. This is a bother for IPython
1699 otherwise kill their mainloop. This is a bother for IPython
1698 which excepts to catch all of the program exceptions with a try:
1700 which excepts to catch all of the program exceptions with a try:
1699 except: statement.
1701 except: statement.
1700
1702
1701 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1703 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1702 any app directly invokes sys.excepthook, it will look to the user like
1704 any app directly invokes sys.excepthook, it will look to the user like
1703 IPython crashed. In order to work around this, we can disable the
1705 IPython crashed. In order to work around this, we can disable the
1704 CrashHandler and replace it with this excepthook instead, which prints a
1706 CrashHandler and replace it with this excepthook instead, which prints a
1705 regular traceback using our InteractiveTB. In this fashion, apps which
1707 regular traceback using our InteractiveTB. In this fashion, apps which
1706 call sys.excepthook will generate a regular-looking exception from
1708 call sys.excepthook will generate a regular-looking exception from
1707 IPython, and the CrashHandler will only be triggered by real IPython
1709 IPython, and the CrashHandler will only be triggered by real IPython
1708 crashes.
1710 crashes.
1709
1711
1710 This hook should be used sparingly, only in places which are not likely
1712 This hook should be used sparingly, only in places which are not likely
1711 to be true IPython errors.
1713 to be true IPython errors.
1712 """
1714 """
1713 self.showtraceback((etype,value,tb),tb_offset=0)
1715 self.showtraceback((etype,value,tb),tb_offset=0)
1714
1716
1715 def expand_aliases(self,fn,rest):
1717 def expand_aliases(self,fn,rest):
1716 """ Expand multiple levels of aliases:
1718 """ Expand multiple levels of aliases:
1717
1719
1718 if:
1720 if:
1719
1721
1720 alias foo bar /tmp
1722 alias foo bar /tmp
1721 alias baz foo
1723 alias baz foo
1722
1724
1723 then:
1725 then:
1724
1726
1725 baz huhhahhei -> bar /tmp huhhahhei
1727 baz huhhahhei -> bar /tmp huhhahhei
1726
1728
1727 """
1729 """
1728 line = fn + " " + rest
1730 line = fn + " " + rest
1729
1731
1730 done = Set()
1732 done = Set()
1731 while 1:
1733 while 1:
1732 pre,fn,rest = prefilter.splitUserInput(line,
1734 pre,fn,rest = prefilter.splitUserInput(line,
1733 prefilter.shell_line_split)
1735 prefilter.shell_line_split)
1734 if fn in self.alias_table:
1736 if fn in self.alias_table:
1735 if fn in done:
1737 if fn in done:
1736 warn("Cyclic alias definition, repeated '%s'" % fn)
1738 warn("Cyclic alias definition, repeated '%s'" % fn)
1737 return ""
1739 return ""
1738 done.add(fn)
1740 done.add(fn)
1739
1741
1740 l2 = self.transform_alias(fn,rest)
1742 l2 = self.transform_alias(fn,rest)
1741 # dir -> dir
1743 # dir -> dir
1742 # print "alias",line, "->",l2 #dbg
1744 # print "alias",line, "->",l2 #dbg
1743 if l2 == line:
1745 if l2 == line:
1744 break
1746 break
1745 # ls -> ls -F should not recurse forever
1747 # ls -> ls -F should not recurse forever
1746 if l2.split(None,1)[0] == line.split(None,1)[0]:
1748 if l2.split(None,1)[0] == line.split(None,1)[0]:
1747 line = l2
1749 line = l2
1748 break
1750 break
1749
1751
1750 line=l2
1752 line=l2
1751
1753
1752
1754
1753 # print "al expand to",line #dbg
1755 # print "al expand to",line #dbg
1754 else:
1756 else:
1755 break
1757 break
1756
1758
1757 return line
1759 return line
1758
1760
1759 def transform_alias(self, alias,rest=''):
1761 def transform_alias(self, alias,rest=''):
1760 """ Transform alias to system command string.
1762 """ Transform alias to system command string.
1761 """
1763 """
1762 trg = self.alias_table[alias]
1764 trg = self.alias_table[alias]
1763
1765
1764 nargs,cmd = trg
1766 nargs,cmd = trg
1765 # print trg #dbg
1767 # print trg #dbg
1766 if ' ' in cmd and os.path.isfile(cmd):
1768 if ' ' in cmd and os.path.isfile(cmd):
1767 cmd = '"%s"' % cmd
1769 cmd = '"%s"' % cmd
1768
1770
1769 # Expand the %l special to be the user's input line
1771 # Expand the %l special to be the user's input line
1770 if cmd.find('%l') >= 0:
1772 if cmd.find('%l') >= 0:
1771 cmd = cmd.replace('%l',rest)
1773 cmd = cmd.replace('%l',rest)
1772 rest = ''
1774 rest = ''
1773 if nargs==0:
1775 if nargs==0:
1774 # Simple, argument-less aliases
1776 # Simple, argument-less aliases
1775 cmd = '%s %s' % (cmd,rest)
1777 cmd = '%s %s' % (cmd,rest)
1776 else:
1778 else:
1777 # Handle aliases with positional arguments
1779 # Handle aliases with positional arguments
1778 args = rest.split(None,nargs)
1780 args = rest.split(None,nargs)
1779 if len(args)< nargs:
1781 if len(args)< nargs:
1780 error('Alias <%s> requires %s arguments, %s given.' %
1782 error('Alias <%s> requires %s arguments, %s given.' %
1781 (alias,nargs,len(args)))
1783 (alias,nargs,len(args)))
1782 return None
1784 return None
1783 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1785 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1784 # Now call the macro, evaluating in the user's namespace
1786 # Now call the macro, evaluating in the user's namespace
1785 #print 'new command: <%r>' % cmd # dbg
1787 #print 'new command: <%r>' % cmd # dbg
1786 return cmd
1788 return cmd
1787
1789
1788 def call_alias(self,alias,rest=''):
1790 def call_alias(self,alias,rest=''):
1789 """Call an alias given its name and the rest of the line.
1791 """Call an alias given its name and the rest of the line.
1790
1792
1791 This is only used to provide backwards compatibility for users of
1793 This is only used to provide backwards compatibility for users of
1792 ipalias(), use of which is not recommended for anymore."""
1794 ipalias(), use of which is not recommended for anymore."""
1793
1795
1794 # Now call the macro, evaluating in the user's namespace
1796 # Now call the macro, evaluating in the user's namespace
1795 cmd = self.transform_alias(alias, rest)
1797 cmd = self.transform_alias(alias, rest)
1796 try:
1798 try:
1797 self.system(cmd)
1799 self.system(cmd)
1798 except:
1800 except:
1799 self.showtraceback()
1801 self.showtraceback()
1800
1802
1801 def indent_current_str(self):
1803 def indent_current_str(self):
1802 """return the current level of indentation as a string"""
1804 """return the current level of indentation as a string"""
1803 return self.indent_current_nsp * ' '
1805 return self.indent_current_nsp * ' '
1804
1806
1805 def autoindent_update(self,line):
1807 def autoindent_update(self,line):
1806 """Keep track of the indent level."""
1808 """Keep track of the indent level."""
1807
1809
1808 #debugx('line')
1810 #debugx('line')
1809 #debugx('self.indent_current_nsp')
1811 #debugx('self.indent_current_nsp')
1810 if self.autoindent:
1812 if self.autoindent:
1811 if line:
1813 if line:
1812 inisp = num_ini_spaces(line)
1814 inisp = num_ini_spaces(line)
1813 if inisp < self.indent_current_nsp:
1815 if inisp < self.indent_current_nsp:
1814 self.indent_current_nsp = inisp
1816 self.indent_current_nsp = inisp
1815
1817
1816 if line[-1] == ':':
1818 if line[-1] == ':':
1817 self.indent_current_nsp += 4
1819 self.indent_current_nsp += 4
1818 elif dedent_re.match(line):
1820 elif dedent_re.match(line):
1819 self.indent_current_nsp -= 4
1821 self.indent_current_nsp -= 4
1820 else:
1822 else:
1821 self.indent_current_nsp = 0
1823 self.indent_current_nsp = 0
1822 def runlines(self,lines):
1824 def runlines(self,lines):
1823 """Run a string of one or more lines of source.
1825 """Run a string of one or more lines of source.
1824
1826
1825 This method is capable of running a string containing multiple source
1827 This method is capable of running a string containing multiple source
1826 lines, as if they had been entered at the IPython prompt. Since it
1828 lines, as if they had been entered at the IPython prompt. Since it
1827 exposes IPython's processing machinery, the given strings can contain
1829 exposes IPython's processing machinery, the given strings can contain
1828 magic calls (%magic), special shell access (!cmd), etc."""
1830 magic calls (%magic), special shell access (!cmd), etc."""
1829
1831
1830 # We must start with a clean buffer, in case this is run from an
1832 # We must start with a clean buffer, in case this is run from an
1831 # interactive IPython session (via a magic, for example).
1833 # interactive IPython session (via a magic, for example).
1832 self.resetbuffer()
1834 self.resetbuffer()
1833 lines = lines.split('\n')
1835 lines = lines.split('\n')
1834 more = 0
1836 more = 0
1835
1837
1836 for line in lines:
1838 for line in lines:
1837 # skip blank lines so we don't mess up the prompt counter, but do
1839 # skip blank lines so we don't mess up the prompt counter, but do
1838 # NOT skip even a blank line if we are in a code block (more is
1840 # NOT skip even a blank line if we are in a code block (more is
1839 # true)
1841 # true)
1840
1842
1841
1843
1842 if line or more:
1844 if line or more:
1843 # push to raw history, so hist line numbers stay in sync
1845 # push to raw history, so hist line numbers stay in sync
1844 self.input_hist_raw.append("# " + line + "\n")
1846 self.input_hist_raw.append("# " + line + "\n")
1845 more = self.push(self.prefilter(line,more))
1847 more = self.push(self.prefilter(line,more))
1846 # IPython's runsource returns None if there was an error
1848 # IPython's runsource returns None if there was an error
1847 # compiling the code. This allows us to stop processing right
1849 # compiling the code. This allows us to stop processing right
1848 # away, so the user gets the error message at the right place.
1850 # away, so the user gets the error message at the right place.
1849 if more is None:
1851 if more is None:
1850 break
1852 break
1851 else:
1853 else:
1852 self.input_hist_raw.append("\n")
1854 self.input_hist_raw.append("\n")
1853 # final newline in case the input didn't have it, so that the code
1855 # final newline in case the input didn't have it, so that the code
1854 # actually does get executed
1856 # actually does get executed
1855 if more:
1857 if more:
1856 self.push('\n')
1858 self.push('\n')
1857
1859
1858 def runsource(self, source, filename='<input>', symbol='single'):
1860 def runsource(self, source, filename='<input>', symbol='single'):
1859 """Compile and run some source in the interpreter.
1861 """Compile and run some source in the interpreter.
1860
1862
1861 Arguments are as for compile_command().
1863 Arguments are as for compile_command().
1862
1864
1863 One several things can happen:
1865 One several things can happen:
1864
1866
1865 1) The input is incorrect; compile_command() raised an
1867 1) The input is incorrect; compile_command() raised an
1866 exception (SyntaxError or OverflowError). A syntax traceback
1868 exception (SyntaxError or OverflowError). A syntax traceback
1867 will be printed by calling the showsyntaxerror() method.
1869 will be printed by calling the showsyntaxerror() method.
1868
1870
1869 2) The input is incomplete, and more input is required;
1871 2) The input is incomplete, and more input is required;
1870 compile_command() returned None. Nothing happens.
1872 compile_command() returned None. Nothing happens.
1871
1873
1872 3) The input is complete; compile_command() returned a code
1874 3) The input is complete; compile_command() returned a code
1873 object. The code is executed by calling self.runcode() (which
1875 object. The code is executed by calling self.runcode() (which
1874 also handles run-time exceptions, except for SystemExit).
1876 also handles run-time exceptions, except for SystemExit).
1875
1877
1876 The return value is:
1878 The return value is:
1877
1879
1878 - True in case 2
1880 - True in case 2
1879
1881
1880 - False in the other cases, unless an exception is raised, where
1882 - False in the other cases, unless an exception is raised, where
1881 None is returned instead. This can be used by external callers to
1883 None is returned instead. This can be used by external callers to
1882 know whether to continue feeding input or not.
1884 know whether to continue feeding input or not.
1883
1885
1884 The return value can be used to decide whether to use sys.ps1 or
1886 The return value can be used to decide whether to use sys.ps1 or
1885 sys.ps2 to prompt the next line."""
1887 sys.ps2 to prompt the next line."""
1886
1888
1887 # if the source code has leading blanks, add 'if 1:\n' to it
1889 # if the source code has leading blanks, add 'if 1:\n' to it
1888 # this allows execution of indented pasted code. It is tempting
1890 # this allows execution of indented pasted code. It is tempting
1889 # to add '\n' at the end of source to run commands like ' a=1'
1891 # to add '\n' at the end of source to run commands like ' a=1'
1890 # directly, but this fails for more complicated scenarios
1892 # directly, but this fails for more complicated scenarios
1891 if source[:1] in [' ', '\t']:
1893 if source[:1] in [' ', '\t']:
1892 source = 'if 1:\n%s' % source
1894 source = 'if 1:\n%s' % source
1893
1895
1894 try:
1896 try:
1895 code = self.compile(source,filename,symbol)
1897 code = self.compile(source,filename,symbol)
1896 except (OverflowError, SyntaxError, ValueError):
1898 except (OverflowError, SyntaxError, ValueError):
1897 # Case 1
1899 # Case 1
1898 self.showsyntaxerror(filename)
1900 self.showsyntaxerror(filename)
1899 return None
1901 return None
1900
1902
1901 if code is None:
1903 if code is None:
1902 # Case 2
1904 # Case 2
1903 return True
1905 return True
1904
1906
1905 # Case 3
1907 # Case 3
1906 # We store the code object so that threaded shells and
1908 # We store the code object so that threaded shells and
1907 # custom exception handlers can access all this info if needed.
1909 # custom exception handlers can access all this info if needed.
1908 # The source corresponding to this can be obtained from the
1910 # The source corresponding to this can be obtained from the
1909 # buffer attribute as '\n'.join(self.buffer).
1911 # buffer attribute as '\n'.join(self.buffer).
1910 self.code_to_run = code
1912 self.code_to_run = code
1911 # now actually execute the code object
1913 # now actually execute the code object
1912 if self.runcode(code) == 0:
1914 if self.runcode(code) == 0:
1913 return False
1915 return False
1914 else:
1916 else:
1915 return None
1917 return None
1916
1918
1917 def runcode(self,code_obj):
1919 def runcode(self,code_obj):
1918 """Execute a code object.
1920 """Execute a code object.
1919
1921
1920 When an exception occurs, self.showtraceback() is called to display a
1922 When an exception occurs, self.showtraceback() is called to display a
1921 traceback.
1923 traceback.
1922
1924
1923 Return value: a flag indicating whether the code to be run completed
1925 Return value: a flag indicating whether the code to be run completed
1924 successfully:
1926 successfully:
1925
1927
1926 - 0: successful execution.
1928 - 0: successful execution.
1927 - 1: an error occurred.
1929 - 1: an error occurred.
1928 """
1930 """
1929
1931
1930 # Set our own excepthook in case the user code tries to call it
1932 # Set our own excepthook in case the user code tries to call it
1931 # directly, so that the IPython crash handler doesn't get triggered
1933 # directly, so that the IPython crash handler doesn't get triggered
1932 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1934 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1933
1935
1934 # we save the original sys.excepthook in the instance, in case config
1936 # we save the original sys.excepthook in the instance, in case config
1935 # code (such as magics) needs access to it.
1937 # code (such as magics) needs access to it.
1936 self.sys_excepthook = old_excepthook
1938 self.sys_excepthook = old_excepthook
1937 outflag = 1 # happens in more places, so it's easier as default
1939 outflag = 1 # happens in more places, so it's easier as default
1938 try:
1940 try:
1939 try:
1941 try:
1940 # Embedded instances require separate global/local namespaces
1942 # Embedded instances require separate global/local namespaces
1941 # so they can see both the surrounding (local) namespace and
1943 # so they can see both the surrounding (local) namespace and
1942 # the module-level globals when called inside another function.
1944 # the module-level globals when called inside another function.
1943 if self.embedded:
1945 if self.embedded:
1944 exec code_obj in self.user_global_ns, self.user_ns
1946 exec code_obj in self.user_global_ns, self.user_ns
1945 # Normal (non-embedded) instances should only have a single
1947 # Normal (non-embedded) instances should only have a single
1946 # namespace for user code execution, otherwise functions won't
1948 # namespace for user code execution, otherwise functions won't
1947 # see interactive top-level globals.
1949 # see interactive top-level globals.
1948 else:
1950 else:
1949 exec code_obj in self.user_ns
1951 exec code_obj in self.user_ns
1950 finally:
1952 finally:
1951 # Reset our crash handler in place
1953 # Reset our crash handler in place
1952 sys.excepthook = old_excepthook
1954 sys.excepthook = old_excepthook
1953 except SystemExit:
1955 except SystemExit:
1954 self.resetbuffer()
1956 self.resetbuffer()
1955 self.showtraceback()
1957 self.showtraceback()
1956 warn("Type %exit or %quit to exit IPython "
1958 warn("Type %exit or %quit to exit IPython "
1957 "(%Exit or %Quit do so unconditionally).",level=1)
1959 "(%Exit or %Quit do so unconditionally).",level=1)
1958 except self.custom_exceptions:
1960 except self.custom_exceptions:
1959 etype,value,tb = sys.exc_info()
1961 etype,value,tb = sys.exc_info()
1960 self.CustomTB(etype,value,tb)
1962 self.CustomTB(etype,value,tb)
1961 except:
1963 except:
1962 self.showtraceback()
1964 self.showtraceback()
1963 else:
1965 else:
1964 outflag = 0
1966 outflag = 0
1965 if softspace(sys.stdout, 0):
1967 if softspace(sys.stdout, 0):
1966 print
1968 print
1967 # Flush out code object which has been run (and source)
1969 # Flush out code object which has been run (and source)
1968 self.code_to_run = None
1970 self.code_to_run = None
1969 return outflag
1971 return outflag
1970
1972
1971 def push(self, line):
1973 def push(self, line):
1972 """Push a line to the interpreter.
1974 """Push a line to the interpreter.
1973
1975
1974 The line should not have a trailing newline; it may have
1976 The line should not have a trailing newline; it may have
1975 internal newlines. The line is appended to a buffer and the
1977 internal newlines. The line is appended to a buffer and the
1976 interpreter's runsource() method is called with the
1978 interpreter's runsource() method is called with the
1977 concatenated contents of the buffer as source. If this
1979 concatenated contents of the buffer as source. If this
1978 indicates that the command was executed or invalid, the buffer
1980 indicates that the command was executed or invalid, the buffer
1979 is reset; otherwise, the command is incomplete, and the buffer
1981 is reset; otherwise, the command is incomplete, and the buffer
1980 is left as it was after the line was appended. The return
1982 is left as it was after the line was appended. The return
1981 value is 1 if more input is required, 0 if the line was dealt
1983 value is 1 if more input is required, 0 if the line was dealt
1982 with in some way (this is the same as runsource()).
1984 with in some way (this is the same as runsource()).
1983 """
1985 """
1984
1986
1985 # autoindent management should be done here, and not in the
1987 # autoindent management should be done here, and not in the
1986 # interactive loop, since that one is only seen by keyboard input. We
1988 # interactive loop, since that one is only seen by keyboard input. We
1987 # need this done correctly even for code run via runlines (which uses
1989 # need this done correctly even for code run via runlines (which uses
1988 # push).
1990 # push).
1989
1991
1990 #print 'push line: <%s>' % line # dbg
1992 #print 'push line: <%s>' % line # dbg
1991 for subline in line.splitlines():
1993 for subline in line.splitlines():
1992 self.autoindent_update(subline)
1994 self.autoindent_update(subline)
1993 self.buffer.append(line)
1995 self.buffer.append(line)
1994 more = self.runsource('\n'.join(self.buffer), self.filename)
1996 more = self.runsource('\n'.join(self.buffer), self.filename)
1995 if not more:
1997 if not more:
1996 self.resetbuffer()
1998 self.resetbuffer()
1997 return more
1999 return more
1998
2000
1999 def split_user_input(self, line):
2001 def split_user_input(self, line):
2000 # This is really a hold-over to support ipapi and some extensions
2002 # This is really a hold-over to support ipapi and some extensions
2001 return prefilter.splitUserInput(line)
2003 return prefilter.splitUserInput(line)
2002
2004
2003 def resetbuffer(self):
2005 def resetbuffer(self):
2004 """Reset the input buffer."""
2006 """Reset the input buffer."""
2005 self.buffer[:] = []
2007 self.buffer[:] = []
2006
2008
2007 def raw_input(self,prompt='',continue_prompt=False):
2009 def raw_input(self,prompt='',continue_prompt=False):
2008 """Write a prompt and read a line.
2010 """Write a prompt and read a line.
2009
2011
2010 The returned line does not include the trailing newline.
2012 The returned line does not include the trailing newline.
2011 When the user enters the EOF key sequence, EOFError is raised.
2013 When the user enters the EOF key sequence, EOFError is raised.
2012
2014
2013 Optional inputs:
2015 Optional inputs:
2014
2016
2015 - prompt(''): a string to be printed to prompt the user.
2017 - prompt(''): a string to be printed to prompt the user.
2016
2018
2017 - continue_prompt(False): whether this line is the first one or a
2019 - continue_prompt(False): whether this line is the first one or a
2018 continuation in a sequence of inputs.
2020 continuation in a sequence of inputs.
2019 """
2021 """
2020
2022
2021 # Code run by the user may have modified the readline completer state.
2023 # Code run by the user may have modified the readline completer state.
2022 # We must ensure that our completer is back in place.
2024 # We must ensure that our completer is back in place.
2023 if self.has_readline:
2025 if self.has_readline:
2024 self.set_completer()
2026 self.set_completer()
2025
2027
2026 try:
2028 try:
2027 line = raw_input_original(prompt).decode(self.stdin_encoding)
2029 line = raw_input_original(prompt).decode(self.stdin_encoding)
2028 except ValueError:
2030 except ValueError:
2029 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2031 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2030 " or sys.stdout.close()!\nExiting IPython!")
2032 " or sys.stdout.close()!\nExiting IPython!")
2031 self.exit_now = True
2033 self.exit_now = True
2032 return ""
2034 return ""
2033
2035
2034 # Try to be reasonably smart about not re-indenting pasted input more
2036 # Try to be reasonably smart about not re-indenting pasted input more
2035 # than necessary. We do this by trimming out the auto-indent initial
2037 # than necessary. We do this by trimming out the auto-indent initial
2036 # spaces, if the user's actual input started itself with whitespace.
2038 # spaces, if the user's actual input started itself with whitespace.
2037 #debugx('self.buffer[-1]')
2039 #debugx('self.buffer[-1]')
2038
2040
2039 if self.autoindent:
2041 if self.autoindent:
2040 if num_ini_spaces(line) > self.indent_current_nsp:
2042 if num_ini_spaces(line) > self.indent_current_nsp:
2041 line = line[self.indent_current_nsp:]
2043 line = line[self.indent_current_nsp:]
2042 self.indent_current_nsp = 0
2044 self.indent_current_nsp = 0
2043
2045
2044 # store the unfiltered input before the user has any chance to modify
2046 # store the unfiltered input before the user has any chance to modify
2045 # it.
2047 # it.
2046 if line.strip():
2048 if line.strip():
2047 if continue_prompt:
2049 if continue_prompt:
2048 self.input_hist_raw[-1] += '%s\n' % line
2050 self.input_hist_raw[-1] += '%s\n' % line
2049 if self.has_readline: # and some config option is set?
2051 if self.has_readline: # and some config option is set?
2050 try:
2052 try:
2051 histlen = self.readline.get_current_history_length()
2053 histlen = self.readline.get_current_history_length()
2052 newhist = self.input_hist_raw[-1].rstrip()
2054 newhist = self.input_hist_raw[-1].rstrip()
2053 self.readline.remove_history_item(histlen-1)
2055 self.readline.remove_history_item(histlen-1)
2054 self.readline.replace_history_item(histlen-2,newhist)
2056 self.readline.replace_history_item(histlen-2,newhist)
2055 except AttributeError:
2057 except AttributeError:
2056 pass # re{move,place}_history_item are new in 2.4.
2058 pass # re{move,place}_history_item are new in 2.4.
2057 else:
2059 else:
2058 self.input_hist_raw.append('%s\n' % line)
2060 self.input_hist_raw.append('%s\n' % line)
2059 # only entries starting at first column go to shadow history
2061 # only entries starting at first column go to shadow history
2060 if line.lstrip() == line:
2062 if line.lstrip() == line:
2061 self.shadowhist.add(line.strip())
2063 self.shadowhist.add(line.strip())
2062 elif not continue_prompt:
2064 elif not continue_prompt:
2063 self.input_hist_raw.append('\n')
2065 self.input_hist_raw.append('\n')
2064 try:
2066 try:
2065 lineout = self.prefilter(line,continue_prompt)
2067 lineout = self.prefilter(line,continue_prompt)
2066 except:
2068 except:
2067 # blanket except, in case a user-defined prefilter crashes, so it
2069 # blanket except, in case a user-defined prefilter crashes, so it
2068 # can't take all of ipython with it.
2070 # can't take all of ipython with it.
2069 self.showtraceback()
2071 self.showtraceback()
2070 return ''
2072 return ''
2071 else:
2073 else:
2072 return lineout
2074 return lineout
2073
2075
2074 def _prefilter(self, line, continue_prompt):
2076 def _prefilter(self, line, continue_prompt):
2075 """Calls different preprocessors, depending on the form of line."""
2077 """Calls different preprocessors, depending on the form of line."""
2076
2078
2077 # All handlers *must* return a value, even if it's blank ('').
2079 # All handlers *must* return a value, even if it's blank ('').
2078
2080
2079 # Lines are NOT logged here. Handlers should process the line as
2081 # Lines are NOT logged here. Handlers should process the line as
2080 # needed, update the cache AND log it (so that the input cache array
2082 # needed, update the cache AND log it (so that the input cache array
2081 # stays synced).
2083 # stays synced).
2082
2084
2083 #.....................................................................
2085 #.....................................................................
2084 # Code begins
2086 # Code begins
2085
2087
2086 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2088 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2087
2089
2088 # save the line away in case we crash, so the post-mortem handler can
2090 # save the line away in case we crash, so the post-mortem handler can
2089 # record it
2091 # record it
2090 self._last_input_line = line
2092 self._last_input_line = line
2091
2093
2092 #print '***line: <%s>' % line # dbg
2094 #print '***line: <%s>' % line # dbg
2093
2095
2094 if not line:
2096 if not line:
2095 # Return immediately on purely empty lines, so that if the user
2097 # Return immediately on purely empty lines, so that if the user
2096 # previously typed some whitespace that started a continuation
2098 # previously typed some whitespace that started a continuation
2097 # prompt, he can break out of that loop with just an empty line.
2099 # prompt, he can break out of that loop with just an empty line.
2098 # This is how the default python prompt works.
2100 # This is how the default python prompt works.
2099
2101
2100 # Only return if the accumulated input buffer was just whitespace!
2102 # Only return if the accumulated input buffer was just whitespace!
2101 if ''.join(self.buffer).isspace():
2103 if ''.join(self.buffer).isspace():
2102 self.buffer[:] = []
2104 self.buffer[:] = []
2103 return ''
2105 return ''
2104
2106
2105 line_info = prefilter.LineInfo(line, continue_prompt)
2107 line_info = prefilter.LineInfo(line, continue_prompt)
2106
2108
2107 # the input history needs to track even empty lines
2109 # the input history needs to track even empty lines
2108 stripped = line.strip()
2110 stripped = line.strip()
2109
2111
2110 if not stripped:
2112 if not stripped:
2111 if not continue_prompt:
2113 if not continue_prompt:
2112 self.outputcache.prompt_count -= 1
2114 self.outputcache.prompt_count -= 1
2113 return self.handle_normal(line_info)
2115 return self.handle_normal(line_info)
2114
2116
2115 # print '***cont',continue_prompt # dbg
2117 # print '***cont',continue_prompt # dbg
2116 # special handlers are only allowed for single line statements
2118 # special handlers are only allowed for single line statements
2117 if continue_prompt and not self.rc.multi_line_specials:
2119 if continue_prompt and not self.rc.multi_line_specials:
2118 return self.handle_normal(line_info)
2120 return self.handle_normal(line_info)
2119
2121
2120
2122
2121 # See whether any pre-existing handler can take care of it
2123 # See whether any pre-existing handler can take care of it
2122 rewritten = self.hooks.input_prefilter(stripped)
2124 rewritten = self.hooks.input_prefilter(stripped)
2123 if rewritten != stripped: # ok, some prefilter did something
2125 if rewritten != stripped: # ok, some prefilter did something
2124 rewritten = line_info.pre + rewritten # add indentation
2126 rewritten = line_info.pre + rewritten # add indentation
2125 return self.handle_normal(prefilter.LineInfo(rewritten,
2127 return self.handle_normal(prefilter.LineInfo(rewritten,
2126 continue_prompt))
2128 continue_prompt))
2127
2129
2128 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2130 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2129
2131
2130 return prefilter.prefilter(line_info, self)
2132 return prefilter.prefilter(line_info, self)
2131
2133
2132
2134
2133 def _prefilter_dumb(self, line, continue_prompt):
2135 def _prefilter_dumb(self, line, continue_prompt):
2134 """simple prefilter function, for debugging"""
2136 """simple prefilter function, for debugging"""
2135 return self.handle_normal(line,continue_prompt)
2137 return self.handle_normal(line,continue_prompt)
2136
2138
2137
2139
2138 def multiline_prefilter(self, line, continue_prompt):
2140 def multiline_prefilter(self, line, continue_prompt):
2139 """ Run _prefilter for each line of input
2141 """ Run _prefilter for each line of input
2140
2142
2141 Covers cases where there are multiple lines in the user entry,
2143 Covers cases where there are multiple lines in the user entry,
2142 which is the case when the user goes back to a multiline history
2144 which is the case when the user goes back to a multiline history
2143 entry and presses enter.
2145 entry and presses enter.
2144
2146
2145 """
2147 """
2146 out = []
2148 out = []
2147 for l in line.rstrip('\n').split('\n'):
2149 for l in line.rstrip('\n').split('\n'):
2148 out.append(self._prefilter(l, continue_prompt))
2150 out.append(self._prefilter(l, continue_prompt))
2149 return '\n'.join(out)
2151 return '\n'.join(out)
2150
2152
2151 # Set the default prefilter() function (this can be user-overridden)
2153 # Set the default prefilter() function (this can be user-overridden)
2152 prefilter = multiline_prefilter
2154 prefilter = multiline_prefilter
2153
2155
2154 def handle_normal(self,line_info):
2156 def handle_normal(self,line_info):
2155 """Handle normal input lines. Use as a template for handlers."""
2157 """Handle normal input lines. Use as a template for handlers."""
2156
2158
2157 # With autoindent on, we need some way to exit the input loop, and I
2159 # With autoindent on, we need some way to exit the input loop, and I
2158 # don't want to force the user to have to backspace all the way to
2160 # don't want to force the user to have to backspace all the way to
2159 # clear the line. The rule will be in this case, that either two
2161 # clear the line. The rule will be in this case, that either two
2160 # lines of pure whitespace in a row, or a line of pure whitespace but
2162 # lines of pure whitespace in a row, or a line of pure whitespace but
2161 # of a size different to the indent level, will exit the input loop.
2163 # of a size different to the indent level, will exit the input loop.
2162 line = line_info.line
2164 line = line_info.line
2163 continue_prompt = line_info.continue_prompt
2165 continue_prompt = line_info.continue_prompt
2164
2166
2165 if (continue_prompt and self.autoindent and line.isspace() and
2167 if (continue_prompt and self.autoindent and line.isspace() and
2166 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2168 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2167 (self.buffer[-1]).isspace() )):
2169 (self.buffer[-1]).isspace() )):
2168 line = ''
2170 line = ''
2169
2171
2170 self.log(line,line,continue_prompt)
2172 self.log(line,line,continue_prompt)
2171 return line
2173 return line
2172
2174
2173 def handle_alias(self,line_info):
2175 def handle_alias(self,line_info):
2174 """Handle alias input lines. """
2176 """Handle alias input lines. """
2175 tgt = self.alias_table[line_info.iFun]
2177 tgt = self.alias_table[line_info.iFun]
2176 # print "=>",tgt #dbg
2178 # print "=>",tgt #dbg
2177 if callable(tgt):
2179 if callable(tgt):
2178 if '$' in line_info.line:
2180 if '$' in line_info.line:
2179 call_meth = '(_ip, _ip.itpl(%s))'
2181 call_meth = '(_ip, _ip.itpl(%s))'
2180 else:
2182 else:
2181 call_meth = '(_ip,%s)'
2183 call_meth = '(_ip,%s)'
2182 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2184 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2183 line_info.iFun,
2185 line_info.iFun,
2184 make_quoted_expr(line_info.line))
2186 make_quoted_expr(line_info.line))
2185 else:
2187 else:
2186 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2188 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2187
2189
2188 # pre is needed, because it carries the leading whitespace. Otherwise
2190 # pre is needed, because it carries the leading whitespace. Otherwise
2189 # aliases won't work in indented sections.
2191 # aliases won't work in indented sections.
2190 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2192 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2191 make_quoted_expr( transformed ))
2193 make_quoted_expr( transformed ))
2192
2194
2193 self.log(line_info.line,line_out,line_info.continue_prompt)
2195 self.log(line_info.line,line_out,line_info.continue_prompt)
2194 #print 'line out:',line_out # dbg
2196 #print 'line out:',line_out # dbg
2195 return line_out
2197 return line_out
2196
2198
2197 def handle_shell_escape(self, line_info):
2199 def handle_shell_escape(self, line_info):
2198 """Execute the line in a shell, empty return value"""
2200 """Execute the line in a shell, empty return value"""
2199 #print 'line in :', `line` # dbg
2201 #print 'line in :', `line` # dbg
2200 line = line_info.line
2202 line = line_info.line
2201 if line.lstrip().startswith('!!'):
2203 if line.lstrip().startswith('!!'):
2202 # rewrite LineInfo's line, iFun and theRest to properly hold the
2204 # rewrite LineInfo's line, iFun and theRest to properly hold the
2203 # call to %sx and the actual command to be executed, so
2205 # call to %sx and the actual command to be executed, so
2204 # handle_magic can work correctly. Note that this works even if
2206 # handle_magic can work correctly. Note that this works even if
2205 # the line is indented, so it handles multi_line_specials
2207 # the line is indented, so it handles multi_line_specials
2206 # properly.
2208 # properly.
2207 new_rest = line.lstrip()[2:]
2209 new_rest = line.lstrip()[2:]
2208 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2210 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2209 line_info.iFun = 'sx'
2211 line_info.iFun = 'sx'
2210 line_info.theRest = new_rest
2212 line_info.theRest = new_rest
2211 return self.handle_magic(line_info)
2213 return self.handle_magic(line_info)
2212 else:
2214 else:
2213 cmd = line.lstrip().lstrip('!')
2215 cmd = line.lstrip().lstrip('!')
2214 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2216 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2215 make_quoted_expr(cmd))
2217 make_quoted_expr(cmd))
2216 # update cache/log and return
2218 # update cache/log and return
2217 self.log(line,line_out,line_info.continue_prompt)
2219 self.log(line,line_out,line_info.continue_prompt)
2218 return line_out
2220 return line_out
2219
2221
2220 def handle_magic(self, line_info):
2222 def handle_magic(self, line_info):
2221 """Execute magic functions."""
2223 """Execute magic functions."""
2222 iFun = line_info.iFun
2224 iFun = line_info.iFun
2223 theRest = line_info.theRest
2225 theRest = line_info.theRest
2224 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2226 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2225 make_quoted_expr(iFun + " " + theRest))
2227 make_quoted_expr(iFun + " " + theRest))
2226 self.log(line_info.line,cmd,line_info.continue_prompt)
2228 self.log(line_info.line,cmd,line_info.continue_prompt)
2227 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2229 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2228 return cmd
2230 return cmd
2229
2231
2230 def handle_auto(self, line_info):
2232 def handle_auto(self, line_info):
2231 """Hande lines which can be auto-executed, quoting if requested."""
2233 """Hande lines which can be auto-executed, quoting if requested."""
2232
2234
2233 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2235 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2234 line = line_info.line
2236 line = line_info.line
2235 iFun = line_info.iFun
2237 iFun = line_info.iFun
2236 theRest = line_info.theRest
2238 theRest = line_info.theRest
2237 pre = line_info.pre
2239 pre = line_info.pre
2238 continue_prompt = line_info.continue_prompt
2240 continue_prompt = line_info.continue_prompt
2239 obj = line_info.ofind(self)['obj']
2241 obj = line_info.ofind(self)['obj']
2240
2242
2241 # This should only be active for single-line input!
2243 # This should only be active for single-line input!
2242 if continue_prompt:
2244 if continue_prompt:
2243 self.log(line,line,continue_prompt)
2245 self.log(line,line,continue_prompt)
2244 return line
2246 return line
2245
2247
2246 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2248 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2247 auto_rewrite = True
2249 auto_rewrite = True
2248
2250
2249 if pre == self.ESC_QUOTE:
2251 if pre == self.ESC_QUOTE:
2250 # Auto-quote splitting on whitespace
2252 # Auto-quote splitting on whitespace
2251 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2253 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2252 elif pre == self.ESC_QUOTE2:
2254 elif pre == self.ESC_QUOTE2:
2253 # Auto-quote whole string
2255 # Auto-quote whole string
2254 newcmd = '%s("%s")' % (iFun,theRest)
2256 newcmd = '%s("%s")' % (iFun,theRest)
2255 elif pre == self.ESC_PAREN:
2257 elif pre == self.ESC_PAREN:
2256 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2258 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2257 else:
2259 else:
2258 # Auto-paren.
2260 # Auto-paren.
2259 # We only apply it to argument-less calls if the autocall
2261 # We only apply it to argument-less calls if the autocall
2260 # parameter is set to 2. We only need to check that autocall is <
2262 # parameter is set to 2. We only need to check that autocall is <
2261 # 2, since this function isn't called unless it's at least 1.
2263 # 2, since this function isn't called unless it's at least 1.
2262 if not theRest and (self.rc.autocall < 2) and not force_auto:
2264 if not theRest and (self.rc.autocall < 2) and not force_auto:
2263 newcmd = '%s %s' % (iFun,theRest)
2265 newcmd = '%s %s' % (iFun,theRest)
2264 auto_rewrite = False
2266 auto_rewrite = False
2265 else:
2267 else:
2266 if not force_auto and theRest.startswith('['):
2268 if not force_auto and theRest.startswith('['):
2267 if hasattr(obj,'__getitem__'):
2269 if hasattr(obj,'__getitem__'):
2268 # Don't autocall in this case: item access for an object
2270 # Don't autocall in this case: item access for an object
2269 # which is BOTH callable and implements __getitem__.
2271 # which is BOTH callable and implements __getitem__.
2270 newcmd = '%s %s' % (iFun,theRest)
2272 newcmd = '%s %s' % (iFun,theRest)
2271 auto_rewrite = False
2273 auto_rewrite = False
2272 else:
2274 else:
2273 # if the object doesn't support [] access, go ahead and
2275 # if the object doesn't support [] access, go ahead and
2274 # autocall
2276 # autocall
2275 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2277 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2276 elif theRest.endswith(';'):
2278 elif theRest.endswith(';'):
2277 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2279 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2278 else:
2280 else:
2279 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2281 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2280
2282
2281 if auto_rewrite:
2283 if auto_rewrite:
2282 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2284 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2283
2285
2284 try:
2286 try:
2285 # plain ascii works better w/ pyreadline, on some machines, so
2287 # plain ascii works better w/ pyreadline, on some machines, so
2286 # we use it and only print uncolored rewrite if we have unicode
2288 # we use it and only print uncolored rewrite if we have unicode
2287 rw = str(rw)
2289 rw = str(rw)
2288 print >>Term.cout, rw
2290 print >>Term.cout, rw
2289 except UnicodeEncodeError:
2291 except UnicodeEncodeError:
2290 print "-------------->" + newcmd
2292 print "-------------->" + newcmd
2291
2293
2292 # log what is now valid Python, not the actual user input (without the
2294 # log what is now valid Python, not the actual user input (without the
2293 # final newline)
2295 # final newline)
2294 self.log(line,newcmd,continue_prompt)
2296 self.log(line,newcmd,continue_prompt)
2295 return newcmd
2297 return newcmd
2296
2298
2297 def handle_help(self, line_info):
2299 def handle_help(self, line_info):
2298 """Try to get some help for the object.
2300 """Try to get some help for the object.
2299
2301
2300 obj? or ?obj -> basic information.
2302 obj? or ?obj -> basic information.
2301 obj?? or ??obj -> more details.
2303 obj?? or ??obj -> more details.
2302 """
2304 """
2303
2305
2304 line = line_info.line
2306 line = line_info.line
2305 # We need to make sure that we don't process lines which would be
2307 # We need to make sure that we don't process lines which would be
2306 # otherwise valid python, such as "x=1 # what?"
2308 # otherwise valid python, such as "x=1 # what?"
2307 try:
2309 try:
2308 codeop.compile_command(line)
2310 codeop.compile_command(line)
2309 except SyntaxError:
2311 except SyntaxError:
2310 # We should only handle as help stuff which is NOT valid syntax
2312 # We should only handle as help stuff which is NOT valid syntax
2311 if line[0]==self.ESC_HELP:
2313 if line[0]==self.ESC_HELP:
2312 line = line[1:]
2314 line = line[1:]
2313 elif line[-1]==self.ESC_HELP:
2315 elif line[-1]==self.ESC_HELP:
2314 line = line[:-1]
2316 line = line[:-1]
2315 self.log(line,'#?'+line,line_info.continue_prompt)
2317 self.log(line,'#?'+line,line_info.continue_prompt)
2316 if line:
2318 if line:
2317 #print 'line:<%r>' % line # dbg
2319 #print 'line:<%r>' % line # dbg
2318 self.magic_pinfo(line)
2320 self.magic_pinfo(line)
2319 else:
2321 else:
2320 page(self.usage,screen_lines=self.rc.screen_length)
2322 page(self.usage,screen_lines=self.rc.screen_length)
2321 return '' # Empty string is needed here!
2323 return '' # Empty string is needed here!
2322 except:
2324 except:
2323 # Pass any other exceptions through to the normal handler
2325 # Pass any other exceptions through to the normal handler
2324 return self.handle_normal(line_info)
2326 return self.handle_normal(line_info)
2325 else:
2327 else:
2326 # If the code compiles ok, we should handle it normally
2328 # If the code compiles ok, we should handle it normally
2327 return self.handle_normal(line_info)
2329 return self.handle_normal(line_info)
2328
2330
2329 def getapi(self):
2331 def getapi(self):
2330 """ Get an IPApi object for this shell instance
2332 """ Get an IPApi object for this shell instance
2331
2333
2332 Getting an IPApi object is always preferable to accessing the shell
2334 Getting an IPApi object is always preferable to accessing the shell
2333 directly, but this holds true especially for extensions.
2335 directly, but this holds true especially for extensions.
2334
2336
2335 It should always be possible to implement an extension with IPApi
2337 It should always be possible to implement an extension with IPApi
2336 alone. If not, contact maintainer to request an addition.
2338 alone. If not, contact maintainer to request an addition.
2337
2339
2338 """
2340 """
2339 return self.api
2341 return self.api
2340
2342
2341 def handle_emacs(self, line_info):
2343 def handle_emacs(self, line_info):
2342 """Handle input lines marked by python-mode."""
2344 """Handle input lines marked by python-mode."""
2343
2345
2344 # Currently, nothing is done. Later more functionality can be added
2346 # Currently, nothing is done. Later more functionality can be added
2345 # here if needed.
2347 # here if needed.
2346
2348
2347 # The input cache shouldn't be updated
2349 # The input cache shouldn't be updated
2348 return line_info.line
2350 return line_info.line
2349
2351
2350
2352
2351 def mktempfile(self,data=None):
2353 def mktempfile(self,data=None):
2352 """Make a new tempfile and return its filename.
2354 """Make a new tempfile and return its filename.
2353
2355
2354 This makes a call to tempfile.mktemp, but it registers the created
2356 This makes a call to tempfile.mktemp, but it registers the created
2355 filename internally so ipython cleans it up at exit time.
2357 filename internally so ipython cleans it up at exit time.
2356
2358
2357 Optional inputs:
2359 Optional inputs:
2358
2360
2359 - data(None): if data is given, it gets written out to the temp file
2361 - data(None): if data is given, it gets written out to the temp file
2360 immediately, and the file is closed again."""
2362 immediately, and the file is closed again."""
2361
2363
2362 filename = tempfile.mktemp('.py','ipython_edit_')
2364 filename = tempfile.mktemp('.py','ipython_edit_')
2363 self.tempfiles.append(filename)
2365 self.tempfiles.append(filename)
2364
2366
2365 if data:
2367 if data:
2366 tmp_file = open(filename,'w')
2368 tmp_file = open(filename,'w')
2367 tmp_file.write(data)
2369 tmp_file.write(data)
2368 tmp_file.close()
2370 tmp_file.close()
2369 return filename
2371 return filename
2370
2372
2371 def write(self,data):
2373 def write(self,data):
2372 """Write a string to the default output"""
2374 """Write a string to the default output"""
2373 Term.cout.write(data)
2375 Term.cout.write(data)
2374
2376
2375 def write_err(self,data):
2377 def write_err(self,data):
2376 """Write a string to the default error output"""
2378 """Write a string to the default error output"""
2377 Term.cerr.write(data)
2379 Term.cerr.write(data)
2378
2380
2379 def exit(self):
2381 def exit(self):
2380 """Handle interactive exit.
2382 """Handle interactive exit.
2381
2383
2382 This method sets the exit_now attribute."""
2384 This method sets the exit_now attribute."""
2383
2385
2384 if self.rc.confirm_exit:
2386 if self.rc.confirm_exit:
2385 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2387 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2386 self.exit_now = True
2388 self.exit_now = True
2387 else:
2389 else:
2388 self.exit_now = True
2390 self.exit_now = True
2389
2391
2390 def safe_execfile(self,fname,*where,**kw):
2392 def safe_execfile(self,fname,*where,**kw):
2391 """A safe version of the builtin execfile().
2393 """A safe version of the builtin execfile().
2392
2394
2393 This version will never throw an exception, and knows how to handle
2395 This version will never throw an exception, and knows how to handle
2394 ipython logs as well.
2396 ipython logs as well.
2395
2397
2396 :Parameters:
2398 :Parameters:
2397 fname : string
2399 fname : string
2398 Name of the file to be executed.
2400 Name of the file to be executed.
2399
2401
2400 where : tuple
2402 where : tuple
2401 One or two namespaces, passed to execfile() as (globals,locals).
2403 One or two namespaces, passed to execfile() as (globals,locals).
2402 If only one is given, it is passed as both.
2404 If only one is given, it is passed as both.
2403
2405
2404 :Keywords:
2406 :Keywords:
2405 islog : boolean (False)
2407 islog : boolean (False)
2406
2408
2407 quiet : boolean (True)
2409 quiet : boolean (True)
2408
2410
2409 exit_ignore : boolean (False)
2411 exit_ignore : boolean (False)
2410 """
2412 """
2411
2413
2412 def syspath_cleanup():
2414 def syspath_cleanup():
2413 """Internal cleanup routine for sys.path."""
2415 """Internal cleanup routine for sys.path."""
2414 if add_dname:
2416 if add_dname:
2415 try:
2417 try:
2416 sys.path.remove(dname)
2418 sys.path.remove(dname)
2417 except ValueError:
2419 except ValueError:
2418 # For some reason the user has already removed it, ignore.
2420 # For some reason the user has already removed it, ignore.
2419 pass
2421 pass
2420
2422
2421 fname = os.path.expanduser(fname)
2423 fname = os.path.expanduser(fname)
2422
2424
2423 # Find things also in current directory. This is needed to mimic the
2425 # Find things also in current directory. This is needed to mimic the
2424 # behavior of running a script from the system command line, where
2426 # behavior of running a script from the system command line, where
2425 # Python inserts the script's directory into sys.path
2427 # Python inserts the script's directory into sys.path
2426 dname = os.path.dirname(os.path.abspath(fname))
2428 dname = os.path.dirname(os.path.abspath(fname))
2427 add_dname = False
2429 add_dname = False
2428 if dname not in sys.path:
2430 if dname not in sys.path:
2429 sys.path.insert(0,dname)
2431 sys.path.insert(0,dname)
2430 add_dname = True
2432 add_dname = True
2431
2433
2432 try:
2434 try:
2433 xfile = open(fname)
2435 xfile = open(fname)
2434 except:
2436 except:
2435 print >> Term.cerr, \
2437 print >> Term.cerr, \
2436 'Could not open file <%s> for safe execution.' % fname
2438 'Could not open file <%s> for safe execution.' % fname
2437 syspath_cleanup()
2439 syspath_cleanup()
2438 return None
2440 return None
2439
2441
2440 kw.setdefault('islog',0)
2442 kw.setdefault('islog',0)
2441 kw.setdefault('quiet',1)
2443 kw.setdefault('quiet',1)
2442 kw.setdefault('exit_ignore',0)
2444 kw.setdefault('exit_ignore',0)
2443
2445
2444 first = xfile.readline()
2446 first = xfile.readline()
2445 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2447 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2446 xfile.close()
2448 xfile.close()
2447 # line by line execution
2449 # line by line execution
2448 if first.startswith(loghead) or kw['islog']:
2450 if first.startswith(loghead) or kw['islog']:
2449 print 'Loading log file <%s> one line at a time...' % fname
2451 print 'Loading log file <%s> one line at a time...' % fname
2450 if kw['quiet']:
2452 if kw['quiet']:
2451 stdout_save = sys.stdout
2453 stdout_save = sys.stdout
2452 sys.stdout = StringIO.StringIO()
2454 sys.stdout = StringIO.StringIO()
2453 try:
2455 try:
2454 globs,locs = where[0:2]
2456 globs,locs = where[0:2]
2455 except:
2457 except:
2456 try:
2458 try:
2457 globs = locs = where[0]
2459 globs = locs = where[0]
2458 except:
2460 except:
2459 globs = locs = globals()
2461 globs = locs = globals()
2460 badblocks = []
2462 badblocks = []
2461
2463
2462 # we also need to identify indented blocks of code when replaying
2464 # we also need to identify indented blocks of code when replaying
2463 # logs and put them together before passing them to an exec
2465 # logs and put them together before passing them to an exec
2464 # statement. This takes a bit of regexp and look-ahead work in the
2466 # statement. This takes a bit of regexp and look-ahead work in the
2465 # file. It's easiest if we swallow the whole thing in memory
2467 # file. It's easiest if we swallow the whole thing in memory
2466 # first, and manually walk through the lines list moving the
2468 # first, and manually walk through the lines list moving the
2467 # counter ourselves.
2469 # counter ourselves.
2468 indent_re = re.compile('\s+\S')
2470 indent_re = re.compile('\s+\S')
2469 xfile = open(fname)
2471 xfile = open(fname)
2470 filelines = xfile.readlines()
2472 filelines = xfile.readlines()
2471 xfile.close()
2473 xfile.close()
2472 nlines = len(filelines)
2474 nlines = len(filelines)
2473 lnum = 0
2475 lnum = 0
2474 while lnum < nlines:
2476 while lnum < nlines:
2475 line = filelines[lnum]
2477 line = filelines[lnum]
2476 lnum += 1
2478 lnum += 1
2477 # don't re-insert logger status info into cache
2479 # don't re-insert logger status info into cache
2478 if line.startswith('#log#'):
2480 if line.startswith('#log#'):
2479 continue
2481 continue
2480 else:
2482 else:
2481 # build a block of code (maybe a single line) for execution
2483 # build a block of code (maybe a single line) for execution
2482 block = line
2484 block = line
2483 try:
2485 try:
2484 next = filelines[lnum] # lnum has already incremented
2486 next = filelines[lnum] # lnum has already incremented
2485 except:
2487 except:
2486 next = None
2488 next = None
2487 while next and indent_re.match(next):
2489 while next and indent_re.match(next):
2488 block += next
2490 block += next
2489 lnum += 1
2491 lnum += 1
2490 try:
2492 try:
2491 next = filelines[lnum]
2493 next = filelines[lnum]
2492 except:
2494 except:
2493 next = None
2495 next = None
2494 # now execute the block of one or more lines
2496 # now execute the block of one or more lines
2495 try:
2497 try:
2496 exec block in globs,locs
2498 exec block in globs,locs
2497 except SystemExit:
2499 except SystemExit:
2498 pass
2500 pass
2499 except:
2501 except:
2500 badblocks.append(block.rstrip())
2502 badblocks.append(block.rstrip())
2501 if kw['quiet']: # restore stdout
2503 if kw['quiet']: # restore stdout
2502 sys.stdout.close()
2504 sys.stdout.close()
2503 sys.stdout = stdout_save
2505 sys.stdout = stdout_save
2504 print 'Finished replaying log file <%s>' % fname
2506 print 'Finished replaying log file <%s>' % fname
2505 if badblocks:
2507 if badblocks:
2506 print >> sys.stderr, ('\nThe following lines/blocks in file '
2508 print >> sys.stderr, ('\nThe following lines/blocks in file '
2507 '<%s> reported errors:' % fname)
2509 '<%s> reported errors:' % fname)
2508
2510
2509 for badline in badblocks:
2511 for badline in badblocks:
2510 print >> sys.stderr, badline
2512 print >> sys.stderr, badline
2511 else: # regular file execution
2513 else: # regular file execution
2512 try:
2514 try:
2513 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2515 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2514 # Work around a bug in Python for Windows. The bug was
2516 # Work around a bug in Python for Windows. The bug was
2515 # fixed in in Python 2.5 r54159 and 54158, but that's still
2517 # fixed in in Python 2.5 r54159 and 54158, but that's still
2516 # SVN Python as of March/07. For details, see:
2518 # SVN Python as of March/07. For details, see:
2517 # http://projects.scipy.org/ipython/ipython/ticket/123
2519 # http://projects.scipy.org/ipython/ipython/ticket/123
2518 try:
2520 try:
2519 globs,locs = where[0:2]
2521 globs,locs = where[0:2]
2520 except:
2522 except:
2521 try:
2523 try:
2522 globs = locs = where[0]
2524 globs = locs = where[0]
2523 except:
2525 except:
2524 globs = locs = globals()
2526 globs = locs = globals()
2525 exec file(fname) in globs,locs
2527 exec file(fname) in globs,locs
2526 else:
2528 else:
2527 execfile(fname,*where)
2529 execfile(fname,*where)
2528 except SyntaxError:
2530 except SyntaxError:
2529 self.showsyntaxerror()
2531 self.showsyntaxerror()
2530 warn('Failure executing file: <%s>' % fname)
2532 warn('Failure executing file: <%s>' % fname)
2531 except SystemExit,status:
2533 except SystemExit,status:
2532 # Code that correctly sets the exit status flag to success (0)
2534 # Code that correctly sets the exit status flag to success (0)
2533 # shouldn't be bothered with a traceback. Note that a plain
2535 # shouldn't be bothered with a traceback. Note that a plain
2534 # sys.exit() does NOT set the message to 0 (it's empty) so that
2536 # sys.exit() does NOT set the message to 0 (it's empty) so that
2535 # will still get a traceback. Note that the structure of the
2537 # will still get a traceback. Note that the structure of the
2536 # SystemExit exception changed between Python 2.4 and 2.5, so
2538 # SystemExit exception changed between Python 2.4 and 2.5, so
2537 # the checks must be done in a version-dependent way.
2539 # the checks must be done in a version-dependent way.
2538 show = False
2540 show = False
2539
2541
2540 if sys.version_info[:2] > (2,5):
2542 if sys.version_info[:2] > (2,5):
2541 if status.message!=0 and not kw['exit_ignore']:
2543 if status.message!=0 and not kw['exit_ignore']:
2542 show = True
2544 show = True
2543 else:
2545 else:
2544 if status.code and not kw['exit_ignore']:
2546 if status.code and not kw['exit_ignore']:
2545 show = True
2547 show = True
2546 if show:
2548 if show:
2547 self.showtraceback()
2549 self.showtraceback()
2548 warn('Failure executing file: <%s>' % fname)
2550 warn('Failure executing file: <%s>' % fname)
2549 except:
2551 except:
2550 self.showtraceback()
2552 self.showtraceback()
2551 warn('Failure executing file: <%s>' % fname)
2553 warn('Failure executing file: <%s>' % fname)
2552
2554
2553 syspath_cleanup()
2555 syspath_cleanup()
2554
2556
2555 #************************* end of file <iplib.py> *****************************
2557 #************************* end of file <iplib.py> *****************************
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now