##// END OF EJS Templates
pre_config_initialization added to enable using the db...
vivainio -
Show More
@@ -1,2804 +1,2808 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 1126 2006-02-06 02:31:40Z fperez $"""
4 $Id: Magic.py 1140 2006-02-10 17:07:11Z vivainio $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt,GetoptError
36 from getopt import getopt,GetoptError
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38
38
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 # Homebrewed
45 # Homebrewed
46 from IPython import Debugger, OInspect, wildcard
46 from IPython import Debugger, OInspect, wildcard
47 from IPython.FakeModule import FakeModule
47 from IPython.FakeModule import FakeModule
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.PyColorize import Parser
49 from IPython.PyColorize import Parser
50 from IPython.ipstruct import Struct
50 from IPython.ipstruct import Struct
51 from IPython.macro import Macro
51 from IPython.macro import Macro
52 from IPython.genutils import *
52 from IPython.genutils import *
53 from IPython import platutils
53 from IPython import platutils
54
54
55 #***************************************************************************
55 #***************************************************************************
56 # Utility functions
56 # Utility functions
57 def on_off(tag):
57 def on_off(tag):
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 return ['OFF','ON'][tag]
59 return ['OFF','ON'][tag]
60
60
61 class Bunch: pass
61 class Bunch: pass
62
62
63 #***************************************************************************
63 #***************************************************************************
64 # Main class implementing Magic functionality
64 # Main class implementing Magic functionality
65 class Magic:
65 class Magic:
66 """Magic functions for InteractiveShell.
66 """Magic functions for InteractiveShell.
67
67
68 Shell functions which can be reached as %function_name. All magic
68 Shell functions which can be reached as %function_name. All magic
69 functions should accept a string, which they can parse for their own
69 functions should accept a string, which they can parse for their own
70 needs. This can make some functions easier to type, eg `%cd ../`
70 needs. This can make some functions easier to type, eg `%cd ../`
71 vs. `%cd("../")`
71 vs. `%cd("../")`
72
72
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
74 at the command line, but it is is needed in the definition. """
74 at the command line, but it is is needed in the definition. """
75
75
76 # class globals
76 # class globals
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
78 'Automagic is ON, % prefix NOT needed for magic functions.']
78 'Automagic is ON, % prefix NOT needed for magic functions.']
79
79
80 #......................................................................
80 #......................................................................
81 # some utility functions
81 # some utility functions
82
82
83 def __init__(self,shell):
83 def __init__(self,shell):
84
84
85 self.options_table = {}
85 self.options_table = {}
86 if profile is None:
86 if profile is None:
87 self.magic_prun = self.profile_missing_notice
87 self.magic_prun = self.profile_missing_notice
88 self.shell = shell
88 self.shell = shell
89
89
90 # namespace for holding state we may need
90 # namespace for holding state we may need
91 self._magic_state = Bunch()
91 self._magic_state = Bunch()
92
92
93 def profile_missing_notice(self, *args, **kwargs):
93 def profile_missing_notice(self, *args, **kwargs):
94 error("""\
94 error("""\
95 The profile module could not be found. If you are a Debian user,
95 The profile module could not be found. If you are a Debian user,
96 it has been removed from the standard Debian package because of its non-free
96 it has been removed from the standard Debian package because of its non-free
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
98
98
99 def default_option(self,fn,optstr):
99 def default_option(self,fn,optstr):
100 """Make an entry in the options_table for fn, with value optstr"""
100 """Make an entry in the options_table for fn, with value optstr"""
101
101
102 if fn not in self.lsmagic():
102 if fn not in self.lsmagic():
103 error("%s is not a magic function" % fn)
103 error("%s is not a magic function" % fn)
104 self.options_table[fn] = optstr
104 self.options_table[fn] = optstr
105
105
106 def lsmagic(self):
106 def lsmagic(self):
107 """Return a list of currently available magic functions.
107 """Return a list of currently available magic functions.
108
108
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
110 ['magic_ls','magic_cd',...]"""
110 ['magic_ls','magic_cd',...]"""
111
111
112 # FIXME. This needs a cleanup, in the way the magics list is built.
112 # FIXME. This needs a cleanup, in the way the magics list is built.
113
113
114 # magics in class definition
114 # magics in class definition
115 class_magic = lambda fn: fn.startswith('magic_') and \
115 class_magic = lambda fn: fn.startswith('magic_') and \
116 callable(Magic.__dict__[fn])
116 callable(Magic.__dict__[fn])
117 # in instance namespace (run-time user additions)
117 # in instance namespace (run-time user additions)
118 inst_magic = lambda fn: fn.startswith('magic_') and \
118 inst_magic = lambda fn: fn.startswith('magic_') and \
119 callable(self.__dict__[fn])
119 callable(self.__dict__[fn])
120 # and bound magics by user (so they can access self):
120 # and bound magics by user (so they can access self):
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
122 callable(self.__class__.__dict__[fn])
122 callable(self.__class__.__dict__[fn])
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
126 out = []
126 out = []
127 for fn in magics:
127 for fn in magics:
128 out.append(fn.replace('magic_','',1))
128 out.append(fn.replace('magic_','',1))
129 out.sort()
129 out.sort()
130 return out
130 return out
131
131
132 def extract_input_slices(self,slices,raw=False):
132 def extract_input_slices(self,slices,raw=False):
133 """Return as a string a set of input history slices.
133 """Return as a string a set of input history slices.
134
134
135 Inputs:
135 Inputs:
136
136
137 - slices: the set of slices is given as a list of strings (like
137 - slices: the set of slices is given as a list of strings (like
138 ['1','4:8','9'], since this function is for use by magic functions
138 ['1','4:8','9'], since this function is for use by magic functions
139 which get their arguments as strings.
139 which get their arguments as strings.
140
140
141 Optional inputs:
141 Optional inputs:
142
142
143 - raw(False): by default, the processed input is used. If this is
143 - raw(False): by default, the processed input is used. If this is
144 true, the raw input history is used instead.
144 true, the raw input history is used instead.
145
145
146 Note that slices can be called with two notations:
146 Note that slices can be called with two notations:
147
147
148 N:M -> standard python form, means including items N...(M-1).
148 N:M -> standard python form, means including items N...(M-1).
149
149
150 N-M -> include items N..M (closed endpoint)."""
150 N-M -> include items N..M (closed endpoint)."""
151
151
152 if raw:
152 if raw:
153 hist = self.shell.input_hist_raw
153 hist = self.shell.input_hist_raw
154 else:
154 else:
155 hist = self.shell.input_hist
155 hist = self.shell.input_hist
156
156
157 cmds = []
157 cmds = []
158 for chunk in slices:
158 for chunk in slices:
159 if ':' in chunk:
159 if ':' in chunk:
160 ini,fin = map(int,chunk.split(':'))
160 ini,fin = map(int,chunk.split(':'))
161 elif '-' in chunk:
161 elif '-' in chunk:
162 ini,fin = map(int,chunk.split('-'))
162 ini,fin = map(int,chunk.split('-'))
163 fin += 1
163 fin += 1
164 else:
164 else:
165 ini = int(chunk)
165 ini = int(chunk)
166 fin = ini+1
166 fin = ini+1
167 cmds.append(hist[ini:fin])
167 cmds.append(hist[ini:fin])
168 return cmds
168 return cmds
169
169
170 def _ofind(self,oname):
170 def _ofind(self,oname):
171 """Find an object in the available namespaces.
171 """Find an object in the available namespaces.
172
172
173 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
173 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
174
174
175 Has special code to detect magic functions.
175 Has special code to detect magic functions.
176 """
176 """
177
177
178 oname = oname.strip()
178 oname = oname.strip()
179
179
180 # Namespaces to search in:
180 # Namespaces to search in:
181 user_ns = self.shell.user_ns
181 user_ns = self.shell.user_ns
182 internal_ns = self.shell.internal_ns
182 internal_ns = self.shell.internal_ns
183 builtin_ns = __builtin__.__dict__
183 builtin_ns = __builtin__.__dict__
184 alias_ns = self.shell.alias_table
184 alias_ns = self.shell.alias_table
185
185
186 # Put them in a list. The order is important so that we find things in
186 # Put them in a list. The order is important so that we find things in
187 # the same order that Python finds them.
187 # the same order that Python finds them.
188 namespaces = [ ('Interactive',user_ns),
188 namespaces = [ ('Interactive',user_ns),
189 ('IPython internal',internal_ns),
189 ('IPython internal',internal_ns),
190 ('Python builtin',builtin_ns),
190 ('Python builtin',builtin_ns),
191 ('Alias',alias_ns),
191 ('Alias',alias_ns),
192 ]
192 ]
193
193
194 # initialize results to 'null'
194 # initialize results to 'null'
195 found = 0; obj = None; ospace = None; ds = None;
195 found = 0; obj = None; ospace = None; ds = None;
196 ismagic = 0; isalias = 0
196 ismagic = 0; isalias = 0
197
197
198 # Look for the given name by splitting it in parts. If the head is
198 # Look for the given name by splitting it in parts. If the head is
199 # found, then we look for all the remaining parts as members, and only
199 # found, then we look for all the remaining parts as members, and only
200 # declare success if we can find them all.
200 # declare success if we can find them all.
201 oname_parts = oname.split('.')
201 oname_parts = oname.split('.')
202 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
202 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
203 for nsname,ns in namespaces:
203 for nsname,ns in namespaces:
204 try:
204 try:
205 obj = ns[oname_head]
205 obj = ns[oname_head]
206 except KeyError:
206 except KeyError:
207 continue
207 continue
208 else:
208 else:
209 for part in oname_rest:
209 for part in oname_rest:
210 try:
210 try:
211 obj = getattr(obj,part)
211 obj = getattr(obj,part)
212 except:
212 except:
213 # Blanket except b/c some badly implemented objects
213 # Blanket except b/c some badly implemented objects
214 # allow __getattr__ to raise exceptions other than
214 # allow __getattr__ to raise exceptions other than
215 # AttributeError, which then crashes IPython.
215 # AttributeError, which then crashes IPython.
216 break
216 break
217 else:
217 else:
218 # If we finish the for loop (no break), we got all members
218 # If we finish the for loop (no break), we got all members
219 found = 1
219 found = 1
220 ospace = nsname
220 ospace = nsname
221 if ns == alias_ns:
221 if ns == alias_ns:
222 isalias = 1
222 isalias = 1
223 break # namespace loop
223 break # namespace loop
224
224
225 # Try to see if it's magic
225 # Try to see if it's magic
226 if not found:
226 if not found:
227 if oname.startswith(self.shell.ESC_MAGIC):
227 if oname.startswith(self.shell.ESC_MAGIC):
228 oname = oname[1:]
228 oname = oname[1:]
229 obj = getattr(self,'magic_'+oname,None)
229 obj = getattr(self,'magic_'+oname,None)
230 if obj is not None:
230 if obj is not None:
231 found = 1
231 found = 1
232 ospace = 'IPython internal'
232 ospace = 'IPython internal'
233 ismagic = 1
233 ismagic = 1
234
234
235 # Last try: special-case some literals like '', [], {}, etc:
235 # Last try: special-case some literals like '', [], {}, etc:
236 if not found and oname_head in ["''",'""','[]','{}','()']:
236 if not found and oname_head in ["''",'""','[]','{}','()']:
237 obj = eval(oname_head)
237 obj = eval(oname_head)
238 found = 1
238 found = 1
239 ospace = 'Interactive'
239 ospace = 'Interactive'
240
240
241 return {'found':found, 'obj':obj, 'namespace':ospace,
241 return {'found':found, 'obj':obj, 'namespace':ospace,
242 'ismagic':ismagic, 'isalias':isalias}
242 'ismagic':ismagic, 'isalias':isalias}
243
243
244 def arg_err(self,func):
244 def arg_err(self,func):
245 """Print docstring if incorrect arguments were passed"""
245 """Print docstring if incorrect arguments were passed"""
246 print 'Error in arguments:'
246 print 'Error in arguments:'
247 print OInspect.getdoc(func)
247 print OInspect.getdoc(func)
248
248
249 def format_latex(self,strng):
249 def format_latex(self,strng):
250 """Format a string for latex inclusion."""
250 """Format a string for latex inclusion."""
251
251
252 # Characters that need to be escaped for latex:
252 # Characters that need to be escaped for latex:
253 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
253 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
254 # Magic command names as headers:
254 # Magic command names as headers:
255 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
255 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
256 re.MULTILINE)
256 re.MULTILINE)
257 # Magic commands
257 # Magic commands
258 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
258 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
259 re.MULTILINE)
259 re.MULTILINE)
260 # Paragraph continue
260 # Paragraph continue
261 par_re = re.compile(r'\\$',re.MULTILINE)
261 par_re = re.compile(r'\\$',re.MULTILINE)
262
262
263 # The "\n" symbol
263 # The "\n" symbol
264 newline_re = re.compile(r'\\n')
264 newline_re = re.compile(r'\\n')
265
265
266 # Now build the string for output:
266 # Now build the string for output:
267 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
267 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
268 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
268 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
269 strng)
269 strng)
270 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
270 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
271 strng = par_re.sub(r'\\\\',strng)
271 strng = par_re.sub(r'\\\\',strng)
272 strng = escape_re.sub(r'\\\1',strng)
272 strng = escape_re.sub(r'\\\1',strng)
273 strng = newline_re.sub(r'\\textbackslash{}n',strng)
273 strng = newline_re.sub(r'\\textbackslash{}n',strng)
274 return strng
274 return strng
275
275
276 def format_screen(self,strng):
276 def format_screen(self,strng):
277 """Format a string for screen printing.
277 """Format a string for screen printing.
278
278
279 This removes some latex-type format codes."""
279 This removes some latex-type format codes."""
280 # Paragraph continue
280 # Paragraph continue
281 par_re = re.compile(r'\\$',re.MULTILINE)
281 par_re = re.compile(r'\\$',re.MULTILINE)
282 strng = par_re.sub('',strng)
282 strng = par_re.sub('',strng)
283 return strng
283 return strng
284
284
285 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
285 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
286 """Parse options passed to an argument string.
286 """Parse options passed to an argument string.
287
287
288 The interface is similar to that of getopt(), but it returns back a
288 The interface is similar to that of getopt(), but it returns back a
289 Struct with the options as keys and the stripped argument string still
289 Struct with the options as keys and the stripped argument string still
290 as a string.
290 as a string.
291
291
292 arg_str is quoted as a true sys.argv vector by using shlex.split.
292 arg_str is quoted as a true sys.argv vector by using shlex.split.
293 This allows us to easily expand variables, glob files, quote
293 This allows us to easily expand variables, glob files, quote
294 arguments, etc.
294 arguments, etc.
295
295
296 Options:
296 Options:
297 -mode: default 'string'. If given as 'list', the argument string is
297 -mode: default 'string'. If given as 'list', the argument string is
298 returned as a list (split on whitespace) instead of a string.
298 returned as a list (split on whitespace) instead of a string.
299
299
300 -list_all: put all option values in lists. Normally only options
300 -list_all: put all option values in lists. Normally only options
301 appearing more than once are put in a list."""
301 appearing more than once are put in a list."""
302
302
303 # inject default options at the beginning of the input line
303 # inject default options at the beginning of the input line
304 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
304 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
305 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
305 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
306
306
307 mode = kw.get('mode','string')
307 mode = kw.get('mode','string')
308 if mode not in ['string','list']:
308 if mode not in ['string','list']:
309 raise ValueError,'incorrect mode given: %s' % mode
309 raise ValueError,'incorrect mode given: %s' % mode
310 # Get options
310 # Get options
311 list_all = kw.get('list_all',0)
311 list_all = kw.get('list_all',0)
312
312
313 # Check if we have more than one argument to warrant extra processing:
313 # Check if we have more than one argument to warrant extra processing:
314 odict = {} # Dictionary with options
314 odict = {} # Dictionary with options
315 args = arg_str.split()
315 args = arg_str.split()
316 if len(args) >= 1:
316 if len(args) >= 1:
317 # If the list of inputs only has 0 or 1 thing in it, there's no
317 # If the list of inputs only has 0 or 1 thing in it, there's no
318 # need to look for options
318 # need to look for options
319 argv = shlex_split(arg_str)
319 argv = shlex_split(arg_str)
320 # Do regular option processing
320 # Do regular option processing
321 try:
321 try:
322 opts,args = getopt(argv,opt_str,*long_opts)
322 opts,args = getopt(argv,opt_str,*long_opts)
323 except GetoptError,e:
323 except GetoptError,e:
324 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
324 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
325 " ".join(long_opts)))
325 " ".join(long_opts)))
326 for o,a in opts:
326 for o,a in opts:
327 if o.startswith('--'):
327 if o.startswith('--'):
328 o = o[2:]
328 o = o[2:]
329 else:
329 else:
330 o = o[1:]
330 o = o[1:]
331 try:
331 try:
332 odict[o].append(a)
332 odict[o].append(a)
333 except AttributeError:
333 except AttributeError:
334 odict[o] = [odict[o],a]
334 odict[o] = [odict[o],a]
335 except KeyError:
335 except KeyError:
336 if list_all:
336 if list_all:
337 odict[o] = [a]
337 odict[o] = [a]
338 else:
338 else:
339 odict[o] = a
339 odict[o] = a
340
340
341 # Prepare opts,args for return
341 # Prepare opts,args for return
342 opts = Struct(odict)
342 opts = Struct(odict)
343 if mode == 'string':
343 if mode == 'string':
344 args = ' '.join(args)
344 args = ' '.join(args)
345
345
346 return opts,args
346 return opts,args
347
347
348 #......................................................................
348 #......................................................................
349 # And now the actual magic functions
349 # And now the actual magic functions
350
350
351 # Functions for IPython shell work (vars,funcs, config, etc)
351 # Functions for IPython shell work (vars,funcs, config, etc)
352 def magic_lsmagic(self, parameter_s = ''):
352 def magic_lsmagic(self, parameter_s = ''):
353 """List currently available magic functions."""
353 """List currently available magic functions."""
354 mesc = self.shell.ESC_MAGIC
354 mesc = self.shell.ESC_MAGIC
355 print 'Available magic functions:\n'+mesc+\
355 print 'Available magic functions:\n'+mesc+\
356 (' '+mesc).join(self.lsmagic())
356 (' '+mesc).join(self.lsmagic())
357 print '\n' + Magic.auto_status[self.shell.rc.automagic]
357 print '\n' + Magic.auto_status[self.shell.rc.automagic]
358 return None
358 return None
359
359
360 def magic_magic(self, parameter_s = ''):
360 def magic_magic(self, parameter_s = ''):
361 """Print information about the magic function system."""
361 """Print information about the magic function system."""
362
362
363 mode = ''
363 mode = ''
364 try:
364 try:
365 if parameter_s.split()[0] == '-latex':
365 if parameter_s.split()[0] == '-latex':
366 mode = 'latex'
366 mode = 'latex'
367 except:
367 except:
368 pass
368 pass
369
369
370 magic_docs = []
370 magic_docs = []
371 for fname in self.lsmagic():
371 for fname in self.lsmagic():
372 mname = 'magic_' + fname
372 mname = 'magic_' + fname
373 for space in (Magic,self,self.__class__):
373 for space in (Magic,self,self.__class__):
374 try:
374 try:
375 fn = space.__dict__[mname]
375 fn = space.__dict__[mname]
376 except KeyError:
376 except KeyError:
377 pass
377 pass
378 else:
378 else:
379 break
379 break
380 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
380 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
381 fname,fn.__doc__))
381 fname,fn.__doc__))
382 magic_docs = ''.join(magic_docs)
382 magic_docs = ''.join(magic_docs)
383
383
384 if mode == 'latex':
384 if mode == 'latex':
385 print self.format_latex(magic_docs)
385 print self.format_latex(magic_docs)
386 return
386 return
387 else:
387 else:
388 magic_docs = self.format_screen(magic_docs)
388 magic_docs = self.format_screen(magic_docs)
389
389
390 outmsg = """
390 outmsg = """
391 IPython's 'magic' functions
391 IPython's 'magic' functions
392 ===========================
392 ===========================
393
393
394 The magic function system provides a series of functions which allow you to
394 The magic function system provides a series of functions which allow you to
395 control the behavior of IPython itself, plus a lot of system-type
395 control the behavior of IPython itself, plus a lot of system-type
396 features. All these functions are prefixed with a % character, but parameters
396 features. All these functions are prefixed with a % character, but parameters
397 are given without parentheses or quotes.
397 are given without parentheses or quotes.
398
398
399 NOTE: If you have 'automagic' enabled (via the command line option or with the
399 NOTE: If you have 'automagic' enabled (via the command line option or with the
400 %automagic function), you don't need to type in the % explicitly. By default,
400 %automagic function), you don't need to type in the % explicitly. By default,
401 IPython ships with automagic on, so you should only rarely need the % escape.
401 IPython ships with automagic on, so you should only rarely need the % escape.
402
402
403 Example: typing '%cd mydir' (without the quotes) changes you working directory
403 Example: typing '%cd mydir' (without the quotes) changes you working directory
404 to 'mydir', if it exists.
404 to 'mydir', if it exists.
405
405
406 You can define your own magic functions to extend the system. See the supplied
406 You can define your own magic functions to extend the system. See the supplied
407 ipythonrc and example-magic.py files for details (in your ipython
407 ipythonrc and example-magic.py files for details (in your ipython
408 configuration directory, typically $HOME/.ipython/).
408 configuration directory, typically $HOME/.ipython/).
409
409
410 You can also define your own aliased names for magic functions. In your
410 You can also define your own aliased names for magic functions. In your
411 ipythonrc file, placing a line like:
411 ipythonrc file, placing a line like:
412
412
413 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
413 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
414
414
415 will define %pf as a new name for %profile.
415 will define %pf as a new name for %profile.
416
416
417 You can also call magics in code using the ipmagic() function, which IPython
417 You can also call magics in code using the ipmagic() function, which IPython
418 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
418 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
419
419
420 For a list of the available magic functions, use %lsmagic. For a description
420 For a list of the available magic functions, use %lsmagic. For a description
421 of any of them, type %magic_name?, e.g. '%cd?'.
421 of any of them, type %magic_name?, e.g. '%cd?'.
422
422
423 Currently the magic system has the following functions:\n"""
423 Currently the magic system has the following functions:\n"""
424
424
425 mesc = self.shell.ESC_MAGIC
425 mesc = self.shell.ESC_MAGIC
426 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
426 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
427 "\n\n%s%s\n\n%s" % (outmsg,
427 "\n\n%s%s\n\n%s" % (outmsg,
428 magic_docs,mesc,mesc,
428 magic_docs,mesc,mesc,
429 (' '+mesc).join(self.lsmagic()),
429 (' '+mesc).join(self.lsmagic()),
430 Magic.auto_status[self.shell.rc.automagic] ) )
430 Magic.auto_status[self.shell.rc.automagic] ) )
431
431
432 page(outmsg,screen_lines=self.shell.rc.screen_length)
432 page(outmsg,screen_lines=self.shell.rc.screen_length)
433
433
434 def magic_automagic(self, parameter_s = ''):
434 def magic_automagic(self, parameter_s = ''):
435 """Make magic functions callable without having to type the initial %.
435 """Make magic functions callable without having to type the initial %.
436
436
437 Toggles on/off (when off, you must call it as %automagic, of
437 Toggles on/off (when off, you must call it as %automagic, of
438 course). Note that magic functions have lowest priority, so if there's
438 course). Note that magic functions have lowest priority, so if there's
439 a variable whose name collides with that of a magic fn, automagic
439 a variable whose name collides with that of a magic fn, automagic
440 won't work for that function (you get the variable instead). However,
440 won't work for that function (you get the variable instead). However,
441 if you delete the variable (del var), the previously shadowed magic
441 if you delete the variable (del var), the previously shadowed magic
442 function becomes visible to automagic again."""
442 function becomes visible to automagic again."""
443
443
444 rc = self.shell.rc
444 rc = self.shell.rc
445 rc.automagic = not rc.automagic
445 rc.automagic = not rc.automagic
446 print '\n' + Magic.auto_status[rc.automagic]
446 print '\n' + Magic.auto_status[rc.automagic]
447
447
448 def magic_autocall(self, parameter_s = ''):
448 def magic_autocall(self, parameter_s = ''):
449 """Make functions callable without having to type parentheses.
449 """Make functions callable without having to type parentheses.
450
450
451 Usage:
451 Usage:
452
452
453 %autocall [mode]
453 %autocall [mode]
454
454
455 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
455 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
456 value is toggled on and off (remembering the previous state)."""
456 value is toggled on and off (remembering the previous state)."""
457
457
458 rc = self.shell.rc
458 rc = self.shell.rc
459
459
460 if parameter_s:
460 if parameter_s:
461 arg = int(parameter_s)
461 arg = int(parameter_s)
462 else:
462 else:
463 arg = 'toggle'
463 arg = 'toggle'
464
464
465 if not arg in (0,1,2,'toggle'):
465 if not arg in (0,1,2,'toggle'):
466 error('Valid modes: (0->Off, 1->Smart, 2->Full')
466 error('Valid modes: (0->Off, 1->Smart, 2->Full')
467 return
467 return
468
468
469 if arg in (0,1,2):
469 if arg in (0,1,2):
470 rc.autocall = arg
470 rc.autocall = arg
471 else: # toggle
471 else: # toggle
472 if rc.autocall:
472 if rc.autocall:
473 self._magic_state.autocall_save = rc.autocall
473 self._magic_state.autocall_save = rc.autocall
474 rc.autocall = 0
474 rc.autocall = 0
475 else:
475 else:
476 try:
476 try:
477 rc.autocall = self._magic_state.autocall_save
477 rc.autocall = self._magic_state.autocall_save
478 except AttributeError:
478 except AttributeError:
479 rc.autocall = self._magic_state.autocall_save = 1
479 rc.autocall = self._magic_state.autocall_save = 1
480
480
481 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
481 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
482
482
483 def magic_autoindent(self, parameter_s = ''):
483 def magic_autoindent(self, parameter_s = ''):
484 """Toggle autoindent on/off (if available)."""
484 """Toggle autoindent on/off (if available)."""
485
485
486 self.shell.set_autoindent()
486 self.shell.set_autoindent()
487 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
487 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
488
488
489 def magic_system_verbose(self, parameter_s = ''):
489 def magic_system_verbose(self, parameter_s = ''):
490 """Toggle verbose printing of system calls on/off."""
490 """Toggle verbose printing of system calls on/off."""
491
491
492 self.shell.rc_set_toggle('system_verbose')
492 self.shell.rc_set_toggle('system_verbose')
493 print "System verbose printing is:",\
493 print "System verbose printing is:",\
494 ['OFF','ON'][self.shell.rc.system_verbose]
494 ['OFF','ON'][self.shell.rc.system_verbose]
495
495
496 def magic_history(self, parameter_s = ''):
496 def magic_history(self, parameter_s = ''):
497 """Print input history (_i<n> variables), with most recent last.
497 """Print input history (_i<n> variables), with most recent last.
498
498
499 %history -> print at most 40 inputs (some may be multi-line)\\
499 %history -> print at most 40 inputs (some may be multi-line)\\
500 %history n -> print at most n inputs\\
500 %history n -> print at most n inputs\\
501 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
501 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
502
502
503 Each input's number <n> is shown, and is accessible as the
503 Each input's number <n> is shown, and is accessible as the
504 automatically generated variable _i<n>. Multi-line statements are
504 automatically generated variable _i<n>. Multi-line statements are
505 printed starting at a new line for easy copy/paste.
505 printed starting at a new line for easy copy/paste.
506
506
507
507
508 Options:
508 Options:
509
509
510 -n: do NOT print line numbers. This is useful if you want to get a
510 -n: do NOT print line numbers. This is useful if you want to get a
511 printout of many lines which can be directly pasted into a text
511 printout of many lines which can be directly pasted into a text
512 editor.
512 editor.
513
513
514 This feature is only available if numbered prompts are in use.
514 This feature is only available if numbered prompts are in use.
515
515
516 -r: print the 'raw' history. IPython filters your input and
516 -r: print the 'raw' history. IPython filters your input and
517 converts it all into valid Python source before executing it (things
517 converts it all into valid Python source before executing it (things
518 like magics or aliases are turned into function calls, for
518 like magics or aliases are turned into function calls, for
519 example). With this option, you'll see the unfiltered history
519 example). With this option, you'll see the unfiltered history
520 instead of the filtered version: '%cd /' will be seen as '%cd /'
520 instead of the filtered version: '%cd /' will be seen as '%cd /'
521 instead of '_ip.magic("%cd /")'.
521 instead of '_ip.magic("%cd /")'.
522 """
522 """
523
523
524 shell = self.shell
524 shell = self.shell
525 if not shell.outputcache.do_full_cache:
525 if not shell.outputcache.do_full_cache:
526 print 'This feature is only available if numbered prompts are in use.'
526 print 'This feature is only available if numbered prompts are in use.'
527 return
527 return
528 opts,args = self.parse_options(parameter_s,'nr',mode='list')
528 opts,args = self.parse_options(parameter_s,'nr',mode='list')
529
529
530 if opts.has_key('r'):
530 if opts.has_key('r'):
531 input_hist = shell.input_hist_raw
531 input_hist = shell.input_hist_raw
532 else:
532 else:
533 input_hist = shell.input_hist
533 input_hist = shell.input_hist
534
534
535 default_length = 40
535 default_length = 40
536 if len(args) == 0:
536 if len(args) == 0:
537 final = len(input_hist)
537 final = len(input_hist)
538 init = max(1,final-default_length)
538 init = max(1,final-default_length)
539 elif len(args) == 1:
539 elif len(args) == 1:
540 final = len(input_hist)
540 final = len(input_hist)
541 init = max(1,final-int(args[0]))
541 init = max(1,final-int(args[0]))
542 elif len(args) == 2:
542 elif len(args) == 2:
543 init,final = map(int,args)
543 init,final = map(int,args)
544 else:
544 else:
545 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
545 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
546 print self.magic_hist.__doc__
546 print self.magic_hist.__doc__
547 return
547 return
548 width = len(str(final))
548 width = len(str(final))
549 line_sep = ['','\n']
549 line_sep = ['','\n']
550 print_nums = not opts.has_key('n')
550 print_nums = not opts.has_key('n')
551 for in_num in range(init,final):
551 for in_num in range(init,final):
552 inline = input_hist[in_num]
552 inline = input_hist[in_num]
553 multiline = int(inline.count('\n') > 1)
553 multiline = int(inline.count('\n') > 1)
554 if print_nums:
554 if print_nums:
555 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
555 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
556 print inline,
556 print inline,
557
557
558 def magic_hist(self, parameter_s=''):
558 def magic_hist(self, parameter_s=''):
559 """Alternate name for %history."""
559 """Alternate name for %history."""
560 return self.magic_history(parameter_s)
560 return self.magic_history(parameter_s)
561
561
562 def magic_p(self, parameter_s=''):
562 def magic_p(self, parameter_s=''):
563 """Just a short alias for Python's 'print'."""
563 """Just a short alias for Python's 'print'."""
564 exec 'print ' + parameter_s in self.shell.user_ns
564 exec 'print ' + parameter_s in self.shell.user_ns
565
565
566 def magic_r(self, parameter_s=''):
566 def magic_r(self, parameter_s=''):
567 """Repeat previous input.
567 """Repeat previous input.
568
568
569 If given an argument, repeats the previous command which starts with
569 If given an argument, repeats the previous command which starts with
570 the same string, otherwise it just repeats the previous input.
570 the same string, otherwise it just repeats the previous input.
571
571
572 Shell escaped commands (with ! as first character) are not recognized
572 Shell escaped commands (with ! as first character) are not recognized
573 by this system, only pure python code and magic commands.
573 by this system, only pure python code and magic commands.
574 """
574 """
575
575
576 start = parameter_s.strip()
576 start = parameter_s.strip()
577 esc_magic = self.shell.ESC_MAGIC
577 esc_magic = self.shell.ESC_MAGIC
578 # Identify magic commands even if automagic is on (which means
578 # Identify magic commands even if automagic is on (which means
579 # the in-memory version is different from that typed by the user).
579 # the in-memory version is different from that typed by the user).
580 if self.shell.rc.automagic:
580 if self.shell.rc.automagic:
581 start_magic = esc_magic+start
581 start_magic = esc_magic+start
582 else:
582 else:
583 start_magic = start
583 start_magic = start
584 # Look through the input history in reverse
584 # Look through the input history in reverse
585 for n in range(len(self.shell.input_hist)-2,0,-1):
585 for n in range(len(self.shell.input_hist)-2,0,-1):
586 input = self.shell.input_hist[n]
586 input = self.shell.input_hist[n]
587 # skip plain 'r' lines so we don't recurse to infinity
587 # skip plain 'r' lines so we don't recurse to infinity
588 if input != '_ip.magic("r")\n' and \
588 if input != '_ip.magic("r")\n' and \
589 (input.startswith(start) or input.startswith(start_magic)):
589 (input.startswith(start) or input.startswith(start_magic)):
590 #print 'match',`input` # dbg
590 #print 'match',`input` # dbg
591 print 'Executing:',input,
591 print 'Executing:',input,
592 self.shell.runlines(input)
592 self.shell.runlines(input)
593 return
593 return
594 print 'No previous input matching `%s` found.' % start
594 print 'No previous input matching `%s` found.' % start
595
595
596 def magic_page(self, parameter_s=''):
596 def magic_page(self, parameter_s=''):
597 """Pretty print the object and display it through a pager.
597 """Pretty print the object and display it through a pager.
598
598
599 If no parameter is given, use _ (last output)."""
599 If no parameter is given, use _ (last output)."""
600 # After a function contributed by Olivier Aubert, slightly modified.
600 # After a function contributed by Olivier Aubert, slightly modified.
601
601
602 oname = parameter_s and parameter_s or '_'
602 oname = parameter_s and parameter_s or '_'
603 info = self._ofind(oname)
603 info = self._ofind(oname)
604 if info['found']:
604 if info['found']:
605 page(pformat(info['obj']))
605 page(pformat(info['obj']))
606 else:
606 else:
607 print 'Object `%s` not found' % oname
607 print 'Object `%s` not found' % oname
608
608
609 def magic_profile(self, parameter_s=''):
609 def magic_profile(self, parameter_s=''):
610 """Print your currently active IPyhton profile."""
610 """Print your currently active IPyhton profile."""
611 if self.shell.rc.profile:
611 if self.shell.rc.profile:
612 printpl('Current IPython profile: $self.shell.rc.profile.')
612 printpl('Current IPython profile: $self.shell.rc.profile.')
613 else:
613 else:
614 print 'No profile active.'
614 print 'No profile active.'
615
615
616 def _inspect(self,meth,oname,**kw):
616 def _inspect(self,meth,oname,**kw):
617 """Generic interface to the inspector system.
617 """Generic interface to the inspector system.
618
618
619 This function is meant to be called by pdef, pdoc & friends."""
619 This function is meant to be called by pdef, pdoc & friends."""
620
620
621 oname = oname.strip()
621 oname = oname.strip()
622 info = Struct(self._ofind(oname))
622 info = Struct(self._ofind(oname))
623 if info.found:
623 if info.found:
624 pmethod = getattr(self.shell.inspector,meth)
624 pmethod = getattr(self.shell.inspector,meth)
625 formatter = info.ismagic and self.format_screen or None
625 formatter = info.ismagic and self.format_screen or None
626 if meth == 'pdoc':
626 if meth == 'pdoc':
627 pmethod(info.obj,oname,formatter)
627 pmethod(info.obj,oname,formatter)
628 elif meth == 'pinfo':
628 elif meth == 'pinfo':
629 pmethod(info.obj,oname,formatter,info,**kw)
629 pmethod(info.obj,oname,formatter,info,**kw)
630 else:
630 else:
631 pmethod(info.obj,oname)
631 pmethod(info.obj,oname)
632 else:
632 else:
633 print 'Object `%s` not found.' % oname
633 print 'Object `%s` not found.' % oname
634 return 'not found' # so callers can take other action
634 return 'not found' # so callers can take other action
635
635
636 def magic_pdef(self, parameter_s=''):
636 def magic_pdef(self, parameter_s=''):
637 """Print the definition header for any callable object.
637 """Print the definition header for any callable object.
638
638
639 If the object is a class, print the constructor information."""
639 If the object is a class, print the constructor information."""
640 self._inspect('pdef',parameter_s)
640 self._inspect('pdef',parameter_s)
641
641
642 def magic_pdoc(self, parameter_s=''):
642 def magic_pdoc(self, parameter_s=''):
643 """Print the docstring for an object.
643 """Print the docstring for an object.
644
644
645 If the given object is a class, it will print both the class and the
645 If the given object is a class, it will print both the class and the
646 constructor docstrings."""
646 constructor docstrings."""
647 self._inspect('pdoc',parameter_s)
647 self._inspect('pdoc',parameter_s)
648
648
649 def magic_psource(self, parameter_s=''):
649 def magic_psource(self, parameter_s=''):
650 """Print (or run through pager) the source code for an object."""
650 """Print (or run through pager) the source code for an object."""
651 self._inspect('psource',parameter_s)
651 self._inspect('psource',parameter_s)
652
652
653 def magic_pfile(self, parameter_s=''):
653 def magic_pfile(self, parameter_s=''):
654 """Print (or run through pager) the file where an object is defined.
654 """Print (or run through pager) the file where an object is defined.
655
655
656 The file opens at the line where the object definition begins. IPython
656 The file opens at the line where the object definition begins. IPython
657 will honor the environment variable PAGER if set, and otherwise will
657 will honor the environment variable PAGER if set, and otherwise will
658 do its best to print the file in a convenient form.
658 do its best to print the file in a convenient form.
659
659
660 If the given argument is not an object currently defined, IPython will
660 If the given argument is not an object currently defined, IPython will
661 try to interpret it as a filename (automatically adding a .py extension
661 try to interpret it as a filename (automatically adding a .py extension
662 if needed). You can thus use %pfile as a syntax highlighting code
662 if needed). You can thus use %pfile as a syntax highlighting code
663 viewer."""
663 viewer."""
664
664
665 # first interpret argument as an object name
665 # first interpret argument as an object name
666 out = self._inspect('pfile',parameter_s)
666 out = self._inspect('pfile',parameter_s)
667 # if not, try the input as a filename
667 # if not, try the input as a filename
668 if out == 'not found':
668 if out == 'not found':
669 try:
669 try:
670 filename = get_py_filename(parameter_s)
670 filename = get_py_filename(parameter_s)
671 except IOError,msg:
671 except IOError,msg:
672 print msg
672 print msg
673 return
673 return
674 page(self.shell.inspector.format(file(filename).read()))
674 page(self.shell.inspector.format(file(filename).read()))
675
675
676 def magic_pinfo(self, parameter_s=''):
676 def magic_pinfo(self, parameter_s=''):
677 """Provide detailed information about an object.
677 """Provide detailed information about an object.
678
678
679 '%pinfo object' is just a synonym for object? or ?object."""
679 '%pinfo object' is just a synonym for object? or ?object."""
680
680
681 #print 'pinfo par: <%s>' % parameter_s # dbg
681 #print 'pinfo par: <%s>' % parameter_s # dbg
682
682
683 # detail_level: 0 -> obj? , 1 -> obj??
683 # detail_level: 0 -> obj? , 1 -> obj??
684 detail_level = 0
684 detail_level = 0
685 # We need to detect if we got called as 'pinfo pinfo foo', which can
685 # We need to detect if we got called as 'pinfo pinfo foo', which can
686 # happen if the user types 'pinfo foo?' at the cmd line.
686 # happen if the user types 'pinfo foo?' at the cmd line.
687 pinfo,qmark1,oname,qmark2 = \
687 pinfo,qmark1,oname,qmark2 = \
688 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
688 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
689 if pinfo or qmark1 or qmark2:
689 if pinfo or qmark1 or qmark2:
690 detail_level = 1
690 detail_level = 1
691 if "*" in oname:
691 if "*" in oname:
692 self.magic_psearch(oname)
692 self.magic_psearch(oname)
693 else:
693 else:
694 self._inspect('pinfo',oname,detail_level=detail_level)
694 self._inspect('pinfo',oname,detail_level=detail_level)
695
695
696 def magic_psearch(self, parameter_s=''):
696 def magic_psearch(self, parameter_s=''):
697 """Search for object in namespaces by wildcard.
697 """Search for object in namespaces by wildcard.
698
698
699 %psearch [options] PATTERN [OBJECT TYPE]
699 %psearch [options] PATTERN [OBJECT TYPE]
700
700
701 Note: ? can be used as a synonym for %psearch, at the beginning or at
701 Note: ? can be used as a synonym for %psearch, at the beginning or at
702 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
702 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
703 rest of the command line must be unchanged (options come first), so
703 rest of the command line must be unchanged (options come first), so
704 for example the following forms are equivalent
704 for example the following forms are equivalent
705
705
706 %psearch -i a* function
706 %psearch -i a* function
707 -i a* function?
707 -i a* function?
708 ?-i a* function
708 ?-i a* function
709
709
710 Arguments:
710 Arguments:
711
711
712 PATTERN
712 PATTERN
713
713
714 where PATTERN is a string containing * as a wildcard similar to its
714 where PATTERN is a string containing * as a wildcard similar to its
715 use in a shell. The pattern is matched in all namespaces on the
715 use in a shell. The pattern is matched in all namespaces on the
716 search path. By default objects starting with a single _ are not
716 search path. By default objects starting with a single _ are not
717 matched, many IPython generated objects have a single
717 matched, many IPython generated objects have a single
718 underscore. The default is case insensitive matching. Matching is
718 underscore. The default is case insensitive matching. Matching is
719 also done on the attributes of objects and not only on the objects
719 also done on the attributes of objects and not only on the objects
720 in a module.
720 in a module.
721
721
722 [OBJECT TYPE]
722 [OBJECT TYPE]
723
723
724 Is the name of a python type from the types module. The name is
724 Is the name of a python type from the types module. The name is
725 given in lowercase without the ending type, ex. StringType is
725 given in lowercase without the ending type, ex. StringType is
726 written string. By adding a type here only objects matching the
726 written string. By adding a type here only objects matching the
727 given type are matched. Using all here makes the pattern match all
727 given type are matched. Using all here makes the pattern match all
728 types (this is the default).
728 types (this is the default).
729
729
730 Options:
730 Options:
731
731
732 -a: makes the pattern match even objects whose names start with a
732 -a: makes the pattern match even objects whose names start with a
733 single underscore. These names are normally ommitted from the
733 single underscore. These names are normally ommitted from the
734 search.
734 search.
735
735
736 -i/-c: make the pattern case insensitive/sensitive. If neither of
736 -i/-c: make the pattern case insensitive/sensitive. If neither of
737 these options is given, the default is read from your ipythonrc
737 these options is given, the default is read from your ipythonrc
738 file. The option name which sets this value is
738 file. The option name which sets this value is
739 'wildcards_case_sensitive'. If this option is not specified in your
739 'wildcards_case_sensitive'. If this option is not specified in your
740 ipythonrc file, IPython's internal default is to do a case sensitive
740 ipythonrc file, IPython's internal default is to do a case sensitive
741 search.
741 search.
742
742
743 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
743 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
744 specifiy can be searched in any of the following namespaces:
744 specifiy can be searched in any of the following namespaces:
745 'builtin', 'user', 'user_global','internal', 'alias', where
745 'builtin', 'user', 'user_global','internal', 'alias', where
746 'builtin' and 'user' are the search defaults. Note that you should
746 'builtin' and 'user' are the search defaults. Note that you should
747 not use quotes when specifying namespaces.
747 not use quotes when specifying namespaces.
748
748
749 'Builtin' contains the python module builtin, 'user' contains all
749 'Builtin' contains the python module builtin, 'user' contains all
750 user data, 'alias' only contain the shell aliases and no python
750 user data, 'alias' only contain the shell aliases and no python
751 objects, 'internal' contains objects used by IPython. The
751 objects, 'internal' contains objects used by IPython. The
752 'user_global' namespace is only used by embedded IPython instances,
752 'user_global' namespace is only used by embedded IPython instances,
753 and it contains module-level globals. You can add namespaces to the
753 and it contains module-level globals. You can add namespaces to the
754 search with -s or exclude them with -e (these options can be given
754 search with -s or exclude them with -e (these options can be given
755 more than once).
755 more than once).
756
756
757 Examples:
757 Examples:
758
758
759 %psearch a* -> objects beginning with an a
759 %psearch a* -> objects beginning with an a
760 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
760 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
761 %psearch a* function -> all functions beginning with an a
761 %psearch a* function -> all functions beginning with an a
762 %psearch re.e* -> objects beginning with an e in module re
762 %psearch re.e* -> objects beginning with an e in module re
763 %psearch r*.e* -> objects that start with e in modules starting in r
763 %psearch r*.e* -> objects that start with e in modules starting in r
764 %psearch r*.* string -> all strings in modules beginning with r
764 %psearch r*.* string -> all strings in modules beginning with r
765
765
766 Case sensitve search:
766 Case sensitve search:
767
767
768 %psearch -c a* list all object beginning with lower case a
768 %psearch -c a* list all object beginning with lower case a
769
769
770 Show objects beginning with a single _:
770 Show objects beginning with a single _:
771
771
772 %psearch -a _* list objects beginning with a single underscore"""
772 %psearch -a _* list objects beginning with a single underscore"""
773
773
774 # default namespaces to be searched
774 # default namespaces to be searched
775 def_search = ['user','builtin']
775 def_search = ['user','builtin']
776
776
777 # Process options/args
777 # Process options/args
778 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
778 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
779 opt = opts.get
779 opt = opts.get
780 shell = self.shell
780 shell = self.shell
781 psearch = shell.inspector.psearch
781 psearch = shell.inspector.psearch
782
782
783 # select case options
783 # select case options
784 if opts.has_key('i'):
784 if opts.has_key('i'):
785 ignore_case = True
785 ignore_case = True
786 elif opts.has_key('c'):
786 elif opts.has_key('c'):
787 ignore_case = False
787 ignore_case = False
788 else:
788 else:
789 ignore_case = not shell.rc.wildcards_case_sensitive
789 ignore_case = not shell.rc.wildcards_case_sensitive
790
790
791 # Build list of namespaces to search from user options
791 # Build list of namespaces to search from user options
792 def_search.extend(opt('s',[]))
792 def_search.extend(opt('s',[]))
793 ns_exclude = ns_exclude=opt('e',[])
793 ns_exclude = ns_exclude=opt('e',[])
794 ns_search = [nm for nm in def_search if nm not in ns_exclude]
794 ns_search = [nm for nm in def_search if nm not in ns_exclude]
795
795
796 # Call the actual search
796 # Call the actual search
797 try:
797 try:
798 psearch(args,shell.ns_table,ns_search,
798 psearch(args,shell.ns_table,ns_search,
799 show_all=opt('a'),ignore_case=ignore_case)
799 show_all=opt('a'),ignore_case=ignore_case)
800 except:
800 except:
801 shell.showtraceback()
801 shell.showtraceback()
802
802
803 def magic_who_ls(self, parameter_s=''):
803 def magic_who_ls(self, parameter_s=''):
804 """Return a sorted list of all interactive variables.
804 """Return a sorted list of all interactive variables.
805
805
806 If arguments are given, only variables of types matching these
806 If arguments are given, only variables of types matching these
807 arguments are returned."""
807 arguments are returned."""
808
808
809 user_ns = self.shell.user_ns
809 user_ns = self.shell.user_ns
810 internal_ns = self.shell.internal_ns
810 internal_ns = self.shell.internal_ns
811 user_config_ns = self.shell.user_config_ns
811 user_config_ns = self.shell.user_config_ns
812 out = []
812 out = []
813 typelist = parameter_s.split()
813 typelist = parameter_s.split()
814
814
815 for i in user_ns:
815 for i in user_ns:
816 if not (i.startswith('_') or i.startswith('_i')) \
816 if not (i.startswith('_') or i.startswith('_i')) \
817 and not (i in internal_ns or i in user_config_ns):
817 and not (i in internal_ns or i in user_config_ns):
818 if typelist:
818 if typelist:
819 if type(user_ns[i]).__name__ in typelist:
819 if type(user_ns[i]).__name__ in typelist:
820 out.append(i)
820 out.append(i)
821 else:
821 else:
822 out.append(i)
822 out.append(i)
823 out.sort()
823 out.sort()
824 return out
824 return out
825
825
826 def magic_who(self, parameter_s=''):
826 def magic_who(self, parameter_s=''):
827 """Print all interactive variables, with some minimal formatting.
827 """Print all interactive variables, with some minimal formatting.
828
828
829 If any arguments are given, only variables whose type matches one of
829 If any arguments are given, only variables whose type matches one of
830 these are printed. For example:
830 these are printed. For example:
831
831
832 %who function str
832 %who function str
833
833
834 will only list functions and strings, excluding all other types of
834 will only list functions and strings, excluding all other types of
835 variables. To find the proper type names, simply use type(var) at a
835 variables. To find the proper type names, simply use type(var) at a
836 command line to see how python prints type names. For example:
836 command line to see how python prints type names. For example:
837
837
838 In [1]: type('hello')\\
838 In [1]: type('hello')\\
839 Out[1]: <type 'str'>
839 Out[1]: <type 'str'>
840
840
841 indicates that the type name for strings is 'str'.
841 indicates that the type name for strings is 'str'.
842
842
843 %who always excludes executed names loaded through your configuration
843 %who always excludes executed names loaded through your configuration
844 file and things which are internal to IPython.
844 file and things which are internal to IPython.
845
845
846 This is deliberate, as typically you may load many modules and the
846 This is deliberate, as typically you may load many modules and the
847 purpose of %who is to show you only what you've manually defined."""
847 purpose of %who is to show you only what you've manually defined."""
848
848
849 varlist = self.magic_who_ls(parameter_s)
849 varlist = self.magic_who_ls(parameter_s)
850 if not varlist:
850 if not varlist:
851 print 'Interactive namespace is empty.'
851 print 'Interactive namespace is empty.'
852 return
852 return
853
853
854 # if we have variables, move on...
854 # if we have variables, move on...
855
855
856 # stupid flushing problem: when prompts have no separators, stdout is
856 # stupid flushing problem: when prompts have no separators, stdout is
857 # getting lost. I'm starting to think this is a python bug. I'm having
857 # getting lost. I'm starting to think this is a python bug. I'm having
858 # to force a flush with a print because even a sys.stdout.flush
858 # to force a flush with a print because even a sys.stdout.flush
859 # doesn't seem to do anything!
859 # doesn't seem to do anything!
860
860
861 count = 0
861 count = 0
862 for i in varlist:
862 for i in varlist:
863 print i+'\t',
863 print i+'\t',
864 count += 1
864 count += 1
865 if count > 8:
865 if count > 8:
866 count = 0
866 count = 0
867 print
867 print
868 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
868 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
869
869
870 print # well, this does force a flush at the expense of an extra \n
870 print # well, this does force a flush at the expense of an extra \n
871
871
872 def magic_whos(self, parameter_s=''):
872 def magic_whos(self, parameter_s=''):
873 """Like %who, but gives some extra information about each variable.
873 """Like %who, but gives some extra information about each variable.
874
874
875 The same type filtering of %who can be applied here.
875 The same type filtering of %who can be applied here.
876
876
877 For all variables, the type is printed. Additionally it prints:
877 For all variables, the type is printed. Additionally it prints:
878
878
879 - For {},[],(): their length.
879 - For {},[],(): their length.
880
880
881 - For Numeric arrays, a summary with shape, number of elements,
881 - For Numeric arrays, a summary with shape, number of elements,
882 typecode and size in memory.
882 typecode and size in memory.
883
883
884 - Everything else: a string representation, snipping their middle if
884 - Everything else: a string representation, snipping their middle if
885 too long."""
885 too long."""
886
886
887 varnames = self.magic_who_ls(parameter_s)
887 varnames = self.magic_who_ls(parameter_s)
888 if not varnames:
888 if not varnames:
889 print 'Interactive namespace is empty.'
889 print 'Interactive namespace is empty.'
890 return
890 return
891
891
892 # if we have variables, move on...
892 # if we have variables, move on...
893
893
894 # for these types, show len() instead of data:
894 # for these types, show len() instead of data:
895 seq_types = [types.DictType,types.ListType,types.TupleType]
895 seq_types = [types.DictType,types.ListType,types.TupleType]
896
896
897 # for Numeric arrays, display summary info
897 # for Numeric arrays, display summary info
898 try:
898 try:
899 import Numeric
899 import Numeric
900 except ImportError:
900 except ImportError:
901 array_type = None
901 array_type = None
902 else:
902 else:
903 array_type = Numeric.ArrayType.__name__
903 array_type = Numeric.ArrayType.__name__
904
904
905 # Find all variable names and types so we can figure out column sizes
905 # Find all variable names and types so we can figure out column sizes
906 get_vars = lambda i: self.shell.user_ns[i]
906 get_vars = lambda i: self.shell.user_ns[i]
907 type_name = lambda v: type(v).__name__
907 type_name = lambda v: type(v).__name__
908 varlist = map(get_vars,varnames)
908 varlist = map(get_vars,varnames)
909
909
910 typelist = []
910 typelist = []
911 for vv in varlist:
911 for vv in varlist:
912 tt = type_name(vv)
912 tt = type_name(vv)
913 if tt=='instance':
913 if tt=='instance':
914 typelist.append(str(vv.__class__))
914 typelist.append(str(vv.__class__))
915 else:
915 else:
916 typelist.append(tt)
916 typelist.append(tt)
917
917
918 # column labels and # of spaces as separator
918 # column labels and # of spaces as separator
919 varlabel = 'Variable'
919 varlabel = 'Variable'
920 typelabel = 'Type'
920 typelabel = 'Type'
921 datalabel = 'Data/Info'
921 datalabel = 'Data/Info'
922 colsep = 3
922 colsep = 3
923 # variable format strings
923 # variable format strings
924 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
924 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
925 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
925 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
926 aformat = "%s: %s elems, type `%s`, %s bytes"
926 aformat = "%s: %s elems, type `%s`, %s bytes"
927 # find the size of the columns to format the output nicely
927 # find the size of the columns to format the output nicely
928 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
928 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
929 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
929 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
930 # table header
930 # table header
931 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
931 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
932 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
932 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
933 # and the table itself
933 # and the table itself
934 kb = 1024
934 kb = 1024
935 Mb = 1048576 # kb**2
935 Mb = 1048576 # kb**2
936 for vname,var,vtype in zip(varnames,varlist,typelist):
936 for vname,var,vtype in zip(varnames,varlist,typelist):
937 print itpl(vformat),
937 print itpl(vformat),
938 if vtype in seq_types:
938 if vtype in seq_types:
939 print len(var)
939 print len(var)
940 elif vtype==array_type:
940 elif vtype==array_type:
941 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
941 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
942 vsize = Numeric.size(var)
942 vsize = Numeric.size(var)
943 vbytes = vsize*var.itemsize()
943 vbytes = vsize*var.itemsize()
944 if vbytes < 100000:
944 if vbytes < 100000:
945 print aformat % (vshape,vsize,var.typecode(),vbytes)
945 print aformat % (vshape,vsize,var.typecode(),vbytes)
946 else:
946 else:
947 print aformat % (vshape,vsize,var.typecode(),vbytes),
947 print aformat % (vshape,vsize,var.typecode(),vbytes),
948 if vbytes < Mb:
948 if vbytes < Mb:
949 print '(%s kb)' % (vbytes/kb,)
949 print '(%s kb)' % (vbytes/kb,)
950 else:
950 else:
951 print '(%s Mb)' % (vbytes/Mb,)
951 print '(%s Mb)' % (vbytes/Mb,)
952 else:
952 else:
953 vstr = str(var).replace('\n','\\n')
953 vstr = str(var).replace('\n','\\n')
954 if len(vstr) < 50:
954 if len(vstr) < 50:
955 print vstr
955 print vstr
956 else:
956 else:
957 printpl(vfmt_short)
957 printpl(vfmt_short)
958
958
959 def magic_reset(self, parameter_s=''):
959 def magic_reset(self, parameter_s=''):
960 """Resets the namespace by removing all names defined by the user.
960 """Resets the namespace by removing all names defined by the user.
961
961
962 Input/Output history are left around in case you need them."""
962 Input/Output history are left around in case you need them."""
963
963
964 ans = raw_input(
964 ans = raw_input(
965 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
965 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
966 if not ans.lower() == 'y':
966 if not ans.lower() == 'y':
967 print 'Nothing done.'
967 print 'Nothing done.'
968 return
968 return
969 user_ns = self.shell.user_ns
969 user_ns = self.shell.user_ns
970 for i in self.magic_who_ls():
970 for i in self.magic_who_ls():
971 del(user_ns[i])
971 del(user_ns[i])
972
972
973 def magic_config(self,parameter_s=''):
973 def magic_config(self,parameter_s=''):
974 """Show IPython's internal configuration."""
974 """Show IPython's internal configuration."""
975
975
976 page('Current configuration structure:\n'+
976 page('Current configuration structure:\n'+
977 pformat(self.shell.rc.dict()))
977 pformat(self.shell.rc.dict()))
978
978
979 def magic_logstart(self,parameter_s=''):
979 def magic_logstart(self,parameter_s=''):
980 """Start logging anywhere in a session.
980 """Start logging anywhere in a session.
981
981
982 %logstart [-o|-t] [log_name [log_mode]]
982 %logstart [-o|-t] [log_name [log_mode]]
983
983
984 If no name is given, it defaults to a file named 'ipython_log.py' in your
984 If no name is given, it defaults to a file named 'ipython_log.py' in your
985 current directory, in 'rotate' mode (see below).
985 current directory, in 'rotate' mode (see below).
986
986
987 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
987 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
988 history up to that point and then continues logging.
988 history up to that point and then continues logging.
989
989
990 %logstart takes a second optional parameter: logging mode. This can be one
990 %logstart takes a second optional parameter: logging mode. This can be one
991 of (note that the modes are given unquoted):\\
991 of (note that the modes are given unquoted):\\
992 append: well, that says it.\\
992 append: well, that says it.\\
993 backup: rename (if exists) to name~ and start name.\\
993 backup: rename (if exists) to name~ and start name.\\
994 global: single logfile in your home dir, appended to.\\
994 global: single logfile in your home dir, appended to.\\
995 over : overwrite existing log.\\
995 over : overwrite existing log.\\
996 rotate: create rotating logs name.1~, name.2~, etc.
996 rotate: create rotating logs name.1~, name.2~, etc.
997
997
998 Options:
998 Options:
999
999
1000 -o: log also IPython's output. In this mode, all commands which
1000 -o: log also IPython's output. In this mode, all commands which
1001 generate an Out[NN] prompt are recorded to the logfile, right after
1001 generate an Out[NN] prompt are recorded to the logfile, right after
1002 their corresponding input line. The output lines are always
1002 their corresponding input line. The output lines are always
1003 prepended with a '#[Out]# ' marker, so that the log remains valid
1003 prepended with a '#[Out]# ' marker, so that the log remains valid
1004 Python code.
1004 Python code.
1005
1005
1006 Since this marker is always the same, filtering only the output from
1006 Since this marker is always the same, filtering only the output from
1007 a log is very easy, using for example a simple awk call:
1007 a log is very easy, using for example a simple awk call:
1008
1008
1009 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1009 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1010
1010
1011 -t: put timestamps before each input line logged (these are put in
1011 -t: put timestamps before each input line logged (these are put in
1012 comments)."""
1012 comments)."""
1013
1013
1014 opts,par = self.parse_options(parameter_s,'ot')
1014 opts,par = self.parse_options(parameter_s,'ot')
1015 log_output = 'o' in opts
1015 log_output = 'o' in opts
1016 timestamp = 't' in opts
1016 timestamp = 't' in opts
1017
1017
1018 rc = self.shell.rc
1018 rc = self.shell.rc
1019 logger = self.shell.logger
1019 logger = self.shell.logger
1020
1020
1021 # if no args are given, the defaults set in the logger constructor by
1021 # if no args are given, the defaults set in the logger constructor by
1022 # ipytohn remain valid
1022 # ipytohn remain valid
1023 if par:
1023 if par:
1024 try:
1024 try:
1025 logfname,logmode = par.split()
1025 logfname,logmode = par.split()
1026 except:
1026 except:
1027 logfname = par
1027 logfname = par
1028 logmode = 'backup'
1028 logmode = 'backup'
1029 else:
1029 else:
1030 logfname = logger.logfname
1030 logfname = logger.logfname
1031 logmode = logger.logmode
1031 logmode = logger.logmode
1032 # put logfname into rc struct as if it had been called on the command
1032 # put logfname into rc struct as if it had been called on the command
1033 # line, so it ends up saved in the log header Save it in case we need
1033 # line, so it ends up saved in the log header Save it in case we need
1034 # to restore it...
1034 # to restore it...
1035 old_logfile = rc.opts.get('logfile','')
1035 old_logfile = rc.opts.get('logfile','')
1036 if logfname:
1036 if logfname:
1037 logfname = os.path.expanduser(logfname)
1037 logfname = os.path.expanduser(logfname)
1038 rc.opts.logfile = logfname
1038 rc.opts.logfile = logfname
1039 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1039 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1040 try:
1040 try:
1041 started = logger.logstart(logfname,loghead,logmode,
1041 started = logger.logstart(logfname,loghead,logmode,
1042 log_output,timestamp)
1042 log_output,timestamp)
1043 except:
1043 except:
1044 rc.opts.logfile = old_logfile
1044 rc.opts.logfile = old_logfile
1045 warn("Couldn't start log: %s" % sys.exc_info()[1])
1045 warn("Couldn't start log: %s" % sys.exc_info()[1])
1046 else:
1046 else:
1047 # log input history up to this point, optionally interleaving
1047 # log input history up to this point, optionally interleaving
1048 # output if requested
1048 # output if requested
1049
1049
1050 if timestamp:
1050 if timestamp:
1051 # disable timestamping for the previous history, since we've
1051 # disable timestamping for the previous history, since we've
1052 # lost those already (no time machine here).
1052 # lost those already (no time machine here).
1053 logger.timestamp = False
1053 logger.timestamp = False
1054 if log_output:
1054 if log_output:
1055 log_write = logger.log_write
1055 log_write = logger.log_write
1056 input_hist = self.shell.input_hist
1056 input_hist = self.shell.input_hist
1057 output_hist = self.shell.output_hist
1057 output_hist = self.shell.output_hist
1058 for n in range(1,len(input_hist)-1):
1058 for n in range(1,len(input_hist)-1):
1059 log_write(input_hist[n].rstrip())
1059 log_write(input_hist[n].rstrip())
1060 if n in output_hist:
1060 if n in output_hist:
1061 log_write(repr(output_hist[n]),'output')
1061 log_write(repr(output_hist[n]),'output')
1062 else:
1062 else:
1063 logger.log_write(self.shell.input_hist[1:])
1063 logger.log_write(self.shell.input_hist[1:])
1064 if timestamp:
1064 if timestamp:
1065 # re-enable timestamping
1065 # re-enable timestamping
1066 logger.timestamp = True
1066 logger.timestamp = True
1067
1067
1068 print ('Activating auto-logging. '
1068 print ('Activating auto-logging. '
1069 'Current session state plus future input saved.')
1069 'Current session state plus future input saved.')
1070 logger.logstate()
1070 logger.logstate()
1071
1071
1072 def magic_logoff(self,parameter_s=''):
1072 def magic_logoff(self,parameter_s=''):
1073 """Temporarily stop logging.
1073 """Temporarily stop logging.
1074
1074
1075 You must have previously started logging."""
1075 You must have previously started logging."""
1076 self.shell.logger.switch_log(0)
1076 self.shell.logger.switch_log(0)
1077
1077
1078 def magic_logon(self,parameter_s=''):
1078 def magic_logon(self,parameter_s=''):
1079 """Restart logging.
1079 """Restart logging.
1080
1080
1081 This function is for restarting logging which you've temporarily
1081 This function is for restarting logging which you've temporarily
1082 stopped with %logoff. For starting logging for the first time, you
1082 stopped with %logoff. For starting logging for the first time, you
1083 must use the %logstart function, which allows you to specify an
1083 must use the %logstart function, which allows you to specify an
1084 optional log filename."""
1084 optional log filename."""
1085
1085
1086 self.shell.logger.switch_log(1)
1086 self.shell.logger.switch_log(1)
1087
1087
1088 def magic_logstate(self,parameter_s=''):
1088 def magic_logstate(self,parameter_s=''):
1089 """Print the status of the logging system."""
1089 """Print the status of the logging system."""
1090
1090
1091 self.shell.logger.logstate()
1091 self.shell.logger.logstate()
1092
1092
1093 def magic_pdb(self, parameter_s=''):
1093 def magic_pdb(self, parameter_s=''):
1094 """Control the calling of the pdb interactive debugger.
1094 """Control the calling of the pdb interactive debugger.
1095
1095
1096 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1096 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1097 argument it works as a toggle.
1097 argument it works as a toggle.
1098
1098
1099 When an exception is triggered, IPython can optionally call the
1099 When an exception is triggered, IPython can optionally call the
1100 interactive pdb debugger after the traceback printout. %pdb toggles
1100 interactive pdb debugger after the traceback printout. %pdb toggles
1101 this feature on and off."""
1101 this feature on and off."""
1102
1102
1103 par = parameter_s.strip().lower()
1103 par = parameter_s.strip().lower()
1104
1104
1105 if par:
1105 if par:
1106 try:
1106 try:
1107 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1107 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1108 except KeyError:
1108 except KeyError:
1109 print ('Incorrect argument. Use on/1, off/0, '
1109 print ('Incorrect argument. Use on/1, off/0, '
1110 'or nothing for a toggle.')
1110 'or nothing for a toggle.')
1111 return
1111 return
1112 else:
1112 else:
1113 # toggle
1113 # toggle
1114 new_pdb = not self.shell.InteractiveTB.call_pdb
1114 new_pdb = not self.shell.InteractiveTB.call_pdb
1115
1115
1116 # set on the shell
1116 # set on the shell
1117 self.shell.call_pdb = new_pdb
1117 self.shell.call_pdb = new_pdb
1118 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1118 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1119
1119
1120 def magic_prun(self, parameter_s ='',user_mode=1,
1120 def magic_prun(self, parameter_s ='',user_mode=1,
1121 opts=None,arg_lst=None,prog_ns=None):
1121 opts=None,arg_lst=None,prog_ns=None):
1122
1122
1123 """Run a statement through the python code profiler.
1123 """Run a statement through the python code profiler.
1124
1124
1125 Usage:\\
1125 Usage:\\
1126 %prun [options] statement
1126 %prun [options] statement
1127
1127
1128 The given statement (which doesn't require quote marks) is run via the
1128 The given statement (which doesn't require quote marks) is run via the
1129 python profiler in a manner similar to the profile.run() function.
1129 python profiler in a manner similar to the profile.run() function.
1130 Namespaces are internally managed to work correctly; profile.run
1130 Namespaces are internally managed to work correctly; profile.run
1131 cannot be used in IPython because it makes certain assumptions about
1131 cannot be used in IPython because it makes certain assumptions about
1132 namespaces which do not hold under IPython.
1132 namespaces which do not hold under IPython.
1133
1133
1134 Options:
1134 Options:
1135
1135
1136 -l <limit>: you can place restrictions on what or how much of the
1136 -l <limit>: you can place restrictions on what or how much of the
1137 profile gets printed. The limit value can be:
1137 profile gets printed. The limit value can be:
1138
1138
1139 * A string: only information for function names containing this string
1139 * A string: only information for function names containing this string
1140 is printed.
1140 is printed.
1141
1141
1142 * An integer: only these many lines are printed.
1142 * An integer: only these many lines are printed.
1143
1143
1144 * A float (between 0 and 1): this fraction of the report is printed
1144 * A float (between 0 and 1): this fraction of the report is printed
1145 (for example, use a limit of 0.4 to see the topmost 40% only).
1145 (for example, use a limit of 0.4 to see the topmost 40% only).
1146
1146
1147 You can combine several limits with repeated use of the option. For
1147 You can combine several limits with repeated use of the option. For
1148 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1148 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1149 information about class constructors.
1149 information about class constructors.
1150
1150
1151 -r: return the pstats.Stats object generated by the profiling. This
1151 -r: return the pstats.Stats object generated by the profiling. This
1152 object has all the information about the profile in it, and you can
1152 object has all the information about the profile in it, and you can
1153 later use it for further analysis or in other functions.
1153 later use it for further analysis or in other functions.
1154
1154
1155 Since magic functions have a particular form of calling which prevents
1155 Since magic functions have a particular form of calling which prevents
1156 you from writing something like:\\
1156 you from writing something like:\\
1157 In [1]: p = %prun -r print 4 # invalid!\\
1157 In [1]: p = %prun -r print 4 # invalid!\\
1158 you must instead use IPython's automatic variables to assign this:\\
1158 you must instead use IPython's automatic variables to assign this:\\
1159 In [1]: %prun -r print 4 \\
1159 In [1]: %prun -r print 4 \\
1160 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1160 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1161 In [2]: stats = _
1161 In [2]: stats = _
1162
1162
1163 If you really need to assign this value via an explicit function call,
1163 If you really need to assign this value via an explicit function call,
1164 you can always tap directly into the true name of the magic function
1164 you can always tap directly into the true name of the magic function
1165 by using the _ip.magic function:\\
1165 by using the _ip.magic function:\\
1166 In [3]: stats = _ip.magic('prun','-r print 4')
1166 In [3]: stats = _ip.magic('prun','-r print 4')
1167
1167
1168 You can type _ip.magic? for more details.
1168 You can type _ip.magic? for more details.
1169
1169
1170 -s <key>: sort profile by given key. You can provide more than one key
1170 -s <key>: sort profile by given key. You can provide more than one key
1171 by using the option several times: '-s key1 -s key2 -s key3...'. The
1171 by using the option several times: '-s key1 -s key2 -s key3...'. The
1172 default sorting key is 'time'.
1172 default sorting key is 'time'.
1173
1173
1174 The following is copied verbatim from the profile documentation
1174 The following is copied verbatim from the profile documentation
1175 referenced below:
1175 referenced below:
1176
1176
1177 When more than one key is provided, additional keys are used as
1177 When more than one key is provided, additional keys are used as
1178 secondary criteria when the there is equality in all keys selected
1178 secondary criteria when the there is equality in all keys selected
1179 before them.
1179 before them.
1180
1180
1181 Abbreviations can be used for any key names, as long as the
1181 Abbreviations can be used for any key names, as long as the
1182 abbreviation is unambiguous. The following are the keys currently
1182 abbreviation is unambiguous. The following are the keys currently
1183 defined:
1183 defined:
1184
1184
1185 Valid Arg Meaning\\
1185 Valid Arg Meaning\\
1186 "calls" call count\\
1186 "calls" call count\\
1187 "cumulative" cumulative time\\
1187 "cumulative" cumulative time\\
1188 "file" file name\\
1188 "file" file name\\
1189 "module" file name\\
1189 "module" file name\\
1190 "pcalls" primitive call count\\
1190 "pcalls" primitive call count\\
1191 "line" line number\\
1191 "line" line number\\
1192 "name" function name\\
1192 "name" function name\\
1193 "nfl" name/file/line\\
1193 "nfl" name/file/line\\
1194 "stdname" standard name\\
1194 "stdname" standard name\\
1195 "time" internal time
1195 "time" internal time
1196
1196
1197 Note that all sorts on statistics are in descending order (placing
1197 Note that all sorts on statistics are in descending order (placing
1198 most time consuming items first), where as name, file, and line number
1198 most time consuming items first), where as name, file, and line number
1199 searches are in ascending order (i.e., alphabetical). The subtle
1199 searches are in ascending order (i.e., alphabetical). The subtle
1200 distinction between "nfl" and "stdname" is that the standard name is a
1200 distinction between "nfl" and "stdname" is that the standard name is a
1201 sort of the name as printed, which means that the embedded line
1201 sort of the name as printed, which means that the embedded line
1202 numbers get compared in an odd way. For example, lines 3, 20, and 40
1202 numbers get compared in an odd way. For example, lines 3, 20, and 40
1203 would (if the file names were the same) appear in the string order
1203 would (if the file names were the same) appear in the string order
1204 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1204 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1205 line numbers. In fact, sort_stats("nfl") is the same as
1205 line numbers. In fact, sort_stats("nfl") is the same as
1206 sort_stats("name", "file", "line").
1206 sort_stats("name", "file", "line").
1207
1207
1208 -T <filename>: save profile results as shown on screen to a text
1208 -T <filename>: save profile results as shown on screen to a text
1209 file. The profile is still shown on screen.
1209 file. The profile is still shown on screen.
1210
1210
1211 -D <filename>: save (via dump_stats) profile statistics to given
1211 -D <filename>: save (via dump_stats) profile statistics to given
1212 filename. This data is in a format understod by the pstats module, and
1212 filename. This data is in a format understod by the pstats module, and
1213 is generated by a call to the dump_stats() method of profile
1213 is generated by a call to the dump_stats() method of profile
1214 objects. The profile is still shown on screen.
1214 objects. The profile is still shown on screen.
1215
1215
1216 If you want to run complete programs under the profiler's control, use
1216 If you want to run complete programs under the profiler's control, use
1217 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1217 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1218 contains profiler specific options as described here.
1218 contains profiler specific options as described here.
1219
1219
1220 You can read the complete documentation for the profile module with:\\
1220 You can read the complete documentation for the profile module with:\\
1221 In [1]: import profile; profile.help() """
1221 In [1]: import profile; profile.help() """
1222
1222
1223 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1223 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1224 # protect user quote marks
1224 # protect user quote marks
1225 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1225 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1226
1226
1227 if user_mode: # regular user call
1227 if user_mode: # regular user call
1228 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1228 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1229 list_all=1)
1229 list_all=1)
1230 namespace = self.shell.user_ns
1230 namespace = self.shell.user_ns
1231 else: # called to run a program by %run -p
1231 else: # called to run a program by %run -p
1232 try:
1232 try:
1233 filename = get_py_filename(arg_lst[0])
1233 filename = get_py_filename(arg_lst[0])
1234 except IOError,msg:
1234 except IOError,msg:
1235 error(msg)
1235 error(msg)
1236 return
1236 return
1237
1237
1238 arg_str = 'execfile(filename,prog_ns)'
1238 arg_str = 'execfile(filename,prog_ns)'
1239 namespace = locals()
1239 namespace = locals()
1240
1240
1241 opts.merge(opts_def)
1241 opts.merge(opts_def)
1242
1242
1243 prof = profile.Profile()
1243 prof = profile.Profile()
1244 try:
1244 try:
1245 prof = prof.runctx(arg_str,namespace,namespace)
1245 prof = prof.runctx(arg_str,namespace,namespace)
1246 sys_exit = ''
1246 sys_exit = ''
1247 except SystemExit:
1247 except SystemExit:
1248 sys_exit = """*** SystemExit exception caught in code being profiled."""
1248 sys_exit = """*** SystemExit exception caught in code being profiled."""
1249
1249
1250 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1250 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1251
1251
1252 lims = opts.l
1252 lims = opts.l
1253 if lims:
1253 if lims:
1254 lims = [] # rebuild lims with ints/floats/strings
1254 lims = [] # rebuild lims with ints/floats/strings
1255 for lim in opts.l:
1255 for lim in opts.l:
1256 try:
1256 try:
1257 lims.append(int(lim))
1257 lims.append(int(lim))
1258 except ValueError:
1258 except ValueError:
1259 try:
1259 try:
1260 lims.append(float(lim))
1260 lims.append(float(lim))
1261 except ValueError:
1261 except ValueError:
1262 lims.append(lim)
1262 lims.append(lim)
1263
1263
1264 # trap output
1264 # trap output
1265 sys_stdout = sys.stdout
1265 sys_stdout = sys.stdout
1266 stdout_trap = StringIO()
1266 stdout_trap = StringIO()
1267 try:
1267 try:
1268 sys.stdout = stdout_trap
1268 sys.stdout = stdout_trap
1269 stats.print_stats(*lims)
1269 stats.print_stats(*lims)
1270 finally:
1270 finally:
1271 sys.stdout = sys_stdout
1271 sys.stdout = sys_stdout
1272 output = stdout_trap.getvalue()
1272 output = stdout_trap.getvalue()
1273 output = output.rstrip()
1273 output = output.rstrip()
1274
1274
1275 page(output,screen_lines=self.shell.rc.screen_length)
1275 page(output,screen_lines=self.shell.rc.screen_length)
1276 print sys_exit,
1276 print sys_exit,
1277
1277
1278 dump_file = opts.D[0]
1278 dump_file = opts.D[0]
1279 text_file = opts.T[0]
1279 text_file = opts.T[0]
1280 if dump_file:
1280 if dump_file:
1281 prof.dump_stats(dump_file)
1281 prof.dump_stats(dump_file)
1282 print '\n*** Profile stats marshalled to file',\
1282 print '\n*** Profile stats marshalled to file',\
1283 `dump_file`+'.',sys_exit
1283 `dump_file`+'.',sys_exit
1284 if text_file:
1284 if text_file:
1285 file(text_file,'w').write(output)
1285 file(text_file,'w').write(output)
1286 print '\n*** Profile printout saved to text file',\
1286 print '\n*** Profile printout saved to text file',\
1287 `text_file`+'.',sys_exit
1287 `text_file`+'.',sys_exit
1288
1288
1289 if opts.has_key('r'):
1289 if opts.has_key('r'):
1290 return stats
1290 return stats
1291 else:
1291 else:
1292 return None
1292 return None
1293
1293
1294 def magic_run(self, parameter_s ='',runner=None):
1294 def magic_run(self, parameter_s ='',runner=None):
1295 """Run the named file inside IPython as a program.
1295 """Run the named file inside IPython as a program.
1296
1296
1297 Usage:\\
1297 Usage:\\
1298 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1298 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1299
1299
1300 Parameters after the filename are passed as command-line arguments to
1300 Parameters after the filename are passed as command-line arguments to
1301 the program (put in sys.argv). Then, control returns to IPython's
1301 the program (put in sys.argv). Then, control returns to IPython's
1302 prompt.
1302 prompt.
1303
1303
1304 This is similar to running at a system prompt:\\
1304 This is similar to running at a system prompt:\\
1305 $ python file args\\
1305 $ python file args\\
1306 but with the advantage of giving you IPython's tracebacks, and of
1306 but with the advantage of giving you IPython's tracebacks, and of
1307 loading all variables into your interactive namespace for further use
1307 loading all variables into your interactive namespace for further use
1308 (unless -p is used, see below).
1308 (unless -p is used, see below).
1309
1309
1310 The file is executed in a namespace initially consisting only of
1310 The file is executed in a namespace initially consisting only of
1311 __name__=='__main__' and sys.argv constructed as indicated. It thus
1311 __name__=='__main__' and sys.argv constructed as indicated. It thus
1312 sees its environment as if it were being run as a stand-alone
1312 sees its environment as if it were being run as a stand-alone
1313 program. But after execution, the IPython interactive namespace gets
1313 program. But after execution, the IPython interactive namespace gets
1314 updated with all variables defined in the program (except for __name__
1314 updated with all variables defined in the program (except for __name__
1315 and sys.argv). This allows for very convenient loading of code for
1315 and sys.argv). This allows for very convenient loading of code for
1316 interactive work, while giving each program a 'clean sheet' to run in.
1316 interactive work, while giving each program a 'clean sheet' to run in.
1317
1317
1318 Options:
1318 Options:
1319
1319
1320 -n: __name__ is NOT set to '__main__', but to the running file's name
1320 -n: __name__ is NOT set to '__main__', but to the running file's name
1321 without extension (as python does under import). This allows running
1321 without extension (as python does under import). This allows running
1322 scripts and reloading the definitions in them without calling code
1322 scripts and reloading the definitions in them without calling code
1323 protected by an ' if __name__ == "__main__" ' clause.
1323 protected by an ' if __name__ == "__main__" ' clause.
1324
1324
1325 -i: run the file in IPython's namespace instead of an empty one. This
1325 -i: run the file in IPython's namespace instead of an empty one. This
1326 is useful if you are experimenting with code written in a text editor
1326 is useful if you are experimenting with code written in a text editor
1327 which depends on variables defined interactively.
1327 which depends on variables defined interactively.
1328
1328
1329 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1329 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1330 being run. This is particularly useful if IPython is being used to
1330 being run. This is particularly useful if IPython is being used to
1331 run unittests, which always exit with a sys.exit() call. In such
1331 run unittests, which always exit with a sys.exit() call. In such
1332 cases you are interested in the output of the test results, not in
1332 cases you are interested in the output of the test results, not in
1333 seeing a traceback of the unittest module.
1333 seeing a traceback of the unittest module.
1334
1334
1335 -t: print timing information at the end of the run. IPython will give
1335 -t: print timing information at the end of the run. IPython will give
1336 you an estimated CPU time consumption for your script, which under
1336 you an estimated CPU time consumption for your script, which under
1337 Unix uses the resource module to avoid the wraparound problems of
1337 Unix uses the resource module to avoid the wraparound problems of
1338 time.clock(). Under Unix, an estimate of time spent on system tasks
1338 time.clock(). Under Unix, an estimate of time spent on system tasks
1339 is also given (for Windows platforms this is reported as 0.0).
1339 is also given (for Windows platforms this is reported as 0.0).
1340
1340
1341 If -t is given, an additional -N<N> option can be given, where <N>
1341 If -t is given, an additional -N<N> option can be given, where <N>
1342 must be an integer indicating how many times you want the script to
1342 must be an integer indicating how many times you want the script to
1343 run. The final timing report will include total and per run results.
1343 run. The final timing report will include total and per run results.
1344
1344
1345 For example (testing the script uniq_stable.py):
1345 For example (testing the script uniq_stable.py):
1346
1346
1347 In [1]: run -t uniq_stable
1347 In [1]: run -t uniq_stable
1348
1348
1349 IPython CPU timings (estimated):\\
1349 IPython CPU timings (estimated):\\
1350 User : 0.19597 s.\\
1350 User : 0.19597 s.\\
1351 System: 0.0 s.\\
1351 System: 0.0 s.\\
1352
1352
1353 In [2]: run -t -N5 uniq_stable
1353 In [2]: run -t -N5 uniq_stable
1354
1354
1355 IPython CPU timings (estimated):\\
1355 IPython CPU timings (estimated):\\
1356 Total runs performed: 5\\
1356 Total runs performed: 5\\
1357 Times : Total Per run\\
1357 Times : Total Per run\\
1358 User : 0.910862 s, 0.1821724 s.\\
1358 User : 0.910862 s, 0.1821724 s.\\
1359 System: 0.0 s, 0.0 s.
1359 System: 0.0 s, 0.0 s.
1360
1360
1361 -d: run your program under the control of pdb, the Python debugger.
1361 -d: run your program under the control of pdb, the Python debugger.
1362 This allows you to execute your program step by step, watch variables,
1362 This allows you to execute your program step by step, watch variables,
1363 etc. Internally, what IPython does is similar to calling:
1363 etc. Internally, what IPython does is similar to calling:
1364
1364
1365 pdb.run('execfile("YOURFILENAME")')
1365 pdb.run('execfile("YOURFILENAME")')
1366
1366
1367 with a breakpoint set on line 1 of your file. You can change the line
1367 with a breakpoint set on line 1 of your file. You can change the line
1368 number for this automatic breakpoint to be <N> by using the -bN option
1368 number for this automatic breakpoint to be <N> by using the -bN option
1369 (where N must be an integer). For example:
1369 (where N must be an integer). For example:
1370
1370
1371 %run -d -b40 myscript
1371 %run -d -b40 myscript
1372
1372
1373 will set the first breakpoint at line 40 in myscript.py. Note that
1373 will set the first breakpoint at line 40 in myscript.py. Note that
1374 the first breakpoint must be set on a line which actually does
1374 the first breakpoint must be set on a line which actually does
1375 something (not a comment or docstring) for it to stop execution.
1375 something (not a comment or docstring) for it to stop execution.
1376
1376
1377 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1377 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1378 first enter 'c' (without qoutes) to start execution up to the first
1378 first enter 'c' (without qoutes) to start execution up to the first
1379 breakpoint.
1379 breakpoint.
1380
1380
1381 Entering 'help' gives information about the use of the debugger. You
1381 Entering 'help' gives information about the use of the debugger. You
1382 can easily see pdb's full documentation with "import pdb;pdb.help()"
1382 can easily see pdb's full documentation with "import pdb;pdb.help()"
1383 at a prompt.
1383 at a prompt.
1384
1384
1385 -p: run program under the control of the Python profiler module (which
1385 -p: run program under the control of the Python profiler module (which
1386 prints a detailed report of execution times, function calls, etc).
1386 prints a detailed report of execution times, function calls, etc).
1387
1387
1388 You can pass other options after -p which affect the behavior of the
1388 You can pass other options after -p which affect the behavior of the
1389 profiler itself. See the docs for %prun for details.
1389 profiler itself. See the docs for %prun for details.
1390
1390
1391 In this mode, the program's variables do NOT propagate back to the
1391 In this mode, the program's variables do NOT propagate back to the
1392 IPython interactive namespace (because they remain in the namespace
1392 IPython interactive namespace (because they remain in the namespace
1393 where the profiler executes them).
1393 where the profiler executes them).
1394
1394
1395 Internally this triggers a call to %prun, see its documentation for
1395 Internally this triggers a call to %prun, see its documentation for
1396 details on the options available specifically for profiling."""
1396 details on the options available specifically for profiling."""
1397
1397
1398 # get arguments and set sys.argv for program to be run.
1398 # get arguments and set sys.argv for program to be run.
1399 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1399 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1400 mode='list',list_all=1)
1400 mode='list',list_all=1)
1401
1401
1402 try:
1402 try:
1403 filename = get_py_filename(arg_lst[0])
1403 filename = get_py_filename(arg_lst[0])
1404 except IndexError:
1404 except IndexError:
1405 warn('you must provide at least a filename.')
1405 warn('you must provide at least a filename.')
1406 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1406 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1407 return
1407 return
1408 except IOError,msg:
1408 except IOError,msg:
1409 error(msg)
1409 error(msg)
1410 return
1410 return
1411
1411
1412 # Control the response to exit() calls made by the script being run
1412 # Control the response to exit() calls made by the script being run
1413 exit_ignore = opts.has_key('e')
1413 exit_ignore = opts.has_key('e')
1414
1414
1415 # Make sure that the running script gets a proper sys.argv as if it
1415 # Make sure that the running script gets a proper sys.argv as if it
1416 # were run from a system shell.
1416 # were run from a system shell.
1417 save_argv = sys.argv # save it for later restoring
1417 save_argv = sys.argv # save it for later restoring
1418 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1418 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1419
1419
1420 if opts.has_key('i'):
1420 if opts.has_key('i'):
1421 prog_ns = self.shell.user_ns
1421 prog_ns = self.shell.user_ns
1422 __name__save = self.shell.user_ns['__name__']
1422 __name__save = self.shell.user_ns['__name__']
1423 prog_ns['__name__'] = '__main__'
1423 prog_ns['__name__'] = '__main__'
1424 else:
1424 else:
1425 if opts.has_key('n'):
1425 if opts.has_key('n'):
1426 name = os.path.splitext(os.path.basename(filename))[0]
1426 name = os.path.splitext(os.path.basename(filename))[0]
1427 else:
1427 else:
1428 name = '__main__'
1428 name = '__main__'
1429 prog_ns = {'__name__':name}
1429 prog_ns = {'__name__':name}
1430
1430
1431 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1431 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1432 # set the __file__ global in the script's namespace
1432 # set the __file__ global in the script's namespace
1433 prog_ns['__file__'] = filename
1433 prog_ns['__file__'] = filename
1434
1434
1435 # pickle fix. See iplib for an explanation. But we need to make sure
1435 # pickle fix. See iplib for an explanation. But we need to make sure
1436 # that, if we overwrite __main__, we replace it at the end
1436 # that, if we overwrite __main__, we replace it at the end
1437 if prog_ns['__name__'] == '__main__':
1437 if prog_ns['__name__'] == '__main__':
1438 restore_main = sys.modules['__main__']
1438 restore_main = sys.modules['__main__']
1439 else:
1439 else:
1440 restore_main = False
1440 restore_main = False
1441
1441
1442 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1442 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1443
1443
1444 stats = None
1444 stats = None
1445 try:
1445 try:
1446 if opts.has_key('p'):
1446 if opts.has_key('p'):
1447 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1447 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1448 else:
1448 else:
1449 if opts.has_key('d'):
1449 if opts.has_key('d'):
1450 deb = Debugger.Pdb(self.shell.rc.colors)
1450 deb = Debugger.Pdb(self.shell.rc.colors)
1451 # reset Breakpoint state, which is moronically kept
1451 # reset Breakpoint state, which is moronically kept
1452 # in a class
1452 # in a class
1453 bdb.Breakpoint.next = 1
1453 bdb.Breakpoint.next = 1
1454 bdb.Breakpoint.bplist = {}
1454 bdb.Breakpoint.bplist = {}
1455 bdb.Breakpoint.bpbynumber = [None]
1455 bdb.Breakpoint.bpbynumber = [None]
1456 # Set an initial breakpoint to stop execution
1456 # Set an initial breakpoint to stop execution
1457 maxtries = 10
1457 maxtries = 10
1458 bp = int(opts.get('b',[1])[0])
1458 bp = int(opts.get('b',[1])[0])
1459 checkline = deb.checkline(filename,bp)
1459 checkline = deb.checkline(filename,bp)
1460 if not checkline:
1460 if not checkline:
1461 for bp in range(bp+1,bp+maxtries+1):
1461 for bp in range(bp+1,bp+maxtries+1):
1462 if deb.checkline(filename,bp):
1462 if deb.checkline(filename,bp):
1463 break
1463 break
1464 else:
1464 else:
1465 msg = ("\nI failed to find a valid line to set "
1465 msg = ("\nI failed to find a valid line to set "
1466 "a breakpoint\n"
1466 "a breakpoint\n"
1467 "after trying up to line: %s.\n"
1467 "after trying up to line: %s.\n"
1468 "Please set a valid breakpoint manually "
1468 "Please set a valid breakpoint manually "
1469 "with the -b option." % bp)
1469 "with the -b option." % bp)
1470 error(msg)
1470 error(msg)
1471 return
1471 return
1472 # if we find a good linenumber, set the breakpoint
1472 # if we find a good linenumber, set the breakpoint
1473 deb.do_break('%s:%s' % (filename,bp))
1473 deb.do_break('%s:%s' % (filename,bp))
1474 # Start file run
1474 # Start file run
1475 print "NOTE: Enter 'c' at the",
1475 print "NOTE: Enter 'c' at the",
1476 print "ipdb> prompt to start your script."
1476 print "ipdb> prompt to start your script."
1477 try:
1477 try:
1478 deb.run('execfile("%s")' % filename,prog_ns)
1478 deb.run('execfile("%s")' % filename,prog_ns)
1479 except:
1479 except:
1480 etype, value, tb = sys.exc_info()
1480 etype, value, tb = sys.exc_info()
1481 # Skip three frames in the traceback: the %run one,
1481 # Skip three frames in the traceback: the %run one,
1482 # one inside bdb.py, and the command-line typed by the
1482 # one inside bdb.py, and the command-line typed by the
1483 # user (run by exec in pdb itself).
1483 # user (run by exec in pdb itself).
1484 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1484 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1485 else:
1485 else:
1486 if runner is None:
1486 if runner is None:
1487 runner = self.shell.safe_execfile
1487 runner = self.shell.safe_execfile
1488 if opts.has_key('t'):
1488 if opts.has_key('t'):
1489 try:
1489 try:
1490 nruns = int(opts['N'][0])
1490 nruns = int(opts['N'][0])
1491 if nruns < 1:
1491 if nruns < 1:
1492 error('Number of runs must be >=1')
1492 error('Number of runs must be >=1')
1493 return
1493 return
1494 except (KeyError):
1494 except (KeyError):
1495 nruns = 1
1495 nruns = 1
1496 if nruns == 1:
1496 if nruns == 1:
1497 t0 = clock2()
1497 t0 = clock2()
1498 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1498 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1499 t1 = clock2()
1499 t1 = clock2()
1500 t_usr = t1[0]-t0[0]
1500 t_usr = t1[0]-t0[0]
1501 t_sys = t1[1]-t1[1]
1501 t_sys = t1[1]-t1[1]
1502 print "\nIPython CPU timings (estimated):"
1502 print "\nIPython CPU timings (estimated):"
1503 print " User : %10s s." % t_usr
1503 print " User : %10s s." % t_usr
1504 print " System: %10s s." % t_sys
1504 print " System: %10s s." % t_sys
1505 else:
1505 else:
1506 runs = range(nruns)
1506 runs = range(nruns)
1507 t0 = clock2()
1507 t0 = clock2()
1508 for nr in runs:
1508 for nr in runs:
1509 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1509 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1510 t1 = clock2()
1510 t1 = clock2()
1511 t_usr = t1[0]-t0[0]
1511 t_usr = t1[0]-t0[0]
1512 t_sys = t1[1]-t1[1]
1512 t_sys = t1[1]-t1[1]
1513 print "\nIPython CPU timings (estimated):"
1513 print "\nIPython CPU timings (estimated):"
1514 print "Total runs performed:",nruns
1514 print "Total runs performed:",nruns
1515 print " Times : %10s %10s" % ('Total','Per run')
1515 print " Times : %10s %10s" % ('Total','Per run')
1516 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1516 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1517 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1517 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1518
1518
1519 else:
1519 else:
1520 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1520 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1521 if opts.has_key('i'):
1521 if opts.has_key('i'):
1522 self.shell.user_ns['__name__'] = __name__save
1522 self.shell.user_ns['__name__'] = __name__save
1523 else:
1523 else:
1524 # update IPython interactive namespace
1524 # update IPython interactive namespace
1525 del prog_ns['__name__']
1525 del prog_ns['__name__']
1526 self.shell.user_ns.update(prog_ns)
1526 self.shell.user_ns.update(prog_ns)
1527 finally:
1527 finally:
1528 sys.argv = save_argv
1528 sys.argv = save_argv
1529 if restore_main:
1529 if restore_main:
1530 sys.modules['__main__'] = restore_main
1530 sys.modules['__main__'] = restore_main
1531 return stats
1531 return stats
1532
1532
1533 def magic_runlog(self, parameter_s =''):
1533 def magic_runlog(self, parameter_s =''):
1534 """Run files as logs.
1534 """Run files as logs.
1535
1535
1536 Usage:\\
1536 Usage:\\
1537 %runlog file1 file2 ...
1537 %runlog file1 file2 ...
1538
1538
1539 Run the named files (treating them as log files) in sequence inside
1539 Run the named files (treating them as log files) in sequence inside
1540 the interpreter, and return to the prompt. This is much slower than
1540 the interpreter, and return to the prompt. This is much slower than
1541 %run because each line is executed in a try/except block, but it
1541 %run because each line is executed in a try/except block, but it
1542 allows running files with syntax errors in them.
1542 allows running files with syntax errors in them.
1543
1543
1544 Normally IPython will guess when a file is one of its own logfiles, so
1544 Normally IPython will guess when a file is one of its own logfiles, so
1545 you can typically use %run even for logs. This shorthand allows you to
1545 you can typically use %run even for logs. This shorthand allows you to
1546 force any file to be treated as a log file."""
1546 force any file to be treated as a log file."""
1547
1547
1548 for f in parameter_s.split():
1548 for f in parameter_s.split():
1549 self.shell.safe_execfile(f,self.shell.user_ns,
1549 self.shell.safe_execfile(f,self.shell.user_ns,
1550 self.shell.user_ns,islog=1)
1550 self.shell.user_ns,islog=1)
1551
1551
1552 def magic_time(self,parameter_s = ''):
1552 def magic_time(self,parameter_s = ''):
1553 """Time execution of a Python statement or expression.
1553 """Time execution of a Python statement or expression.
1554
1554
1555 The CPU and wall clock times are printed, and the value of the
1555 The CPU and wall clock times are printed, and the value of the
1556 expression (if any) is returned. Note that under Win32, system time
1556 expression (if any) is returned. Note that under Win32, system time
1557 is always reported as 0, since it can not be measured.
1557 is always reported as 0, since it can not be measured.
1558
1558
1559 This function provides very basic timing functionality. In Python
1559 This function provides very basic timing functionality. In Python
1560 2.3, the timeit module offers more control and sophistication, but for
1560 2.3, the timeit module offers more control and sophistication, but for
1561 now IPython supports Python 2.2, so we can not rely on timeit being
1561 now IPython supports Python 2.2, so we can not rely on timeit being
1562 present.
1562 present.
1563
1563
1564 Some examples:
1564 Some examples:
1565
1565
1566 In [1]: time 2**128
1566 In [1]: time 2**128
1567 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1567 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1568 Wall time: 0.00
1568 Wall time: 0.00
1569 Out[1]: 340282366920938463463374607431768211456L
1569 Out[1]: 340282366920938463463374607431768211456L
1570
1570
1571 In [2]: n = 1000000
1571 In [2]: n = 1000000
1572
1572
1573 In [3]: time sum(range(n))
1573 In [3]: time sum(range(n))
1574 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1574 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1575 Wall time: 1.37
1575 Wall time: 1.37
1576 Out[3]: 499999500000L
1576 Out[3]: 499999500000L
1577
1577
1578 In [4]: time print 'hello world'
1578 In [4]: time print 'hello world'
1579 hello world
1579 hello world
1580 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1580 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1581 Wall time: 0.00
1581 Wall time: 0.00
1582 """
1582 """
1583
1583
1584 # fail immediately if the given expression can't be compiled
1584 # fail immediately if the given expression can't be compiled
1585 try:
1585 try:
1586 mode = 'eval'
1586 mode = 'eval'
1587 code = compile(parameter_s,'<timed eval>',mode)
1587 code = compile(parameter_s,'<timed eval>',mode)
1588 except SyntaxError:
1588 except SyntaxError:
1589 mode = 'exec'
1589 mode = 'exec'
1590 code = compile(parameter_s,'<timed exec>',mode)
1590 code = compile(parameter_s,'<timed exec>',mode)
1591 # skew measurement as little as possible
1591 # skew measurement as little as possible
1592 glob = self.shell.user_ns
1592 glob = self.shell.user_ns
1593 clk = clock2
1593 clk = clock2
1594 wtime = time.time
1594 wtime = time.time
1595 # time execution
1595 # time execution
1596 wall_st = wtime()
1596 wall_st = wtime()
1597 if mode=='eval':
1597 if mode=='eval':
1598 st = clk()
1598 st = clk()
1599 out = eval(code,glob)
1599 out = eval(code,glob)
1600 end = clk()
1600 end = clk()
1601 else:
1601 else:
1602 st = clk()
1602 st = clk()
1603 exec code in glob
1603 exec code in glob
1604 end = clk()
1604 end = clk()
1605 out = None
1605 out = None
1606 wall_end = wtime()
1606 wall_end = wtime()
1607 # Compute actual times and report
1607 # Compute actual times and report
1608 wall_time = wall_end-wall_st
1608 wall_time = wall_end-wall_st
1609 cpu_user = end[0]-st[0]
1609 cpu_user = end[0]-st[0]
1610 cpu_sys = end[1]-st[1]
1610 cpu_sys = end[1]-st[1]
1611 cpu_tot = cpu_user+cpu_sys
1611 cpu_tot = cpu_user+cpu_sys
1612 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1612 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1613 (cpu_user,cpu_sys,cpu_tot)
1613 (cpu_user,cpu_sys,cpu_tot)
1614 print "Wall time: %.2f" % wall_time
1614 print "Wall time: %.2f" % wall_time
1615 return out
1615 return out
1616
1616
1617 def magic_macro(self,parameter_s = ''):
1617 def magic_macro(self,parameter_s = ''):
1618 """Define a set of input lines as a macro for future re-execution.
1618 """Define a set of input lines as a macro for future re-execution.
1619
1619
1620 Usage:\\
1620 Usage:\\
1621 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1621 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1622
1622
1623 Options:
1623 Options:
1624
1624
1625 -r: use 'raw' input. By default, the 'processed' history is used,
1625 -r: use 'raw' input. By default, the 'processed' history is used,
1626 so that magics are loaded in their transformed version to valid
1626 so that magics are loaded in their transformed version to valid
1627 Python. If this option is given, the raw input as typed as the
1627 Python. If this option is given, the raw input as typed as the
1628 command line is used instead.
1628 command line is used instead.
1629
1629
1630 This will define a global variable called `name` which is a string
1630 This will define a global variable called `name` which is a string
1631 made of joining the slices and lines you specify (n1,n2,... numbers
1631 made of joining the slices and lines you specify (n1,n2,... numbers
1632 above) from your input history into a single string. This variable
1632 above) from your input history into a single string. This variable
1633 acts like an automatic function which re-executes those lines as if
1633 acts like an automatic function which re-executes those lines as if
1634 you had typed them. You just type 'name' at the prompt and the code
1634 you had typed them. You just type 'name' at the prompt and the code
1635 executes.
1635 executes.
1636
1636
1637 The notation for indicating number ranges is: n1-n2 means 'use line
1637 The notation for indicating number ranges is: n1-n2 means 'use line
1638 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1638 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1639 using the lines numbered 5,6 and 7.
1639 using the lines numbered 5,6 and 7.
1640
1640
1641 Note: as a 'hidden' feature, you can also use traditional python slice
1641 Note: as a 'hidden' feature, you can also use traditional python slice
1642 notation, where N:M means numbers N through M-1.
1642 notation, where N:M means numbers N through M-1.
1643
1643
1644 For example, if your history contains (%hist prints it):
1644 For example, if your history contains (%hist prints it):
1645
1645
1646 44: x=1\\
1646 44: x=1\\
1647 45: y=3\\
1647 45: y=3\\
1648 46: z=x+y\\
1648 46: z=x+y\\
1649 47: print x\\
1649 47: print x\\
1650 48: a=5\\
1650 48: a=5\\
1651 49: print 'x',x,'y',y\\
1651 49: print 'x',x,'y',y\\
1652
1652
1653 you can create a macro with lines 44 through 47 (included) and line 49
1653 you can create a macro with lines 44 through 47 (included) and line 49
1654 called my_macro with:
1654 called my_macro with:
1655
1655
1656 In [51]: %macro my_macro 44-47 49
1656 In [51]: %macro my_macro 44-47 49
1657
1657
1658 Now, typing `my_macro` (without quotes) will re-execute all this code
1658 Now, typing `my_macro` (without quotes) will re-execute all this code
1659 in one pass.
1659 in one pass.
1660
1660
1661 You don't need to give the line-numbers in order, and any given line
1661 You don't need to give the line-numbers in order, and any given line
1662 number can appear multiple times. You can assemble macros with any
1662 number can appear multiple times. You can assemble macros with any
1663 lines from your input history in any order.
1663 lines from your input history in any order.
1664
1664
1665 The macro is a simple object which holds its value in an attribute,
1665 The macro is a simple object which holds its value in an attribute,
1666 but IPython's display system checks for macros and executes them as
1666 but IPython's display system checks for macros and executes them as
1667 code instead of printing them when you type their name.
1667 code instead of printing them when you type their name.
1668
1668
1669 You can view a macro's contents by explicitly printing it with:
1669 You can view a macro's contents by explicitly printing it with:
1670
1670
1671 'print macro_name'.
1671 'print macro_name'.
1672
1672
1673 For one-off cases which DON'T contain magic function calls in them you
1673 For one-off cases which DON'T contain magic function calls in them you
1674 can obtain similar results by explicitly executing slices from your
1674 can obtain similar results by explicitly executing slices from your
1675 input history with:
1675 input history with:
1676
1676
1677 In [60]: exec In[44:48]+In[49]"""
1677 In [60]: exec In[44:48]+In[49]"""
1678
1678
1679 opts,args = self.parse_options(parameter_s,'r')
1679 opts,args = self.parse_options(parameter_s,'r')
1680 name,ranges = args[0], args[1:]
1680 name,ranges = args[0], args[1:]
1681 #print 'rng',ranges # dbg
1681 #print 'rng',ranges # dbg
1682 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1682 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1683 macro = Macro(lines)
1683 macro = Macro(lines)
1684 self.shell.user_ns.update({name:macro})
1684 self.shell.user_ns.update({name:macro})
1685 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1685 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1686 print 'Macro contents:'
1686 print 'Macro contents:'
1687 print macro,
1687 print macro,
1688
1688
1689 def magic_save(self,parameter_s = ''):
1689 def magic_save(self,parameter_s = ''):
1690 """Save a set of lines to a given filename.
1690 """Save a set of lines to a given filename.
1691
1691
1692 Usage:\\
1692 Usage:\\
1693 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1693 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1694
1694
1695 Options:
1695 Options:
1696
1696
1697 -r: use 'raw' input. By default, the 'processed' history is used,
1697 -r: use 'raw' input. By default, the 'processed' history is used,
1698 so that magics are loaded in their transformed version to valid
1698 so that magics are loaded in their transformed version to valid
1699 Python. If this option is given, the raw input as typed as the
1699 Python. If this option is given, the raw input as typed as the
1700 command line is used instead.
1700 command line is used instead.
1701
1701
1702 This function uses the same syntax as %macro for line extraction, but
1702 This function uses the same syntax as %macro for line extraction, but
1703 instead of creating a macro it saves the resulting string to the
1703 instead of creating a macro it saves the resulting string to the
1704 filename you specify.
1704 filename you specify.
1705
1705
1706 It adds a '.py' extension to the file if you don't do so yourself, and
1706 It adds a '.py' extension to the file if you don't do so yourself, and
1707 it asks for confirmation before overwriting existing files."""
1707 it asks for confirmation before overwriting existing files."""
1708
1708
1709 opts,args = self.parse_options(parameter_s,'r')
1709 opts,args = self.parse_options(parameter_s,'r')
1710 fname,ranges = args[0], args[1:]
1710 fname,ranges = args[0], args[1:]
1711 if not fname.endswith('.py'):
1711 if not fname.endswith('.py'):
1712 fname += '.py'
1712 fname += '.py'
1713 if os.path.isfile(fname):
1713 if os.path.isfile(fname):
1714 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1714 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1715 if ans.lower() not in ['y','yes']:
1715 if ans.lower() not in ['y','yes']:
1716 print 'Operation cancelled.'
1716 print 'Operation cancelled.'
1717 return
1717 return
1718 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1718 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1719 f = file(fname,'w')
1719 f = file(fname,'w')
1720 f.write(cmds)
1720 f.write(cmds)
1721 f.close()
1721 f.close()
1722 print 'The following commands were written to file `%s`:' % fname
1722 print 'The following commands were written to file `%s`:' % fname
1723 print cmds
1723 print cmds
1724
1724
1725 def _edit_macro(self,mname,macro):
1725 def _edit_macro(self,mname,macro):
1726 """open an editor with the macro data in a file"""
1726 """open an editor with the macro data in a file"""
1727 filename = self.shell.mktempfile(macro.value)
1727 filename = self.shell.mktempfile(macro.value)
1728 self.shell.hooks.editor(filename)
1728 self.shell.hooks.editor(filename)
1729
1729
1730 # and make a new macro object, to replace the old one
1730 # and make a new macro object, to replace the old one
1731 mfile = open(filename)
1731 mfile = open(filename)
1732 mvalue = mfile.read()
1732 mvalue = mfile.read()
1733 mfile.close()
1733 mfile.close()
1734 self.shell.user_ns[mname] = Macro(mvalue)
1734 self.shell.user_ns[mname] = Macro(mvalue)
1735
1735
1736 def magic_ed(self,parameter_s=''):
1736 def magic_ed(self,parameter_s=''):
1737 """Alias to %edit."""
1737 """Alias to %edit."""
1738 return self.magic_edit(parameter_s)
1738 return self.magic_edit(parameter_s)
1739
1739
1740 def magic_edit(self,parameter_s='',last_call=['','']):
1740 def magic_edit(self,parameter_s='',last_call=['','']):
1741 """Bring up an editor and execute the resulting code.
1741 """Bring up an editor and execute the resulting code.
1742
1742
1743 Usage:
1743 Usage:
1744 %edit [options] [args]
1744 %edit [options] [args]
1745
1745
1746 %edit runs IPython's editor hook. The default version of this hook is
1746 %edit runs IPython's editor hook. The default version of this hook is
1747 set to call the __IPYTHON__.rc.editor command. This is read from your
1747 set to call the __IPYTHON__.rc.editor command. This is read from your
1748 environment variable $EDITOR. If this isn't found, it will default to
1748 environment variable $EDITOR. If this isn't found, it will default to
1749 vi under Linux/Unix and to notepad under Windows. See the end of this
1749 vi under Linux/Unix and to notepad under Windows. See the end of this
1750 docstring for how to change the editor hook.
1750 docstring for how to change the editor hook.
1751
1751
1752 You can also set the value of this editor via the command line option
1752 You can also set the value of this editor via the command line option
1753 '-editor' or in your ipythonrc file. This is useful if you wish to use
1753 '-editor' or in your ipythonrc file. This is useful if you wish to use
1754 specifically for IPython an editor different from your typical default
1754 specifically for IPython an editor different from your typical default
1755 (and for Windows users who typically don't set environment variables).
1755 (and for Windows users who typically don't set environment variables).
1756
1756
1757 This command allows you to conveniently edit multi-line code right in
1757 This command allows you to conveniently edit multi-line code right in
1758 your IPython session.
1758 your IPython session.
1759
1759
1760 If called without arguments, %edit opens up an empty editor with a
1760 If called without arguments, %edit opens up an empty editor with a
1761 temporary file and will execute the contents of this file when you
1761 temporary file and will execute the contents of this file when you
1762 close it (don't forget to save it!).
1762 close it (don't forget to save it!).
1763
1763
1764
1764
1765 Options:
1765 Options:
1766
1766
1767 -p: this will call the editor with the same data as the previous time
1767 -p: this will call the editor with the same data as the previous time
1768 it was used, regardless of how long ago (in your current session) it
1768 it was used, regardless of how long ago (in your current session) it
1769 was.
1769 was.
1770
1770
1771 -r: use 'raw' input. This option only applies to input taken from the
1771 -r: use 'raw' input. This option only applies to input taken from the
1772 user's history. By default, the 'processed' history is used, so that
1772 user's history. By default, the 'processed' history is used, so that
1773 magics are loaded in their transformed version to valid Python. If
1773 magics are loaded in their transformed version to valid Python. If
1774 this option is given, the raw input as typed as the command line is
1774 this option is given, the raw input as typed as the command line is
1775 used instead. When you exit the editor, it will be executed by
1775 used instead. When you exit the editor, it will be executed by
1776 IPython's own processor.
1776 IPython's own processor.
1777
1777
1778 -x: do not execute the edited code immediately upon exit. This is
1778 -x: do not execute the edited code immediately upon exit. This is
1779 mainly useful if you are editing programs which need to be called with
1779 mainly useful if you are editing programs which need to be called with
1780 command line arguments, which you can then do using %run.
1780 command line arguments, which you can then do using %run.
1781
1781
1782
1782
1783 Arguments:
1783 Arguments:
1784
1784
1785 If arguments are given, the following possibilites exist:
1785 If arguments are given, the following possibilites exist:
1786
1786
1787 - The arguments are numbers or pairs of colon-separated numbers (like
1787 - The arguments are numbers or pairs of colon-separated numbers (like
1788 1 4:8 9). These are interpreted as lines of previous input to be
1788 1 4:8 9). These are interpreted as lines of previous input to be
1789 loaded into the editor. The syntax is the same of the %macro command.
1789 loaded into the editor. The syntax is the same of the %macro command.
1790
1790
1791 - If the argument doesn't start with a number, it is evaluated as a
1791 - If the argument doesn't start with a number, it is evaluated as a
1792 variable and its contents loaded into the editor. You can thus edit
1792 variable and its contents loaded into the editor. You can thus edit
1793 any string which contains python code (including the result of
1793 any string which contains python code (including the result of
1794 previous edits).
1794 previous edits).
1795
1795
1796 - If the argument is the name of an object (other than a string),
1796 - If the argument is the name of an object (other than a string),
1797 IPython will try to locate the file where it was defined and open the
1797 IPython will try to locate the file where it was defined and open the
1798 editor at the point where it is defined. You can use `%edit function`
1798 editor at the point where it is defined. You can use `%edit function`
1799 to load an editor exactly at the point where 'function' is defined,
1799 to load an editor exactly at the point where 'function' is defined,
1800 edit it and have the file be executed automatically.
1800 edit it and have the file be executed automatically.
1801
1801
1802 If the object is a macro (see %macro for details), this opens up your
1802 If the object is a macro (see %macro for details), this opens up your
1803 specified editor with a temporary file containing the macro's data.
1803 specified editor with a temporary file containing the macro's data.
1804 Upon exit, the macro is reloaded with the contents of the file.
1804 Upon exit, the macro is reloaded with the contents of the file.
1805
1805
1806 Note: opening at an exact line is only supported under Unix, and some
1806 Note: opening at an exact line is only supported under Unix, and some
1807 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1807 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1808 '+NUMBER' parameter necessary for this feature. Good editors like
1808 '+NUMBER' parameter necessary for this feature. Good editors like
1809 (X)Emacs, vi, jed, pico and joe all do.
1809 (X)Emacs, vi, jed, pico and joe all do.
1810
1810
1811 - If the argument is not found as a variable, IPython will look for a
1811 - If the argument is not found as a variable, IPython will look for a
1812 file with that name (adding .py if necessary) and load it into the
1812 file with that name (adding .py if necessary) and load it into the
1813 editor. It will execute its contents with execfile() when you exit,
1813 editor. It will execute its contents with execfile() when you exit,
1814 loading any code in the file into your interactive namespace.
1814 loading any code in the file into your interactive namespace.
1815
1815
1816 After executing your code, %edit will return as output the code you
1816 After executing your code, %edit will return as output the code you
1817 typed in the editor (except when it was an existing file). This way
1817 typed in the editor (except when it was an existing file). This way
1818 you can reload the code in further invocations of %edit as a variable,
1818 you can reload the code in further invocations of %edit as a variable,
1819 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1819 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1820 the output.
1820 the output.
1821
1821
1822 Note that %edit is also available through the alias %ed.
1822 Note that %edit is also available through the alias %ed.
1823
1823
1824 This is an example of creating a simple function inside the editor and
1824 This is an example of creating a simple function inside the editor and
1825 then modifying it. First, start up the editor:
1825 then modifying it. First, start up the editor:
1826
1826
1827 In [1]: ed\\
1827 In [1]: ed\\
1828 Editing... done. Executing edited code...\\
1828 Editing... done. Executing edited code...\\
1829 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1829 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1830
1830
1831 We can then call the function foo():
1831 We can then call the function foo():
1832
1832
1833 In [2]: foo()\\
1833 In [2]: foo()\\
1834 foo() was defined in an editing session
1834 foo() was defined in an editing session
1835
1835
1836 Now we edit foo. IPython automatically loads the editor with the
1836 Now we edit foo. IPython automatically loads the editor with the
1837 (temporary) file where foo() was previously defined:
1837 (temporary) file where foo() was previously defined:
1838
1838
1839 In [3]: ed foo\\
1839 In [3]: ed foo\\
1840 Editing... done. Executing edited code...
1840 Editing... done. Executing edited code...
1841
1841
1842 And if we call foo() again we get the modified version:
1842 And if we call foo() again we get the modified version:
1843
1843
1844 In [4]: foo()\\
1844 In [4]: foo()\\
1845 foo() has now been changed!
1845 foo() has now been changed!
1846
1846
1847 Here is an example of how to edit a code snippet successive
1847 Here is an example of how to edit a code snippet successive
1848 times. First we call the editor:
1848 times. First we call the editor:
1849
1849
1850 In [8]: ed\\
1850 In [8]: ed\\
1851 Editing... done. Executing edited code...\\
1851 Editing... done. Executing edited code...\\
1852 hello\\
1852 hello\\
1853 Out[8]: "print 'hello'\\n"
1853 Out[8]: "print 'hello'\\n"
1854
1854
1855 Now we call it again with the previous output (stored in _):
1855 Now we call it again with the previous output (stored in _):
1856
1856
1857 In [9]: ed _\\
1857 In [9]: ed _\\
1858 Editing... done. Executing edited code...\\
1858 Editing... done. Executing edited code...\\
1859 hello world\\
1859 hello world\\
1860 Out[9]: "print 'hello world'\\n"
1860 Out[9]: "print 'hello world'\\n"
1861
1861
1862 Now we call it with the output #8 (stored in _8, also as Out[8]):
1862 Now we call it with the output #8 (stored in _8, also as Out[8]):
1863
1863
1864 In [10]: ed _8\\
1864 In [10]: ed _8\\
1865 Editing... done. Executing edited code...\\
1865 Editing... done. Executing edited code...\\
1866 hello again\\
1866 hello again\\
1867 Out[10]: "print 'hello again'\\n"
1867 Out[10]: "print 'hello again'\\n"
1868
1868
1869
1869
1870 Changing the default editor hook:
1870 Changing the default editor hook:
1871
1871
1872 If you wish to write your own editor hook, you can put it in a
1872 If you wish to write your own editor hook, you can put it in a
1873 configuration file which you load at startup time. The default hook
1873 configuration file which you load at startup time. The default hook
1874 is defined in the IPython.hooks module, and you can use that as a
1874 is defined in the IPython.hooks module, and you can use that as a
1875 starting example for further modifications. That file also has
1875 starting example for further modifications. That file also has
1876 general instructions on how to set a new hook for use once you've
1876 general instructions on how to set a new hook for use once you've
1877 defined it."""
1877 defined it."""
1878
1878
1879 # FIXME: This function has become a convoluted mess. It needs a
1879 # FIXME: This function has become a convoluted mess. It needs a
1880 # ground-up rewrite with clean, simple logic.
1880 # ground-up rewrite with clean, simple logic.
1881
1881
1882 def make_filename(arg):
1882 def make_filename(arg):
1883 "Make a filename from the given args"
1883 "Make a filename from the given args"
1884 try:
1884 try:
1885 filename = get_py_filename(arg)
1885 filename = get_py_filename(arg)
1886 except IOError:
1886 except IOError:
1887 if args.endswith('.py'):
1887 if args.endswith('.py'):
1888 filename = arg
1888 filename = arg
1889 else:
1889 else:
1890 filename = None
1890 filename = None
1891 return filename
1891 return filename
1892
1892
1893 # custom exceptions
1893 # custom exceptions
1894 class DataIsObject(Exception): pass
1894 class DataIsObject(Exception): pass
1895
1895
1896 opts,args = self.parse_options(parameter_s,'prx')
1896 opts,args = self.parse_options(parameter_s,'prx')
1897 # Set a few locals from the options for convenience:
1897 # Set a few locals from the options for convenience:
1898 opts_p = opts.has_key('p')
1898 opts_p = opts.has_key('p')
1899 opts_r = opts.has_key('r')
1899 opts_r = opts.has_key('r')
1900
1900
1901 # Default line number value
1901 # Default line number value
1902 lineno = None
1902 lineno = None
1903 if opts_p:
1903 if opts_p:
1904 args = '_%s' % last_call[0]
1904 args = '_%s' % last_call[0]
1905 if not self.shell.user_ns.has_key(args):
1905 if not self.shell.user_ns.has_key(args):
1906 args = last_call[1]
1906 args = last_call[1]
1907
1907
1908 # use last_call to remember the state of the previous call, but don't
1908 # use last_call to remember the state of the previous call, but don't
1909 # let it be clobbered by successive '-p' calls.
1909 # let it be clobbered by successive '-p' calls.
1910 try:
1910 try:
1911 last_call[0] = self.shell.outputcache.prompt_count
1911 last_call[0] = self.shell.outputcache.prompt_count
1912 if not opts_p:
1912 if not opts_p:
1913 last_call[1] = parameter_s
1913 last_call[1] = parameter_s
1914 except:
1914 except:
1915 pass
1915 pass
1916
1916
1917 # by default this is done with temp files, except when the given
1917 # by default this is done with temp files, except when the given
1918 # arg is a filename
1918 # arg is a filename
1919 use_temp = 1
1919 use_temp = 1
1920
1920
1921 if re.match(r'\d',args):
1921 if re.match(r'\d',args):
1922 # Mode where user specifies ranges of lines, like in %macro.
1922 # Mode where user specifies ranges of lines, like in %macro.
1923 # This means that you can't edit files whose names begin with
1923 # This means that you can't edit files whose names begin with
1924 # numbers this way. Tough.
1924 # numbers this way. Tough.
1925 ranges = args.split()
1925 ranges = args.split()
1926 data = ''.join(self.extract_input_slices(ranges,opts_r))
1926 data = ''.join(self.extract_input_slices(ranges,opts_r))
1927 elif args.endswith('.py'):
1927 elif args.endswith('.py'):
1928 filename = make_filename(args)
1928 filename = make_filename(args)
1929 data = ''
1929 data = ''
1930 use_temp = 0
1930 use_temp = 0
1931 elif args:
1931 elif args:
1932 try:
1932 try:
1933 # Load the parameter given as a variable. If not a string,
1933 # Load the parameter given as a variable. If not a string,
1934 # process it as an object instead (below)
1934 # process it as an object instead (below)
1935
1935
1936 #print '*** args',args,'type',type(args) # dbg
1936 #print '*** args',args,'type',type(args) # dbg
1937 data = eval(args,self.shell.user_ns)
1937 data = eval(args,self.shell.user_ns)
1938 if not type(data) in StringTypes:
1938 if not type(data) in StringTypes:
1939 raise DataIsObject
1939 raise DataIsObject
1940
1940
1941 except (NameError,SyntaxError):
1941 except (NameError,SyntaxError):
1942 # given argument is not a variable, try as a filename
1942 # given argument is not a variable, try as a filename
1943 filename = make_filename(args)
1943 filename = make_filename(args)
1944 if filename is None:
1944 if filename is None:
1945 warn("Argument given (%s) can't be found as a variable "
1945 warn("Argument given (%s) can't be found as a variable "
1946 "or as a filename." % args)
1946 "or as a filename." % args)
1947 return
1947 return
1948
1948
1949 data = ''
1949 data = ''
1950 use_temp = 0
1950 use_temp = 0
1951 except DataIsObject:
1951 except DataIsObject:
1952
1952
1953 # macros have a special edit function
1953 # macros have a special edit function
1954 if isinstance(data,Macro):
1954 if isinstance(data,Macro):
1955 self._edit_macro(args,data)
1955 self._edit_macro(args,data)
1956 return
1956 return
1957
1957
1958 # For objects, try to edit the file where they are defined
1958 # For objects, try to edit the file where they are defined
1959 try:
1959 try:
1960 filename = inspect.getabsfile(data)
1960 filename = inspect.getabsfile(data)
1961 datafile = 1
1961 datafile = 1
1962 except TypeError:
1962 except TypeError:
1963 filename = make_filename(args)
1963 filename = make_filename(args)
1964 datafile = 1
1964 datafile = 1
1965 warn('Could not find file where `%s` is defined.\n'
1965 warn('Could not find file where `%s` is defined.\n'
1966 'Opening a file named `%s`' % (args,filename))
1966 'Opening a file named `%s`' % (args,filename))
1967 # Now, make sure we can actually read the source (if it was in
1967 # Now, make sure we can actually read the source (if it was in
1968 # a temp file it's gone by now).
1968 # a temp file it's gone by now).
1969 if datafile:
1969 if datafile:
1970 try:
1970 try:
1971 lineno = inspect.getsourcelines(data)[1]
1971 lineno = inspect.getsourcelines(data)[1]
1972 except IOError:
1972 except IOError:
1973 filename = make_filename(args)
1973 filename = make_filename(args)
1974 if filename is None:
1974 if filename is None:
1975 warn('The file `%s` where `%s` was defined cannot '
1975 warn('The file `%s` where `%s` was defined cannot '
1976 'be read.' % (filename,data))
1976 'be read.' % (filename,data))
1977 return
1977 return
1978 use_temp = 0
1978 use_temp = 0
1979 else:
1979 else:
1980 data = ''
1980 data = ''
1981
1981
1982 if use_temp:
1982 if use_temp:
1983 filename = self.shell.mktempfile(data)
1983 filename = self.shell.mktempfile(data)
1984 print 'IPython will make a temporary file named:',filename
1984 print 'IPython will make a temporary file named:',filename
1985
1985
1986 # do actual editing here
1986 # do actual editing here
1987 print 'Editing...',
1987 print 'Editing...',
1988 sys.stdout.flush()
1988 sys.stdout.flush()
1989 self.shell.hooks.editor(filename,lineno)
1989 self.shell.hooks.editor(filename,lineno)
1990 if opts.has_key('x'): # -x prevents actual execution
1990 if opts.has_key('x'): # -x prevents actual execution
1991 print
1991 print
1992 else:
1992 else:
1993 print 'done. Executing edited code...'
1993 print 'done. Executing edited code...'
1994 if opts_r:
1994 if opts_r:
1995 self.shell.runlines(file_read(filename))
1995 self.shell.runlines(file_read(filename))
1996 else:
1996 else:
1997 self.shell.safe_execfile(filename,self.shell.user_ns)
1997 self.shell.safe_execfile(filename,self.shell.user_ns)
1998 if use_temp:
1998 if use_temp:
1999 try:
1999 try:
2000 return open(filename).read()
2000 return open(filename).read()
2001 except IOError,msg:
2001 except IOError,msg:
2002 if msg.filename == filename:
2002 if msg.filename == filename:
2003 warn('File not found. Did you forget to save?')
2003 warn('File not found. Did you forget to save?')
2004 return
2004 return
2005 else:
2005 else:
2006 self.shell.showtraceback()
2006 self.shell.showtraceback()
2007
2007
2008 def magic_xmode(self,parameter_s = ''):
2008 def magic_xmode(self,parameter_s = ''):
2009 """Switch modes for the exception handlers.
2009 """Switch modes for the exception handlers.
2010
2010
2011 Valid modes: Plain, Context and Verbose.
2011 Valid modes: Plain, Context and Verbose.
2012
2012
2013 If called without arguments, acts as a toggle."""
2013 If called without arguments, acts as a toggle."""
2014
2014
2015 def xmode_switch_err(name):
2015 def xmode_switch_err(name):
2016 warn('Error changing %s exception modes.\n%s' %
2016 warn('Error changing %s exception modes.\n%s' %
2017 (name,sys.exc_info()[1]))
2017 (name,sys.exc_info()[1]))
2018
2018
2019 shell = self.shell
2019 shell = self.shell
2020 new_mode = parameter_s.strip().capitalize()
2020 new_mode = parameter_s.strip().capitalize()
2021 try:
2021 try:
2022 shell.InteractiveTB.set_mode(mode=new_mode)
2022 shell.InteractiveTB.set_mode(mode=new_mode)
2023 print 'Exception reporting mode:',shell.InteractiveTB.mode
2023 print 'Exception reporting mode:',shell.InteractiveTB.mode
2024 except:
2024 except:
2025 xmode_switch_err('user')
2025 xmode_switch_err('user')
2026
2026
2027 # threaded shells use a special handler in sys.excepthook
2027 # threaded shells use a special handler in sys.excepthook
2028 if shell.isthreaded:
2028 if shell.isthreaded:
2029 try:
2029 try:
2030 shell.sys_excepthook.set_mode(mode=new_mode)
2030 shell.sys_excepthook.set_mode(mode=new_mode)
2031 except:
2031 except:
2032 xmode_switch_err('threaded')
2032 xmode_switch_err('threaded')
2033
2033
2034 def magic_colors(self,parameter_s = ''):
2034 def magic_colors(self,parameter_s = ''):
2035 """Switch color scheme for prompts, info system and exception handlers.
2035 """Switch color scheme for prompts, info system and exception handlers.
2036
2036
2037 Currently implemented schemes: NoColor, Linux, LightBG.
2037 Currently implemented schemes: NoColor, Linux, LightBG.
2038
2038
2039 Color scheme names are not case-sensitive."""
2039 Color scheme names are not case-sensitive."""
2040
2040
2041 def color_switch_err(name):
2041 def color_switch_err(name):
2042 warn('Error changing %s color schemes.\n%s' %
2042 warn('Error changing %s color schemes.\n%s' %
2043 (name,sys.exc_info()[1]))
2043 (name,sys.exc_info()[1]))
2044
2044
2045
2045
2046 new_scheme = parameter_s.strip()
2046 new_scheme = parameter_s.strip()
2047 if not new_scheme:
2047 if not new_scheme:
2048 print 'You must specify a color scheme.'
2048 print 'You must specify a color scheme.'
2049 return
2049 return
2050 import IPython.rlineimpl as readline
2050 import IPython.rlineimpl as readline
2051 if not readline.have_readline:
2051 if not readline.have_readline:
2052 msg = """\
2052 msg = """\
2053 Proper color support under MS Windows requires Gary Bishop's readline library.
2053 Proper color support under MS Windows requires Gary Bishop's readline library.
2054 You can find it at:
2054 You can find it at:
2055 http://sourceforge.net/projects/uncpythontools
2055 http://sourceforge.net/projects/uncpythontools
2056 Gary's readline needs the ctypes module, from:
2056 Gary's readline needs the ctypes module, from:
2057 http://starship.python.net/crew/theller/ctypes
2057 http://starship.python.net/crew/theller/ctypes
2058
2058
2059 Defaulting color scheme to 'NoColor'"""
2059 Defaulting color scheme to 'NoColor'"""
2060 new_scheme = 'NoColor'
2060 new_scheme = 'NoColor'
2061 warn(msg)
2061 warn(msg)
2062 # local shortcut
2062 # local shortcut
2063 shell = self.shell
2063 shell = self.shell
2064
2064
2065 # Set prompt colors
2065 # Set prompt colors
2066 try:
2066 try:
2067 shell.outputcache.set_colors(new_scheme)
2067 shell.outputcache.set_colors(new_scheme)
2068 except:
2068 except:
2069 color_switch_err('prompt')
2069 color_switch_err('prompt')
2070 else:
2070 else:
2071 shell.rc.colors = \
2071 shell.rc.colors = \
2072 shell.outputcache.color_table.active_scheme_name
2072 shell.outputcache.color_table.active_scheme_name
2073 # Set exception colors
2073 # Set exception colors
2074 try:
2074 try:
2075 shell.InteractiveTB.set_colors(scheme = new_scheme)
2075 shell.InteractiveTB.set_colors(scheme = new_scheme)
2076 shell.SyntaxTB.set_colors(scheme = new_scheme)
2076 shell.SyntaxTB.set_colors(scheme = new_scheme)
2077 except:
2077 except:
2078 color_switch_err('exception')
2078 color_switch_err('exception')
2079
2079
2080 # threaded shells use a verbose traceback in sys.excepthook
2080 # threaded shells use a verbose traceback in sys.excepthook
2081 if shell.isthreaded:
2081 if shell.isthreaded:
2082 try:
2082 try:
2083 shell.sys_excepthook.set_colors(scheme=new_scheme)
2083 shell.sys_excepthook.set_colors(scheme=new_scheme)
2084 except:
2084 except:
2085 color_switch_err('system exception handler')
2085 color_switch_err('system exception handler')
2086
2086
2087 # Set info (for 'object?') colors
2087 # Set info (for 'object?') colors
2088 if shell.rc.color_info:
2088 if shell.rc.color_info:
2089 try:
2089 try:
2090 shell.inspector.set_active_scheme(new_scheme)
2090 shell.inspector.set_active_scheme(new_scheme)
2091 except:
2091 except:
2092 color_switch_err('object inspector')
2092 color_switch_err('object inspector')
2093 else:
2093 else:
2094 shell.inspector.set_active_scheme('NoColor')
2094 shell.inspector.set_active_scheme('NoColor')
2095
2095
2096 def magic_color_info(self,parameter_s = ''):
2096 def magic_color_info(self,parameter_s = ''):
2097 """Toggle color_info.
2097 """Toggle color_info.
2098
2098
2099 The color_info configuration parameter controls whether colors are
2099 The color_info configuration parameter controls whether colors are
2100 used for displaying object details (by things like %psource, %pfile or
2100 used for displaying object details (by things like %psource, %pfile or
2101 the '?' system). This function toggles this value with each call.
2101 the '?' system). This function toggles this value with each call.
2102
2102
2103 Note that unless you have a fairly recent pager (less works better
2103 Note that unless you have a fairly recent pager (less works better
2104 than more) in your system, using colored object information displays
2104 than more) in your system, using colored object information displays
2105 will not work properly. Test it and see."""
2105 will not work properly. Test it and see."""
2106
2106
2107 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2107 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2108 self.magic_colors(self.shell.rc.colors)
2108 self.magic_colors(self.shell.rc.colors)
2109 print 'Object introspection functions have now coloring:',
2109 print 'Object introspection functions have now coloring:',
2110 print ['OFF','ON'][self.shell.rc.color_info]
2110 print ['OFF','ON'][self.shell.rc.color_info]
2111
2111
2112 def magic_Pprint(self, parameter_s=''):
2112 def magic_Pprint(self, parameter_s=''):
2113 """Toggle pretty printing on/off."""
2113 """Toggle pretty printing on/off."""
2114
2114
2115 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2115 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2116 print 'Pretty printing has been turned', \
2116 print 'Pretty printing has been turned', \
2117 ['OFF','ON'][self.shell.outputcache.Pprint]
2117 ['OFF','ON'][self.shell.outputcache.Pprint]
2118
2118
2119 def magic_exit(self, parameter_s=''):
2119 def magic_exit(self, parameter_s=''):
2120 """Exit IPython, confirming if configured to do so.
2120 """Exit IPython, confirming if configured to do so.
2121
2121
2122 You can configure whether IPython asks for confirmation upon exit by
2122 You can configure whether IPython asks for confirmation upon exit by
2123 setting the confirm_exit flag in the ipythonrc file."""
2123 setting the confirm_exit flag in the ipythonrc file."""
2124
2124
2125 self.shell.exit()
2125 self.shell.exit()
2126
2126
2127 def magic_quit(self, parameter_s=''):
2127 def magic_quit(self, parameter_s=''):
2128 """Exit IPython, confirming if configured to do so (like %exit)"""
2128 """Exit IPython, confirming if configured to do so (like %exit)"""
2129
2129
2130 self.shell.exit()
2130 self.shell.exit()
2131
2131
2132 def magic_Exit(self, parameter_s=''):
2132 def magic_Exit(self, parameter_s=''):
2133 """Exit IPython without confirmation."""
2133 """Exit IPython without confirmation."""
2134
2134
2135 self.shell.exit_now = True
2135 self.shell.exit_now = True
2136
2136
2137 def magic_Quit(self, parameter_s=''):
2137 def magic_Quit(self, parameter_s=''):
2138 """Exit IPython without confirmation (like %Exit)."""
2138 """Exit IPython without confirmation (like %Exit)."""
2139
2139
2140 self.shell.exit_now = True
2140 self.shell.exit_now = True
2141
2141
2142 #......................................................................
2142 #......................................................................
2143 # Functions to implement unix shell-type things
2143 # Functions to implement unix shell-type things
2144
2144
2145 def magic_alias(self, parameter_s = ''):
2145 def magic_alias(self, parameter_s = ''):
2146 """Define an alias for a system command.
2146 """Define an alias for a system command.
2147
2147
2148 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2148 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2149
2149
2150 Then, typing 'alias_name params' will execute the system command 'cmd
2150 Then, typing 'alias_name params' will execute the system command 'cmd
2151 params' (from your underlying operating system).
2151 params' (from your underlying operating system).
2152
2152
2153 Aliases have lower precedence than magic functions and Python normal
2153 Aliases have lower precedence than magic functions and Python normal
2154 variables, so if 'foo' is both a Python variable and an alias, the
2154 variables, so if 'foo' is both a Python variable and an alias, the
2155 alias can not be executed until 'del foo' removes the Python variable.
2155 alias can not be executed until 'del foo' removes the Python variable.
2156
2156
2157 You can use the %l specifier in an alias definition to represent the
2157 You can use the %l specifier in an alias definition to represent the
2158 whole line when the alias is called. For example:
2158 whole line when the alias is called. For example:
2159
2159
2160 In [2]: alias all echo "Input in brackets: <%l>"\\
2160 In [2]: alias all echo "Input in brackets: <%l>"\\
2161 In [3]: all hello world\\
2161 In [3]: all hello world\\
2162 Input in brackets: <hello world>
2162 Input in brackets: <hello world>
2163
2163
2164 You can also define aliases with parameters using %s specifiers (one
2164 You can also define aliases with parameters using %s specifiers (one
2165 per parameter):
2165 per parameter):
2166
2166
2167 In [1]: alias parts echo first %s second %s\\
2167 In [1]: alias parts echo first %s second %s\\
2168 In [2]: %parts A B\\
2168 In [2]: %parts A B\\
2169 first A second B\\
2169 first A second B\\
2170 In [3]: %parts A\\
2170 In [3]: %parts A\\
2171 Incorrect number of arguments: 2 expected.\\
2171 Incorrect number of arguments: 2 expected.\\
2172 parts is an alias to: 'echo first %s second %s'
2172 parts is an alias to: 'echo first %s second %s'
2173
2173
2174 Note that %l and %s are mutually exclusive. You can only use one or
2174 Note that %l and %s are mutually exclusive. You can only use one or
2175 the other in your aliases.
2175 the other in your aliases.
2176
2176
2177 Aliases expand Python variables just like system calls using ! or !!
2177 Aliases expand Python variables just like system calls using ! or !!
2178 do: all expressions prefixed with '$' get expanded. For details of
2178 do: all expressions prefixed with '$' get expanded. For details of
2179 the semantic rules, see PEP-215:
2179 the semantic rules, see PEP-215:
2180 http://www.python.org/peps/pep-0215.html. This is the library used by
2180 http://www.python.org/peps/pep-0215.html. This is the library used by
2181 IPython for variable expansion. If you want to access a true shell
2181 IPython for variable expansion. If you want to access a true shell
2182 variable, an extra $ is necessary to prevent its expansion by IPython:
2182 variable, an extra $ is necessary to prevent its expansion by IPython:
2183
2183
2184 In [6]: alias show echo\\
2184 In [6]: alias show echo\\
2185 In [7]: PATH='A Python string'\\
2185 In [7]: PATH='A Python string'\\
2186 In [8]: show $PATH\\
2186 In [8]: show $PATH\\
2187 A Python string\\
2187 A Python string\\
2188 In [9]: show $$PATH\\
2188 In [9]: show $$PATH\\
2189 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2189 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2190
2190
2191 You can use the alias facility to acess all of $PATH. See the %rehash
2191 You can use the alias facility to acess all of $PATH. See the %rehash
2192 and %rehashx functions, which automatically create aliases for the
2192 and %rehashx functions, which automatically create aliases for the
2193 contents of your $PATH.
2193 contents of your $PATH.
2194
2194
2195 If called with no parameters, %alias prints the current alias table."""
2195 If called with no parameters, %alias prints the current alias table."""
2196
2196
2197 par = parameter_s.strip()
2197 par = parameter_s.strip()
2198 if not par:
2198 if not par:
2199 if self.shell.rc.automagic:
2199 if self.shell.rc.automagic:
2200 prechar = ''
2200 prechar = ''
2201 else:
2201 else:
2202 prechar = self.shell.ESC_MAGIC
2202 prechar = self.shell.ESC_MAGIC
2203 #print 'Alias\t\tSystem Command\n'+'-'*30
2203 #print 'Alias\t\tSystem Command\n'+'-'*30
2204 atab = self.shell.alias_table
2204 atab = self.shell.alias_table
2205 aliases = atab.keys()
2205 aliases = atab.keys()
2206 aliases.sort()
2206 aliases.sort()
2207 res = []
2207 res = []
2208 for alias in aliases:
2208 for alias in aliases:
2209 res.append((alias, atab[alias][1]))
2209 res.append((alias, atab[alias][1]))
2210 print "Total number of aliases:",len(aliases)
2210 print "Total number of aliases:",len(aliases)
2211 return res
2211 return res
2212 try:
2212 try:
2213 alias,cmd = par.split(None,1)
2213 alias,cmd = par.split(None,1)
2214 except:
2214 except:
2215 print OInspect.getdoc(self.magic_alias)
2215 print OInspect.getdoc(self.magic_alias)
2216 else:
2216 else:
2217 nargs = cmd.count('%s')
2217 nargs = cmd.count('%s')
2218 if nargs>0 and cmd.find('%l')>=0:
2218 if nargs>0 and cmd.find('%l')>=0:
2219 error('The %s and %l specifiers are mutually exclusive '
2219 error('The %s and %l specifiers are mutually exclusive '
2220 'in alias definitions.')
2220 'in alias definitions.')
2221 else: # all looks OK
2221 else: # all looks OK
2222 self.shell.alias_table[alias] = (nargs,cmd)
2222 self.shell.alias_table[alias] = (nargs,cmd)
2223 self.shell.alias_table_validate(verbose=1)
2223 self.shell.alias_table_validate(verbose=0)
2224 # end magic_alias
2224 # end magic_alias
2225
2225
2226 def magic_unalias(self, parameter_s = ''):
2226 def magic_unalias(self, parameter_s = ''):
2227 """Remove an alias"""
2227 """Remove an alias"""
2228
2228
2229 aname = parameter_s.strip()
2229 aname = parameter_s.strip()
2230 if aname in self.shell.alias_table:
2230 if aname in self.shell.alias_table:
2231 del self.shell.alias_table[aname]
2231 del self.shell.alias_table[aname]
2232
2232
2233 def magic_rehash(self, parameter_s = ''):
2233 def magic_rehash(self, parameter_s = ''):
2234 """Update the alias table with all entries in $PATH.
2234 """Update the alias table with all entries in $PATH.
2235
2235
2236 This version does no checks on execute permissions or whether the
2236 This version does no checks on execute permissions or whether the
2237 contents of $PATH are truly files (instead of directories or something
2237 contents of $PATH are truly files (instead of directories or something
2238 else). For such a safer (but slower) version, use %rehashx."""
2238 else). For such a safer (but slower) version, use %rehashx."""
2239
2239
2240 # This function (and rehashx) manipulate the alias_table directly
2240 # This function (and rehashx) manipulate the alias_table directly
2241 # rather than calling magic_alias, for speed reasons. A rehash on a
2241 # rather than calling magic_alias, for speed reasons. A rehash on a
2242 # typical Linux box involves several thousand entries, so efficiency
2242 # typical Linux box involves several thousand entries, so efficiency
2243 # here is a top concern.
2243 # here is a top concern.
2244
2244
2245 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2245 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2246 alias_table = self.shell.alias_table
2246 alias_table = self.shell.alias_table
2247 for pdir in path:
2247 for pdir in path:
2248 for ff in os.listdir(pdir):
2248 for ff in os.listdir(pdir):
2249 # each entry in the alias table must be (N,name), where
2249 # each entry in the alias table must be (N,name), where
2250 # N is the number of positional arguments of the alias.
2250 # N is the number of positional arguments of the alias.
2251 alias_table[ff] = (0,ff)
2251 alias_table[ff] = (0,ff)
2252 # Make sure the alias table doesn't contain keywords or builtins
2252 # Make sure the alias table doesn't contain keywords or builtins
2253 self.shell.alias_table_validate()
2253 self.shell.alias_table_validate()
2254 # Call again init_auto_alias() so we get 'rm -i' and other modified
2254 # Call again init_auto_alias() so we get 'rm -i' and other modified
2255 # aliases since %rehash will probably clobber them
2255 # aliases since %rehash will probably clobber them
2256 self.shell.init_auto_alias()
2256 self.shell.init_auto_alias()
2257
2257
2258 def magic_rehashx(self, parameter_s = ''):
2258 def magic_rehashx(self, parameter_s = ''):
2259 """Update the alias table with all executable files in $PATH.
2259 """Update the alias table with all executable files in $PATH.
2260
2260
2261 This version explicitly checks that every entry in $PATH is a file
2261 This version explicitly checks that every entry in $PATH is a file
2262 with execute access (os.X_OK), so it is much slower than %rehash.
2262 with execute access (os.X_OK), so it is much slower than %rehash.
2263
2263
2264 Under Windows, it checks executability as a match agains a
2264 Under Windows, it checks executability as a match agains a
2265 '|'-separated string of extensions, stored in the IPython config
2265 '|'-separated string of extensions, stored in the IPython config
2266 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2266 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2267
2267
2268 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2268 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2269 alias_table = self.shell.alias_table
2269 alias_table = self.shell.alias_table
2270
2270 syscmdlist = []
2271 if os.name == 'posix':
2271 if os.name == 'posix':
2272 isexec = lambda fname:os.path.isfile(fname) and \
2272 isexec = lambda fname:os.path.isfile(fname) and \
2273 os.access(fname,os.X_OK)
2273 os.access(fname,os.X_OK)
2274 else:
2274 else:
2275
2275
2276 try:
2276 try:
2277 winext = os.environ['pathext'].replace(';','|').replace('.','')
2277 winext = os.environ['pathext'].replace(';','|').replace('.','')
2278 except KeyError:
2278 except KeyError:
2279 winext = 'exe|com|bat'
2279 winext = 'exe|com|bat'
2280
2280
2281 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2281 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2282 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2282 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2283 savedir = os.getcwd()
2283 savedir = os.getcwd()
2284 try:
2284 try:
2285 # write the whole loop for posix/Windows so we don't have an if in
2285 # write the whole loop for posix/Windows so we don't have an if in
2286 # the innermost part
2286 # the innermost part
2287 if os.name == 'posix':
2287 if os.name == 'posix':
2288 for pdir in path:
2288 for pdir in path:
2289 os.chdir(pdir)
2289 os.chdir(pdir)
2290 for ff in os.listdir(pdir):
2290 for ff in os.listdir(pdir):
2291 if isexec(ff):
2291 if isexec(ff):
2292 # each entry in the alias table must be (N,name),
2292 # each entry in the alias table must be (N,name),
2293 # where N is the number of positional arguments of the
2293 # where N is the number of positional arguments of the
2294 # alias.
2294 # alias.
2295 alias_table[ff] = (0,ff)
2295 alias_table[ff] = (0,ff)
2296 syscmdlist.append(ff)
2296 else:
2297 else:
2297 for pdir in path:
2298 for pdir in path:
2298 os.chdir(pdir)
2299 os.chdir(pdir)
2299 for ff in os.listdir(pdir):
2300 for ff in os.listdir(pdir):
2300 if isexec(ff):
2301 if isexec(ff):
2301 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2302 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2303 syscmdlist.append(ff)
2302 # Make sure the alias table doesn't contain keywords or builtins
2304 # Make sure the alias table doesn't contain keywords or builtins
2303 self.shell.alias_table_validate()
2305 self.shell.alias_table_validate()
2304 # Call again init_auto_alias() so we get 'rm -i' and other
2306 # Call again init_auto_alias() so we get 'rm -i' and other
2305 # modified aliases since %rehashx will probably clobber them
2307 # modified aliases since %rehashx will probably clobber them
2306 self.shell.init_auto_alias()
2308 self.shell.init_auto_alias()
2309 db = self.getapi().getdb()
2310 db['syscmdlist'] = syscmdlist
2307 finally:
2311 finally:
2308 os.chdir(savedir)
2312 os.chdir(savedir)
2309
2313
2310 def magic_pwd(self, parameter_s = ''):
2314 def magic_pwd(self, parameter_s = ''):
2311 """Return the current working directory path."""
2315 """Return the current working directory path."""
2312 return os.getcwd()
2316 return os.getcwd()
2313
2317
2314 def magic_cd(self, parameter_s=''):
2318 def magic_cd(self, parameter_s=''):
2315 """Change the current working directory.
2319 """Change the current working directory.
2316
2320
2317 This command automatically maintains an internal list of directories
2321 This command automatically maintains an internal list of directories
2318 you visit during your IPython session, in the variable _dh. The
2322 you visit during your IPython session, in the variable _dh. The
2319 command %dhist shows this history nicely formatted.
2323 command %dhist shows this history nicely formatted.
2320
2324
2321 Usage:
2325 Usage:
2322
2326
2323 cd 'dir': changes to directory 'dir'.
2327 cd 'dir': changes to directory 'dir'.
2324
2328
2325 cd -: changes to the last visited directory.
2329 cd -: changes to the last visited directory.
2326
2330
2327 cd -<n>: changes to the n-th directory in the directory history.
2331 cd -<n>: changes to the n-th directory in the directory history.
2328
2332
2329 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2333 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2330 (note: cd <bookmark_name> is enough if there is no
2334 (note: cd <bookmark_name> is enough if there is no
2331 directory <bookmark_name>, but a bookmark with the name exists.)
2335 directory <bookmark_name>, but a bookmark with the name exists.)
2332
2336
2333 Options:
2337 Options:
2334
2338
2335 -q: quiet. Do not print the working directory after the cd command is
2339 -q: quiet. Do not print the working directory after the cd command is
2336 executed. By default IPython's cd command does print this directory,
2340 executed. By default IPython's cd command does print this directory,
2337 since the default prompts do not display path information.
2341 since the default prompts do not display path information.
2338
2342
2339 Note that !cd doesn't work for this purpose because the shell where
2343 Note that !cd doesn't work for this purpose because the shell where
2340 !command runs is immediately discarded after executing 'command'."""
2344 !command runs is immediately discarded after executing 'command'."""
2341
2345
2342 parameter_s = parameter_s.strip()
2346 parameter_s = parameter_s.strip()
2343 #bkms = self.shell.persist.get("bookmarks",{})
2347 #bkms = self.shell.persist.get("bookmarks",{})
2344
2348
2345 numcd = re.match(r'(-)(\d+)$',parameter_s)
2349 numcd = re.match(r'(-)(\d+)$',parameter_s)
2346 # jump in directory history by number
2350 # jump in directory history by number
2347 if numcd:
2351 if numcd:
2348 nn = int(numcd.group(2))
2352 nn = int(numcd.group(2))
2349 try:
2353 try:
2350 ps = self.shell.user_ns['_dh'][nn]
2354 ps = self.shell.user_ns['_dh'][nn]
2351 except IndexError:
2355 except IndexError:
2352 print 'The requested directory does not exist in history.'
2356 print 'The requested directory does not exist in history.'
2353 return
2357 return
2354 else:
2358 else:
2355 opts = {}
2359 opts = {}
2356 else:
2360 else:
2357 #turn all non-space-escaping backslashes to slashes,
2361 #turn all non-space-escaping backslashes to slashes,
2358 # for c:\windows\directory\names\
2362 # for c:\windows\directory\names\
2359 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2363 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2360 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2364 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2361 # jump to previous
2365 # jump to previous
2362 if ps == '-':
2366 if ps == '-':
2363 try:
2367 try:
2364 ps = self.shell.user_ns['_dh'][-2]
2368 ps = self.shell.user_ns['_dh'][-2]
2365 except IndexError:
2369 except IndexError:
2366 print 'No previous directory to change to.'
2370 print 'No previous directory to change to.'
2367 return
2371 return
2368 # jump to bookmark if needed
2372 # jump to bookmark if needed
2369 else:
2373 else:
2370 if not os.path.isdir(ps) or opts.has_key('b'):
2374 if not os.path.isdir(ps) or opts.has_key('b'):
2371 bkms = self.db.get('bookmarks', {})
2375 bkms = self.db.get('bookmarks', {})
2372
2376
2373 if bkms.has_key(ps):
2377 if bkms.has_key(ps):
2374 target = bkms[ps]
2378 target = bkms[ps]
2375 print '(bookmark:%s) -> %s' % (ps,target)
2379 print '(bookmark:%s) -> %s' % (ps,target)
2376 ps = target
2380 ps = target
2377 else:
2381 else:
2378 if opts.has_key('b'):
2382 if opts.has_key('b'):
2379 error("Bookmark '%s' not found. "
2383 error("Bookmark '%s' not found. "
2380 "Use '%%bookmark -l' to see your bookmarks." % ps)
2384 "Use '%%bookmark -l' to see your bookmarks." % ps)
2381 return
2385 return
2382
2386
2383 # at this point ps should point to the target dir
2387 # at this point ps should point to the target dir
2384 if ps:
2388 if ps:
2385 try:
2389 try:
2386 os.chdir(os.path.expanduser(ps))
2390 os.chdir(os.path.expanduser(ps))
2387 ttitle = ("IPy:" + (
2391 ttitle = ("IPy:" + (
2388 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2392 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2389 platutils.set_term_title(ttitle)
2393 platutils.set_term_title(ttitle)
2390 except OSError:
2394 except OSError:
2391 print sys.exc_info()[1]
2395 print sys.exc_info()[1]
2392 else:
2396 else:
2393 self.shell.user_ns['_dh'].append(os.getcwd())
2397 self.shell.user_ns['_dh'].append(os.getcwd())
2394 else:
2398 else:
2395 os.chdir(self.shell.home_dir)
2399 os.chdir(self.shell.home_dir)
2396 platutils.set_term_title("IPy:~")
2400 platutils.set_term_title("IPy:~")
2397 self.shell.user_ns['_dh'].append(os.getcwd())
2401 self.shell.user_ns['_dh'].append(os.getcwd())
2398 if not 'q' in opts:
2402 if not 'q' in opts:
2399 print self.shell.user_ns['_dh'][-1]
2403 print self.shell.user_ns['_dh'][-1]
2400
2404
2401 def magic_dhist(self, parameter_s=''):
2405 def magic_dhist(self, parameter_s=''):
2402 """Print your history of visited directories.
2406 """Print your history of visited directories.
2403
2407
2404 %dhist -> print full history\\
2408 %dhist -> print full history\\
2405 %dhist n -> print last n entries only\\
2409 %dhist n -> print last n entries only\\
2406 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2410 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2407
2411
2408 This history is automatically maintained by the %cd command, and
2412 This history is automatically maintained by the %cd command, and
2409 always available as the global list variable _dh. You can use %cd -<n>
2413 always available as the global list variable _dh. You can use %cd -<n>
2410 to go to directory number <n>."""
2414 to go to directory number <n>."""
2411
2415
2412 dh = self.shell.user_ns['_dh']
2416 dh = self.shell.user_ns['_dh']
2413 if parameter_s:
2417 if parameter_s:
2414 try:
2418 try:
2415 args = map(int,parameter_s.split())
2419 args = map(int,parameter_s.split())
2416 except:
2420 except:
2417 self.arg_err(Magic.magic_dhist)
2421 self.arg_err(Magic.magic_dhist)
2418 return
2422 return
2419 if len(args) == 1:
2423 if len(args) == 1:
2420 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2424 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2421 elif len(args) == 2:
2425 elif len(args) == 2:
2422 ini,fin = args
2426 ini,fin = args
2423 else:
2427 else:
2424 self.arg_err(Magic.magic_dhist)
2428 self.arg_err(Magic.magic_dhist)
2425 return
2429 return
2426 else:
2430 else:
2427 ini,fin = 0,len(dh)
2431 ini,fin = 0,len(dh)
2428 nlprint(dh,
2432 nlprint(dh,
2429 header = 'Directory history (kept in _dh)',
2433 header = 'Directory history (kept in _dh)',
2430 start=ini,stop=fin)
2434 start=ini,stop=fin)
2431
2435
2432 def magic_env(self, parameter_s=''):
2436 def magic_env(self, parameter_s=''):
2433 """List environment variables."""
2437 """List environment variables."""
2434
2438
2435 return os.environ.data
2439 return os.environ.data
2436
2440
2437 def magic_pushd(self, parameter_s=''):
2441 def magic_pushd(self, parameter_s=''):
2438 """Place the current dir on stack and change directory.
2442 """Place the current dir on stack and change directory.
2439
2443
2440 Usage:\\
2444 Usage:\\
2441 %pushd ['dirname']
2445 %pushd ['dirname']
2442
2446
2443 %pushd with no arguments does a %pushd to your home directory.
2447 %pushd with no arguments does a %pushd to your home directory.
2444 """
2448 """
2445 if parameter_s == '': parameter_s = '~'
2449 if parameter_s == '': parameter_s = '~'
2446 dir_s = self.shell.dir_stack
2450 dir_s = self.shell.dir_stack
2447 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2451 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2448 os.path.expanduser(self.shell.dir_stack[0]):
2452 os.path.expanduser(self.shell.dir_stack[0]):
2449 try:
2453 try:
2450 self.magic_cd(parameter_s)
2454 self.magic_cd(parameter_s)
2451 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2455 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2452 self.magic_dirs()
2456 self.magic_dirs()
2453 except:
2457 except:
2454 print 'Invalid directory'
2458 print 'Invalid directory'
2455 else:
2459 else:
2456 print 'You are already there!'
2460 print 'You are already there!'
2457
2461
2458 def magic_popd(self, parameter_s=''):
2462 def magic_popd(self, parameter_s=''):
2459 """Change to directory popped off the top of the stack.
2463 """Change to directory popped off the top of the stack.
2460 """
2464 """
2461 if len (self.shell.dir_stack) > 1:
2465 if len (self.shell.dir_stack) > 1:
2462 self.shell.dir_stack.pop(0)
2466 self.shell.dir_stack.pop(0)
2463 self.magic_cd(self.shell.dir_stack[0])
2467 self.magic_cd(self.shell.dir_stack[0])
2464 print self.shell.dir_stack[0]
2468 print self.shell.dir_stack[0]
2465 else:
2469 else:
2466 print "You can't remove the starting directory from the stack:",\
2470 print "You can't remove the starting directory from the stack:",\
2467 self.shell.dir_stack
2471 self.shell.dir_stack
2468
2472
2469 def magic_dirs(self, parameter_s=''):
2473 def magic_dirs(self, parameter_s=''):
2470 """Return the current directory stack."""
2474 """Return the current directory stack."""
2471
2475
2472 return self.shell.dir_stack[:]
2476 return self.shell.dir_stack[:]
2473
2477
2474 def magic_sc(self, parameter_s=''):
2478 def magic_sc(self, parameter_s=''):
2475 """Shell capture - execute a shell command and capture its output.
2479 """Shell capture - execute a shell command and capture its output.
2476
2480
2477 DEPRECATED. Suboptimal, retained for backwards compatibility.
2481 DEPRECATED. Suboptimal, retained for backwards compatibility.
2478
2482
2479 You should use the form 'var = !command' instead. Example:
2483 You should use the form 'var = !command' instead. Example:
2480
2484
2481 "%sc -l myfiles = ls ~" should now be written as
2485 "%sc -l myfiles = ls ~" should now be written as
2482
2486
2483 "myfiles = !ls ~"
2487 "myfiles = !ls ~"
2484
2488
2485 myfiles.s, myfiles.l and myfiles.n still apply as documented
2489 myfiles.s, myfiles.l and myfiles.n still apply as documented
2486 below.
2490 below.
2487
2491
2488 --
2492 --
2489 %sc [options] varname=command
2493 %sc [options] varname=command
2490
2494
2491 IPython will run the given command using commands.getoutput(), and
2495 IPython will run the given command using commands.getoutput(), and
2492 will then update the user's interactive namespace with a variable
2496 will then update the user's interactive namespace with a variable
2493 called varname, containing the value of the call. Your command can
2497 called varname, containing the value of the call. Your command can
2494 contain shell wildcards, pipes, etc.
2498 contain shell wildcards, pipes, etc.
2495
2499
2496 The '=' sign in the syntax is mandatory, and the variable name you
2500 The '=' sign in the syntax is mandatory, and the variable name you
2497 supply must follow Python's standard conventions for valid names.
2501 supply must follow Python's standard conventions for valid names.
2498
2502
2499 (A special format without variable name exists for internal use)
2503 (A special format without variable name exists for internal use)
2500
2504
2501 Options:
2505 Options:
2502
2506
2503 -l: list output. Split the output on newlines into a list before
2507 -l: list output. Split the output on newlines into a list before
2504 assigning it to the given variable. By default the output is stored
2508 assigning it to the given variable. By default the output is stored
2505 as a single string.
2509 as a single string.
2506
2510
2507 -v: verbose. Print the contents of the variable.
2511 -v: verbose. Print the contents of the variable.
2508
2512
2509 In most cases you should not need to split as a list, because the
2513 In most cases you should not need to split as a list, because the
2510 returned value is a special type of string which can automatically
2514 returned value is a special type of string which can automatically
2511 provide its contents either as a list (split on newlines) or as a
2515 provide its contents either as a list (split on newlines) or as a
2512 space-separated string. These are convenient, respectively, either
2516 space-separated string. These are convenient, respectively, either
2513 for sequential processing or to be passed to a shell command.
2517 for sequential processing or to be passed to a shell command.
2514
2518
2515 For example:
2519 For example:
2516
2520
2517 # Capture into variable a
2521 # Capture into variable a
2518 In [9]: sc a=ls *py
2522 In [9]: sc a=ls *py
2519
2523
2520 # a is a string with embedded newlines
2524 # a is a string with embedded newlines
2521 In [10]: a
2525 In [10]: a
2522 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2526 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2523
2527
2524 # which can be seen as a list:
2528 # which can be seen as a list:
2525 In [11]: a.l
2529 In [11]: a.l
2526 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2530 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2527
2531
2528 # or as a whitespace-separated string:
2532 # or as a whitespace-separated string:
2529 In [12]: a.s
2533 In [12]: a.s
2530 Out[12]: 'setup.py win32_manual_post_install.py'
2534 Out[12]: 'setup.py win32_manual_post_install.py'
2531
2535
2532 # a.s is useful to pass as a single command line:
2536 # a.s is useful to pass as a single command line:
2533 In [13]: !wc -l $a.s
2537 In [13]: !wc -l $a.s
2534 146 setup.py
2538 146 setup.py
2535 130 win32_manual_post_install.py
2539 130 win32_manual_post_install.py
2536 276 total
2540 276 total
2537
2541
2538 # while the list form is useful to loop over:
2542 # while the list form is useful to loop over:
2539 In [14]: for f in a.l:
2543 In [14]: for f in a.l:
2540 ....: !wc -l $f
2544 ....: !wc -l $f
2541 ....:
2545 ....:
2542 146 setup.py
2546 146 setup.py
2543 130 win32_manual_post_install.py
2547 130 win32_manual_post_install.py
2544
2548
2545 Similiarly, the lists returned by the -l option are also special, in
2549 Similiarly, the lists returned by the -l option are also special, in
2546 the sense that you can equally invoke the .s attribute on them to
2550 the sense that you can equally invoke the .s attribute on them to
2547 automatically get a whitespace-separated string from their contents:
2551 automatically get a whitespace-separated string from their contents:
2548
2552
2549 In [1]: sc -l b=ls *py
2553 In [1]: sc -l b=ls *py
2550
2554
2551 In [2]: b
2555 In [2]: b
2552 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2556 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2553
2557
2554 In [3]: b.s
2558 In [3]: b.s
2555 Out[3]: 'setup.py win32_manual_post_install.py'
2559 Out[3]: 'setup.py win32_manual_post_install.py'
2556
2560
2557 In summary, both the lists and strings used for ouptut capture have
2561 In summary, both the lists and strings used for ouptut capture have
2558 the following special attributes:
2562 the following special attributes:
2559
2563
2560 .l (or .list) : value as list.
2564 .l (or .list) : value as list.
2561 .n (or .nlstr): value as newline-separated string.
2565 .n (or .nlstr): value as newline-separated string.
2562 .s (or .spstr): value as space-separated string.
2566 .s (or .spstr): value as space-separated string.
2563 """
2567 """
2564
2568
2565 opts,args = self.parse_options(parameter_s,'lv')
2569 opts,args = self.parse_options(parameter_s,'lv')
2566 # Try to get a variable name and command to run
2570 # Try to get a variable name and command to run
2567 try:
2571 try:
2568 # the variable name must be obtained from the parse_options
2572 # the variable name must be obtained from the parse_options
2569 # output, which uses shlex.split to strip options out.
2573 # output, which uses shlex.split to strip options out.
2570 var,_ = args.split('=',1)
2574 var,_ = args.split('=',1)
2571 var = var.strip()
2575 var = var.strip()
2572 # But the the command has to be extracted from the original input
2576 # But the the command has to be extracted from the original input
2573 # parameter_s, not on what parse_options returns, to avoid the
2577 # parameter_s, not on what parse_options returns, to avoid the
2574 # quote stripping which shlex.split performs on it.
2578 # quote stripping which shlex.split performs on it.
2575 _,cmd = parameter_s.split('=',1)
2579 _,cmd = parameter_s.split('=',1)
2576 except ValueError:
2580 except ValueError:
2577 var,cmd = '',''
2581 var,cmd = '',''
2578 # If all looks ok, proceed
2582 # If all looks ok, proceed
2579 out,err = self.shell.getoutputerror(cmd)
2583 out,err = self.shell.getoutputerror(cmd)
2580 if err:
2584 if err:
2581 print >> Term.cerr,err
2585 print >> Term.cerr,err
2582 if opts.has_key('l'):
2586 if opts.has_key('l'):
2583 out = SList(out.split('\n'))
2587 out = SList(out.split('\n'))
2584 else:
2588 else:
2585 out = LSString(out)
2589 out = LSString(out)
2586 if opts.has_key('v'):
2590 if opts.has_key('v'):
2587 print '%s ==\n%s' % (var,pformat(out))
2591 print '%s ==\n%s' % (var,pformat(out))
2588 if var:
2592 if var:
2589 self.shell.user_ns.update({var:out})
2593 self.shell.user_ns.update({var:out})
2590 else:
2594 else:
2591 return out
2595 return out
2592
2596
2593 def magic_sx(self, parameter_s=''):
2597 def magic_sx(self, parameter_s=''):
2594 """Shell execute - run a shell command and capture its output.
2598 """Shell execute - run a shell command and capture its output.
2595
2599
2596 %sx command
2600 %sx command
2597
2601
2598 IPython will run the given command using commands.getoutput(), and
2602 IPython will run the given command using commands.getoutput(), and
2599 return the result formatted as a list (split on '\\n'). Since the
2603 return the result formatted as a list (split on '\\n'). Since the
2600 output is _returned_, it will be stored in ipython's regular output
2604 output is _returned_, it will be stored in ipython's regular output
2601 cache Out[N] and in the '_N' automatic variables.
2605 cache Out[N] and in the '_N' automatic variables.
2602
2606
2603 Notes:
2607 Notes:
2604
2608
2605 1) If an input line begins with '!!', then %sx is automatically
2609 1) If an input line begins with '!!', then %sx is automatically
2606 invoked. That is, while:
2610 invoked. That is, while:
2607 !ls
2611 !ls
2608 causes ipython to simply issue system('ls'), typing
2612 causes ipython to simply issue system('ls'), typing
2609 !!ls
2613 !!ls
2610 is a shorthand equivalent to:
2614 is a shorthand equivalent to:
2611 %sx ls
2615 %sx ls
2612
2616
2613 2) %sx differs from %sc in that %sx automatically splits into a list,
2617 2) %sx differs from %sc in that %sx automatically splits into a list,
2614 like '%sc -l'. The reason for this is to make it as easy as possible
2618 like '%sc -l'. The reason for this is to make it as easy as possible
2615 to process line-oriented shell output via further python commands.
2619 to process line-oriented shell output via further python commands.
2616 %sc is meant to provide much finer control, but requires more
2620 %sc is meant to provide much finer control, but requires more
2617 typing.
2621 typing.
2618
2622
2619 3) Just like %sc -l, this is a list with special attributes:
2623 3) Just like %sc -l, this is a list with special attributes:
2620
2624
2621 .l (or .list) : value as list.
2625 .l (or .list) : value as list.
2622 .n (or .nlstr): value as newline-separated string.
2626 .n (or .nlstr): value as newline-separated string.
2623 .s (or .spstr): value as whitespace-separated string.
2627 .s (or .spstr): value as whitespace-separated string.
2624
2628
2625 This is very useful when trying to use such lists as arguments to
2629 This is very useful when trying to use such lists as arguments to
2626 system commands."""
2630 system commands."""
2627
2631
2628 if parameter_s:
2632 if parameter_s:
2629 out,err = self.shell.getoutputerror(parameter_s)
2633 out,err = self.shell.getoutputerror(parameter_s)
2630 if err:
2634 if err:
2631 print >> Term.cerr,err
2635 print >> Term.cerr,err
2632 return SList(out.split('\n'))
2636 return SList(out.split('\n'))
2633
2637
2634 def magic_bg(self, parameter_s=''):
2638 def magic_bg(self, parameter_s=''):
2635 """Run a job in the background, in a separate thread.
2639 """Run a job in the background, in a separate thread.
2636
2640
2637 For example,
2641 For example,
2638
2642
2639 %bg myfunc(x,y,z=1)
2643 %bg myfunc(x,y,z=1)
2640
2644
2641 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2645 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2642 execution starts, a message will be printed indicating the job
2646 execution starts, a message will be printed indicating the job
2643 number. If your job number is 5, you can use
2647 number. If your job number is 5, you can use
2644
2648
2645 myvar = jobs.result(5) or myvar = jobs[5].result
2649 myvar = jobs.result(5) or myvar = jobs[5].result
2646
2650
2647 to assign this result to variable 'myvar'.
2651 to assign this result to variable 'myvar'.
2648
2652
2649 IPython has a job manager, accessible via the 'jobs' object. You can
2653 IPython has a job manager, accessible via the 'jobs' object. You can
2650 type jobs? to get more information about it, and use jobs.<TAB> to see
2654 type jobs? to get more information about it, and use jobs.<TAB> to see
2651 its attributes. All attributes not starting with an underscore are
2655 its attributes. All attributes not starting with an underscore are
2652 meant for public use.
2656 meant for public use.
2653
2657
2654 In particular, look at the jobs.new() method, which is used to create
2658 In particular, look at the jobs.new() method, which is used to create
2655 new jobs. This magic %bg function is just a convenience wrapper
2659 new jobs. This magic %bg function is just a convenience wrapper
2656 around jobs.new(), for expression-based jobs. If you want to create a
2660 around jobs.new(), for expression-based jobs. If you want to create a
2657 new job with an explicit function object and arguments, you must call
2661 new job with an explicit function object and arguments, you must call
2658 jobs.new() directly.
2662 jobs.new() directly.
2659
2663
2660 The jobs.new docstring also describes in detail several important
2664 The jobs.new docstring also describes in detail several important
2661 caveats associated with a thread-based model for background job
2665 caveats associated with a thread-based model for background job
2662 execution. Type jobs.new? for details.
2666 execution. Type jobs.new? for details.
2663
2667
2664 You can check the status of all jobs with jobs.status().
2668 You can check the status of all jobs with jobs.status().
2665
2669
2666 The jobs variable is set by IPython into the Python builtin namespace.
2670 The jobs variable is set by IPython into the Python builtin namespace.
2667 If you ever declare a variable named 'jobs', you will shadow this
2671 If you ever declare a variable named 'jobs', you will shadow this
2668 name. You can either delete your global jobs variable to regain
2672 name. You can either delete your global jobs variable to regain
2669 access to the job manager, or make a new name and assign it manually
2673 access to the job manager, or make a new name and assign it manually
2670 to the manager (stored in IPython's namespace). For example, to
2674 to the manager (stored in IPython's namespace). For example, to
2671 assign the job manager to the Jobs name, use:
2675 assign the job manager to the Jobs name, use:
2672
2676
2673 Jobs = __builtins__.jobs"""
2677 Jobs = __builtins__.jobs"""
2674
2678
2675 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2679 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2676
2680
2677
2681
2678 def magic_bookmark(self, parameter_s=''):
2682 def magic_bookmark(self, parameter_s=''):
2679 """Manage IPython's bookmark system.
2683 """Manage IPython's bookmark system.
2680
2684
2681 %bookmark <name> - set bookmark to current dir
2685 %bookmark <name> - set bookmark to current dir
2682 %bookmark <name> <dir> - set bookmark to <dir>
2686 %bookmark <name> <dir> - set bookmark to <dir>
2683 %bookmark -l - list all bookmarks
2687 %bookmark -l - list all bookmarks
2684 %bookmark -d <name> - remove bookmark
2688 %bookmark -d <name> - remove bookmark
2685 %bookmark -r - remove all bookmarks
2689 %bookmark -r - remove all bookmarks
2686
2690
2687 You can later on access a bookmarked folder with:
2691 You can later on access a bookmarked folder with:
2688 %cd -b <name>
2692 %cd -b <name>
2689 or simply '%cd <name>' if there is no directory called <name> AND
2693 or simply '%cd <name>' if there is no directory called <name> AND
2690 there is such a bookmark defined.
2694 there is such a bookmark defined.
2691
2695
2692 Your bookmarks persist through IPython sessions, but they are
2696 Your bookmarks persist through IPython sessions, but they are
2693 associated with each profile."""
2697 associated with each profile."""
2694
2698
2695 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2699 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2696 if len(args) > 2:
2700 if len(args) > 2:
2697 error('You can only give at most two arguments')
2701 error('You can only give at most two arguments')
2698 return
2702 return
2699
2703
2700 bkms = self.db.get('bookmarks',{})
2704 bkms = self.db.get('bookmarks',{})
2701
2705
2702 if opts.has_key('d'):
2706 if opts.has_key('d'):
2703 try:
2707 try:
2704 todel = args[0]
2708 todel = args[0]
2705 except IndexError:
2709 except IndexError:
2706 error('You must provide a bookmark to delete')
2710 error('You must provide a bookmark to delete')
2707 else:
2711 else:
2708 try:
2712 try:
2709 del bkms[todel]
2713 del bkms[todel]
2710 except:
2714 except:
2711 error("Can't delete bookmark '%s'" % todel)
2715 error("Can't delete bookmark '%s'" % todel)
2712 elif opts.has_key('r'):
2716 elif opts.has_key('r'):
2713 bkms = {}
2717 bkms = {}
2714 elif opts.has_key('l'):
2718 elif opts.has_key('l'):
2715 bks = bkms.keys()
2719 bks = bkms.keys()
2716 bks.sort()
2720 bks.sort()
2717 if bks:
2721 if bks:
2718 size = max(map(len,bks))
2722 size = max(map(len,bks))
2719 else:
2723 else:
2720 size = 0
2724 size = 0
2721 fmt = '%-'+str(size)+'s -> %s'
2725 fmt = '%-'+str(size)+'s -> %s'
2722 print 'Current bookmarks:'
2726 print 'Current bookmarks:'
2723 for bk in bks:
2727 for bk in bks:
2724 print fmt % (bk,bkms[bk])
2728 print fmt % (bk,bkms[bk])
2725 else:
2729 else:
2726 if not args:
2730 if not args:
2727 error("You must specify the bookmark name")
2731 error("You must specify the bookmark name")
2728 elif len(args)==1:
2732 elif len(args)==1:
2729 bkms[args[0]] = os.getcwd()
2733 bkms[args[0]] = os.getcwd()
2730 elif len(args)==2:
2734 elif len(args)==2:
2731 bkms[args[0]] = args[1]
2735 bkms[args[0]] = args[1]
2732 self.db['bookmarks'] = bkms
2736 self.db['bookmarks'] = bkms
2733
2737
2734 def magic_pycat(self, parameter_s=''):
2738 def magic_pycat(self, parameter_s=''):
2735 """Show a syntax-highlighted file through a pager.
2739 """Show a syntax-highlighted file through a pager.
2736
2740
2737 This magic is similar to the cat utility, but it will assume the file
2741 This magic is similar to the cat utility, but it will assume the file
2738 to be Python source and will show it with syntax highlighting. """
2742 to be Python source and will show it with syntax highlighting. """
2739
2743
2740 try:
2744 try:
2741 filename = get_py_filename(parameter_s)
2745 filename = get_py_filename(parameter_s)
2742 cont = file_read(filename)
2746 cont = file_read(filename)
2743 except IOError:
2747 except IOError:
2744 try:
2748 try:
2745 cont = eval(parameter_s,self.user_ns)
2749 cont = eval(parameter_s,self.user_ns)
2746 except NameError:
2750 except NameError:
2747 cont = None
2751 cont = None
2748 if cont is None:
2752 if cont is None:
2749 print "Error: no such file or variable"
2753 print "Error: no such file or variable"
2750 return
2754 return
2751
2755
2752 page(self.shell.pycolorize(cont),
2756 page(self.shell.pycolorize(cont),
2753 screen_lines=self.shell.rc.screen_length)
2757 screen_lines=self.shell.rc.screen_length)
2754
2758
2755 def magic_cpaste(self, parameter_s=''):
2759 def magic_cpaste(self, parameter_s=''):
2756 """Allows you to paste & execute a pre-formatted code block from
2760 """Allows you to paste & execute a pre-formatted code block from
2757 clipboard.
2761 clipboard.
2758
2762
2759 You must terminate the block with '--' (two minus-signs) alone on the
2763 You must terminate the block with '--' (two minus-signs) alone on the
2760 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2764 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2761 is the new sentinel for this operation)
2765 is the new sentinel for this operation)
2762
2766
2763 The block is dedented prior to execution to enable execution of
2767 The block is dedented prior to execution to enable execution of
2764 method definitions. The executed block is also assigned to variable
2768 method definitions. The executed block is also assigned to variable
2765 named 'pasted_block' for later editing with '%edit pasted_block'.
2769 named 'pasted_block' for later editing with '%edit pasted_block'.
2766
2770
2767 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2771 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2768 This assigns the pasted block to variable 'foo' as string, without
2772 This assigns the pasted block to variable 'foo' as string, without
2769 dedenting or executing it.
2773 dedenting or executing it.
2770
2774
2771 Do not be alarmed by garbled output on Windows (it's a readline bug).
2775 Do not be alarmed by garbled output on Windows (it's a readline bug).
2772 Just press enter and type -- (and press enter again) and the block
2776 Just press enter and type -- (and press enter again) and the block
2773 will be what was just pasted.
2777 will be what was just pasted.
2774
2778
2775 IPython statements (magics, shell escapes) are not supported (yet).
2779 IPython statements (magics, shell escapes) are not supported (yet).
2776 """
2780 """
2777 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2781 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2778 par = args.strip()
2782 par = args.strip()
2779 sentinel = opts.get('s','--')
2783 sentinel = opts.get('s','--')
2780
2784
2781 from IPython import iplib
2785 from IPython import iplib
2782 lines = []
2786 lines = []
2783 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2787 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2784 while 1:
2788 while 1:
2785 l = iplib.raw_input_original(':')
2789 l = iplib.raw_input_original(':')
2786 if l ==sentinel:
2790 if l ==sentinel:
2787 break
2791 break
2788 lines.append(l)
2792 lines.append(l)
2789 block = "\n".join(lines) + '\n'
2793 block = "\n".join(lines) + '\n'
2790 #print "block:\n",block
2794 #print "block:\n",block
2791 if not par:
2795 if not par:
2792 b = textwrap.dedent(block)
2796 b = textwrap.dedent(block)
2793 exec b in self.user_ns
2797 exec b in self.user_ns
2794 self.user_ns['pasted_block'] = b
2798 self.user_ns['pasted_block'] = b
2795 else:
2799 else:
2796 self.user_ns[par] = block
2800 self.user_ns[par] = block
2797 print "Block assigned to '%s'" % par
2801 print "Block assigned to '%s'" % par
2798 def magic_quickref(self,arg):
2802 def magic_quickref(self,arg):
2799 import IPython.usage
2803 import IPython.usage
2800 page(IPython.usage.quick_reference)
2804 page(IPython.usage.quick_reference)
2801 del IPython.usage
2805 del IPython.usage
2802
2806
2803
2807
2804 # end Magic
2808 # end Magic
@@ -1,2256 +1,2268 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 1131 2006-02-07 11:51:54Z vivainio $
9 $Id: iplib.py 1140 2006-02-10 17:07:11Z vivainio $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import tempfile
58 import tempfile
59 import traceback
59 import traceback
60 import types
60 import types
61 import pickleshare
61 import pickleshare
62
62
63 from pprint import pprint, pformat
63 from pprint import pprint, pformat
64
64
65 # IPython's own modules
65 # IPython's own modules
66 import IPython
66 import IPython
67 from IPython import OInspect,PyColorize,ultraTB
67 from IPython import OInspect,PyColorize,ultraTB
68 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
68 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
69 from IPython.FakeModule import FakeModule
69 from IPython.FakeModule import FakeModule
70 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
70 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
71 from IPython.Logger import Logger
71 from IPython.Logger import Logger
72 from IPython.Magic import Magic
72 from IPython.Magic import Magic
73 from IPython.Prompts import CachedOutput
73 from IPython.Prompts import CachedOutput
74 from IPython.ipstruct import Struct
74 from IPython.ipstruct import Struct
75 from IPython.background_jobs import BackgroundJobManager
75 from IPython.background_jobs import BackgroundJobManager
76 from IPython.usage import cmd_line_usage,interactive_usage
76 from IPython.usage import cmd_line_usage,interactive_usage
77 from IPython.genutils import *
77 from IPython.genutils import *
78 import IPython.ipapi
78 import IPython.ipapi
79
79
80 # Globals
80 # Globals
81
81
82 # 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
83 # overwrites it (like wx.py.PyShell does)
83 # overwrites it (like wx.py.PyShell does)
84 raw_input_original = raw_input
84 raw_input_original = raw_input
85
85
86 # compiled regexps for autoindent management
86 # compiled regexps for autoindent management
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88
88
89
89
90 #****************************************************************************
90 #****************************************************************************
91 # Some utility function definitions
91 # Some utility function definitions
92
92
93 ini_spaces_re = re.compile(r'^(\s+)')
93 ini_spaces_re = re.compile(r'^(\s+)')
94
94
95 def num_ini_spaces(strng):
95 def num_ini_spaces(strng):
96 """Return the number of initial spaces in a string"""
96 """Return the number of initial spaces in a string"""
97
97
98 ini_spaces = ini_spaces_re.match(strng)
98 ini_spaces = ini_spaces_re.match(strng)
99 if ini_spaces:
99 if ini_spaces:
100 return ini_spaces.end()
100 return ini_spaces.end()
101 else:
101 else:
102 return 0
102 return 0
103
103
104 def softspace(file, newvalue):
104 def softspace(file, newvalue):
105 """Copied from code.py, to remove the dependency"""
105 """Copied from code.py, to remove the dependency"""
106
106
107 oldvalue = 0
107 oldvalue = 0
108 try:
108 try:
109 oldvalue = file.softspace
109 oldvalue = file.softspace
110 except AttributeError:
110 except AttributeError:
111 pass
111 pass
112 try:
112 try:
113 file.softspace = newvalue
113 file.softspace = newvalue
114 except (AttributeError, TypeError):
114 except (AttributeError, TypeError):
115 # "attribute-less object" or "read-only attributes"
115 # "attribute-less object" or "read-only attributes"
116 pass
116 pass
117 return oldvalue
117 return oldvalue
118
118
119
119
120 #****************************************************************************
120 #****************************************************************************
121 # Local use exceptions
121 # Local use exceptions
122 class SpaceInInput(exceptions.Exception): pass
122 class SpaceInInput(exceptions.Exception): pass
123
123
124
124
125 #****************************************************************************
125 #****************************************************************************
126 # Local use classes
126 # Local use classes
127 class Bunch: pass
127 class Bunch: pass
128
128
129 class Undefined: pass
129 class Undefined: pass
130
130
131 class InputList(list):
131 class InputList(list):
132 """Class to store user input.
132 """Class to store user input.
133
133
134 It's basically a list, but slices return a string instead of a list, thus
134 It's basically a list, but slices return a string instead of a list, thus
135 allowing things like (assuming 'In' is an instance):
135 allowing things like (assuming 'In' is an instance):
136
136
137 exec In[4:7]
137 exec In[4:7]
138
138
139 or
139 or
140
140
141 exec In[5:9] + In[14] + In[21:25]"""
141 exec In[5:9] + In[14] + In[21:25]"""
142
142
143 def __getslice__(self,i,j):
143 def __getslice__(self,i,j):
144 return ''.join(list.__getslice__(self,i,j))
144 return ''.join(list.__getslice__(self,i,j))
145
145
146 class SyntaxTB(ultraTB.ListTB):
146 class SyntaxTB(ultraTB.ListTB):
147 """Extension which holds some state: the last exception value"""
147 """Extension which holds some state: the last exception value"""
148
148
149 def __init__(self,color_scheme = 'NoColor'):
149 def __init__(self,color_scheme = 'NoColor'):
150 ultraTB.ListTB.__init__(self,color_scheme)
150 ultraTB.ListTB.__init__(self,color_scheme)
151 self.last_syntax_error = None
151 self.last_syntax_error = None
152
152
153 def __call__(self, etype, value, elist):
153 def __call__(self, etype, value, elist):
154 self.last_syntax_error = value
154 self.last_syntax_error = value
155 ultraTB.ListTB.__call__(self,etype,value,elist)
155 ultraTB.ListTB.__call__(self,etype,value,elist)
156
156
157 def clear_err_state(self):
157 def clear_err_state(self):
158 """Return the current error state and clear it"""
158 """Return the current error state and clear it"""
159 e = self.last_syntax_error
159 e = self.last_syntax_error
160 self.last_syntax_error = None
160 self.last_syntax_error = None
161 return e
161 return e
162
162
163 #****************************************************************************
163 #****************************************************************************
164 # Main IPython class
164 # Main IPython class
165
165
166 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
166 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
167 # until a full rewrite is made. I've cleaned all cross-class uses of
167 # until a full rewrite is made. I've cleaned all cross-class uses of
168 # attributes and methods, but too much user code out there relies on the
168 # attributes and methods, but too much user code out there relies on the
169 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
169 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
170 #
170 #
171 # But at least now, all the pieces have been separated and we could, in
171 # But at least now, all the pieces have been separated and we could, in
172 # principle, stop using the mixin. This will ease the transition to the
172 # principle, stop using the mixin. This will ease the transition to the
173 # chainsaw branch.
173 # chainsaw branch.
174
174
175 # For reference, the following is the list of 'self.foo' uses in the Magic
175 # For reference, the following is the list of 'self.foo' uses in the Magic
176 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
176 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
177 # class, to prevent clashes.
177 # class, to prevent clashes.
178
178
179 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
179 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
180 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
180 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
181 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
181 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
182 # 'self.value']
182 # 'self.value']
183
183
184 class InteractiveShell(object,Magic):
184 class InteractiveShell(object,Magic):
185 """An enhanced console for Python."""
185 """An enhanced console for Python."""
186
186
187 # class attribute to indicate whether the class supports threads or not.
187 # class attribute to indicate whether the class supports threads or not.
188 # Subclasses with thread support should override this as needed.
188 # Subclasses with thread support should override this as needed.
189 isthreaded = False
189 isthreaded = False
190
190
191 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
191 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
192 user_ns = None,user_global_ns=None,banner2='',
192 user_ns = None,user_global_ns=None,banner2='',
193 custom_exceptions=((),None),embedded=False):
193 custom_exceptions=((),None),embedded=False):
194
194
195
195
196 # log system
196 # log system
197 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
197 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
198
198
199 # Produce a public API instance
199 # Produce a public API instance
200
200
201 self.api = IPython.ipapi.IPApi(self)
201 self.api = IPython.ipapi.IPApi(self)
202
202
203 # some minimal strict typechecks. For some core data structures, I
203 # some minimal strict typechecks. For some core data structures, I
204 # want actual basic python types, not just anything that looks like
204 # want actual basic python types, not just anything that looks like
205 # one. This is especially true for namespaces.
205 # one. This is especially true for namespaces.
206 for ns in (user_ns,user_global_ns):
206 for ns in (user_ns,user_global_ns):
207 if ns is not None and type(ns) != types.DictType:
207 if ns is not None and type(ns) != types.DictType:
208 raise TypeError,'namespace must be a dictionary'
208 raise TypeError,'namespace must be a dictionary'
209
209
210 # Job manager (for jobs run as background threads)
210 # Job manager (for jobs run as background threads)
211 self.jobs = BackgroundJobManager()
211 self.jobs = BackgroundJobManager()
212
212
213 # track which builtins we add, so we can clean up later
213 # track which builtins we add, so we can clean up later
214 self.builtins_added = {}
214 self.builtins_added = {}
215 # This method will add the necessary builtins for operation, but
215 # This method will add the necessary builtins for operation, but
216 # tracking what it did via the builtins_added dict.
216 # tracking what it did via the builtins_added dict.
217 self.add_builtins()
217 self.add_builtins()
218
218
219 # Do the intuitively correct thing for quit/exit: we remove the
219 # Do the intuitively correct thing for quit/exit: we remove the
220 # builtins if they exist, and our own magics will deal with this
220 # builtins if they exist, and our own magics will deal with this
221 try:
221 try:
222 del __builtin__.exit, __builtin__.quit
222 del __builtin__.exit, __builtin__.quit
223 except AttributeError:
223 except AttributeError:
224 pass
224 pass
225
225
226 # Store the actual shell's name
226 # Store the actual shell's name
227 self.name = name
227 self.name = name
228
228
229 # We need to know whether the instance is meant for embedding, since
229 # We need to know whether the instance is meant for embedding, since
230 # global/local namespaces need to be handled differently in that case
230 # global/local namespaces need to be handled differently in that case
231 self.embedded = embedded
231 self.embedded = embedded
232
232
233 # command compiler
233 # command compiler
234 self.compile = codeop.CommandCompiler()
234 self.compile = codeop.CommandCompiler()
235
235
236 # User input buffer
236 # User input buffer
237 self.buffer = []
237 self.buffer = []
238
238
239 # Default name given in compilation of code
239 # Default name given in compilation of code
240 self.filename = '<ipython console>'
240 self.filename = '<ipython console>'
241
241
242 # Make an empty namespace, which extension writers can rely on both
242 # Make an empty namespace, which extension writers can rely on both
243 # existing and NEVER being used by ipython itself. This gives them a
243 # existing and NEVER being used by ipython itself. This gives them a
244 # convenient location for storing additional information and state
244 # convenient location for storing additional information and state
245 # their extensions may require, without fear of collisions with other
245 # their extensions may require, without fear of collisions with other
246 # ipython names that may develop later.
246 # ipython names that may develop later.
247 self.meta = Struct()
247 self.meta = Struct()
248
248
249 # Create the namespace where the user will operate. user_ns is
249 # Create the namespace where the user will operate. user_ns is
250 # normally the only one used, and it is passed to the exec calls as
250 # normally the only one used, and it is passed to the exec calls as
251 # the locals argument. But we do carry a user_global_ns namespace
251 # the locals argument. But we do carry a user_global_ns namespace
252 # given as the exec 'globals' argument, This is useful in embedding
252 # given as the exec 'globals' argument, This is useful in embedding
253 # situations where the ipython shell opens in a context where the
253 # situations where the ipython shell opens in a context where the
254 # distinction between locals and globals is meaningful.
254 # distinction between locals and globals is meaningful.
255
255
256 # FIXME. For some strange reason, __builtins__ is showing up at user
256 # FIXME. For some strange reason, __builtins__ is showing up at user
257 # level as a dict instead of a module. This is a manual fix, but I
257 # level as a dict instead of a module. This is a manual fix, but I
258 # should really track down where the problem is coming from. Alex
258 # should really track down where the problem is coming from. Alex
259 # Schmolck reported this problem first.
259 # Schmolck reported this problem first.
260
260
261 # A useful post by Alex Martelli on this topic:
261 # A useful post by Alex Martelli on this topic:
262 # Re: inconsistent value from __builtins__
262 # Re: inconsistent value from __builtins__
263 # Von: Alex Martelli <aleaxit@yahoo.com>
263 # Von: Alex Martelli <aleaxit@yahoo.com>
264 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
264 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
265 # Gruppen: comp.lang.python
265 # Gruppen: comp.lang.python
266
266
267 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
267 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
268 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
268 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
269 # > <type 'dict'>
269 # > <type 'dict'>
270 # > >>> print type(__builtins__)
270 # > >>> print type(__builtins__)
271 # > <type 'module'>
271 # > <type 'module'>
272 # > Is this difference in return value intentional?
272 # > Is this difference in return value intentional?
273
273
274 # Well, it's documented that '__builtins__' can be either a dictionary
274 # Well, it's documented that '__builtins__' can be either a dictionary
275 # or a module, and it's been that way for a long time. Whether it's
275 # or a module, and it's been that way for a long time. Whether it's
276 # intentional (or sensible), I don't know. In any case, the idea is
276 # intentional (or sensible), I don't know. In any case, the idea is
277 # that if you need to access the built-in namespace directly, you
277 # that if you need to access the built-in namespace directly, you
278 # should start with "import __builtin__" (note, no 's') which will
278 # should start with "import __builtin__" (note, no 's') which will
279 # definitely give you a module. Yeah, it's somewhat confusing:-(.
279 # definitely give you a module. Yeah, it's somewhat confusing:-(.
280
280
281 if user_ns is None:
281 if user_ns is None:
282 # Set __name__ to __main__ to better match the behavior of the
282 # Set __name__ to __main__ to better match the behavior of the
283 # normal interpreter.
283 # normal interpreter.
284 user_ns = {'__name__' :'__main__',
284 user_ns = {'__name__' :'__main__',
285 '__builtins__' : __builtin__,
285 '__builtins__' : __builtin__,
286 }
286 }
287
287
288 if user_global_ns is None:
288 if user_global_ns is None:
289 user_global_ns = {}
289 user_global_ns = {}
290
290
291 # Assign namespaces
291 # Assign namespaces
292 # This is the namespace where all normal user variables live
292 # This is the namespace where all normal user variables live
293 self.user_ns = user_ns
293 self.user_ns = user_ns
294 # Embedded instances require a separate namespace for globals.
294 # Embedded instances require a separate namespace for globals.
295 # Normally this one is unused by non-embedded instances.
295 # Normally this one is unused by non-embedded instances.
296 self.user_global_ns = user_global_ns
296 self.user_global_ns = user_global_ns
297 # A namespace to keep track of internal data structures to prevent
297 # A namespace to keep track of internal data structures to prevent
298 # them from cluttering user-visible stuff. Will be updated later
298 # them from cluttering user-visible stuff. Will be updated later
299 self.internal_ns = {}
299 self.internal_ns = {}
300
300
301 # Namespace of system aliases. Each entry in the alias
301 # Namespace of system aliases. Each entry in the alias
302 # table must be a 2-tuple of the form (N,name), where N is the number
302 # table must be a 2-tuple of the form (N,name), where N is the number
303 # of positional arguments of the alias.
303 # of positional arguments of the alias.
304 self.alias_table = {}
304 self.alias_table = {}
305
305
306 # A table holding all the namespaces IPython deals with, so that
306 # A table holding all the namespaces IPython deals with, so that
307 # introspection facilities can search easily.
307 # introspection facilities can search easily.
308 self.ns_table = {'user':user_ns,
308 self.ns_table = {'user':user_ns,
309 'user_global':user_global_ns,
309 'user_global':user_global_ns,
310 'alias':self.alias_table,
310 'alias':self.alias_table,
311 'internal':self.internal_ns,
311 'internal':self.internal_ns,
312 'builtin':__builtin__.__dict__
312 'builtin':__builtin__.__dict__
313 }
313 }
314
314
315 # The user namespace MUST have a pointer to the shell itself.
315 # The user namespace MUST have a pointer to the shell itself.
316 self.user_ns[name] = self
316 self.user_ns[name] = self
317
317
318 # We need to insert into sys.modules something that looks like a
318 # We need to insert into sys.modules something that looks like a
319 # module but which accesses the IPython namespace, for shelve and
319 # module but which accesses the IPython namespace, for shelve and
320 # pickle to work interactively. Normally they rely on getting
320 # pickle to work interactively. Normally they rely on getting
321 # everything out of __main__, but for embedding purposes each IPython
321 # everything out of __main__, but for embedding purposes each IPython
322 # instance has its own private namespace, so we can't go shoving
322 # instance has its own private namespace, so we can't go shoving
323 # everything into __main__.
323 # everything into __main__.
324
324
325 # note, however, that we should only do this for non-embedded
325 # note, however, that we should only do this for non-embedded
326 # ipythons, which really mimic the __main__.__dict__ with their own
326 # ipythons, which really mimic the __main__.__dict__ with their own
327 # namespace. Embedded instances, on the other hand, should not do
327 # namespace. Embedded instances, on the other hand, should not do
328 # this because they need to manage the user local/global namespaces
328 # this because they need to manage the user local/global namespaces
329 # only, but they live within a 'normal' __main__ (meaning, they
329 # only, but they live within a 'normal' __main__ (meaning, they
330 # shouldn't overtake the execution environment of the script they're
330 # shouldn't overtake the execution environment of the script they're
331 # embedded in).
331 # embedded in).
332
332
333 if not embedded:
333 if not embedded:
334 try:
334 try:
335 main_name = self.user_ns['__name__']
335 main_name = self.user_ns['__name__']
336 except KeyError:
336 except KeyError:
337 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
337 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
338 else:
338 else:
339 #print "pickle hack in place" # dbg
339 #print "pickle hack in place" # dbg
340 #print 'main_name:',main_name # dbg
340 #print 'main_name:',main_name # dbg
341 sys.modules[main_name] = FakeModule(self.user_ns)
341 sys.modules[main_name] = FakeModule(self.user_ns)
342
342
343 # List of input with multi-line handling.
343 # List of input with multi-line handling.
344 # Fill its zero entry, user counter starts at 1
344 # Fill its zero entry, user counter starts at 1
345 self.input_hist = InputList(['\n'])
345 self.input_hist = InputList(['\n'])
346 # This one will hold the 'raw' input history, without any
346 # This one will hold the 'raw' input history, without any
347 # pre-processing. This will allow users to retrieve the input just as
347 # pre-processing. This will allow users to retrieve the input just as
348 # it was exactly typed in by the user, with %hist -r.
348 # it was exactly typed in by the user, with %hist -r.
349 self.input_hist_raw = InputList(['\n'])
349 self.input_hist_raw = InputList(['\n'])
350
350
351 # list of visited directories
351 # list of visited directories
352 try:
352 try:
353 self.dir_hist = [os.getcwd()]
353 self.dir_hist = [os.getcwd()]
354 except IOError, e:
354 except IOError, e:
355 self.dir_hist = []
355 self.dir_hist = []
356
356
357 # dict of output history
357 # dict of output history
358 self.output_hist = {}
358 self.output_hist = {}
359
359
360 # dict of things NOT to alias (keywords, builtins and some magics)
360 # dict of things NOT to alias (keywords, builtins and some magics)
361 no_alias = {}
361 no_alias = {}
362 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
362 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
363 for key in keyword.kwlist + no_alias_magics:
363 for key in keyword.kwlist + no_alias_magics:
364 no_alias[key] = 1
364 no_alias[key] = 1
365 no_alias.update(__builtin__.__dict__)
365 no_alias.update(__builtin__.__dict__)
366 self.no_alias = no_alias
366 self.no_alias = no_alias
367
367
368 # make global variables for user access to these
368 # make global variables for user access to these
369 self.user_ns['_ih'] = self.input_hist
369 self.user_ns['_ih'] = self.input_hist
370 self.user_ns['_oh'] = self.output_hist
370 self.user_ns['_oh'] = self.output_hist
371 self.user_ns['_dh'] = self.dir_hist
371 self.user_ns['_dh'] = self.dir_hist
372
372
373 # user aliases to input and output histories
373 # user aliases to input and output histories
374 self.user_ns['In'] = self.input_hist
374 self.user_ns['In'] = self.input_hist
375 self.user_ns['Out'] = self.output_hist
375 self.user_ns['Out'] = self.output_hist
376
376
377 # Object variable to store code object waiting execution. This is
377 # Object variable to store code object waiting execution. This is
378 # used mainly by the multithreaded shells, but it can come in handy in
378 # used mainly by the multithreaded shells, but it can come in handy in
379 # other situations. No need to use a Queue here, since it's a single
379 # other situations. No need to use a Queue here, since it's a single
380 # item which gets cleared once run.
380 # item which gets cleared once run.
381 self.code_to_run = None
381 self.code_to_run = None
382
382
383 # escapes for automatic behavior on the command line
383 # escapes for automatic behavior on the command line
384 self.ESC_SHELL = '!'
384 self.ESC_SHELL = '!'
385 self.ESC_HELP = '?'
385 self.ESC_HELP = '?'
386 self.ESC_MAGIC = '%'
386 self.ESC_MAGIC = '%'
387 self.ESC_QUOTE = ','
387 self.ESC_QUOTE = ','
388 self.ESC_QUOTE2 = ';'
388 self.ESC_QUOTE2 = ';'
389 self.ESC_PAREN = '/'
389 self.ESC_PAREN = '/'
390
390
391 # And their associated handlers
391 # And their associated handlers
392 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
392 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
393 self.ESC_QUOTE : self.handle_auto,
393 self.ESC_QUOTE : self.handle_auto,
394 self.ESC_QUOTE2 : self.handle_auto,
394 self.ESC_QUOTE2 : self.handle_auto,
395 self.ESC_MAGIC : self.handle_magic,
395 self.ESC_MAGIC : self.handle_magic,
396 self.ESC_HELP : self.handle_help,
396 self.ESC_HELP : self.handle_help,
397 self.ESC_SHELL : self.handle_shell_escape,
397 self.ESC_SHELL : self.handle_shell_escape,
398 }
398 }
399
399
400 # class initializations
400 # class initializations
401 Magic.__init__(self,self)
401 Magic.__init__(self,self)
402
402
403 # Python source parser/formatter for syntax highlighting
403 # Python source parser/formatter for syntax highlighting
404 pyformat = PyColorize.Parser().format
404 pyformat = PyColorize.Parser().format
405 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
405 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
406
406
407 # hooks holds pointers used for user-side customizations
407 # hooks holds pointers used for user-side customizations
408 self.hooks = Struct()
408 self.hooks = Struct()
409
409
410 # Set all default hooks, defined in the IPython.hooks module.
410 # Set all default hooks, defined in the IPython.hooks module.
411 hooks = IPython.hooks
411 hooks = IPython.hooks
412 for hook_name in hooks.__all__:
412 for hook_name in hooks.__all__:
413 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
413 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
414 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
414 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
415 #print "bound hook",hook_name
415 #print "bound hook",hook_name
416
416
417 # Flag to mark unconditional exit
417 # Flag to mark unconditional exit
418 self.exit_now = False
418 self.exit_now = False
419
419
420 self.usage_min = """\
420 self.usage_min = """\
421 An enhanced console for Python.
421 An enhanced console for Python.
422 Some of its features are:
422 Some of its features are:
423 - Readline support if the readline library is present.
423 - Readline support if the readline library is present.
424 - Tab completion in the local namespace.
424 - Tab completion in the local namespace.
425 - Logging of input, see command-line options.
425 - Logging of input, see command-line options.
426 - System shell escape via ! , eg !ls.
426 - System shell escape via ! , eg !ls.
427 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
427 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
428 - Keeps track of locally defined variables via %who, %whos.
428 - Keeps track of locally defined variables via %who, %whos.
429 - Show object information with a ? eg ?x or x? (use ?? for more info).
429 - Show object information with a ? eg ?x or x? (use ?? for more info).
430 """
430 """
431 if usage: self.usage = usage
431 if usage: self.usage = usage
432 else: self.usage = self.usage_min
432 else: self.usage = self.usage_min
433
433
434 # Storage
434 # Storage
435 self.rc = rc # This will hold all configuration information
435 self.rc = rc # This will hold all configuration information
436 self.pager = 'less'
436 self.pager = 'less'
437 # temporary files used for various purposes. Deleted at exit.
437 # temporary files used for various purposes. Deleted at exit.
438 self.tempfiles = []
438 self.tempfiles = []
439
439
440 # Keep track of readline usage (later set by init_readline)
440 # Keep track of readline usage (later set by init_readline)
441 self.has_readline = False
441 self.has_readline = False
442
442
443 # template for logfile headers. It gets resolved at runtime by the
443 # template for logfile headers. It gets resolved at runtime by the
444 # logstart method.
444 # logstart method.
445 self.loghead_tpl = \
445 self.loghead_tpl = \
446 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
446 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
447 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
447 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
448 #log# opts = %s
448 #log# opts = %s
449 #log# args = %s
449 #log# args = %s
450 #log# It is safe to make manual edits below here.
450 #log# It is safe to make manual edits below here.
451 #log#-----------------------------------------------------------------------
451 #log#-----------------------------------------------------------------------
452 """
452 """
453 # for pushd/popd management
453 # for pushd/popd management
454 try:
454 try:
455 self.home_dir = get_home_dir()
455 self.home_dir = get_home_dir()
456 except HomeDirError,msg:
456 except HomeDirError,msg:
457 fatal(msg)
457 fatal(msg)
458
458
459 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
459 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
460
460
461 # Functions to call the underlying shell.
461 # Functions to call the underlying shell.
462
462
463 # utility to expand user variables via Itpl
463 # utility to expand user variables via Itpl
464 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
464 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
465 self.user_ns))
465 self.user_ns))
466 # The first is similar to os.system, but it doesn't return a value,
466 # The first is similar to os.system, but it doesn't return a value,
467 # and it allows interpolation of variables in the user's namespace.
467 # and it allows interpolation of variables in the user's namespace.
468 self.system = lambda cmd: shell(self.var_expand(cmd),
468 self.system = lambda cmd: shell(self.var_expand(cmd),
469 header='IPython system call: ',
469 header='IPython system call: ',
470 verbose=self.rc.system_verbose)
470 verbose=self.rc.system_verbose)
471 # These are for getoutput and getoutputerror:
471 # These are for getoutput and getoutputerror:
472 self.getoutput = lambda cmd: \
472 self.getoutput = lambda cmd: \
473 getoutput(self.var_expand(cmd),
473 getoutput(self.var_expand(cmd),
474 header='IPython system call: ',
474 header='IPython system call: ',
475 verbose=self.rc.system_verbose)
475 verbose=self.rc.system_verbose)
476 self.getoutputerror = lambda cmd: \
476 self.getoutputerror = lambda cmd: \
477 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
477 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
478 self.user_ns)),
478 self.user_ns)),
479 header='IPython system call: ',
479 header='IPython system call: ',
480 verbose=self.rc.system_verbose)
480 verbose=self.rc.system_verbose)
481
481
482 # RegExp for splitting line contents into pre-char//first
482 # RegExp for splitting line contents into pre-char//first
483 # word-method//rest. For clarity, each group in on one line.
483 # word-method//rest. For clarity, each group in on one line.
484
484
485 # WARNING: update the regexp if the above escapes are changed, as they
485 # WARNING: update the regexp if the above escapes are changed, as they
486 # are hardwired in.
486 # are hardwired in.
487
487
488 # Don't get carried away with trying to make the autocalling catch too
488 # Don't get carried away with trying to make the autocalling catch too
489 # much: it's better to be conservative rather than to trigger hidden
489 # much: it's better to be conservative rather than to trigger hidden
490 # evals() somewhere and end up causing side effects.
490 # evals() somewhere and end up causing side effects.
491
491
492 self.line_split = re.compile(r'^([\s*,;/])'
492 self.line_split = re.compile(r'^([\s*,;/])'
493 r'([\?\w\.]+\w*\s*)'
493 r'([\?\w\.]+\w*\s*)'
494 r'(\(?.*$)')
494 r'(\(?.*$)')
495
495
496 # Original re, keep around for a while in case changes break something
496 # Original re, keep around for a while in case changes break something
497 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
497 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
498 # r'(\s*[\?\w\.]+\w*\s*)'
498 # r'(\s*[\?\w\.]+\w*\s*)'
499 # r'(\(?.*$)')
499 # r'(\(?.*$)')
500
500
501 # RegExp to identify potential function names
501 # RegExp to identify potential function names
502 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
502 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
503
503
504 # RegExp to exclude strings with this start from autocalling. In
504 # RegExp to exclude strings with this start from autocalling. In
505 # particular, all binary operators should be excluded, so that if foo
505 # particular, all binary operators should be excluded, so that if foo
506 # is callable, foo OP bar doesn't become foo(OP bar), which is
506 # is callable, foo OP bar doesn't become foo(OP bar), which is
507 # invalid. The characters '!=()' don't need to be checked for, as the
507 # invalid. The characters '!=()' don't need to be checked for, as the
508 # _prefilter routine explicitely does so, to catch direct calls and
508 # _prefilter routine explicitely does so, to catch direct calls and
509 # rebindings of existing names.
509 # rebindings of existing names.
510
510
511 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
511 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
512 # it affects the rest of the group in square brackets.
512 # it affects the rest of the group in square brackets.
513 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
513 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
514 '|^is |^not |^in |^and |^or ')
514 '|^is |^not |^in |^and |^or ')
515
515
516 # try to catch also methods for stuff in lists/tuples/dicts: off
516 # try to catch also methods for stuff in lists/tuples/dicts: off
517 # (experimental). For this to work, the line_split regexp would need
517 # (experimental). For this to work, the line_split regexp would need
518 # to be modified so it wouldn't break things at '['. That line is
518 # to be modified so it wouldn't break things at '['. That line is
519 # nasty enough that I shouldn't change it until I can test it _well_.
519 # nasty enough that I shouldn't change it until I can test it _well_.
520 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
520 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
521
521
522 # keep track of where we started running (mainly for crash post-mortem)
522 # keep track of where we started running (mainly for crash post-mortem)
523 self.starting_dir = os.getcwd()
523 self.starting_dir = os.getcwd()
524
524
525 # Various switches which can be set
525 # Various switches which can be set
526 self.CACHELENGTH = 5000 # this is cheap, it's just text
526 self.CACHELENGTH = 5000 # this is cheap, it's just text
527 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
527 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
528 self.banner2 = banner2
528 self.banner2 = banner2
529
529
530 # TraceBack handlers:
530 # TraceBack handlers:
531
531
532 # Syntax error handler.
532 # Syntax error handler.
533 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
533 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
534
534
535 # The interactive one is initialized with an offset, meaning we always
535 # The interactive one is initialized with an offset, meaning we always
536 # want to remove the topmost item in the traceback, which is our own
536 # want to remove the topmost item in the traceback, which is our own
537 # internal code. Valid modes: ['Plain','Context','Verbose']
537 # internal code. Valid modes: ['Plain','Context','Verbose']
538 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
538 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
539 color_scheme='NoColor',
539 color_scheme='NoColor',
540 tb_offset = 1)
540 tb_offset = 1)
541
541
542 # IPython itself shouldn't crash. This will produce a detailed
542 # IPython itself shouldn't crash. This will produce a detailed
543 # post-mortem if it does. But we only install the crash handler for
543 # post-mortem if it does. But we only install the crash handler for
544 # non-threaded shells, the threaded ones use a normal verbose reporter
544 # non-threaded shells, the threaded ones use a normal verbose reporter
545 # and lose the crash handler. This is because exceptions in the main
545 # and lose the crash handler. This is because exceptions in the main
546 # thread (such as in GUI code) propagate directly to sys.excepthook,
546 # thread (such as in GUI code) propagate directly to sys.excepthook,
547 # and there's no point in printing crash dumps for every user exception.
547 # and there's no point in printing crash dumps for every user exception.
548 if self.isthreaded:
548 if self.isthreaded:
549 sys.excepthook = ultraTB.FormattedTB()
549 sys.excepthook = ultraTB.FormattedTB()
550 else:
550 else:
551 from IPython import CrashHandler
551 from IPython import CrashHandler
552 sys.excepthook = CrashHandler.CrashHandler(self)
552 sys.excepthook = CrashHandler.CrashHandler(self)
553
553
554 # The instance will store a pointer to this, so that runtime code
554 # The instance will store a pointer to this, so that runtime code
555 # (such as magics) can access it. This is because during the
555 # (such as magics) can access it. This is because during the
556 # read-eval loop, it gets temporarily overwritten (to deal with GUI
556 # read-eval loop, it gets temporarily overwritten (to deal with GUI
557 # frameworks).
557 # frameworks).
558 self.sys_excepthook = sys.excepthook
558 self.sys_excepthook = sys.excepthook
559
559
560 # and add any custom exception handlers the user may have specified
560 # and add any custom exception handlers the user may have specified
561 self.set_custom_exc(*custom_exceptions)
561 self.set_custom_exc(*custom_exceptions)
562
562
563 # Object inspector
563 # Object inspector
564 self.inspector = OInspect.Inspector(OInspect.InspectColors,
564 self.inspector = OInspect.Inspector(OInspect.InspectColors,
565 PyColorize.ANSICodeColors,
565 PyColorize.ANSICodeColors,
566 'NoColor')
566 'NoColor')
567 # indentation management
567 # indentation management
568 self.autoindent = False
568 self.autoindent = False
569 self.indent_current_nsp = 0
569 self.indent_current_nsp = 0
570
570
571 # Make some aliases automatically
571 # Make some aliases automatically
572 # Prepare list of shell aliases to auto-define
572 # Prepare list of shell aliases to auto-define
573 if os.name == 'posix':
573 if os.name == 'posix':
574 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
574 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
575 'mv mv -i','rm rm -i','cp cp -i',
575 'mv mv -i','rm rm -i','cp cp -i',
576 'cat cat','less less','clear clear',
576 'cat cat','less less','clear clear',
577 # a better ls
577 # a better ls
578 'ls ls -F',
578 'ls ls -F',
579 # long ls
579 # long ls
580 'll ls -lF',
580 'll ls -lF',
581 # color ls
581 # color ls
582 'lc ls -F -o --color',
582 'lc ls -F -o --color',
583 # ls normal files only
583 # ls normal files only
584 'lf ls -F -o --color %l | grep ^-',
584 'lf ls -F -o --color %l | grep ^-',
585 # ls symbolic links
585 # ls symbolic links
586 'lk ls -F -o --color %l | grep ^l',
586 'lk ls -F -o --color %l | grep ^l',
587 # directories or links to directories,
587 # directories or links to directories,
588 'ldir ls -F -o --color %l | grep /$',
588 'ldir ls -F -o --color %l | grep /$',
589 # things which are executable
589 # things which are executable
590 'lx ls -F -o --color %l | grep ^-..x',
590 'lx ls -F -o --color %l | grep ^-..x',
591 )
591 )
592 elif os.name in ['nt','dos']:
592 elif os.name in ['nt','dos']:
593 auto_alias = ('dir dir /on', 'ls dir /on',
593 auto_alias = ('dir dir /on', 'ls dir /on',
594 'ddir dir /ad /on', 'ldir dir /ad /on',
594 'ddir dir /ad /on', 'ldir dir /ad /on',
595 'mkdir mkdir','rmdir rmdir','echo echo',
595 'mkdir mkdir','rmdir rmdir','echo echo',
596 'ren ren','cls cls','copy copy')
596 'ren ren','cls cls','copy copy')
597 else:
597 else:
598 auto_alias = ()
598 auto_alias = ()
599 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
599 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
600 # Call the actual (public) initializer
600 # Call the actual (public) initializer
601 self.init_auto_alias()
601 self.init_auto_alias()
602 # end __init__
602 # end __init__
603
603
604 def pre_config_initialization(self):
605 """Pre-configuration init method
606
607 This is called before the configuration files are processed to
608 prepare the services the config files might need.
609
610 self.rc already has reasonable default values at this point.
611 """
612 rc = self.rc
613
614 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
615
616
604 def post_config_initialization(self):
617 def post_config_initialization(self):
605 """Post configuration init method
618 """Post configuration init method
606
619
607 This is called after the configuration files have been processed to
620 This is called after the configuration files have been processed to
608 'finalize' the initialization."""
621 'finalize' the initialization."""
609
622
610 rc = self.rc
623 rc = self.rc
611
624
612 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
613 # Load readline proper
625 # Load readline proper
614 if rc.readline:
626 if rc.readline:
615 self.init_readline()
627 self.init_readline()
616
628
617 # local shortcut, this is used a LOT
629 # local shortcut, this is used a LOT
618 self.log = self.logger.log
630 self.log = self.logger.log
619
631
620 # Initialize cache, set in/out prompts and printing system
632 # Initialize cache, set in/out prompts and printing system
621 self.outputcache = CachedOutput(self,
633 self.outputcache = CachedOutput(self,
622 rc.cache_size,
634 rc.cache_size,
623 rc.pprint,
635 rc.pprint,
624 input_sep = rc.separate_in,
636 input_sep = rc.separate_in,
625 output_sep = rc.separate_out,
637 output_sep = rc.separate_out,
626 output_sep2 = rc.separate_out2,
638 output_sep2 = rc.separate_out2,
627 ps1 = rc.prompt_in1,
639 ps1 = rc.prompt_in1,
628 ps2 = rc.prompt_in2,
640 ps2 = rc.prompt_in2,
629 ps_out = rc.prompt_out,
641 ps_out = rc.prompt_out,
630 pad_left = rc.prompts_pad_left)
642 pad_left = rc.prompts_pad_left)
631
643
632 # user may have over-ridden the default print hook:
644 # user may have over-ridden the default print hook:
633 try:
645 try:
634 self.outputcache.__class__.display = self.hooks.display
646 self.outputcache.__class__.display = self.hooks.display
635 except AttributeError:
647 except AttributeError:
636 pass
648 pass
637
649
638 # I don't like assigning globally to sys, because it means when embedding
650 # I don't like assigning globally to sys, because it means when embedding
639 # instances, each embedded instance overrides the previous choice. But
651 # instances, each embedded instance overrides the previous choice. But
640 # sys.displayhook seems to be called internally by exec, so I don't see a
652 # sys.displayhook seems to be called internally by exec, so I don't see a
641 # way around it.
653 # way around it.
642 sys.displayhook = self.outputcache
654 sys.displayhook = self.outputcache
643
655
644 # Set user colors (don't do it in the constructor above so that it
656 # Set user colors (don't do it in the constructor above so that it
645 # doesn't crash if colors option is invalid)
657 # doesn't crash if colors option is invalid)
646 self.magic_colors(rc.colors)
658 self.magic_colors(rc.colors)
647
659
648 # Set calling of pdb on exceptions
660 # Set calling of pdb on exceptions
649 self.call_pdb = rc.pdb
661 self.call_pdb = rc.pdb
650
662
651 # Load user aliases
663 # Load user aliases
652 for alias in rc.alias:
664 for alias in rc.alias:
653 self.magic_alias(alias)
665 self.magic_alias(alias)
654 self.hooks.late_startup_hook()
666 self.hooks.late_startup_hook()
655
667
656
668
657 def add_builtins(self):
669 def add_builtins(self):
658 """Store ipython references into the builtin namespace.
670 """Store ipython references into the builtin namespace.
659
671
660 Some parts of ipython operate via builtins injected here, which hold a
672 Some parts of ipython operate via builtins injected here, which hold a
661 reference to IPython itself."""
673 reference to IPython itself."""
662
674
663 # TODO: deprecate all except _ip; 'jobs' should be installed
675 # TODO: deprecate all except _ip; 'jobs' should be installed
664 # by an extension and the rest are under _ip, ipalias is redundant
676 # by an extension and the rest are under _ip, ipalias is redundant
665 builtins_new = dict(__IPYTHON__ = self,
677 builtins_new = dict(__IPYTHON__ = self,
666 ip_set_hook = self.set_hook,
678 ip_set_hook = self.set_hook,
667 jobs = self.jobs,
679 jobs = self.jobs,
668 ipmagic = self.ipmagic,
680 ipmagic = self.ipmagic,
669 ipalias = self.ipalias,
681 ipalias = self.ipalias,
670 ipsystem = self.ipsystem,
682 ipsystem = self.ipsystem,
671 _ip = self.api
683 _ip = self.api
672 )
684 )
673 for biname,bival in builtins_new.items():
685 for biname,bival in builtins_new.items():
674 try:
686 try:
675 # store the orignal value so we can restore it
687 # store the orignal value so we can restore it
676 self.builtins_added[biname] = __builtin__.__dict__[biname]
688 self.builtins_added[biname] = __builtin__.__dict__[biname]
677 except KeyError:
689 except KeyError:
678 # or mark that it wasn't defined, and we'll just delete it at
690 # or mark that it wasn't defined, and we'll just delete it at
679 # cleanup
691 # cleanup
680 self.builtins_added[biname] = Undefined
692 self.builtins_added[biname] = Undefined
681 __builtin__.__dict__[biname] = bival
693 __builtin__.__dict__[biname] = bival
682
694
683 # Keep in the builtins a flag for when IPython is active. We set it
695 # Keep in the builtins a flag for when IPython is active. We set it
684 # with setdefault so that multiple nested IPythons don't clobber one
696 # with setdefault so that multiple nested IPythons don't clobber one
685 # another. Each will increase its value by one upon being activated,
697 # another. Each will increase its value by one upon being activated,
686 # which also gives us a way to determine the nesting level.
698 # which also gives us a way to determine the nesting level.
687 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
699 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
688
700
689 def clean_builtins(self):
701 def clean_builtins(self):
690 """Remove any builtins which might have been added by add_builtins, or
702 """Remove any builtins which might have been added by add_builtins, or
691 restore overwritten ones to their previous values."""
703 restore overwritten ones to their previous values."""
692 for biname,bival in self.builtins_added.items():
704 for biname,bival in self.builtins_added.items():
693 if bival is Undefined:
705 if bival is Undefined:
694 del __builtin__.__dict__[biname]
706 del __builtin__.__dict__[biname]
695 else:
707 else:
696 __builtin__.__dict__[biname] = bival
708 __builtin__.__dict__[biname] = bival
697 self.builtins_added.clear()
709 self.builtins_added.clear()
698
710
699 def set_hook(self,name,hook, priority = 50):
711 def set_hook(self,name,hook, priority = 50):
700 """set_hook(name,hook) -> sets an internal IPython hook.
712 """set_hook(name,hook) -> sets an internal IPython hook.
701
713
702 IPython exposes some of its internal API as user-modifiable hooks. By
714 IPython exposes some of its internal API as user-modifiable hooks. By
703 adding your function to one of these hooks, you can modify IPython's
715 adding your function to one of these hooks, you can modify IPython's
704 behavior to call at runtime your own routines."""
716 behavior to call at runtime your own routines."""
705
717
706 # At some point in the future, this should validate the hook before it
718 # At some point in the future, this should validate the hook before it
707 # accepts it. Probably at least check that the hook takes the number
719 # accepts it. Probably at least check that the hook takes the number
708 # of args it's supposed to.
720 # of args it's supposed to.
709 dp = getattr(self.hooks, name, None)
721 dp = getattr(self.hooks, name, None)
710 if name not in IPython.hooks.__all__:
722 if name not in IPython.hooks.__all__:
711 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
723 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
712 if not dp:
724 if not dp:
713 dp = IPython.hooks.CommandChainDispatcher()
725 dp = IPython.hooks.CommandChainDispatcher()
714
726
715 f = new.instancemethod(hook,self,self.__class__)
727 f = new.instancemethod(hook,self,self.__class__)
716 try:
728 try:
717 dp.add(f,priority)
729 dp.add(f,priority)
718 except AttributeError:
730 except AttributeError:
719 # it was not commandchain, plain old func - replace
731 # it was not commandchain, plain old func - replace
720 dp = f
732 dp = f
721
733
722 setattr(self.hooks,name, dp)
734 setattr(self.hooks,name, dp)
723
735
724
736
725 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
737 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
726
738
727 def set_custom_exc(self,exc_tuple,handler):
739 def set_custom_exc(self,exc_tuple,handler):
728 """set_custom_exc(exc_tuple,handler)
740 """set_custom_exc(exc_tuple,handler)
729
741
730 Set a custom exception handler, which will be called if any of the
742 Set a custom exception handler, which will be called if any of the
731 exceptions in exc_tuple occur in the mainloop (specifically, in the
743 exceptions in exc_tuple occur in the mainloop (specifically, in the
732 runcode() method.
744 runcode() method.
733
745
734 Inputs:
746 Inputs:
735
747
736 - exc_tuple: a *tuple* of valid exceptions to call the defined
748 - exc_tuple: a *tuple* of valid exceptions to call the defined
737 handler for. It is very important that you use a tuple, and NOT A
749 handler for. It is very important that you use a tuple, and NOT A
738 LIST here, because of the way Python's except statement works. If
750 LIST here, because of the way Python's except statement works. If
739 you only want to trap a single exception, use a singleton tuple:
751 you only want to trap a single exception, use a singleton tuple:
740
752
741 exc_tuple == (MyCustomException,)
753 exc_tuple == (MyCustomException,)
742
754
743 - handler: this must be defined as a function with the following
755 - handler: this must be defined as a function with the following
744 basic interface: def my_handler(self,etype,value,tb).
756 basic interface: def my_handler(self,etype,value,tb).
745
757
746 This will be made into an instance method (via new.instancemethod)
758 This will be made into an instance method (via new.instancemethod)
747 of IPython itself, and it will be called if any of the exceptions
759 of IPython itself, and it will be called if any of the exceptions
748 listed in the exc_tuple are caught. If the handler is None, an
760 listed in the exc_tuple are caught. If the handler is None, an
749 internal basic one is used, which just prints basic info.
761 internal basic one is used, which just prints basic info.
750
762
751 WARNING: by putting in your own exception handler into IPython's main
763 WARNING: by putting in your own exception handler into IPython's main
752 execution loop, you run a very good chance of nasty crashes. This
764 execution loop, you run a very good chance of nasty crashes. This
753 facility should only be used if you really know what you are doing."""
765 facility should only be used if you really know what you are doing."""
754
766
755 assert type(exc_tuple)==type(()) , \
767 assert type(exc_tuple)==type(()) , \
756 "The custom exceptions must be given AS A TUPLE."
768 "The custom exceptions must be given AS A TUPLE."
757
769
758 def dummy_handler(self,etype,value,tb):
770 def dummy_handler(self,etype,value,tb):
759 print '*** Simple custom exception handler ***'
771 print '*** Simple custom exception handler ***'
760 print 'Exception type :',etype
772 print 'Exception type :',etype
761 print 'Exception value:',value
773 print 'Exception value:',value
762 print 'Traceback :',tb
774 print 'Traceback :',tb
763 print 'Source code :','\n'.join(self.buffer)
775 print 'Source code :','\n'.join(self.buffer)
764
776
765 if handler is None: handler = dummy_handler
777 if handler is None: handler = dummy_handler
766
778
767 self.CustomTB = new.instancemethod(handler,self,self.__class__)
779 self.CustomTB = new.instancemethod(handler,self,self.__class__)
768 self.custom_exceptions = exc_tuple
780 self.custom_exceptions = exc_tuple
769
781
770 def set_custom_completer(self,completer,pos=0):
782 def set_custom_completer(self,completer,pos=0):
771 """set_custom_completer(completer,pos=0)
783 """set_custom_completer(completer,pos=0)
772
784
773 Adds a new custom completer function.
785 Adds a new custom completer function.
774
786
775 The position argument (defaults to 0) is the index in the completers
787 The position argument (defaults to 0) is the index in the completers
776 list where you want the completer to be inserted."""
788 list where you want the completer to be inserted."""
777
789
778 newcomp = new.instancemethod(completer,self.Completer,
790 newcomp = new.instancemethod(completer,self.Completer,
779 self.Completer.__class__)
791 self.Completer.__class__)
780 self.Completer.matchers.insert(pos,newcomp)
792 self.Completer.matchers.insert(pos,newcomp)
781
793
782 def _get_call_pdb(self):
794 def _get_call_pdb(self):
783 return self._call_pdb
795 return self._call_pdb
784
796
785 def _set_call_pdb(self,val):
797 def _set_call_pdb(self,val):
786
798
787 if val not in (0,1,False,True):
799 if val not in (0,1,False,True):
788 raise ValueError,'new call_pdb value must be boolean'
800 raise ValueError,'new call_pdb value must be boolean'
789
801
790 # store value in instance
802 # store value in instance
791 self._call_pdb = val
803 self._call_pdb = val
792
804
793 # notify the actual exception handlers
805 # notify the actual exception handlers
794 self.InteractiveTB.call_pdb = val
806 self.InteractiveTB.call_pdb = val
795 if self.isthreaded:
807 if self.isthreaded:
796 try:
808 try:
797 self.sys_excepthook.call_pdb = val
809 self.sys_excepthook.call_pdb = val
798 except:
810 except:
799 warn('Failed to activate pdb for threaded exception handler')
811 warn('Failed to activate pdb for threaded exception handler')
800
812
801 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
813 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
802 'Control auto-activation of pdb at exceptions')
814 'Control auto-activation of pdb at exceptions')
803
815
804
816
805 # These special functions get installed in the builtin namespace, to
817 # These special functions get installed in the builtin namespace, to
806 # provide programmatic (pure python) access to magics, aliases and system
818 # provide programmatic (pure python) access to magics, aliases and system
807 # calls. This is important for logging, user scripting, and more.
819 # calls. This is important for logging, user scripting, and more.
808
820
809 # We are basically exposing, via normal python functions, the three
821 # We are basically exposing, via normal python functions, the three
810 # mechanisms in which ipython offers special call modes (magics for
822 # mechanisms in which ipython offers special call modes (magics for
811 # internal control, aliases for direct system access via pre-selected
823 # internal control, aliases for direct system access via pre-selected
812 # names, and !cmd for calling arbitrary system commands).
824 # names, and !cmd for calling arbitrary system commands).
813
825
814 def ipmagic(self,arg_s):
826 def ipmagic(self,arg_s):
815 """Call a magic function by name.
827 """Call a magic function by name.
816
828
817 Input: a string containing the name of the magic function to call and any
829 Input: a string containing the name of the magic function to call and any
818 additional arguments to be passed to the magic.
830 additional arguments to be passed to the magic.
819
831
820 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
832 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
821 prompt:
833 prompt:
822
834
823 In[1]: %name -opt foo bar
835 In[1]: %name -opt foo bar
824
836
825 To call a magic without arguments, simply use ipmagic('name').
837 To call a magic without arguments, simply use ipmagic('name').
826
838
827 This provides a proper Python function to call IPython's magics in any
839 This provides a proper Python function to call IPython's magics in any
828 valid Python code you can type at the interpreter, including loops and
840 valid Python code you can type at the interpreter, including loops and
829 compound statements. It is added by IPython to the Python builtin
841 compound statements. It is added by IPython to the Python builtin
830 namespace upon initialization."""
842 namespace upon initialization."""
831
843
832 args = arg_s.split(' ',1)
844 args = arg_s.split(' ',1)
833 magic_name = args[0]
845 magic_name = args[0]
834 magic_name = magic_name.lstrip(self.ESC_MAGIC)
846 magic_name = magic_name.lstrip(self.ESC_MAGIC)
835
847
836 try:
848 try:
837 magic_args = args[1]
849 magic_args = args[1]
838 except IndexError:
850 except IndexError:
839 magic_args = ''
851 magic_args = ''
840 fn = getattr(self,'magic_'+magic_name,None)
852 fn = getattr(self,'magic_'+magic_name,None)
841 if fn is None:
853 if fn is None:
842 error("Magic function `%s` not found." % magic_name)
854 error("Magic function `%s` not found." % magic_name)
843 else:
855 else:
844 magic_args = self.var_expand(magic_args)
856 magic_args = self.var_expand(magic_args)
845 return fn(magic_args)
857 return fn(magic_args)
846
858
847 def ipalias(self,arg_s):
859 def ipalias(self,arg_s):
848 """Call an alias by name.
860 """Call an alias by name.
849
861
850 Input: a string containing the name of the alias to call and any
862 Input: a string containing the name of the alias to call and any
851 additional arguments to be passed to the magic.
863 additional arguments to be passed to the magic.
852
864
853 ipalias('name -opt foo bar') is equivalent to typing at the ipython
865 ipalias('name -opt foo bar') is equivalent to typing at the ipython
854 prompt:
866 prompt:
855
867
856 In[1]: name -opt foo bar
868 In[1]: name -opt foo bar
857
869
858 To call an alias without arguments, simply use ipalias('name').
870 To call an alias without arguments, simply use ipalias('name').
859
871
860 This provides a proper Python function to call IPython's aliases in any
872 This provides a proper Python function to call IPython's aliases in any
861 valid Python code you can type at the interpreter, including loops and
873 valid Python code you can type at the interpreter, including loops and
862 compound statements. It is added by IPython to the Python builtin
874 compound statements. It is added by IPython to the Python builtin
863 namespace upon initialization."""
875 namespace upon initialization."""
864
876
865 args = arg_s.split(' ',1)
877 args = arg_s.split(' ',1)
866 alias_name = args[0]
878 alias_name = args[0]
867 try:
879 try:
868 alias_args = args[1]
880 alias_args = args[1]
869 except IndexError:
881 except IndexError:
870 alias_args = ''
882 alias_args = ''
871 if alias_name in self.alias_table:
883 if alias_name in self.alias_table:
872 self.call_alias(alias_name,alias_args)
884 self.call_alias(alias_name,alias_args)
873 else:
885 else:
874 error("Alias `%s` not found." % alias_name)
886 error("Alias `%s` not found." % alias_name)
875
887
876 def ipsystem(self,arg_s):
888 def ipsystem(self,arg_s):
877 """Make a system call, using IPython."""
889 """Make a system call, using IPython."""
878
890
879 self.system(arg_s)
891 self.system(arg_s)
880
892
881 def complete(self,text):
893 def complete(self,text):
882 """Return a sorted list of all possible completions on text.
894 """Return a sorted list of all possible completions on text.
883
895
884 Inputs:
896 Inputs:
885
897
886 - text: a string of text to be completed on.
898 - text: a string of text to be completed on.
887
899
888 This is a wrapper around the completion mechanism, similar to what
900 This is a wrapper around the completion mechanism, similar to what
889 readline does at the command line when the TAB key is hit. By
901 readline does at the command line when the TAB key is hit. By
890 exposing it as a method, it can be used by other non-readline
902 exposing it as a method, it can be used by other non-readline
891 environments (such as GUIs) for text completion.
903 environments (such as GUIs) for text completion.
892
904
893 Simple usage example:
905 Simple usage example:
894
906
895 In [1]: x = 'hello'
907 In [1]: x = 'hello'
896
908
897 In [2]: __IP.complete('x.l')
909 In [2]: __IP.complete('x.l')
898 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
910 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
899
911
900 complete = self.Completer.complete
912 complete = self.Completer.complete
901 state = 0
913 state = 0
902 # use a dict so we get unique keys, since ipyhton's multiple
914 # use a dict so we get unique keys, since ipyhton's multiple
903 # completers can return duplicates.
915 # completers can return duplicates.
904 comps = {}
916 comps = {}
905 while True:
917 while True:
906 newcomp = complete(text,state)
918 newcomp = complete(text,state)
907 if newcomp is None:
919 if newcomp is None:
908 break
920 break
909 comps[newcomp] = 1
921 comps[newcomp] = 1
910 state += 1
922 state += 1
911 outcomps = comps.keys()
923 outcomps = comps.keys()
912 outcomps.sort()
924 outcomps.sort()
913 return outcomps
925 return outcomps
914
926
915 def set_completer_frame(self, frame=None):
927 def set_completer_frame(self, frame=None):
916 if frame:
928 if frame:
917 self.Completer.namespace = frame.f_locals
929 self.Completer.namespace = frame.f_locals
918 self.Completer.global_namespace = frame.f_globals
930 self.Completer.global_namespace = frame.f_globals
919 else:
931 else:
920 self.Completer.namespace = self.user_ns
932 self.Completer.namespace = self.user_ns
921 self.Completer.global_namespace = self.user_global_ns
933 self.Completer.global_namespace = self.user_global_ns
922
934
923 def init_auto_alias(self):
935 def init_auto_alias(self):
924 """Define some aliases automatically.
936 """Define some aliases automatically.
925
937
926 These are ALL parameter-less aliases"""
938 These are ALL parameter-less aliases"""
927
939
928 for alias,cmd in self.auto_alias:
940 for alias,cmd in self.auto_alias:
929 self.alias_table[alias] = (0,cmd)
941 self.alias_table[alias] = (0,cmd)
930
942
931 def alias_table_validate(self,verbose=0):
943 def alias_table_validate(self,verbose=0):
932 """Update information about the alias table.
944 """Update information about the alias table.
933
945
934 In particular, make sure no Python keywords/builtins are in it."""
946 In particular, make sure no Python keywords/builtins are in it."""
935
947
936 no_alias = self.no_alias
948 no_alias = self.no_alias
937 for k in self.alias_table.keys():
949 for k in self.alias_table.keys():
938 if k in no_alias:
950 if k in no_alias:
939 del self.alias_table[k]
951 del self.alias_table[k]
940 if verbose:
952 if verbose:
941 print ("Deleting alias <%s>, it's a Python "
953 print ("Deleting alias <%s>, it's a Python "
942 "keyword or builtin." % k)
954 "keyword or builtin." % k)
943
955
944 def set_autoindent(self,value=None):
956 def set_autoindent(self,value=None):
945 """Set the autoindent flag, checking for readline support.
957 """Set the autoindent flag, checking for readline support.
946
958
947 If called with no arguments, it acts as a toggle."""
959 If called with no arguments, it acts as a toggle."""
948
960
949 if not self.has_readline:
961 if not self.has_readline:
950 if os.name == 'posix':
962 if os.name == 'posix':
951 warn("The auto-indent feature requires the readline library")
963 warn("The auto-indent feature requires the readline library")
952 self.autoindent = 0
964 self.autoindent = 0
953 return
965 return
954 if value is None:
966 if value is None:
955 self.autoindent = not self.autoindent
967 self.autoindent = not self.autoindent
956 else:
968 else:
957 self.autoindent = value
969 self.autoindent = value
958
970
959 def rc_set_toggle(self,rc_field,value=None):
971 def rc_set_toggle(self,rc_field,value=None):
960 """Set or toggle a field in IPython's rc config. structure.
972 """Set or toggle a field in IPython's rc config. structure.
961
973
962 If called with no arguments, it acts as a toggle.
974 If called with no arguments, it acts as a toggle.
963
975
964 If called with a non-existent field, the resulting AttributeError
976 If called with a non-existent field, the resulting AttributeError
965 exception will propagate out."""
977 exception will propagate out."""
966
978
967 rc_val = getattr(self.rc,rc_field)
979 rc_val = getattr(self.rc,rc_field)
968 if value is None:
980 if value is None:
969 value = not rc_val
981 value = not rc_val
970 setattr(self.rc,rc_field,value)
982 setattr(self.rc,rc_field,value)
971
983
972 def user_setup(self,ipythondir,rc_suffix,mode='install'):
984 def user_setup(self,ipythondir,rc_suffix,mode='install'):
973 """Install the user configuration directory.
985 """Install the user configuration directory.
974
986
975 Can be called when running for the first time or to upgrade the user's
987 Can be called when running for the first time or to upgrade the user's
976 .ipython/ directory with the mode parameter. Valid modes are 'install'
988 .ipython/ directory with the mode parameter. Valid modes are 'install'
977 and 'upgrade'."""
989 and 'upgrade'."""
978
990
979 def wait():
991 def wait():
980 try:
992 try:
981 raw_input("Please press <RETURN> to start IPython.")
993 raw_input("Please press <RETURN> to start IPython.")
982 except EOFError:
994 except EOFError:
983 print >> Term.cout
995 print >> Term.cout
984 print '*'*70
996 print '*'*70
985
997
986 cwd = os.getcwd() # remember where we started
998 cwd = os.getcwd() # remember where we started
987 glb = glob.glob
999 glb = glob.glob
988 print '*'*70
1000 print '*'*70
989 if mode == 'install':
1001 if mode == 'install':
990 print \
1002 print \
991 """Welcome to IPython. I will try to create a personal configuration directory
1003 """Welcome to IPython. I will try to create a personal configuration directory
992 where you can customize many aspects of IPython's functionality in:\n"""
1004 where you can customize many aspects of IPython's functionality in:\n"""
993 else:
1005 else:
994 print 'I am going to upgrade your configuration in:'
1006 print 'I am going to upgrade your configuration in:'
995
1007
996 print ipythondir
1008 print ipythondir
997
1009
998 rcdirend = os.path.join('IPython','UserConfig')
1010 rcdirend = os.path.join('IPython','UserConfig')
999 cfg = lambda d: os.path.join(d,rcdirend)
1011 cfg = lambda d: os.path.join(d,rcdirend)
1000 try:
1012 try:
1001 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1013 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1002 except IOError:
1014 except IOError:
1003 warning = """
1015 warning = """
1004 Installation error. IPython's directory was not found.
1016 Installation error. IPython's directory was not found.
1005
1017
1006 Check the following:
1018 Check the following:
1007
1019
1008 The ipython/IPython directory should be in a directory belonging to your
1020 The ipython/IPython directory should be in a directory belonging to your
1009 PYTHONPATH environment variable (that is, it should be in a directory
1021 PYTHONPATH environment variable (that is, it should be in a directory
1010 belonging to sys.path). You can copy it explicitly there or just link to it.
1022 belonging to sys.path). You can copy it explicitly there or just link to it.
1011
1023
1012 IPython will proceed with builtin defaults.
1024 IPython will proceed with builtin defaults.
1013 """
1025 """
1014 warn(warning)
1026 warn(warning)
1015 wait()
1027 wait()
1016 return
1028 return
1017
1029
1018 if mode == 'install':
1030 if mode == 'install':
1019 try:
1031 try:
1020 shutil.copytree(rcdir,ipythondir)
1032 shutil.copytree(rcdir,ipythondir)
1021 os.chdir(ipythondir)
1033 os.chdir(ipythondir)
1022 rc_files = glb("ipythonrc*")
1034 rc_files = glb("ipythonrc*")
1023 for rc_file in rc_files:
1035 for rc_file in rc_files:
1024 os.rename(rc_file,rc_file+rc_suffix)
1036 os.rename(rc_file,rc_file+rc_suffix)
1025 except:
1037 except:
1026 warning = """
1038 warning = """
1027
1039
1028 There was a problem with the installation:
1040 There was a problem with the installation:
1029 %s
1041 %s
1030 Try to correct it or contact the developers if you think it's a bug.
1042 Try to correct it or contact the developers if you think it's a bug.
1031 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1043 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1032 warn(warning)
1044 warn(warning)
1033 wait()
1045 wait()
1034 return
1046 return
1035
1047
1036 elif mode == 'upgrade':
1048 elif mode == 'upgrade':
1037 try:
1049 try:
1038 os.chdir(ipythondir)
1050 os.chdir(ipythondir)
1039 except:
1051 except:
1040 print """
1052 print """
1041 Can not upgrade: changing to directory %s failed. Details:
1053 Can not upgrade: changing to directory %s failed. Details:
1042 %s
1054 %s
1043 """ % (ipythondir,sys.exc_info()[1])
1055 """ % (ipythondir,sys.exc_info()[1])
1044 wait()
1056 wait()
1045 return
1057 return
1046 else:
1058 else:
1047 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1059 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1048 for new_full_path in sources:
1060 for new_full_path in sources:
1049 new_filename = os.path.basename(new_full_path)
1061 new_filename = os.path.basename(new_full_path)
1050 if new_filename.startswith('ipythonrc'):
1062 if new_filename.startswith('ipythonrc'):
1051 new_filename = new_filename + rc_suffix
1063 new_filename = new_filename + rc_suffix
1052 # The config directory should only contain files, skip any
1064 # The config directory should only contain files, skip any
1053 # directories which may be there (like CVS)
1065 # directories which may be there (like CVS)
1054 if os.path.isdir(new_full_path):
1066 if os.path.isdir(new_full_path):
1055 continue
1067 continue
1056 if os.path.exists(new_filename):
1068 if os.path.exists(new_filename):
1057 old_file = new_filename+'.old'
1069 old_file = new_filename+'.old'
1058 if os.path.exists(old_file):
1070 if os.path.exists(old_file):
1059 os.remove(old_file)
1071 os.remove(old_file)
1060 os.rename(new_filename,old_file)
1072 os.rename(new_filename,old_file)
1061 shutil.copy(new_full_path,new_filename)
1073 shutil.copy(new_full_path,new_filename)
1062 else:
1074 else:
1063 raise ValueError,'unrecognized mode for install:',`mode`
1075 raise ValueError,'unrecognized mode for install:',`mode`
1064
1076
1065 # Fix line-endings to those native to each platform in the config
1077 # Fix line-endings to those native to each platform in the config
1066 # directory.
1078 # directory.
1067 try:
1079 try:
1068 os.chdir(ipythondir)
1080 os.chdir(ipythondir)
1069 except:
1081 except:
1070 print """
1082 print """
1071 Problem: changing to directory %s failed.
1083 Problem: changing to directory %s failed.
1072 Details:
1084 Details:
1073 %s
1085 %s
1074
1086
1075 Some configuration files may have incorrect line endings. This should not
1087 Some configuration files may have incorrect line endings. This should not
1076 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1088 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1077 wait()
1089 wait()
1078 else:
1090 else:
1079 for fname in glb('ipythonrc*'):
1091 for fname in glb('ipythonrc*'):
1080 try:
1092 try:
1081 native_line_ends(fname,backup=0)
1093 native_line_ends(fname,backup=0)
1082 except IOError:
1094 except IOError:
1083 pass
1095 pass
1084
1096
1085 if mode == 'install':
1097 if mode == 'install':
1086 print """
1098 print """
1087 Successful installation!
1099 Successful installation!
1088
1100
1089 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1101 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1090 IPython manual (there are both HTML and PDF versions supplied with the
1102 IPython manual (there are both HTML and PDF versions supplied with the
1091 distribution) to make sure that your system environment is properly configured
1103 distribution) to make sure that your system environment is properly configured
1092 to take advantage of IPython's features.
1104 to take advantage of IPython's features.
1093
1105
1094 Important note: the configuration system has changed! The old system is
1106 Important note: the configuration system has changed! The old system is
1095 still in place, but its setting may be partly overridden by the settings in
1107 still in place, but its setting may be partly overridden by the settings in
1096 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1108 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1097 if some of the new settings bother you.
1109 if some of the new settings bother you.
1098
1110
1099 """
1111 """
1100 else:
1112 else:
1101 print """
1113 print """
1102 Successful upgrade!
1114 Successful upgrade!
1103
1115
1104 All files in your directory:
1116 All files in your directory:
1105 %(ipythondir)s
1117 %(ipythondir)s
1106 which would have been overwritten by the upgrade were backed up with a .old
1118 which would have been overwritten by the upgrade were backed up with a .old
1107 extension. If you had made particular customizations in those files you may
1119 extension. If you had made particular customizations in those files you may
1108 want to merge them back into the new files.""" % locals()
1120 want to merge them back into the new files.""" % locals()
1109 wait()
1121 wait()
1110 os.chdir(cwd)
1122 os.chdir(cwd)
1111 # end user_setup()
1123 # end user_setup()
1112
1124
1113 def atexit_operations(self):
1125 def atexit_operations(self):
1114 """This will be executed at the time of exit.
1126 """This will be executed at the time of exit.
1115
1127
1116 Saving of persistent data should be performed here. """
1128 Saving of persistent data should be performed here. """
1117
1129
1118 #print '*** IPython exit cleanup ***' # dbg
1130 #print '*** IPython exit cleanup ***' # dbg
1119 # input history
1131 # input history
1120 self.savehist()
1132 self.savehist()
1121
1133
1122 # Cleanup all tempfiles left around
1134 # Cleanup all tempfiles left around
1123 for tfile in self.tempfiles:
1135 for tfile in self.tempfiles:
1124 try:
1136 try:
1125 os.unlink(tfile)
1137 os.unlink(tfile)
1126 except OSError:
1138 except OSError:
1127 pass
1139 pass
1128
1140
1129 # save the "persistent data" catch-all dictionary
1141 # save the "persistent data" catch-all dictionary
1130 self.hooks.shutdown_hook()
1142 self.hooks.shutdown_hook()
1131
1143
1132 def savehist(self):
1144 def savehist(self):
1133 """Save input history to a file (via readline library)."""
1145 """Save input history to a file (via readline library)."""
1134 try:
1146 try:
1135 self.readline.write_history_file(self.histfile)
1147 self.readline.write_history_file(self.histfile)
1136 except:
1148 except:
1137 print 'Unable to save IPython command history to file: ' + \
1149 print 'Unable to save IPython command history to file: ' + \
1138 `self.histfile`
1150 `self.histfile`
1139
1151
1140 def pre_readline(self):
1152 def pre_readline(self):
1141 """readline hook to be used at the start of each line.
1153 """readline hook to be used at the start of each line.
1142
1154
1143 Currently it handles auto-indent only."""
1155 Currently it handles auto-indent only."""
1144
1156
1145 #debugx('self.indent_current_nsp','pre_readline:')
1157 #debugx('self.indent_current_nsp','pre_readline:')
1146 self.readline.insert_text(self.indent_current_str())
1158 self.readline.insert_text(self.indent_current_str())
1147
1159
1148 def init_readline(self):
1160 def init_readline(self):
1149 """Command history completion/saving/reloading."""
1161 """Command history completion/saving/reloading."""
1150
1162
1151 import IPython.rlineimpl as readline
1163 import IPython.rlineimpl as readline
1152 if not readline.have_readline:
1164 if not readline.have_readline:
1153 self.has_readline = 0
1165 self.has_readline = 0
1154 self.readline = None
1166 self.readline = None
1155 # no point in bugging windows users with this every time:
1167 # no point in bugging windows users with this every time:
1156 warn('Readline services not available on this platform.')
1168 warn('Readline services not available on this platform.')
1157 else:
1169 else:
1158 sys.modules['readline'] = readline
1170 sys.modules['readline'] = readline
1159 import atexit
1171 import atexit
1160 from IPython.completer import IPCompleter
1172 from IPython.completer import IPCompleter
1161 self.Completer = IPCompleter(self,
1173 self.Completer = IPCompleter(self,
1162 self.user_ns,
1174 self.user_ns,
1163 self.user_global_ns,
1175 self.user_global_ns,
1164 self.rc.readline_omit__names,
1176 self.rc.readline_omit__names,
1165 self.alias_table)
1177 self.alias_table)
1166
1178
1167 # Platform-specific configuration
1179 # Platform-specific configuration
1168 if os.name == 'nt':
1180 if os.name == 'nt':
1169 self.readline_startup_hook = readline.set_pre_input_hook
1181 self.readline_startup_hook = readline.set_pre_input_hook
1170 else:
1182 else:
1171 self.readline_startup_hook = readline.set_startup_hook
1183 self.readline_startup_hook = readline.set_startup_hook
1172
1184
1173 # Load user's initrc file (readline config)
1185 # Load user's initrc file (readline config)
1174 inputrc_name = os.environ.get('INPUTRC')
1186 inputrc_name = os.environ.get('INPUTRC')
1175 if inputrc_name is None:
1187 if inputrc_name is None:
1176 home_dir = get_home_dir()
1188 home_dir = get_home_dir()
1177 if home_dir is not None:
1189 if home_dir is not None:
1178 inputrc_name = os.path.join(home_dir,'.inputrc')
1190 inputrc_name = os.path.join(home_dir,'.inputrc')
1179 if os.path.isfile(inputrc_name):
1191 if os.path.isfile(inputrc_name):
1180 try:
1192 try:
1181 readline.read_init_file(inputrc_name)
1193 readline.read_init_file(inputrc_name)
1182 except:
1194 except:
1183 warn('Problems reading readline initialization file <%s>'
1195 warn('Problems reading readline initialization file <%s>'
1184 % inputrc_name)
1196 % inputrc_name)
1185
1197
1186 self.has_readline = 1
1198 self.has_readline = 1
1187 self.readline = readline
1199 self.readline = readline
1188 # save this in sys so embedded copies can restore it properly
1200 # save this in sys so embedded copies can restore it properly
1189 sys.ipcompleter = self.Completer.complete
1201 sys.ipcompleter = self.Completer.complete
1190 readline.set_completer(self.Completer.complete)
1202 readline.set_completer(self.Completer.complete)
1191
1203
1192 # Configure readline according to user's prefs
1204 # Configure readline according to user's prefs
1193 for rlcommand in self.rc.readline_parse_and_bind:
1205 for rlcommand in self.rc.readline_parse_and_bind:
1194 readline.parse_and_bind(rlcommand)
1206 readline.parse_and_bind(rlcommand)
1195
1207
1196 # remove some chars from the delimiters list
1208 # remove some chars from the delimiters list
1197 delims = readline.get_completer_delims()
1209 delims = readline.get_completer_delims()
1198 delims = delims.translate(string._idmap,
1210 delims = delims.translate(string._idmap,
1199 self.rc.readline_remove_delims)
1211 self.rc.readline_remove_delims)
1200 readline.set_completer_delims(delims)
1212 readline.set_completer_delims(delims)
1201 # otherwise we end up with a monster history after a while:
1213 # otherwise we end up with a monster history after a while:
1202 readline.set_history_length(1000)
1214 readline.set_history_length(1000)
1203 try:
1215 try:
1204 #print '*** Reading readline history' # dbg
1216 #print '*** Reading readline history' # dbg
1205 readline.read_history_file(self.histfile)
1217 readline.read_history_file(self.histfile)
1206 except IOError:
1218 except IOError:
1207 pass # It doesn't exist yet.
1219 pass # It doesn't exist yet.
1208
1220
1209 atexit.register(self.atexit_operations)
1221 atexit.register(self.atexit_operations)
1210 del atexit
1222 del atexit
1211
1223
1212 # Configure auto-indent for all platforms
1224 # Configure auto-indent for all platforms
1213 self.set_autoindent(self.rc.autoindent)
1225 self.set_autoindent(self.rc.autoindent)
1214
1226
1215 def _should_recompile(self,e):
1227 def _should_recompile(self,e):
1216 """Utility routine for edit_syntax_error"""
1228 """Utility routine for edit_syntax_error"""
1217
1229
1218 if e.filename in ('<ipython console>','<input>','<string>',
1230 if e.filename in ('<ipython console>','<input>','<string>',
1219 '<console>',None):
1231 '<console>',None):
1220
1232
1221 return False
1233 return False
1222 try:
1234 try:
1223 if (self.rc.autoedit_syntax and
1235 if (self.rc.autoedit_syntax and
1224 not ask_yes_no('Return to editor to correct syntax error? '
1236 not ask_yes_no('Return to editor to correct syntax error? '
1225 '[Y/n] ','y')):
1237 '[Y/n] ','y')):
1226 return False
1238 return False
1227 except EOFError:
1239 except EOFError:
1228 return False
1240 return False
1229
1241
1230 def int0(x):
1242 def int0(x):
1231 try:
1243 try:
1232 return int(x)
1244 return int(x)
1233 except TypeError:
1245 except TypeError:
1234 return 0
1246 return 0
1235 # always pass integer line and offset values to editor hook
1247 # always pass integer line and offset values to editor hook
1236 self.hooks.fix_error_editor(e.filename,
1248 self.hooks.fix_error_editor(e.filename,
1237 int0(e.lineno),int0(e.offset),e.msg)
1249 int0(e.lineno),int0(e.offset),e.msg)
1238 return True
1250 return True
1239
1251
1240 def edit_syntax_error(self):
1252 def edit_syntax_error(self):
1241 """The bottom half of the syntax error handler called in the main loop.
1253 """The bottom half of the syntax error handler called in the main loop.
1242
1254
1243 Loop until syntax error is fixed or user cancels.
1255 Loop until syntax error is fixed or user cancels.
1244 """
1256 """
1245
1257
1246 while self.SyntaxTB.last_syntax_error:
1258 while self.SyntaxTB.last_syntax_error:
1247 # copy and clear last_syntax_error
1259 # copy and clear last_syntax_error
1248 err = self.SyntaxTB.clear_err_state()
1260 err = self.SyntaxTB.clear_err_state()
1249 if not self._should_recompile(err):
1261 if not self._should_recompile(err):
1250 return
1262 return
1251 try:
1263 try:
1252 # may set last_syntax_error again if a SyntaxError is raised
1264 # may set last_syntax_error again if a SyntaxError is raised
1253 self.safe_execfile(err.filename,self.shell.user_ns)
1265 self.safe_execfile(err.filename,self.shell.user_ns)
1254 except:
1266 except:
1255 self.showtraceback()
1267 self.showtraceback()
1256 else:
1268 else:
1257 f = file(err.filename)
1269 f = file(err.filename)
1258 try:
1270 try:
1259 sys.displayhook(f.read())
1271 sys.displayhook(f.read())
1260 finally:
1272 finally:
1261 f.close()
1273 f.close()
1262
1274
1263 def showsyntaxerror(self, filename=None):
1275 def showsyntaxerror(self, filename=None):
1264 """Display the syntax error that just occurred.
1276 """Display the syntax error that just occurred.
1265
1277
1266 This doesn't display a stack trace because there isn't one.
1278 This doesn't display a stack trace because there isn't one.
1267
1279
1268 If a filename is given, it is stuffed in the exception instead
1280 If a filename is given, it is stuffed in the exception instead
1269 of what was there before (because Python's parser always uses
1281 of what was there before (because Python's parser always uses
1270 "<string>" when reading from a string).
1282 "<string>" when reading from a string).
1271 """
1283 """
1272 etype, value, last_traceback = sys.exc_info()
1284 etype, value, last_traceback = sys.exc_info()
1273 if filename and etype is SyntaxError:
1285 if filename and etype is SyntaxError:
1274 # Work hard to stuff the correct filename in the exception
1286 # Work hard to stuff the correct filename in the exception
1275 try:
1287 try:
1276 msg, (dummy_filename, lineno, offset, line) = value
1288 msg, (dummy_filename, lineno, offset, line) = value
1277 except:
1289 except:
1278 # Not the format we expect; leave it alone
1290 # Not the format we expect; leave it alone
1279 pass
1291 pass
1280 else:
1292 else:
1281 # Stuff in the right filename
1293 # Stuff in the right filename
1282 try:
1294 try:
1283 # Assume SyntaxError is a class exception
1295 # Assume SyntaxError is a class exception
1284 value = SyntaxError(msg, (filename, lineno, offset, line))
1296 value = SyntaxError(msg, (filename, lineno, offset, line))
1285 except:
1297 except:
1286 # If that failed, assume SyntaxError is a string
1298 # If that failed, assume SyntaxError is a string
1287 value = msg, (filename, lineno, offset, line)
1299 value = msg, (filename, lineno, offset, line)
1288 self.SyntaxTB(etype,value,[])
1300 self.SyntaxTB(etype,value,[])
1289
1301
1290 def debugger(self):
1302 def debugger(self):
1291 """Call the pdb debugger."""
1303 """Call the pdb debugger."""
1292
1304
1293 if not self.rc.pdb:
1305 if not self.rc.pdb:
1294 return
1306 return
1295 pdb.pm()
1307 pdb.pm()
1296
1308
1297 def showtraceback(self,exc_tuple = None,filename=None):
1309 def showtraceback(self,exc_tuple = None,filename=None):
1298 """Display the exception that just occurred."""
1310 """Display the exception that just occurred."""
1299
1311
1300 # Though this won't be called by syntax errors in the input line,
1312 # Though this won't be called by syntax errors in the input line,
1301 # there may be SyntaxError cases whith imported code.
1313 # there may be SyntaxError cases whith imported code.
1302 if exc_tuple is None:
1314 if exc_tuple is None:
1303 type, value, tb = sys.exc_info()
1315 type, value, tb = sys.exc_info()
1304 else:
1316 else:
1305 type, value, tb = exc_tuple
1317 type, value, tb = exc_tuple
1306 if type is SyntaxError:
1318 if type is SyntaxError:
1307 self.showsyntaxerror(filename)
1319 self.showsyntaxerror(filename)
1308 else:
1320 else:
1309 self.InteractiveTB()
1321 self.InteractiveTB()
1310 if self.InteractiveTB.call_pdb and self.has_readline:
1322 if self.InteractiveTB.call_pdb and self.has_readline:
1311 # pdb mucks up readline, fix it back
1323 # pdb mucks up readline, fix it back
1312 self.readline.set_completer(self.Completer.complete)
1324 self.readline.set_completer(self.Completer.complete)
1313
1325
1314 def mainloop(self,banner=None):
1326 def mainloop(self,banner=None):
1315 """Creates the local namespace and starts the mainloop.
1327 """Creates the local namespace and starts the mainloop.
1316
1328
1317 If an optional banner argument is given, it will override the
1329 If an optional banner argument is given, it will override the
1318 internally created default banner."""
1330 internally created default banner."""
1319
1331
1320 if self.rc.c: # Emulate Python's -c option
1332 if self.rc.c: # Emulate Python's -c option
1321 self.exec_init_cmd()
1333 self.exec_init_cmd()
1322 if banner is None:
1334 if banner is None:
1323 if not self.rc.banner:
1335 if not self.rc.banner:
1324 banner = ''
1336 banner = ''
1325 # banner is string? Use it directly!
1337 # banner is string? Use it directly!
1326 elif isinstance(self.rc.banner,basestring):
1338 elif isinstance(self.rc.banner,basestring):
1327 banner = self.rc.banner
1339 banner = self.rc.banner
1328 else:
1340 else:
1329 banner = self.BANNER+self.banner2
1341 banner = self.BANNER+self.banner2
1330
1342
1331 self.interact(banner)
1343 self.interact(banner)
1332
1344
1333 def exec_init_cmd(self):
1345 def exec_init_cmd(self):
1334 """Execute a command given at the command line.
1346 """Execute a command given at the command line.
1335
1347
1336 This emulates Python's -c option."""
1348 This emulates Python's -c option."""
1337
1349
1338 #sys.argv = ['-c']
1350 #sys.argv = ['-c']
1339 self.push(self.rc.c)
1351 self.push(self.rc.c)
1340
1352
1341 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1353 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1342 """Embeds IPython into a running python program.
1354 """Embeds IPython into a running python program.
1343
1355
1344 Input:
1356 Input:
1345
1357
1346 - header: An optional header message can be specified.
1358 - header: An optional header message can be specified.
1347
1359
1348 - local_ns, global_ns: working namespaces. If given as None, the
1360 - local_ns, global_ns: working namespaces. If given as None, the
1349 IPython-initialized one is updated with __main__.__dict__, so that
1361 IPython-initialized one is updated with __main__.__dict__, so that
1350 program variables become visible but user-specific configuration
1362 program variables become visible but user-specific configuration
1351 remains possible.
1363 remains possible.
1352
1364
1353 - stack_depth: specifies how many levels in the stack to go to
1365 - stack_depth: specifies how many levels in the stack to go to
1354 looking for namespaces (when local_ns and global_ns are None). This
1366 looking for namespaces (when local_ns and global_ns are None). This
1355 allows an intermediate caller to make sure that this function gets
1367 allows an intermediate caller to make sure that this function gets
1356 the namespace from the intended level in the stack. By default (0)
1368 the namespace from the intended level in the stack. By default (0)
1357 it will get its locals and globals from the immediate caller.
1369 it will get its locals and globals from the immediate caller.
1358
1370
1359 Warning: it's possible to use this in a program which is being run by
1371 Warning: it's possible to use this in a program which is being run by
1360 IPython itself (via %run), but some funny things will happen (a few
1372 IPython itself (via %run), but some funny things will happen (a few
1361 globals get overwritten). In the future this will be cleaned up, as
1373 globals get overwritten). In the future this will be cleaned up, as
1362 there is no fundamental reason why it can't work perfectly."""
1374 there is no fundamental reason why it can't work perfectly."""
1363
1375
1364 # Get locals and globals from caller
1376 # Get locals and globals from caller
1365 if local_ns is None or global_ns is None:
1377 if local_ns is None or global_ns is None:
1366 call_frame = sys._getframe(stack_depth).f_back
1378 call_frame = sys._getframe(stack_depth).f_back
1367
1379
1368 if local_ns is None:
1380 if local_ns is None:
1369 local_ns = call_frame.f_locals
1381 local_ns = call_frame.f_locals
1370 if global_ns is None:
1382 if global_ns is None:
1371 global_ns = call_frame.f_globals
1383 global_ns = call_frame.f_globals
1372
1384
1373 # Update namespaces and fire up interpreter
1385 # Update namespaces and fire up interpreter
1374
1386
1375 # The global one is easy, we can just throw it in
1387 # The global one is easy, we can just throw it in
1376 self.user_global_ns = global_ns
1388 self.user_global_ns = global_ns
1377
1389
1378 # but the user/local one is tricky: ipython needs it to store internal
1390 # but the user/local one is tricky: ipython needs it to store internal
1379 # data, but we also need the locals. We'll copy locals in the user
1391 # data, but we also need the locals. We'll copy locals in the user
1380 # one, but will track what got copied so we can delete them at exit.
1392 # one, but will track what got copied so we can delete them at exit.
1381 # This is so that a later embedded call doesn't see locals from a
1393 # This is so that a later embedded call doesn't see locals from a
1382 # previous call (which most likely existed in a separate scope).
1394 # previous call (which most likely existed in a separate scope).
1383 local_varnames = local_ns.keys()
1395 local_varnames = local_ns.keys()
1384 self.user_ns.update(local_ns)
1396 self.user_ns.update(local_ns)
1385
1397
1386 # Patch for global embedding to make sure that things don't overwrite
1398 # Patch for global embedding to make sure that things don't overwrite
1387 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1399 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1388 # FIXME. Test this a bit more carefully (the if.. is new)
1400 # FIXME. Test this a bit more carefully (the if.. is new)
1389 if local_ns is None and global_ns is None:
1401 if local_ns is None and global_ns is None:
1390 self.user_global_ns.update(__main__.__dict__)
1402 self.user_global_ns.update(__main__.__dict__)
1391
1403
1392 # make sure the tab-completer has the correct frame information, so it
1404 # make sure the tab-completer has the correct frame information, so it
1393 # actually completes using the frame's locals/globals
1405 # actually completes using the frame's locals/globals
1394 self.set_completer_frame()
1406 self.set_completer_frame()
1395
1407
1396 # before activating the interactive mode, we need to make sure that
1408 # before activating the interactive mode, we need to make sure that
1397 # all names in the builtin namespace needed by ipython point to
1409 # all names in the builtin namespace needed by ipython point to
1398 # ourselves, and not to other instances.
1410 # ourselves, and not to other instances.
1399 self.add_builtins()
1411 self.add_builtins()
1400
1412
1401 self.interact(header)
1413 self.interact(header)
1402
1414
1403 # now, purge out the user namespace from anything we might have added
1415 # now, purge out the user namespace from anything we might have added
1404 # from the caller's local namespace
1416 # from the caller's local namespace
1405 delvar = self.user_ns.pop
1417 delvar = self.user_ns.pop
1406 for var in local_varnames:
1418 for var in local_varnames:
1407 delvar(var,None)
1419 delvar(var,None)
1408 # and clean builtins we may have overridden
1420 # and clean builtins we may have overridden
1409 self.clean_builtins()
1421 self.clean_builtins()
1410
1422
1411 def interact(self, banner=None):
1423 def interact(self, banner=None):
1412 """Closely emulate the interactive Python console.
1424 """Closely emulate the interactive Python console.
1413
1425
1414 The optional banner argument specify the banner to print
1426 The optional banner argument specify the banner to print
1415 before the first interaction; by default it prints a banner
1427 before the first interaction; by default it prints a banner
1416 similar to the one printed by the real Python interpreter,
1428 similar to the one printed by the real Python interpreter,
1417 followed by the current class name in parentheses (so as not
1429 followed by the current class name in parentheses (so as not
1418 to confuse this with the real interpreter -- since it's so
1430 to confuse this with the real interpreter -- since it's so
1419 close!).
1431 close!).
1420
1432
1421 """
1433 """
1422 cprt = 'Type "copyright", "credits" or "license" for more information.'
1434 cprt = 'Type "copyright", "credits" or "license" for more information.'
1423 if banner is None:
1435 if banner is None:
1424 self.write("Python %s on %s\n%s\n(%s)\n" %
1436 self.write("Python %s on %s\n%s\n(%s)\n" %
1425 (sys.version, sys.platform, cprt,
1437 (sys.version, sys.platform, cprt,
1426 self.__class__.__name__))
1438 self.__class__.__name__))
1427 else:
1439 else:
1428 self.write(banner)
1440 self.write(banner)
1429
1441
1430 more = 0
1442 more = 0
1431
1443
1432 # Mark activity in the builtins
1444 # Mark activity in the builtins
1433 __builtin__.__dict__['__IPYTHON__active'] += 1
1445 __builtin__.__dict__['__IPYTHON__active'] += 1
1434
1446
1435 # exit_now is set by a call to %Exit or %Quit
1447 # exit_now is set by a call to %Exit or %Quit
1436 self.exit_now = False
1448 self.exit_now = False
1437 while not self.exit_now:
1449 while not self.exit_now:
1438 if more:
1450 if more:
1439 prompt = self.outputcache.prompt2
1451 prompt = self.outputcache.prompt2
1440 if self.autoindent:
1452 if self.autoindent:
1441 self.readline_startup_hook(self.pre_readline)
1453 self.readline_startup_hook(self.pre_readline)
1442 else:
1454 else:
1443 prompt = self.outputcache.prompt1
1455 prompt = self.outputcache.prompt1
1444 try:
1456 try:
1445 line = self.raw_input(prompt,more)
1457 line = self.raw_input(prompt,more)
1446 if self.autoindent:
1458 if self.autoindent:
1447 self.readline_startup_hook(None)
1459 self.readline_startup_hook(None)
1448 except KeyboardInterrupt:
1460 except KeyboardInterrupt:
1449 self.write('\nKeyboardInterrupt\n')
1461 self.write('\nKeyboardInterrupt\n')
1450 self.resetbuffer()
1462 self.resetbuffer()
1451 # keep cache in sync with the prompt counter:
1463 # keep cache in sync with the prompt counter:
1452 self.outputcache.prompt_count -= 1
1464 self.outputcache.prompt_count -= 1
1453
1465
1454 if self.autoindent:
1466 if self.autoindent:
1455 self.indent_current_nsp = 0
1467 self.indent_current_nsp = 0
1456 more = 0
1468 more = 0
1457 except EOFError:
1469 except EOFError:
1458 if self.autoindent:
1470 if self.autoindent:
1459 self.readline_startup_hook(None)
1471 self.readline_startup_hook(None)
1460 self.write('\n')
1472 self.write('\n')
1461 self.exit()
1473 self.exit()
1462 except bdb.BdbQuit:
1474 except bdb.BdbQuit:
1463 warn('The Python debugger has exited with a BdbQuit exception.\n'
1475 warn('The Python debugger has exited with a BdbQuit exception.\n'
1464 'Because of how pdb handles the stack, it is impossible\n'
1476 'Because of how pdb handles the stack, it is impossible\n'
1465 'for IPython to properly format this particular exception.\n'
1477 'for IPython to properly format this particular exception.\n'
1466 'IPython will resume normal operation.')
1478 'IPython will resume normal operation.')
1467 except:
1479 except:
1468 # exceptions here are VERY RARE, but they can be triggered
1480 # exceptions here are VERY RARE, but they can be triggered
1469 # asynchronously by signal handlers, for example.
1481 # asynchronously by signal handlers, for example.
1470 self.showtraceback()
1482 self.showtraceback()
1471 else:
1483 else:
1472 more = self.push(line)
1484 more = self.push(line)
1473 if (self.SyntaxTB.last_syntax_error and
1485 if (self.SyntaxTB.last_syntax_error and
1474 self.rc.autoedit_syntax):
1486 self.rc.autoedit_syntax):
1475 self.edit_syntax_error()
1487 self.edit_syntax_error()
1476
1488
1477 # We are off again...
1489 # We are off again...
1478 __builtin__.__dict__['__IPYTHON__active'] -= 1
1490 __builtin__.__dict__['__IPYTHON__active'] -= 1
1479
1491
1480 def excepthook(self, type, value, tb):
1492 def excepthook(self, type, value, tb):
1481 """One more defense for GUI apps that call sys.excepthook.
1493 """One more defense for GUI apps that call sys.excepthook.
1482
1494
1483 GUI frameworks like wxPython trap exceptions and call
1495 GUI frameworks like wxPython trap exceptions and call
1484 sys.excepthook themselves. I guess this is a feature that
1496 sys.excepthook themselves. I guess this is a feature that
1485 enables them to keep running after exceptions that would
1497 enables them to keep running after exceptions that would
1486 otherwise kill their mainloop. This is a bother for IPython
1498 otherwise kill their mainloop. This is a bother for IPython
1487 which excepts to catch all of the program exceptions with a try:
1499 which excepts to catch all of the program exceptions with a try:
1488 except: statement.
1500 except: statement.
1489
1501
1490 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1502 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1491 any app directly invokes sys.excepthook, it will look to the user like
1503 any app directly invokes sys.excepthook, it will look to the user like
1492 IPython crashed. In order to work around this, we can disable the
1504 IPython crashed. In order to work around this, we can disable the
1493 CrashHandler and replace it with this excepthook instead, which prints a
1505 CrashHandler and replace it with this excepthook instead, which prints a
1494 regular traceback using our InteractiveTB. In this fashion, apps which
1506 regular traceback using our InteractiveTB. In this fashion, apps which
1495 call sys.excepthook will generate a regular-looking exception from
1507 call sys.excepthook will generate a regular-looking exception from
1496 IPython, and the CrashHandler will only be triggered by real IPython
1508 IPython, and the CrashHandler will only be triggered by real IPython
1497 crashes.
1509 crashes.
1498
1510
1499 This hook should be used sparingly, only in places which are not likely
1511 This hook should be used sparingly, only in places which are not likely
1500 to be true IPython errors.
1512 to be true IPython errors.
1501 """
1513 """
1502
1514
1503 self.InteractiveTB(type, value, tb, tb_offset=0)
1515 self.InteractiveTB(type, value, tb, tb_offset=0)
1504 if self.InteractiveTB.call_pdb and self.has_readline:
1516 if self.InteractiveTB.call_pdb and self.has_readline:
1505 self.readline.set_completer(self.Completer.complete)
1517 self.readline.set_completer(self.Completer.complete)
1506
1518
1507 def transform_alias(self, alias,rest=''):
1519 def transform_alias(self, alias,rest=''):
1508 """ Transform alias to system command string
1520 """ Transform alias to system command string
1509
1521
1510 """
1522 """
1511 nargs,cmd = self.alias_table[alias]
1523 nargs,cmd = self.alias_table[alias]
1512 # Expand the %l special to be the user's input line
1524 # Expand the %l special to be the user's input line
1513 if cmd.find('%l') >= 0:
1525 if cmd.find('%l') >= 0:
1514 cmd = cmd.replace('%l',rest)
1526 cmd = cmd.replace('%l',rest)
1515 rest = ''
1527 rest = ''
1516 if nargs==0:
1528 if nargs==0:
1517 # Simple, argument-less aliases
1529 # Simple, argument-less aliases
1518 cmd = '%s %s' % (cmd,rest)
1530 cmd = '%s %s' % (cmd,rest)
1519 else:
1531 else:
1520 # Handle aliases with positional arguments
1532 # Handle aliases with positional arguments
1521 args = rest.split(None,nargs)
1533 args = rest.split(None,nargs)
1522 if len(args)< nargs:
1534 if len(args)< nargs:
1523 error('Alias <%s> requires %s arguments, %s given.' %
1535 error('Alias <%s> requires %s arguments, %s given.' %
1524 (alias,nargs,len(args)))
1536 (alias,nargs,len(args)))
1525 return None
1537 return None
1526 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1538 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1527 # Now call the macro, evaluating in the user's namespace
1539 # Now call the macro, evaluating in the user's namespace
1528
1540
1529 return cmd
1541 return cmd
1530
1542
1531 def call_alias(self,alias,rest=''):
1543 def call_alias(self,alias,rest=''):
1532 """Call an alias given its name and the rest of the line.
1544 """Call an alias given its name and the rest of the line.
1533
1545
1534 This is only used to provide backwards compatibility for users of
1546 This is only used to provide backwards compatibility for users of
1535 ipalias(), use of which is not recommended for anymore."""
1547 ipalias(), use of which is not recommended for anymore."""
1536
1548
1537 # Now call the macro, evaluating in the user's namespace
1549 # Now call the macro, evaluating in the user's namespace
1538 cmd = self.transform_alias(alias, rest)
1550 cmd = self.transform_alias(alias, rest)
1539 try:
1551 try:
1540 self.system(cmd)
1552 self.system(cmd)
1541 except:
1553 except:
1542 self.showtraceback()
1554 self.showtraceback()
1543
1555
1544 def indent_current_str(self):
1556 def indent_current_str(self):
1545 """return the current level of indentation as a string"""
1557 """return the current level of indentation as a string"""
1546 return self.indent_current_nsp * ' '
1558 return self.indent_current_nsp * ' '
1547
1559
1548 def autoindent_update(self,line):
1560 def autoindent_update(self,line):
1549 """Keep track of the indent level."""
1561 """Keep track of the indent level."""
1550
1562
1551 #debugx('line')
1563 #debugx('line')
1552 #debugx('self.indent_current_nsp')
1564 #debugx('self.indent_current_nsp')
1553 if self.autoindent:
1565 if self.autoindent:
1554 if line:
1566 if line:
1555 inisp = num_ini_spaces(line)
1567 inisp = num_ini_spaces(line)
1556 if inisp < self.indent_current_nsp:
1568 if inisp < self.indent_current_nsp:
1557 self.indent_current_nsp = inisp
1569 self.indent_current_nsp = inisp
1558
1570
1559 if line[-1] == ':':
1571 if line[-1] == ':':
1560 self.indent_current_nsp += 4
1572 self.indent_current_nsp += 4
1561 elif dedent_re.match(line):
1573 elif dedent_re.match(line):
1562 self.indent_current_nsp -= 4
1574 self.indent_current_nsp -= 4
1563 else:
1575 else:
1564 self.indent_current_nsp = 0
1576 self.indent_current_nsp = 0
1565
1577
1566 def runlines(self,lines):
1578 def runlines(self,lines):
1567 """Run a string of one or more lines of source.
1579 """Run a string of one or more lines of source.
1568
1580
1569 This method is capable of running a string containing multiple source
1581 This method is capable of running a string containing multiple source
1570 lines, as if they had been entered at the IPython prompt. Since it
1582 lines, as if they had been entered at the IPython prompt. Since it
1571 exposes IPython's processing machinery, the given strings can contain
1583 exposes IPython's processing machinery, the given strings can contain
1572 magic calls (%magic), special shell access (!cmd), etc."""
1584 magic calls (%magic), special shell access (!cmd), etc."""
1573
1585
1574 # We must start with a clean buffer, in case this is run from an
1586 # We must start with a clean buffer, in case this is run from an
1575 # interactive IPython session (via a magic, for example).
1587 # interactive IPython session (via a magic, for example).
1576 self.resetbuffer()
1588 self.resetbuffer()
1577 lines = lines.split('\n')
1589 lines = lines.split('\n')
1578 more = 0
1590 more = 0
1579 for line in lines:
1591 for line in lines:
1580 # skip blank lines so we don't mess up the prompt counter, but do
1592 # skip blank lines so we don't mess up the prompt counter, but do
1581 # NOT skip even a blank line if we are in a code block (more is
1593 # NOT skip even a blank line if we are in a code block (more is
1582 # true)
1594 # true)
1583 if line or more:
1595 if line or more:
1584 more = self.push(self.prefilter(line,more))
1596 more = self.push(self.prefilter(line,more))
1585 # IPython's runsource returns None if there was an error
1597 # IPython's runsource returns None if there was an error
1586 # compiling the code. This allows us to stop processing right
1598 # compiling the code. This allows us to stop processing right
1587 # away, so the user gets the error message at the right place.
1599 # away, so the user gets the error message at the right place.
1588 if more is None:
1600 if more is None:
1589 break
1601 break
1590 # final newline in case the input didn't have it, so that the code
1602 # final newline in case the input didn't have it, so that the code
1591 # actually does get executed
1603 # actually does get executed
1592 if more:
1604 if more:
1593 self.push('\n')
1605 self.push('\n')
1594
1606
1595 def runsource(self, source, filename='<input>', symbol='single'):
1607 def runsource(self, source, filename='<input>', symbol='single'):
1596 """Compile and run some source in the interpreter.
1608 """Compile and run some source in the interpreter.
1597
1609
1598 Arguments are as for compile_command().
1610 Arguments are as for compile_command().
1599
1611
1600 One several things can happen:
1612 One several things can happen:
1601
1613
1602 1) The input is incorrect; compile_command() raised an
1614 1) The input is incorrect; compile_command() raised an
1603 exception (SyntaxError or OverflowError). A syntax traceback
1615 exception (SyntaxError or OverflowError). A syntax traceback
1604 will be printed by calling the showsyntaxerror() method.
1616 will be printed by calling the showsyntaxerror() method.
1605
1617
1606 2) The input is incomplete, and more input is required;
1618 2) The input is incomplete, and more input is required;
1607 compile_command() returned None. Nothing happens.
1619 compile_command() returned None. Nothing happens.
1608
1620
1609 3) The input is complete; compile_command() returned a code
1621 3) The input is complete; compile_command() returned a code
1610 object. The code is executed by calling self.runcode() (which
1622 object. The code is executed by calling self.runcode() (which
1611 also handles run-time exceptions, except for SystemExit).
1623 also handles run-time exceptions, except for SystemExit).
1612
1624
1613 The return value is:
1625 The return value is:
1614
1626
1615 - True in case 2
1627 - True in case 2
1616
1628
1617 - False in the other cases, unless an exception is raised, where
1629 - False in the other cases, unless an exception is raised, where
1618 None is returned instead. This can be used by external callers to
1630 None is returned instead. This can be used by external callers to
1619 know whether to continue feeding input or not.
1631 know whether to continue feeding input or not.
1620
1632
1621 The return value can be used to decide whether to use sys.ps1 or
1633 The return value can be used to decide whether to use sys.ps1 or
1622 sys.ps2 to prompt the next line."""
1634 sys.ps2 to prompt the next line."""
1623
1635
1624 try:
1636 try:
1625 code = self.compile(source,filename,symbol)
1637 code = self.compile(source,filename,symbol)
1626 except (OverflowError, SyntaxError, ValueError):
1638 except (OverflowError, SyntaxError, ValueError):
1627 # Case 1
1639 # Case 1
1628 self.showsyntaxerror(filename)
1640 self.showsyntaxerror(filename)
1629 return None
1641 return None
1630
1642
1631 if code is None:
1643 if code is None:
1632 # Case 2
1644 # Case 2
1633 return True
1645 return True
1634
1646
1635 # Case 3
1647 # Case 3
1636 # We store the code object so that threaded shells and
1648 # We store the code object so that threaded shells and
1637 # custom exception handlers can access all this info if needed.
1649 # custom exception handlers can access all this info if needed.
1638 # The source corresponding to this can be obtained from the
1650 # The source corresponding to this can be obtained from the
1639 # buffer attribute as '\n'.join(self.buffer).
1651 # buffer attribute as '\n'.join(self.buffer).
1640 self.code_to_run = code
1652 self.code_to_run = code
1641 # now actually execute the code object
1653 # now actually execute the code object
1642 if self.runcode(code) == 0:
1654 if self.runcode(code) == 0:
1643 return False
1655 return False
1644 else:
1656 else:
1645 return None
1657 return None
1646
1658
1647 def runcode(self,code_obj):
1659 def runcode(self,code_obj):
1648 """Execute a code object.
1660 """Execute a code object.
1649
1661
1650 When an exception occurs, self.showtraceback() is called to display a
1662 When an exception occurs, self.showtraceback() is called to display a
1651 traceback.
1663 traceback.
1652
1664
1653 Return value: a flag indicating whether the code to be run completed
1665 Return value: a flag indicating whether the code to be run completed
1654 successfully:
1666 successfully:
1655
1667
1656 - 0: successful execution.
1668 - 0: successful execution.
1657 - 1: an error occurred.
1669 - 1: an error occurred.
1658 """
1670 """
1659
1671
1660 # Set our own excepthook in case the user code tries to call it
1672 # Set our own excepthook in case the user code tries to call it
1661 # directly, so that the IPython crash handler doesn't get triggered
1673 # directly, so that the IPython crash handler doesn't get triggered
1662 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1674 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1663
1675
1664 # we save the original sys.excepthook in the instance, in case config
1676 # we save the original sys.excepthook in the instance, in case config
1665 # code (such as magics) needs access to it.
1677 # code (such as magics) needs access to it.
1666 self.sys_excepthook = old_excepthook
1678 self.sys_excepthook = old_excepthook
1667 outflag = 1 # happens in more places, so it's easier as default
1679 outflag = 1 # happens in more places, so it's easier as default
1668 try:
1680 try:
1669 try:
1681 try:
1670 # Embedded instances require separate global/local namespaces
1682 # Embedded instances require separate global/local namespaces
1671 # so they can see both the surrounding (local) namespace and
1683 # so they can see both the surrounding (local) namespace and
1672 # the module-level globals when called inside another function.
1684 # the module-level globals when called inside another function.
1673 if self.embedded:
1685 if self.embedded:
1674 exec code_obj in self.user_global_ns, self.user_ns
1686 exec code_obj in self.user_global_ns, self.user_ns
1675 # Normal (non-embedded) instances should only have a single
1687 # Normal (non-embedded) instances should only have a single
1676 # namespace for user code execution, otherwise functions won't
1688 # namespace for user code execution, otherwise functions won't
1677 # see interactive top-level globals.
1689 # see interactive top-level globals.
1678 else:
1690 else:
1679 exec code_obj in self.user_ns
1691 exec code_obj in self.user_ns
1680 finally:
1692 finally:
1681 # Reset our crash handler in place
1693 # Reset our crash handler in place
1682 sys.excepthook = old_excepthook
1694 sys.excepthook = old_excepthook
1683 except SystemExit:
1695 except SystemExit:
1684 self.resetbuffer()
1696 self.resetbuffer()
1685 self.showtraceback()
1697 self.showtraceback()
1686 warn("Type exit or quit to exit IPython "
1698 warn("Type exit or quit to exit IPython "
1687 "(%Exit or %Quit do so unconditionally).",level=1)
1699 "(%Exit or %Quit do so unconditionally).",level=1)
1688 except self.custom_exceptions:
1700 except self.custom_exceptions:
1689 etype,value,tb = sys.exc_info()
1701 etype,value,tb = sys.exc_info()
1690 self.CustomTB(etype,value,tb)
1702 self.CustomTB(etype,value,tb)
1691 except:
1703 except:
1692 self.showtraceback()
1704 self.showtraceback()
1693 else:
1705 else:
1694 outflag = 0
1706 outflag = 0
1695 if softspace(sys.stdout, 0):
1707 if softspace(sys.stdout, 0):
1696 print
1708 print
1697 # Flush out code object which has been run (and source)
1709 # Flush out code object which has been run (and source)
1698 self.code_to_run = None
1710 self.code_to_run = None
1699 return outflag
1711 return outflag
1700
1712
1701 def push(self, line):
1713 def push(self, line):
1702 """Push a line to the interpreter.
1714 """Push a line to the interpreter.
1703
1715
1704 The line should not have a trailing newline; it may have
1716 The line should not have a trailing newline; it may have
1705 internal newlines. The line is appended to a buffer and the
1717 internal newlines. The line is appended to a buffer and the
1706 interpreter's runsource() method is called with the
1718 interpreter's runsource() method is called with the
1707 concatenated contents of the buffer as source. If this
1719 concatenated contents of the buffer as source. If this
1708 indicates that the command was executed or invalid, the buffer
1720 indicates that the command was executed or invalid, the buffer
1709 is reset; otherwise, the command is incomplete, and the buffer
1721 is reset; otherwise, the command is incomplete, and the buffer
1710 is left as it was after the line was appended. The return
1722 is left as it was after the line was appended. The return
1711 value is 1 if more input is required, 0 if the line was dealt
1723 value is 1 if more input is required, 0 if the line was dealt
1712 with in some way (this is the same as runsource()).
1724 with in some way (this is the same as runsource()).
1713 """
1725 """
1714
1726
1715 # autoindent management should be done here, and not in the
1727 # autoindent management should be done here, and not in the
1716 # interactive loop, since that one is only seen by keyboard input. We
1728 # interactive loop, since that one is only seen by keyboard input. We
1717 # need this done correctly even for code run via runlines (which uses
1729 # need this done correctly even for code run via runlines (which uses
1718 # push).
1730 # push).
1719
1731
1720 #print 'push line: <%s>' % line # dbg
1732 #print 'push line: <%s>' % line # dbg
1721 self.autoindent_update(line)
1733 self.autoindent_update(line)
1722
1734
1723 self.buffer.append(line)
1735 self.buffer.append(line)
1724 more = self.runsource('\n'.join(self.buffer), self.filename)
1736 more = self.runsource('\n'.join(self.buffer), self.filename)
1725 if not more:
1737 if not more:
1726 self.resetbuffer()
1738 self.resetbuffer()
1727 return more
1739 return more
1728
1740
1729 def resetbuffer(self):
1741 def resetbuffer(self):
1730 """Reset the input buffer."""
1742 """Reset the input buffer."""
1731 self.buffer[:] = []
1743 self.buffer[:] = []
1732
1744
1733 def raw_input(self,prompt='',continue_prompt=False):
1745 def raw_input(self,prompt='',continue_prompt=False):
1734 """Write a prompt and read a line.
1746 """Write a prompt and read a line.
1735
1747
1736 The returned line does not include the trailing newline.
1748 The returned line does not include the trailing newline.
1737 When the user enters the EOF key sequence, EOFError is raised.
1749 When the user enters the EOF key sequence, EOFError is raised.
1738
1750
1739 Optional inputs:
1751 Optional inputs:
1740
1752
1741 - prompt(''): a string to be printed to prompt the user.
1753 - prompt(''): a string to be printed to prompt the user.
1742
1754
1743 - continue_prompt(False): whether this line is the first one or a
1755 - continue_prompt(False): whether this line is the first one or a
1744 continuation in a sequence of inputs.
1756 continuation in a sequence of inputs.
1745 """
1757 """
1746
1758
1747 line = raw_input_original(prompt)
1759 line = raw_input_original(prompt)
1748
1760
1749 # Try to be reasonably smart about not re-indenting pasted input more
1761 # Try to be reasonably smart about not re-indenting pasted input more
1750 # than necessary. We do this by trimming out the auto-indent initial
1762 # than necessary. We do this by trimming out the auto-indent initial
1751 # spaces, if the user's actual input started itself with whitespace.
1763 # spaces, if the user's actual input started itself with whitespace.
1752 #debugx('self.buffer[-1]')
1764 #debugx('self.buffer[-1]')
1753
1765
1754 if self.autoindent:
1766 if self.autoindent:
1755 if num_ini_spaces(line) > self.indent_current_nsp:
1767 if num_ini_spaces(line) > self.indent_current_nsp:
1756 line = line[self.indent_current_nsp:]
1768 line = line[self.indent_current_nsp:]
1757 self.indent_current_nsp = 0
1769 self.indent_current_nsp = 0
1758
1770
1759 # store the unfiltered input before the user has any chance to modify
1771 # store the unfiltered input before the user has any chance to modify
1760 # it.
1772 # it.
1761 if line.strip():
1773 if line.strip():
1762 if continue_prompt:
1774 if continue_prompt:
1763 self.input_hist_raw[-1] += '%s\n' % line
1775 self.input_hist_raw[-1] += '%s\n' % line
1764 else:
1776 else:
1765 self.input_hist_raw.append('%s\n' % line)
1777 self.input_hist_raw.append('%s\n' % line)
1766
1778
1767 lineout = self.prefilter(line,continue_prompt)
1779 lineout = self.prefilter(line,continue_prompt)
1768 return lineout
1780 return lineout
1769
1781
1770 def split_user_input(self,line):
1782 def split_user_input(self,line):
1771 """Split user input into pre-char, function part and rest."""
1783 """Split user input into pre-char, function part and rest."""
1772
1784
1773 lsplit = self.line_split.match(line)
1785 lsplit = self.line_split.match(line)
1774 if lsplit is None: # no regexp match returns None
1786 if lsplit is None: # no regexp match returns None
1775 try:
1787 try:
1776 iFun,theRest = line.split(None,1)
1788 iFun,theRest = line.split(None,1)
1777 except ValueError:
1789 except ValueError:
1778 iFun,theRest = line,''
1790 iFun,theRest = line,''
1779 pre = re.match('^(\s*)(.*)',line).groups()[0]
1791 pre = re.match('^(\s*)(.*)',line).groups()[0]
1780 else:
1792 else:
1781 pre,iFun,theRest = lsplit.groups()
1793 pre,iFun,theRest = lsplit.groups()
1782
1794
1783 #print 'line:<%s>' % line # dbg
1795 #print 'line:<%s>' % line # dbg
1784 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1796 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1785 return pre,iFun.strip(),theRest
1797 return pre,iFun.strip(),theRest
1786
1798
1787 def _prefilter(self, line, continue_prompt):
1799 def _prefilter(self, line, continue_prompt):
1788 """Calls different preprocessors, depending on the form of line."""
1800 """Calls different preprocessors, depending on the form of line."""
1789
1801
1790 # All handlers *must* return a value, even if it's blank ('').
1802 # All handlers *must* return a value, even if it's blank ('').
1791
1803
1792 # Lines are NOT logged here. Handlers should process the line as
1804 # Lines are NOT logged here. Handlers should process the line as
1793 # needed, update the cache AND log it (so that the input cache array
1805 # needed, update the cache AND log it (so that the input cache array
1794 # stays synced).
1806 # stays synced).
1795
1807
1796 # This function is _very_ delicate, and since it's also the one which
1808 # This function is _very_ delicate, and since it's also the one which
1797 # determines IPython's response to user input, it must be as efficient
1809 # determines IPython's response to user input, it must be as efficient
1798 # as possible. For this reason it has _many_ returns in it, trying
1810 # as possible. For this reason it has _many_ returns in it, trying
1799 # always to exit as quickly as it can figure out what it needs to do.
1811 # always to exit as quickly as it can figure out what it needs to do.
1800
1812
1801 # This function is the main responsible for maintaining IPython's
1813 # This function is the main responsible for maintaining IPython's
1802 # behavior respectful of Python's semantics. So be _very_ careful if
1814 # behavior respectful of Python's semantics. So be _very_ careful if
1803 # making changes to anything here.
1815 # making changes to anything here.
1804
1816
1805 #.....................................................................
1817 #.....................................................................
1806 # Code begins
1818 # Code begins
1807
1819
1808 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1820 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1809
1821
1810 # save the line away in case we crash, so the post-mortem handler can
1822 # save the line away in case we crash, so the post-mortem handler can
1811 # record it
1823 # record it
1812 self._last_input_line = line
1824 self._last_input_line = line
1813
1825
1814 #print '***line: <%s>' % line # dbg
1826 #print '***line: <%s>' % line # dbg
1815
1827
1816 # the input history needs to track even empty lines
1828 # the input history needs to track even empty lines
1817 stripped = line.strip()
1829 stripped = line.strip()
1818
1830
1819 if not stripped:
1831 if not stripped:
1820 if not continue_prompt:
1832 if not continue_prompt:
1821 self.outputcache.prompt_count -= 1
1833 self.outputcache.prompt_count -= 1
1822 return self.handle_normal(line,continue_prompt)
1834 return self.handle_normal(line,continue_prompt)
1823 #return self.handle_normal('',continue_prompt)
1835 #return self.handle_normal('',continue_prompt)
1824
1836
1825 # print '***cont',continue_prompt # dbg
1837 # print '***cont',continue_prompt # dbg
1826 # special handlers are only allowed for single line statements
1838 # special handlers are only allowed for single line statements
1827 if continue_prompt and not self.rc.multi_line_specials:
1839 if continue_prompt and not self.rc.multi_line_specials:
1828 return self.handle_normal(line,continue_prompt)
1840 return self.handle_normal(line,continue_prompt)
1829
1841
1830
1842
1831 # For the rest, we need the structure of the input
1843 # For the rest, we need the structure of the input
1832 pre,iFun,theRest = self.split_user_input(line)
1844 pre,iFun,theRest = self.split_user_input(line)
1833
1845
1834 # See whether any pre-existing handler can take care of it
1846 # See whether any pre-existing handler can take care of it
1835
1847
1836 rewritten = self.hooks.input_prefilter(stripped)
1848 rewritten = self.hooks.input_prefilter(stripped)
1837 if rewritten != stripped: # ok, some prefilter did something
1849 if rewritten != stripped: # ok, some prefilter did something
1838 rewritten = pre + rewritten # add indentation
1850 rewritten = pre + rewritten # add indentation
1839 return self.handle_normal(rewritten)
1851 return self.handle_normal(rewritten)
1840
1852
1841
1853
1842
1854
1843
1855
1844 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1856 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1845
1857
1846 # First check for explicit escapes in the last/first character
1858 # First check for explicit escapes in the last/first character
1847 handler = None
1859 handler = None
1848 if line[-1] == self.ESC_HELP:
1860 if line[-1] == self.ESC_HELP:
1849 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1861 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1850 if handler is None:
1862 if handler is None:
1851 # look at the first character of iFun, NOT of line, so we skip
1863 # look at the first character of iFun, NOT of line, so we skip
1852 # leading whitespace in multiline input
1864 # leading whitespace in multiline input
1853 handler = self.esc_handlers.get(iFun[0:1])
1865 handler = self.esc_handlers.get(iFun[0:1])
1854 if handler is not None:
1866 if handler is not None:
1855 return handler(line,continue_prompt,pre,iFun,theRest)
1867 return handler(line,continue_prompt,pre,iFun,theRest)
1856 # Emacs ipython-mode tags certain input lines
1868 # Emacs ipython-mode tags certain input lines
1857 if line.endswith('# PYTHON-MODE'):
1869 if line.endswith('# PYTHON-MODE'):
1858 return self.handle_emacs(line,continue_prompt)
1870 return self.handle_emacs(line,continue_prompt)
1859
1871
1860 # Next, check if we can automatically execute this thing
1872 # Next, check if we can automatically execute this thing
1861
1873
1862 # Allow ! in multi-line statements if multi_line_specials is on:
1874 # Allow ! in multi-line statements if multi_line_specials is on:
1863 if continue_prompt and self.rc.multi_line_specials and \
1875 if continue_prompt and self.rc.multi_line_specials and \
1864 iFun.startswith(self.ESC_SHELL):
1876 iFun.startswith(self.ESC_SHELL):
1865 return self.handle_shell_escape(line,continue_prompt,
1877 return self.handle_shell_escape(line,continue_prompt,
1866 pre=pre,iFun=iFun,
1878 pre=pre,iFun=iFun,
1867 theRest=theRest)
1879 theRest=theRest)
1868
1880
1869 # Let's try to find if the input line is a magic fn
1881 # Let's try to find if the input line is a magic fn
1870 oinfo = None
1882 oinfo = None
1871 if hasattr(self,'magic_'+iFun):
1883 if hasattr(self,'magic_'+iFun):
1872 # WARNING: _ofind uses getattr(), so it can consume generators and
1884 # WARNING: _ofind uses getattr(), so it can consume generators and
1873 # cause other side effects.
1885 # cause other side effects.
1874 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1886 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1875 if oinfo['ismagic']:
1887 if oinfo['ismagic']:
1876 # Be careful not to call magics when a variable assignment is
1888 # Be careful not to call magics when a variable assignment is
1877 # being made (ls='hi', for example)
1889 # being made (ls='hi', for example)
1878 if self.rc.automagic and \
1890 if self.rc.automagic and \
1879 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1891 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1880 (self.rc.multi_line_specials or not continue_prompt):
1892 (self.rc.multi_line_specials or not continue_prompt):
1881 return self.handle_magic(line,continue_prompt,
1893 return self.handle_magic(line,continue_prompt,
1882 pre,iFun,theRest)
1894 pre,iFun,theRest)
1883 else:
1895 else:
1884 return self.handle_normal(line,continue_prompt)
1896 return self.handle_normal(line,continue_prompt)
1885
1897
1886 # If the rest of the line begins with an (in)equality, assginment or
1898 # If the rest of the line begins with an (in)equality, assginment or
1887 # function call, we should not call _ofind but simply execute it.
1899 # function call, we should not call _ofind but simply execute it.
1888 # This avoids spurious geattr() accesses on objects upon assignment.
1900 # This avoids spurious geattr() accesses on objects upon assignment.
1889 #
1901 #
1890 # It also allows users to assign to either alias or magic names true
1902 # It also allows users to assign to either alias or magic names true
1891 # python variables (the magic/alias systems always take second seat to
1903 # python variables (the magic/alias systems always take second seat to
1892 # true python code).
1904 # true python code).
1893 if theRest and theRest[0] in '!=()':
1905 if theRest and theRest[0] in '!=()':
1894 return self.handle_normal(line,continue_prompt)
1906 return self.handle_normal(line,continue_prompt)
1895
1907
1896 if oinfo is None:
1908 if oinfo is None:
1897 # let's try to ensure that _oinfo is ONLY called when autocall is
1909 # let's try to ensure that _oinfo is ONLY called when autocall is
1898 # on. Since it has inevitable potential side effects, at least
1910 # on. Since it has inevitable potential side effects, at least
1899 # having autocall off should be a guarantee to the user that no
1911 # having autocall off should be a guarantee to the user that no
1900 # weird things will happen.
1912 # weird things will happen.
1901
1913
1902 if self.rc.autocall:
1914 if self.rc.autocall:
1903 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1915 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1904 else:
1916 else:
1905 # in this case, all that's left is either an alias or
1917 # in this case, all that's left is either an alias or
1906 # processing the line normally.
1918 # processing the line normally.
1907 if iFun in self.alias_table:
1919 if iFun in self.alias_table:
1908 return self.handle_alias(line,continue_prompt,
1920 return self.handle_alias(line,continue_prompt,
1909 pre,iFun,theRest)
1921 pre,iFun,theRest)
1910
1922
1911 else:
1923 else:
1912 return self.handle_normal(line,continue_prompt)
1924 return self.handle_normal(line,continue_prompt)
1913
1925
1914 if not oinfo['found']:
1926 if not oinfo['found']:
1915 return self.handle_normal(line,continue_prompt)
1927 return self.handle_normal(line,continue_prompt)
1916 else:
1928 else:
1917 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1929 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1918 if oinfo['isalias']:
1930 if oinfo['isalias']:
1919 return self.handle_alias(line,continue_prompt,
1931 return self.handle_alias(line,continue_prompt,
1920 pre,iFun,theRest)
1932 pre,iFun,theRest)
1921
1933
1922 if (self.rc.autocall
1934 if (self.rc.autocall
1923 and
1935 and
1924 (
1936 (
1925 #only consider exclusion re if not "," or ";" autoquoting
1937 #only consider exclusion re if not "," or ";" autoquoting
1926 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
1938 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
1927 or pre == self.ESC_PAREN) or
1939 or pre == self.ESC_PAREN) or
1928 (not self.re_exclude_auto.match(theRest)))
1940 (not self.re_exclude_auto.match(theRest)))
1929 and
1941 and
1930 self.re_fun_name.match(iFun) and
1942 self.re_fun_name.match(iFun) and
1931 callable(oinfo['obj'])) :
1943 callable(oinfo['obj'])) :
1932 #print 'going auto' # dbg
1944 #print 'going auto' # dbg
1933 return self.handle_auto(line,continue_prompt,
1945 return self.handle_auto(line,continue_prompt,
1934 pre,iFun,theRest,oinfo['obj'])
1946 pre,iFun,theRest,oinfo['obj'])
1935 else:
1947 else:
1936 #print 'was callable?', callable(oinfo['obj']) # dbg
1948 #print 'was callable?', callable(oinfo['obj']) # dbg
1937 return self.handle_normal(line,continue_prompt)
1949 return self.handle_normal(line,continue_prompt)
1938
1950
1939 # If we get here, we have a normal Python line. Log and return.
1951 # If we get here, we have a normal Python line. Log and return.
1940 return self.handle_normal(line,continue_prompt)
1952 return self.handle_normal(line,continue_prompt)
1941
1953
1942 def _prefilter_dumb(self, line, continue_prompt):
1954 def _prefilter_dumb(self, line, continue_prompt):
1943 """simple prefilter function, for debugging"""
1955 """simple prefilter function, for debugging"""
1944 return self.handle_normal(line,continue_prompt)
1956 return self.handle_normal(line,continue_prompt)
1945
1957
1946 # Set the default prefilter() function (this can be user-overridden)
1958 # Set the default prefilter() function (this can be user-overridden)
1947 prefilter = _prefilter
1959 prefilter = _prefilter
1948
1960
1949 def handle_normal(self,line,continue_prompt=None,
1961 def handle_normal(self,line,continue_prompt=None,
1950 pre=None,iFun=None,theRest=None):
1962 pre=None,iFun=None,theRest=None):
1951 """Handle normal input lines. Use as a template for handlers."""
1963 """Handle normal input lines. Use as a template for handlers."""
1952
1964
1953 # With autoindent on, we need some way to exit the input loop, and I
1965 # With autoindent on, we need some way to exit the input loop, and I
1954 # don't want to force the user to have to backspace all the way to
1966 # don't want to force the user to have to backspace all the way to
1955 # clear the line. The rule will be in this case, that either two
1967 # clear the line. The rule will be in this case, that either two
1956 # lines of pure whitespace in a row, or a line of pure whitespace but
1968 # lines of pure whitespace in a row, or a line of pure whitespace but
1957 # of a size different to the indent level, will exit the input loop.
1969 # of a size different to the indent level, will exit the input loop.
1958
1970
1959 if (continue_prompt and self.autoindent and line.isspace() and
1971 if (continue_prompt and self.autoindent and line.isspace() and
1960 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
1972 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
1961 (self.buffer[-1]).isspace() )):
1973 (self.buffer[-1]).isspace() )):
1962 line = ''
1974 line = ''
1963
1975
1964 self.log(line,continue_prompt)
1976 self.log(line,continue_prompt)
1965 return line
1977 return line
1966
1978
1967 def handle_alias(self,line,continue_prompt=None,
1979 def handle_alias(self,line,continue_prompt=None,
1968 pre=None,iFun=None,theRest=None):
1980 pre=None,iFun=None,theRest=None):
1969 """Handle alias input lines. """
1981 """Handle alias input lines. """
1970
1982
1971 # pre is needed, because it carries the leading whitespace. Otherwise
1983 # pre is needed, because it carries the leading whitespace. Otherwise
1972 # aliases won't work in indented sections.
1984 # aliases won't work in indented sections.
1973 transformed = self.transform_alias(iFun, theRest)
1985 transformed = self.transform_alias(iFun, theRest)
1974 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
1986 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
1975 self.log(line_out,continue_prompt)
1987 self.log(line_out,continue_prompt)
1976 return line_out
1988 return line_out
1977
1989
1978 def handle_shell_escape(self, line, continue_prompt=None,
1990 def handle_shell_escape(self, line, continue_prompt=None,
1979 pre=None,iFun=None,theRest=None):
1991 pre=None,iFun=None,theRest=None):
1980 """Execute the line in a shell, empty return value"""
1992 """Execute the line in a shell, empty return value"""
1981
1993
1982 #print 'line in :', `line` # dbg
1994 #print 'line in :', `line` # dbg
1983 # Example of a special handler. Others follow a similar pattern.
1995 # Example of a special handler. Others follow a similar pattern.
1984 if line.lstrip().startswith('!!'):
1996 if line.lstrip().startswith('!!'):
1985 # rewrite iFun/theRest to properly hold the call to %sx and
1997 # rewrite iFun/theRest to properly hold the call to %sx and
1986 # the actual command to be executed, so handle_magic can work
1998 # the actual command to be executed, so handle_magic can work
1987 # correctly
1999 # correctly
1988 theRest = '%s %s' % (iFun[2:],theRest)
2000 theRest = '%s %s' % (iFun[2:],theRest)
1989 iFun = 'sx'
2001 iFun = 'sx'
1990 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2002 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
1991 line.lstrip()[2:]),
2003 line.lstrip()[2:]),
1992 continue_prompt,pre,iFun,theRest)
2004 continue_prompt,pre,iFun,theRest)
1993 else:
2005 else:
1994 cmd=line.lstrip().lstrip('!')
2006 cmd=line.lstrip().lstrip('!')
1995 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2007 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
1996 # update cache/log and return
2008 # update cache/log and return
1997 self.log(line_out,continue_prompt)
2009 self.log(line_out,continue_prompt)
1998 return line_out
2010 return line_out
1999
2011
2000 def handle_magic(self, line, continue_prompt=None,
2012 def handle_magic(self, line, continue_prompt=None,
2001 pre=None,iFun=None,theRest=None):
2013 pre=None,iFun=None,theRest=None):
2002 """Execute magic functions."""
2014 """Execute magic functions."""
2003
2015
2004
2016
2005 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2017 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2006 self.log(cmd,continue_prompt)
2018 self.log(cmd,continue_prompt)
2007 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2019 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2008 return cmd
2020 return cmd
2009
2021
2010 def handle_auto(self, line, continue_prompt=None,
2022 def handle_auto(self, line, continue_prompt=None,
2011 pre=None,iFun=None,theRest=None,obj=None):
2023 pre=None,iFun=None,theRest=None,obj=None):
2012 """Hande lines which can be auto-executed, quoting if requested."""
2024 """Hande lines which can be auto-executed, quoting if requested."""
2013
2025
2014 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2026 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2015
2027
2016 # This should only be active for single-line input!
2028 # This should only be active for single-line input!
2017 if continue_prompt:
2029 if continue_prompt:
2018 self.log(line,continue_prompt)
2030 self.log(line,continue_prompt)
2019 return line
2031 return line
2020
2032
2021 auto_rewrite = True
2033 auto_rewrite = True
2022
2034
2023 if pre == self.ESC_QUOTE:
2035 if pre == self.ESC_QUOTE:
2024 # Auto-quote splitting on whitespace
2036 # Auto-quote splitting on whitespace
2025 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2037 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2026 elif pre == self.ESC_QUOTE2:
2038 elif pre == self.ESC_QUOTE2:
2027 # Auto-quote whole string
2039 # Auto-quote whole string
2028 newcmd = '%s("%s")' % (iFun,theRest)
2040 newcmd = '%s("%s")' % (iFun,theRest)
2029 elif pre == self.ESC_PAREN:
2041 elif pre == self.ESC_PAREN:
2030 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2042 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2031 else:
2043 else:
2032 # Auto-paren.
2044 # Auto-paren.
2033 # We only apply it to argument-less calls if the autocall
2045 # We only apply it to argument-less calls if the autocall
2034 # parameter is set to 2. We only need to check that autocall is <
2046 # parameter is set to 2. We only need to check that autocall is <
2035 # 2, since this function isn't called unless it's at least 1.
2047 # 2, since this function isn't called unless it's at least 1.
2036 if not theRest and (self.rc.autocall < 2):
2048 if not theRest and (self.rc.autocall < 2):
2037 newcmd = '%s %s' % (iFun,theRest)
2049 newcmd = '%s %s' % (iFun,theRest)
2038 auto_rewrite = False
2050 auto_rewrite = False
2039 else:
2051 else:
2040 if theRest.startswith('['):
2052 if theRest.startswith('['):
2041 if hasattr(obj,'__getitem__'):
2053 if hasattr(obj,'__getitem__'):
2042 # Don't autocall in this case: item access for an object
2054 # Don't autocall in this case: item access for an object
2043 # which is BOTH callable and implements __getitem__.
2055 # which is BOTH callable and implements __getitem__.
2044 newcmd = '%s %s' % (iFun,theRest)
2056 newcmd = '%s %s' % (iFun,theRest)
2045 auto_rewrite = False
2057 auto_rewrite = False
2046 else:
2058 else:
2047 # if the object doesn't support [] access, go ahead and
2059 # if the object doesn't support [] access, go ahead and
2048 # autocall
2060 # autocall
2049 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2061 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2050 elif theRest.endswith(';'):
2062 elif theRest.endswith(';'):
2051 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2063 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2052 else:
2064 else:
2053 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2065 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2054
2066
2055 if auto_rewrite:
2067 if auto_rewrite:
2056 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2068 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2057 # log what is now valid Python, not the actual user input (without the
2069 # log what is now valid Python, not the actual user input (without the
2058 # final newline)
2070 # final newline)
2059 self.log(newcmd,continue_prompt)
2071 self.log(newcmd,continue_prompt)
2060 return newcmd
2072 return newcmd
2061
2073
2062 def handle_help(self, line, continue_prompt=None,
2074 def handle_help(self, line, continue_prompt=None,
2063 pre=None,iFun=None,theRest=None):
2075 pre=None,iFun=None,theRest=None):
2064 """Try to get some help for the object.
2076 """Try to get some help for the object.
2065
2077
2066 obj? or ?obj -> basic information.
2078 obj? or ?obj -> basic information.
2067 obj?? or ??obj -> more details.
2079 obj?? or ??obj -> more details.
2068 """
2080 """
2069
2081
2070 # We need to make sure that we don't process lines which would be
2082 # We need to make sure that we don't process lines which would be
2071 # otherwise valid python, such as "x=1 # what?"
2083 # otherwise valid python, such as "x=1 # what?"
2072 try:
2084 try:
2073 codeop.compile_command(line)
2085 codeop.compile_command(line)
2074 except SyntaxError:
2086 except SyntaxError:
2075 # We should only handle as help stuff which is NOT valid syntax
2087 # We should only handle as help stuff which is NOT valid syntax
2076 if line[0]==self.ESC_HELP:
2088 if line[0]==self.ESC_HELP:
2077 line = line[1:]
2089 line = line[1:]
2078 elif line[-1]==self.ESC_HELP:
2090 elif line[-1]==self.ESC_HELP:
2079 line = line[:-1]
2091 line = line[:-1]
2080 self.log('#?'+line)
2092 self.log('#?'+line)
2081 if line:
2093 if line:
2082 self.magic_pinfo(line)
2094 self.magic_pinfo(line)
2083 else:
2095 else:
2084 page(self.usage,screen_lines=self.rc.screen_length)
2096 page(self.usage,screen_lines=self.rc.screen_length)
2085 return '' # Empty string is needed here!
2097 return '' # Empty string is needed here!
2086 except:
2098 except:
2087 # Pass any other exceptions through to the normal handler
2099 # Pass any other exceptions through to the normal handler
2088 return self.handle_normal(line,continue_prompt)
2100 return self.handle_normal(line,continue_prompt)
2089 else:
2101 else:
2090 # If the code compiles ok, we should handle it normally
2102 # If the code compiles ok, we should handle it normally
2091 return self.handle_normal(line,continue_prompt)
2103 return self.handle_normal(line,continue_prompt)
2092
2104
2093 def getapi(self):
2105 def getapi(self):
2094 """ Get an IPApi object for this shell instance
2106 """ Get an IPApi object for this shell instance
2095
2107
2096 Getting an IPApi object is always preferable to accessing the shell
2108 Getting an IPApi object is always preferable to accessing the shell
2097 directly, but this holds true especially for extensions.
2109 directly, but this holds true especially for extensions.
2098
2110
2099 It should always be possible to implement an extension with IPApi
2111 It should always be possible to implement an extension with IPApi
2100 alone. If not, contact maintainer to request an addition.
2112 alone. If not, contact maintainer to request an addition.
2101
2113
2102 """
2114 """
2103 return self.api
2115 return self.api
2104
2116
2105 def handle_emacs(self,line,continue_prompt=None,
2117 def handle_emacs(self,line,continue_prompt=None,
2106 pre=None,iFun=None,theRest=None):
2118 pre=None,iFun=None,theRest=None):
2107 """Handle input lines marked by python-mode."""
2119 """Handle input lines marked by python-mode."""
2108
2120
2109 # Currently, nothing is done. Later more functionality can be added
2121 # Currently, nothing is done. Later more functionality can be added
2110 # here if needed.
2122 # here if needed.
2111
2123
2112 # The input cache shouldn't be updated
2124 # The input cache shouldn't be updated
2113
2125
2114 return line
2126 return line
2115
2127
2116 def mktempfile(self,data=None):
2128 def mktempfile(self,data=None):
2117 """Make a new tempfile and return its filename.
2129 """Make a new tempfile and return its filename.
2118
2130
2119 This makes a call to tempfile.mktemp, but it registers the created
2131 This makes a call to tempfile.mktemp, but it registers the created
2120 filename internally so ipython cleans it up at exit time.
2132 filename internally so ipython cleans it up at exit time.
2121
2133
2122 Optional inputs:
2134 Optional inputs:
2123
2135
2124 - data(None): if data is given, it gets written out to the temp file
2136 - data(None): if data is given, it gets written out to the temp file
2125 immediately, and the file is closed again."""
2137 immediately, and the file is closed again."""
2126
2138
2127 filename = tempfile.mktemp('.py','ipython_edit_')
2139 filename = tempfile.mktemp('.py','ipython_edit_')
2128 self.tempfiles.append(filename)
2140 self.tempfiles.append(filename)
2129
2141
2130 if data:
2142 if data:
2131 tmp_file = open(filename,'w')
2143 tmp_file = open(filename,'w')
2132 tmp_file.write(data)
2144 tmp_file.write(data)
2133 tmp_file.close()
2145 tmp_file.close()
2134 return filename
2146 return filename
2135
2147
2136 def write(self,data):
2148 def write(self,data):
2137 """Write a string to the default output"""
2149 """Write a string to the default output"""
2138 Term.cout.write(data)
2150 Term.cout.write(data)
2139
2151
2140 def write_err(self,data):
2152 def write_err(self,data):
2141 """Write a string to the default error output"""
2153 """Write a string to the default error output"""
2142 Term.cerr.write(data)
2154 Term.cerr.write(data)
2143
2155
2144 def exit(self):
2156 def exit(self):
2145 """Handle interactive exit.
2157 """Handle interactive exit.
2146
2158
2147 This method sets the exit_now attribute."""
2159 This method sets the exit_now attribute."""
2148
2160
2149 if self.rc.confirm_exit:
2161 if self.rc.confirm_exit:
2150 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2162 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2151 self.exit_now = True
2163 self.exit_now = True
2152 else:
2164 else:
2153 self.exit_now = True
2165 self.exit_now = True
2154 return self.exit_now
2166 return self.exit_now
2155
2167
2156 def safe_execfile(self,fname,*where,**kw):
2168 def safe_execfile(self,fname,*where,**kw):
2157 fname = os.path.expanduser(fname)
2169 fname = os.path.expanduser(fname)
2158
2170
2159 # find things also in current directory
2171 # find things also in current directory
2160 dname = os.path.dirname(fname)
2172 dname = os.path.dirname(fname)
2161 if not sys.path.count(dname):
2173 if not sys.path.count(dname):
2162 sys.path.append(dname)
2174 sys.path.append(dname)
2163
2175
2164 try:
2176 try:
2165 xfile = open(fname)
2177 xfile = open(fname)
2166 except:
2178 except:
2167 print >> Term.cerr, \
2179 print >> Term.cerr, \
2168 'Could not open file <%s> for safe execution.' % fname
2180 'Could not open file <%s> for safe execution.' % fname
2169 return None
2181 return None
2170
2182
2171 kw.setdefault('islog',0)
2183 kw.setdefault('islog',0)
2172 kw.setdefault('quiet',1)
2184 kw.setdefault('quiet',1)
2173 kw.setdefault('exit_ignore',0)
2185 kw.setdefault('exit_ignore',0)
2174 first = xfile.readline()
2186 first = xfile.readline()
2175 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2187 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2176 xfile.close()
2188 xfile.close()
2177 # line by line execution
2189 # line by line execution
2178 if first.startswith(loghead) or kw['islog']:
2190 if first.startswith(loghead) or kw['islog']:
2179 print 'Loading log file <%s> one line at a time...' % fname
2191 print 'Loading log file <%s> one line at a time...' % fname
2180 if kw['quiet']:
2192 if kw['quiet']:
2181 stdout_save = sys.stdout
2193 stdout_save = sys.stdout
2182 sys.stdout = StringIO.StringIO()
2194 sys.stdout = StringIO.StringIO()
2183 try:
2195 try:
2184 globs,locs = where[0:2]
2196 globs,locs = where[0:2]
2185 except:
2197 except:
2186 try:
2198 try:
2187 globs = locs = where[0]
2199 globs = locs = where[0]
2188 except:
2200 except:
2189 globs = locs = globals()
2201 globs = locs = globals()
2190 badblocks = []
2202 badblocks = []
2191
2203
2192 # we also need to identify indented blocks of code when replaying
2204 # we also need to identify indented blocks of code when replaying
2193 # logs and put them together before passing them to an exec
2205 # logs and put them together before passing them to an exec
2194 # statement. This takes a bit of regexp and look-ahead work in the
2206 # statement. This takes a bit of regexp and look-ahead work in the
2195 # file. It's easiest if we swallow the whole thing in memory
2207 # file. It's easiest if we swallow the whole thing in memory
2196 # first, and manually walk through the lines list moving the
2208 # first, and manually walk through the lines list moving the
2197 # counter ourselves.
2209 # counter ourselves.
2198 indent_re = re.compile('\s+\S')
2210 indent_re = re.compile('\s+\S')
2199 xfile = open(fname)
2211 xfile = open(fname)
2200 filelines = xfile.readlines()
2212 filelines = xfile.readlines()
2201 xfile.close()
2213 xfile.close()
2202 nlines = len(filelines)
2214 nlines = len(filelines)
2203 lnum = 0
2215 lnum = 0
2204 while lnum < nlines:
2216 while lnum < nlines:
2205 line = filelines[lnum]
2217 line = filelines[lnum]
2206 lnum += 1
2218 lnum += 1
2207 # don't re-insert logger status info into cache
2219 # don't re-insert logger status info into cache
2208 if line.startswith('#log#'):
2220 if line.startswith('#log#'):
2209 continue
2221 continue
2210 else:
2222 else:
2211 # build a block of code (maybe a single line) for execution
2223 # build a block of code (maybe a single line) for execution
2212 block = line
2224 block = line
2213 try:
2225 try:
2214 next = filelines[lnum] # lnum has already incremented
2226 next = filelines[lnum] # lnum has already incremented
2215 except:
2227 except:
2216 next = None
2228 next = None
2217 while next and indent_re.match(next):
2229 while next and indent_re.match(next):
2218 block += next
2230 block += next
2219 lnum += 1
2231 lnum += 1
2220 try:
2232 try:
2221 next = filelines[lnum]
2233 next = filelines[lnum]
2222 except:
2234 except:
2223 next = None
2235 next = None
2224 # now execute the block of one or more lines
2236 # now execute the block of one or more lines
2225 try:
2237 try:
2226 exec block in globs,locs
2238 exec block in globs,locs
2227 except SystemExit:
2239 except SystemExit:
2228 pass
2240 pass
2229 except:
2241 except:
2230 badblocks.append(block.rstrip())
2242 badblocks.append(block.rstrip())
2231 if kw['quiet']: # restore stdout
2243 if kw['quiet']: # restore stdout
2232 sys.stdout.close()
2244 sys.stdout.close()
2233 sys.stdout = stdout_save
2245 sys.stdout = stdout_save
2234 print 'Finished replaying log file <%s>' % fname
2246 print 'Finished replaying log file <%s>' % fname
2235 if badblocks:
2247 if badblocks:
2236 print >> sys.stderr, ('\nThe following lines/blocks in file '
2248 print >> sys.stderr, ('\nThe following lines/blocks in file '
2237 '<%s> reported errors:' % fname)
2249 '<%s> reported errors:' % fname)
2238
2250
2239 for badline in badblocks:
2251 for badline in badblocks:
2240 print >> sys.stderr, badline
2252 print >> sys.stderr, badline
2241 else: # regular file execution
2253 else: # regular file execution
2242 try:
2254 try:
2243 execfile(fname,*where)
2255 execfile(fname,*where)
2244 except SyntaxError:
2256 except SyntaxError:
2245 etype,evalue = sys.exc_info()[:2]
2257 etype,evalue = sys.exc_info()[:2]
2246 self.SyntaxTB(etype,evalue,[])
2258 self.SyntaxTB(etype,evalue,[])
2247 warn('Failure executing file: <%s>' % fname)
2259 warn('Failure executing file: <%s>' % fname)
2248 except SystemExit,status:
2260 except SystemExit,status:
2249 if not kw['exit_ignore']:
2261 if not kw['exit_ignore']:
2250 self.InteractiveTB()
2262 self.InteractiveTB()
2251 warn('Failure executing file: <%s>' % fname)
2263 warn('Failure executing file: <%s>' % fname)
2252 except:
2264 except:
2253 self.InteractiveTB()
2265 self.InteractiveTB()
2254 warn('Failure executing file: <%s>' % fname)
2266 warn('Failure executing file: <%s>' % fname)
2255
2267
2256 #************************* end of file <iplib.py> *****************************
2268 #************************* end of file <iplib.py> *****************************
@@ -1,735 +1,736 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or better.
5 Requires Python 2.1 or better.
6
6
7 This file contains the main make_IPython() starter function.
7 This file contains the main make_IPython() starter function.
8
8
9 $Id: ipmaker.py 1120 2006-02-01 20:08:48Z vivainio $"""
9 $Id: ipmaker.py 1140 2006-02-10 17:07:11Z vivainio $"""
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 from IPython import Release
18 from IPython import Release
19 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __license__ = Release.license
20 __license__ = Release.license
21 __version__ = Release.version
21 __version__ = Release.version
22
22
23 credits._Printer__data = """
23 credits._Printer__data = """
24 Python: %s
24 Python: %s
25
25
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 See http://ipython.scipy.org for more information.""" \
27 See http://ipython.scipy.org for more information.""" \
28 % credits._Printer__data
28 % credits._Printer__data
29
29
30 copyright._Printer__data += """
30 copyright._Printer__data += """
31
31
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 All Rights Reserved."""
33 All Rights Reserved."""
34
34
35 #****************************************************************************
35 #****************************************************************************
36 # Required modules
36 # Required modules
37
37
38 # From the standard library
38 # From the standard library
39 import __main__
39 import __main__
40 import __builtin__
40 import __builtin__
41 import os
41 import os
42 import re
42 import re
43 import sys
43 import sys
44 import types
44 import types
45 from pprint import pprint,pformat
45 from pprint import pprint,pformat
46
46
47 # Our own
47 # Our own
48 from IPython import DPyGetOpt
48 from IPython import DPyGetOpt
49 from IPython.ipstruct import Struct
49 from IPython.ipstruct import Struct
50 from IPython.OutputTrap import OutputTrap
50 from IPython.OutputTrap import OutputTrap
51 from IPython.ConfigLoader import ConfigLoader
51 from IPython.ConfigLoader import ConfigLoader
52 from IPython.iplib import InteractiveShell
52 from IPython.iplib import InteractiveShell
53 from IPython.usage import cmd_line_usage,interactive_usage
53 from IPython.usage import cmd_line_usage,interactive_usage
54 from IPython.genutils import *
54 from IPython.genutils import *
55
55
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 rc_override=None,shell_class=InteractiveShell,
58 rc_override=None,shell_class=InteractiveShell,
59 embedded=False,**kw):
59 embedded=False,**kw):
60 """This is a dump of IPython into a single function.
60 """This is a dump of IPython into a single function.
61
61
62 Later it will have to be broken up in a sensible manner.
62 Later it will have to be broken up in a sensible manner.
63
63
64 Arguments:
64 Arguments:
65
65
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 script name, b/c DPyGetOpt strips the first argument only for the real
67 script name, b/c DPyGetOpt strips the first argument only for the real
68 sys.argv.
68 sys.argv.
69
69
70 - user_ns: a dict to be used as the user's namespace."""
70 - user_ns: a dict to be used as the user's namespace."""
71
71
72 #----------------------------------------------------------------------
72 #----------------------------------------------------------------------
73 # Defaults and initialization
73 # Defaults and initialization
74
74
75 # For developer debugging, deactivates crash handler and uses pdb.
75 # For developer debugging, deactivates crash handler and uses pdb.
76 DEVDEBUG = False
76 DEVDEBUG = False
77
77
78 if argv is None:
78 if argv is None:
79 argv = sys.argv
79 argv = sys.argv
80
80
81 # __IP is the main global that lives throughout and represents the whole
81 # __IP is the main global that lives throughout and represents the whole
82 # application. If the user redefines it, all bets are off as to what
82 # application. If the user redefines it, all bets are off as to what
83 # happens.
83 # happens.
84
84
85 # __IP is the name of he global which the caller will have accessible as
85 # __IP is the name of he global which the caller will have accessible as
86 # __IP.name. We set its name via the first parameter passed to
86 # __IP.name. We set its name via the first parameter passed to
87 # InteractiveShell:
87 # InteractiveShell:
88
88
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 embedded=embedded,**kw)
90 embedded=embedded,**kw)
91
91
92 # Put 'help' in the user namespace
92 # Put 'help' in the user namespace
93 from site import _Helper
93 from site import _Helper
94 IP.user_ns['help'] = _Helper()
94 IP.user_ns['help'] = _Helper()
95
95
96
96
97 if DEVDEBUG:
97 if DEVDEBUG:
98 # For developer debugging only (global flag)
98 # For developer debugging only (global flag)
99 from IPython import ultraTB
99 from IPython import ultraTB
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101
101
102 IP.BANNER_PARTS = ['Python %s\n'
102 IP.BANNER_PARTS = ['Python %s\n'
103 'Type "copyright", "credits" or "license" '
103 'Type "copyright", "credits" or "license" '
104 'for more information.\n'
104 'for more information.\n'
105 % (sys.version.split('\n')[0],),
105 % (sys.version.split('\n')[0],),
106 "IPython %s -- An enhanced Interactive Python."
106 "IPython %s -- An enhanced Interactive Python."
107 % (__version__,),
107 % (__version__,),
108 """? -> Introduction to IPython's features.
108 """? -> Introduction to IPython's features.
109 %magic -> Information about IPython's 'magic' % functions.
109 %magic -> Information about IPython's 'magic' % functions.
110 help -> Python's own help system.
110 help -> Python's own help system.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 """ ]
112 """ ]
113
113
114 IP.usage = interactive_usage
114 IP.usage = interactive_usage
115
115
116 # Platform-dependent suffix and directory names. We use _ipython instead
116 # Platform-dependent suffix and directory names. We use _ipython instead
117 # of .ipython under win32 b/c there's software that breaks with .named
117 # of .ipython under win32 b/c there's software that breaks with .named
118 # directories on that platform.
118 # directories on that platform.
119 if os.name == 'posix':
119 if os.name == 'posix':
120 rc_suffix = ''
120 rc_suffix = ''
121 ipdir_def = '.ipython'
121 ipdir_def = '.ipython'
122 else:
122 else:
123 rc_suffix = '.ini'
123 rc_suffix = '.ini'
124 ipdir_def = '_ipython'
124 ipdir_def = '_ipython'
125
125
126 # default directory for configuration
126 # default directory for configuration
127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
128 os.path.join(IP.home_dir,ipdir_def)))
128 os.path.join(IP.home_dir,ipdir_def)))
129
129
130 # add personal .ipython dir to sys.path so that users can put things in
130 # add personal .ipython dir to sys.path so that users can put things in
131 # there for customization
131 # there for customization
132 sys.path.append(ipythondir)
132 sys.path.append(ipythondir)
133
133
134 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
134 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
135
135
136 # we need the directory where IPython itself is installed
136 # we need the directory where IPython itself is installed
137 import IPython
137 import IPython
138 IPython_dir = os.path.dirname(IPython.__file__)
138 IPython_dir = os.path.dirname(IPython.__file__)
139 del IPython
139 del IPython
140
140
141 #-------------------------------------------------------------------------
141 #-------------------------------------------------------------------------
142 # Command line handling
142 # Command line handling
143
143
144 # Valid command line options (uses DPyGetOpt syntax, like Perl's
144 # Valid command line options (uses DPyGetOpt syntax, like Perl's
145 # GetOpt::Long)
145 # GetOpt::Long)
146
146
147 # Any key not listed here gets deleted even if in the file (like session
147 # Any key not listed here gets deleted even if in the file (like session
148 # or profile). That's deliberate, to maintain the rc namespace clean.
148 # or profile). That's deliberate, to maintain the rc namespace clean.
149
149
150 # Each set of options appears twice: under _conv only the names are
150 # Each set of options appears twice: under _conv only the names are
151 # listed, indicating which type they must be converted to when reading the
151 # listed, indicating which type they must be converted to when reading the
152 # ipythonrc file. And under DPyGetOpt they are listed with the regular
152 # ipythonrc file. And under DPyGetOpt they are listed with the regular
153 # DPyGetOpt syntax (=s,=i,:f,etc).
153 # DPyGetOpt syntax (=s,=i,:f,etc).
154
154
155 # Make sure there's a space before each end of line (they get auto-joined!)
155 # Make sure there's a space before each end of line (they get auto-joined!)
156 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
156 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
157 'c=s classic|cl color_info! colors=s confirm_exit! '
157 'c=s classic|cl color_info! colors=s confirm_exit! '
158 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
158 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
159 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
159 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
160 'quick screen_length|sl=i prompts_pad_left=i '
160 'quick screen_length|sl=i prompts_pad_left=i '
161 'logfile|lf=s logplay|lp=s profile|p=s '
161 'logfile|lf=s logplay|lp=s profile|p=s '
162 'readline! readline_merge_completions! '
162 'readline! readline_merge_completions! '
163 'readline_omit__names! '
163 'readline_omit__names! '
164 'rcfile=s separate_in|si=s separate_out|so=s '
164 'rcfile=s separate_in|si=s separate_out|so=s '
165 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
165 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
166 'magic_docstrings system_verbose! '
166 'magic_docstrings system_verbose! '
167 'multi_line_specials! '
167 'multi_line_specials! '
168 'wxversion=s '
168 'wxversion=s '
169 'autoedit_syntax!')
169 'autoedit_syntax!')
170
170
171 # Options that can *only* appear at the cmd line (not in rcfiles).
171 # Options that can *only* appear at the cmd line (not in rcfiles).
172
172
173 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
173 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
174 # the 'C-c !' command in emacs automatically appends a -i option at the end.
174 # the 'C-c !' command in emacs automatically appends a -i option at the end.
175 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
175 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
176 'gthread! qthread! wthread! pylab! tk!')
176 'gthread! qthread! wthread! pylab! tk!')
177
177
178 # Build the actual name list to be used by DPyGetOpt
178 # Build the actual name list to be used by DPyGetOpt
179 opts_names = qw(cmdline_opts) + qw(cmdline_only)
179 opts_names = qw(cmdline_opts) + qw(cmdline_only)
180
180
181 # Set sensible command line defaults.
181 # Set sensible command line defaults.
182 # This should have everything from cmdline_opts and cmdline_only
182 # This should have everything from cmdline_opts and cmdline_only
183 opts_def = Struct(autocall = 1,
183 opts_def = Struct(autocall = 1,
184 autoedit_syntax = 1,
184 autoedit_syntax = 1,
185 autoindent=0,
185 autoindent=0,
186 automagic = 1,
186 automagic = 1,
187 banner = 1,
187 banner = 1,
188 cache_size = 1000,
188 cache_size = 1000,
189 c = '',
189 c = '',
190 classic = 0,
190 classic = 0,
191 colors = 'NoColor',
191 colors = 'NoColor',
192 color_info = 0,
192 color_info = 0,
193 confirm_exit = 1,
193 confirm_exit = 1,
194 debug = 0,
194 debug = 0,
195 deep_reload = 0,
195 deep_reload = 0,
196 editor = '0',
196 editor = '0',
197 help = 0,
197 help = 0,
198 ignore = 0,
198 ignore = 0,
199 ipythondir = ipythondir,
199 ipythondir = ipythondir,
200 log = 0,
200 log = 0,
201 logfile = '',
201 logfile = '',
202 logplay = '',
202 logplay = '',
203 multi_line_specials = 1,
203 multi_line_specials = 1,
204 messages = 1,
204 messages = 1,
205 nosep = 0,
205 nosep = 0,
206 pdb = 0,
206 pdb = 0,
207 pprint = 0,
207 pprint = 0,
208 profile = '',
208 profile = '',
209 prompt_in1 = 'In [\\#]: ',
209 prompt_in1 = 'In [\\#]: ',
210 prompt_in2 = ' .\\D.: ',
210 prompt_in2 = ' .\\D.: ',
211 prompt_out = 'Out[\\#]: ',
211 prompt_out = 'Out[\\#]: ',
212 prompts_pad_left = 1,
212 prompts_pad_left = 1,
213 quick = 0,
213 quick = 0,
214 readline = 1,
214 readline = 1,
215 readline_merge_completions = 1,
215 readline_merge_completions = 1,
216 readline_omit__names = 0,
216 readline_omit__names = 0,
217 rcfile = 'ipythonrc' + rc_suffix,
217 rcfile = 'ipythonrc' + rc_suffix,
218 screen_length = 0,
218 screen_length = 0,
219 separate_in = '\n',
219 separate_in = '\n',
220 separate_out = '\n',
220 separate_out = '\n',
221 separate_out2 = '',
221 separate_out2 = '',
222 system_verbose = 0,
222 system_verbose = 0,
223 gthread = 0,
223 gthread = 0,
224 qthread = 0,
224 qthread = 0,
225 wthread = 0,
225 wthread = 0,
226 pylab = 0,
226 pylab = 0,
227 tk = 0,
227 tk = 0,
228 upgrade = 0,
228 upgrade = 0,
229 Version = 0,
229 Version = 0,
230 xmode = 'Verbose',
230 xmode = 'Verbose',
231 wildcards_case_sensitive = 1,
231 wildcards_case_sensitive = 1,
232 wxversion = '0',
232 wxversion = '0',
233 magic_docstrings = 0, # undocumented, for doc generation
233 magic_docstrings = 0, # undocumented, for doc generation
234 )
234 )
235
235
236 # Things that will *only* appear in rcfiles (not at the command line).
236 # Things that will *only* appear in rcfiles (not at the command line).
237 # Make sure there's a space before each end of line (they get auto-joined!)
237 # Make sure there's a space before each end of line (they get auto-joined!)
238 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
238 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
239 qw_lol: 'import_some ',
239 qw_lol: 'import_some ',
240 # for things with embedded whitespace:
240 # for things with embedded whitespace:
241 list_strings:'execute alias readline_parse_and_bind ',
241 list_strings:'execute alias readline_parse_and_bind ',
242 # Regular strings need no conversion:
242 # Regular strings need no conversion:
243 None:'readline_remove_delims ',
243 None:'readline_remove_delims ',
244 }
244 }
245 # Default values for these
245 # Default values for these
246 rc_def = Struct(include = [],
246 rc_def = Struct(include = [],
247 import_mod = [],
247 import_mod = [],
248 import_all = [],
248 import_all = [],
249 import_some = [[]],
249 import_some = [[]],
250 execute = [],
250 execute = [],
251 execfile = [],
251 execfile = [],
252 alias = [],
252 alias = [],
253 readline_parse_and_bind = [],
253 readline_parse_and_bind = [],
254 readline_remove_delims = '',
254 readline_remove_delims = '',
255 )
255 )
256
256
257 # Build the type conversion dictionary from the above tables:
257 # Build the type conversion dictionary from the above tables:
258 typeconv = rcfile_opts.copy()
258 typeconv = rcfile_opts.copy()
259 typeconv.update(optstr2types(cmdline_opts))
259 typeconv.update(optstr2types(cmdline_opts))
260
260
261 # FIXME: the None key appears in both, put that back together by hand. Ugly!
261 # FIXME: the None key appears in both, put that back together by hand. Ugly!
262 typeconv[None] += ' ' + rcfile_opts[None]
262 typeconv[None] += ' ' + rcfile_opts[None]
263
263
264 # Remove quotes at ends of all strings (used to protect spaces)
264 # Remove quotes at ends of all strings (used to protect spaces)
265 typeconv[unquote_ends] = typeconv[None]
265 typeconv[unquote_ends] = typeconv[None]
266 del typeconv[None]
266 del typeconv[None]
267
267
268 # Build the list we'll use to make all config decisions with defaults:
268 # Build the list we'll use to make all config decisions with defaults:
269 opts_all = opts_def.copy()
269 opts_all = opts_def.copy()
270 opts_all.update(rc_def)
270 opts_all.update(rc_def)
271
271
272 # Build conflict resolver for recursive loading of config files:
272 # Build conflict resolver for recursive loading of config files:
273 # - preserve means the outermost file maintains the value, it is not
273 # - preserve means the outermost file maintains the value, it is not
274 # overwritten if an included file has the same key.
274 # overwritten if an included file has the same key.
275 # - add_flip applies + to the two values, so it better make sense to add
275 # - add_flip applies + to the two values, so it better make sense to add
276 # those types of keys. But it flips them first so that things loaded
276 # those types of keys. But it flips them first so that things loaded
277 # deeper in the inclusion chain have lower precedence.
277 # deeper in the inclusion chain have lower precedence.
278 conflict = {'preserve': ' '.join([ typeconv[int],
278 conflict = {'preserve': ' '.join([ typeconv[int],
279 typeconv[unquote_ends] ]),
279 typeconv[unquote_ends] ]),
280 'add_flip': ' '.join([ typeconv[qwflat],
280 'add_flip': ' '.join([ typeconv[qwflat],
281 typeconv[qw_lol],
281 typeconv[qw_lol],
282 typeconv[list_strings] ])
282 typeconv[list_strings] ])
283 }
283 }
284
284
285 # Now actually process the command line
285 # Now actually process the command line
286 getopt = DPyGetOpt.DPyGetOpt()
286 getopt = DPyGetOpt.DPyGetOpt()
287 getopt.setIgnoreCase(0)
287 getopt.setIgnoreCase(0)
288
288
289 getopt.parseConfiguration(opts_names)
289 getopt.parseConfiguration(opts_names)
290
290
291 try:
291 try:
292 getopt.processArguments(argv)
292 getopt.processArguments(argv)
293 except:
293 except:
294 print cmd_line_usage
294 print cmd_line_usage
295 warn('\nError in Arguments: ' + `sys.exc_value`)
295 warn('\nError in Arguments: ' + `sys.exc_value`)
296 sys.exit(1)
296 sys.exit(1)
297
297
298 # convert the options dict to a struct for much lighter syntax later
298 # convert the options dict to a struct for much lighter syntax later
299 opts = Struct(getopt.optionValues)
299 opts = Struct(getopt.optionValues)
300 args = getopt.freeValues
300 args = getopt.freeValues
301
301
302 # this is the struct (which has default values at this point) with which
302 # this is the struct (which has default values at this point) with which
303 # we make all decisions:
303 # we make all decisions:
304 opts_all.update(opts)
304 opts_all.update(opts)
305
305
306 # Options that force an immediate exit
306 # Options that force an immediate exit
307 if opts_all.help:
307 if opts_all.help:
308 page(cmd_line_usage)
308 page(cmd_line_usage)
309 sys.exit()
309 sys.exit()
310
310
311 if opts_all.Version:
311 if opts_all.Version:
312 print __version__
312 print __version__
313 sys.exit()
313 sys.exit()
314
314
315 if opts_all.magic_docstrings:
315 if opts_all.magic_docstrings:
316 IP.magic_magic('-latex')
316 IP.magic_magic('-latex')
317 sys.exit()
317 sys.exit()
318
318
319 # Create user config directory if it doesn't exist. This must be done
319 # Create user config directory if it doesn't exist. This must be done
320 # *after* getting the cmd line options.
320 # *after* getting the cmd line options.
321 if not os.path.isdir(opts_all.ipythondir):
321 if not os.path.isdir(opts_all.ipythondir):
322 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
322 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
323
323
324 # upgrade user config files while preserving a copy of the originals
324 # upgrade user config files while preserving a copy of the originals
325 if opts_all.upgrade:
325 if opts_all.upgrade:
326 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
326 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
327
327
328 # check mutually exclusive options in the *original* command line
328 # check mutually exclusive options in the *original* command line
329 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
329 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
330 qw('classic profile'),qw('classic rcfile')])
330 qw('classic profile'),qw('classic rcfile')])
331
331
332 #---------------------------------------------------------------------------
332 #---------------------------------------------------------------------------
333 # Log replay
333 # Log replay
334
334
335 # if -logplay, we need to 'become' the other session. That basically means
335 # if -logplay, we need to 'become' the other session. That basically means
336 # replacing the current command line environment with that of the old
336 # replacing the current command line environment with that of the old
337 # session and moving on.
337 # session and moving on.
338
338
339 # this is needed so that later we know we're in session reload mode, as
339 # this is needed so that later we know we're in session reload mode, as
340 # opts_all will get overwritten:
340 # opts_all will get overwritten:
341 load_logplay = 0
341 load_logplay = 0
342
342
343 if opts_all.logplay:
343 if opts_all.logplay:
344 load_logplay = opts_all.logplay
344 load_logplay = opts_all.logplay
345 opts_debug_save = opts_all.debug
345 opts_debug_save = opts_all.debug
346 try:
346 try:
347 logplay = open(opts_all.logplay)
347 logplay = open(opts_all.logplay)
348 except IOError:
348 except IOError:
349 if opts_all.debug: IP.InteractiveTB()
349 if opts_all.debug: IP.InteractiveTB()
350 warn('Could not open logplay file '+`opts_all.logplay`)
350 warn('Could not open logplay file '+`opts_all.logplay`)
351 # restore state as if nothing had happened and move on, but make
351 # restore state as if nothing had happened and move on, but make
352 # sure that later we don't try to actually load the session file
352 # sure that later we don't try to actually load the session file
353 logplay = None
353 logplay = None
354 load_logplay = 0
354 load_logplay = 0
355 del opts_all.logplay
355 del opts_all.logplay
356 else:
356 else:
357 try:
357 try:
358 logplay.readline()
358 logplay.readline()
359 logplay.readline();
359 logplay.readline();
360 # this reloads that session's command line
360 # this reloads that session's command line
361 cmd = logplay.readline()[6:]
361 cmd = logplay.readline()[6:]
362 exec cmd
362 exec cmd
363 # restore the true debug flag given so that the process of
363 # restore the true debug flag given so that the process of
364 # session loading itself can be monitored.
364 # session loading itself can be monitored.
365 opts.debug = opts_debug_save
365 opts.debug = opts_debug_save
366 # save the logplay flag so later we don't overwrite the log
366 # save the logplay flag so later we don't overwrite the log
367 opts.logplay = load_logplay
367 opts.logplay = load_logplay
368 # now we must update our own structure with defaults
368 # now we must update our own structure with defaults
369 opts_all.update(opts)
369 opts_all.update(opts)
370 # now load args
370 # now load args
371 cmd = logplay.readline()[6:]
371 cmd = logplay.readline()[6:]
372 exec cmd
372 exec cmd
373 logplay.close()
373 logplay.close()
374 except:
374 except:
375 logplay.close()
375 logplay.close()
376 if opts_all.debug: IP.InteractiveTB()
376 if opts_all.debug: IP.InteractiveTB()
377 warn("Logplay file lacking full configuration information.\n"
377 warn("Logplay file lacking full configuration information.\n"
378 "I'll try to read it, but some things may not work.")
378 "I'll try to read it, but some things may not work.")
379
379
380 #-------------------------------------------------------------------------
380 #-------------------------------------------------------------------------
381 # set up output traps: catch all output from files, being run, modules
381 # set up output traps: catch all output from files, being run, modules
382 # loaded, etc. Then give it to the user in a clean form at the end.
382 # loaded, etc. Then give it to the user in a clean form at the end.
383
383
384 msg_out = 'Output messages. '
384 msg_out = 'Output messages. '
385 msg_err = 'Error messages. '
385 msg_err = 'Error messages. '
386 msg_sep = '\n'
386 msg_sep = '\n'
387 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
387 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
388 msg_err,msg_sep,debug,
388 msg_err,msg_sep,debug,
389 quiet_out=1),
389 quiet_out=1),
390 user_exec = OutputTrap('User File Execution',msg_out,
390 user_exec = OutputTrap('User File Execution',msg_out,
391 msg_err,msg_sep,debug),
391 msg_err,msg_sep,debug),
392 logplay = OutputTrap('Log Loader',msg_out,
392 logplay = OutputTrap('Log Loader',msg_out,
393 msg_err,msg_sep,debug),
393 msg_err,msg_sep,debug),
394 summary = ''
394 summary = ''
395 )
395 )
396
396
397 #-------------------------------------------------------------------------
397 #-------------------------------------------------------------------------
398 # Process user ipythonrc-type configuration files
398 # Process user ipythonrc-type configuration files
399
399
400 # turn on output trapping and log to msg.config
400 # turn on output trapping and log to msg.config
401 # remember that with debug on, trapping is actually disabled
401 # remember that with debug on, trapping is actually disabled
402 msg.config.trap_all()
402 msg.config.trap_all()
403
403
404 # look for rcfile in current or default directory
404 # look for rcfile in current or default directory
405 try:
405 try:
406 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
406 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
407 except IOError:
407 except IOError:
408 if opts_all.debug: IP.InteractiveTB()
408 if opts_all.debug: IP.InteractiveTB()
409 warn('Configuration file %s not found. Ignoring request.'
409 warn('Configuration file %s not found. Ignoring request.'
410 % (opts_all.rcfile) )
410 % (opts_all.rcfile) )
411
411
412 # 'profiles' are a shorthand notation for config filenames
412 # 'profiles' are a shorthand notation for config filenames
413 if opts_all.profile:
413 if opts_all.profile:
414
414
415 try:
415 try:
416 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
416 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
417 + rc_suffix,
417 + rc_suffix,
418 opts_all.ipythondir)
418 opts_all.ipythondir)
419 except IOError:
419 except IOError:
420 if opts_all.debug: IP.InteractiveTB()
420 if opts_all.debug: IP.InteractiveTB()
421 opts.profile = '' # remove profile from options if invalid
421 opts.profile = '' # remove profile from options if invalid
422 # We won't warn anymore, primary method is ipy_profile_PROFNAME
422 # We won't warn anymore, primary method is ipy_profile_PROFNAME
423 # which does trigger a warning.
423 # which does trigger a warning.
424
424
425 # load the config file
425 # load the config file
426 rcfiledata = None
426 rcfiledata = None
427 if opts_all.quick:
427 if opts_all.quick:
428 print 'Launching IPython in quick mode. No config file read.'
428 print 'Launching IPython in quick mode. No config file read.'
429 elif opts_all.classic:
429 elif opts_all.classic:
430 print 'Launching IPython in classic mode. No config file read.'
430 print 'Launching IPython in classic mode. No config file read.'
431 elif opts_all.rcfile:
431 elif opts_all.rcfile:
432 try:
432 try:
433 cfg_loader = ConfigLoader(conflict)
433 cfg_loader = ConfigLoader(conflict)
434 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
434 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
435 'include',opts_all.ipythondir,
435 'include',opts_all.ipythondir,
436 purge = 1,
436 purge = 1,
437 unique = conflict['preserve'])
437 unique = conflict['preserve'])
438 except:
438 except:
439 IP.InteractiveTB()
439 IP.InteractiveTB()
440 warn('Problems loading configuration file '+
440 warn('Problems loading configuration file '+
441 `opts_all.rcfile`+
441 `opts_all.rcfile`+
442 '\nStarting with default -bare bones- configuration.')
442 '\nStarting with default -bare bones- configuration.')
443 else:
443 else:
444 warn('No valid configuration file found in either currrent directory\n'+
444 warn('No valid configuration file found in either currrent directory\n'+
445 'or in the IPython config. directory: '+`opts_all.ipythondir`+
445 'or in the IPython config. directory: '+`opts_all.ipythondir`+
446 '\nProceeding with internal defaults.')
446 '\nProceeding with internal defaults.')
447
447
448 #------------------------------------------------------------------------
448 #------------------------------------------------------------------------
449 # Set exception handlers in mode requested by user.
449 # Set exception handlers in mode requested by user.
450 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
450 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
451 IP.magic_xmode(opts_all.xmode)
451 IP.magic_xmode(opts_all.xmode)
452 otrap.release_out()
452 otrap.release_out()
453
453
454 #------------------------------------------------------------------------
454 #------------------------------------------------------------------------
455 # Execute user config
455 # Execute user config
456
456
457 # Create a valid config structure with the right precedence order:
457 # Create a valid config structure with the right precedence order:
458 # defaults < rcfile < command line. This needs to be in the instance, so
458 # defaults < rcfile < command line. This needs to be in the instance, so
459 # that method calls below that rely on it find it.
459 # that method calls below that rely on it find it.
460 IP.rc = rc_def.copy()
460 IP.rc = rc_def.copy()
461
461
462 # Work with a local alias inside this routine to avoid unnecessary
462 # Work with a local alias inside this routine to avoid unnecessary
463 # attribute lookups.
463 # attribute lookups.
464 IP_rc = IP.rc
464 IP_rc = IP.rc
465
465
466 IP_rc.update(opts_def)
466 IP_rc.update(opts_def)
467 if rcfiledata:
467 if rcfiledata:
468 # now we can update
468 # now we can update
469 IP_rc.update(rcfiledata)
469 IP_rc.update(rcfiledata)
470 IP_rc.update(opts)
470 IP_rc.update(opts)
471 IP_rc.update(rc_override)
471 IP_rc.update(rc_override)
472
472
473 # Store the original cmd line for reference:
473 # Store the original cmd line for reference:
474 IP_rc.opts = opts
474 IP_rc.opts = opts
475 IP_rc.args = args
475 IP_rc.args = args
476
476
477 # create a *runtime* Struct like rc for holding parameters which may be
477 # create a *runtime* Struct like rc for holding parameters which may be
478 # created and/or modified by runtime user extensions.
478 # created and/or modified by runtime user extensions.
479 IP.runtime_rc = Struct()
479 IP.runtime_rc = Struct()
480
480
481 # from this point on, all config should be handled through IP_rc,
481 # from this point on, all config should be handled through IP_rc,
482 # opts* shouldn't be used anymore.
482 # opts* shouldn't be used anymore.
483
483
484
484
485 # update IP_rc with some special things that need manual
485 # update IP_rc with some special things that need manual
486 # tweaks. Basically options which affect other options. I guess this
486 # tweaks. Basically options which affect other options. I guess this
487 # should just be written so that options are fully orthogonal and we
487 # should just be written so that options are fully orthogonal and we
488 # wouldn't worry about this stuff!
488 # wouldn't worry about this stuff!
489
489
490 if IP_rc.classic:
490 if IP_rc.classic:
491 IP_rc.quick = 1
491 IP_rc.quick = 1
492 IP_rc.cache_size = 0
492 IP_rc.cache_size = 0
493 IP_rc.pprint = 0
493 IP_rc.pprint = 0
494 IP_rc.prompt_in1 = '>>> '
494 IP_rc.prompt_in1 = '>>> '
495 IP_rc.prompt_in2 = '... '
495 IP_rc.prompt_in2 = '... '
496 IP_rc.prompt_out = ''
496 IP_rc.prompt_out = ''
497 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
497 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
498 IP_rc.colors = 'NoColor'
498 IP_rc.colors = 'NoColor'
499 IP_rc.xmode = 'Plain'
499 IP_rc.xmode = 'Plain'
500
500
501 IP.pre_config_initialization()
501 # configure readline
502 # configure readline
502 # Define the history file for saving commands in between sessions
503 # Define the history file for saving commands in between sessions
503 if IP_rc.profile:
504 if IP_rc.profile:
504 histfname = 'history-%s' % IP_rc.profile
505 histfname = 'history-%s' % IP_rc.profile
505 else:
506 else:
506 histfname = 'history'
507 histfname = 'history'
507 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
508 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
508
509
509 # update exception handlers with rc file status
510 # update exception handlers with rc file status
510 otrap.trap_out() # I don't want these messages ever.
511 otrap.trap_out() # I don't want these messages ever.
511 IP.magic_xmode(IP_rc.xmode)
512 IP.magic_xmode(IP_rc.xmode)
512 otrap.release_out()
513 otrap.release_out()
513
514
514 # activate logging if requested and not reloading a log
515 # activate logging if requested and not reloading a log
515 if IP_rc.logplay:
516 if IP_rc.logplay:
516 IP.magic_logstart(IP_rc.logplay + ' append')
517 IP.magic_logstart(IP_rc.logplay + ' append')
517 elif IP_rc.logfile:
518 elif IP_rc.logfile:
518 IP.magic_logstart(IP_rc.logfile)
519 IP.magic_logstart(IP_rc.logfile)
519 elif IP_rc.log:
520 elif IP_rc.log:
520 IP.magic_logstart()
521 IP.magic_logstart()
521
522
522 # find user editor so that it we don't have to look it up constantly
523 # find user editor so that it we don't have to look it up constantly
523 if IP_rc.editor.strip()=='0':
524 if IP_rc.editor.strip()=='0':
524 try:
525 try:
525 ed = os.environ['EDITOR']
526 ed = os.environ['EDITOR']
526 except KeyError:
527 except KeyError:
527 if os.name == 'posix':
528 if os.name == 'posix':
528 ed = 'vi' # the only one guaranteed to be there!
529 ed = 'vi' # the only one guaranteed to be there!
529 else:
530 else:
530 ed = 'notepad' # same in Windows!
531 ed = 'notepad' # same in Windows!
531 IP_rc.editor = ed
532 IP_rc.editor = ed
532
533
533 # Keep track of whether this is an embedded instance or not (useful for
534 # Keep track of whether this is an embedded instance or not (useful for
534 # post-mortems).
535 # post-mortems).
535 IP_rc.embedded = IP.embedded
536 IP_rc.embedded = IP.embedded
536
537
537 # Recursive reload
538 # Recursive reload
538 try:
539 try:
539 from IPython import deep_reload
540 from IPython import deep_reload
540 if IP_rc.deep_reload:
541 if IP_rc.deep_reload:
541 __builtin__.reload = deep_reload.reload
542 __builtin__.reload = deep_reload.reload
542 else:
543 else:
543 __builtin__.dreload = deep_reload.reload
544 __builtin__.dreload = deep_reload.reload
544 del deep_reload
545 del deep_reload
545 except ImportError:
546 except ImportError:
546 pass
547 pass
547
548
548 # Save the current state of our namespace so that the interactive shell
549 # Save the current state of our namespace so that the interactive shell
549 # can later know which variables have been created by us from config files
550 # can later know which variables have been created by us from config files
550 # and loading. This way, loading a file (in any way) is treated just like
551 # and loading. This way, loading a file (in any way) is treated just like
551 # defining things on the command line, and %who works as expected.
552 # defining things on the command line, and %who works as expected.
552
553
553 # DON'T do anything that affects the namespace beyond this point!
554 # DON'T do anything that affects the namespace beyond this point!
554 IP.internal_ns.update(__main__.__dict__)
555 IP.internal_ns.update(__main__.__dict__)
555
556
556 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
557 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
557
558
558 # Now run through the different sections of the users's config
559 # Now run through the different sections of the users's config
559 if IP_rc.debug:
560 if IP_rc.debug:
560 print 'Trying to execute the following configuration structure:'
561 print 'Trying to execute the following configuration structure:'
561 print '(Things listed first are deeper in the inclusion tree and get'
562 print '(Things listed first are deeper in the inclusion tree and get'
562 print 'loaded first).\n'
563 print 'loaded first).\n'
563 pprint(IP_rc.__dict__)
564 pprint(IP_rc.__dict__)
564
565
565 for mod in IP_rc.import_mod:
566 for mod in IP_rc.import_mod:
566 try:
567 try:
567 exec 'import '+mod in IP.user_ns
568 exec 'import '+mod in IP.user_ns
568 except :
569 except :
569 IP.InteractiveTB()
570 IP.InteractiveTB()
570 import_fail_info(mod)
571 import_fail_info(mod)
571
572
572 for mod_fn in IP_rc.import_some:
573 for mod_fn in IP_rc.import_some:
573 if mod_fn == []: break
574 if mod_fn == []: break
574 mod,fn = mod_fn[0],','.join(mod_fn[1:])
575 mod,fn = mod_fn[0],','.join(mod_fn[1:])
575 try:
576 try:
576 exec 'from '+mod+' import '+fn in IP.user_ns
577 exec 'from '+mod+' import '+fn in IP.user_ns
577 except :
578 except :
578 IP.InteractiveTB()
579 IP.InteractiveTB()
579 import_fail_info(mod,fn)
580 import_fail_info(mod,fn)
580
581
581 for mod in IP_rc.import_all:
582 for mod in IP_rc.import_all:
582 try:
583 try:
583 exec 'from '+mod+' import *' in IP.user_ns
584 exec 'from '+mod+' import *' in IP.user_ns
584 except :
585 except :
585 IP.InteractiveTB()
586 IP.InteractiveTB()
586 import_fail_info(mod)
587 import_fail_info(mod)
587
588
588 for code in IP_rc.execute:
589 for code in IP_rc.execute:
589 try:
590 try:
590 exec code in IP.user_ns
591 exec code in IP.user_ns
591 except:
592 except:
592 IP.InteractiveTB()
593 IP.InteractiveTB()
593 warn('Failure executing code: ' + `code`)
594 warn('Failure executing code: ' + `code`)
594
595
595 # Execute the files the user wants in ipythonrc
596 # Execute the files the user wants in ipythonrc
596 for file in IP_rc.execfile:
597 for file in IP_rc.execfile:
597 try:
598 try:
598 file = filefind(file,sys.path+[IPython_dir])
599 file = filefind(file,sys.path+[IPython_dir])
599 except IOError:
600 except IOError:
600 warn(itpl('File $file not found. Skipping it.'))
601 warn(itpl('File $file not found. Skipping it.'))
601 else:
602 else:
602 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
603 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
603
604
604 # finally, try importing ipy_*_conf for final configuration
605 # finally, try importing ipy_*_conf for final configuration
605 try:
606 try:
606 import ipy_system_conf
607 import ipy_system_conf
607 except ImportError:
608 except ImportError:
608 if opts_all.debug: IP.InteractiveTB()
609 if opts_all.debug: IP.InteractiveTB()
609 warn("Could not import 'ipy_system_conf'")
610 warn("Could not import 'ipy_system_conf'")
610
611
611 if opts_all.profile:
612 if opts_all.profile:
612 profmodname = 'ipy_profile_' + opts_all.profile
613 profmodname = 'ipy_profile_' + opts_all.profile
613 try:
614 try:
614 __import__(profmodname)
615 __import__(profmodname)
615 except ImportError:
616 except ImportError:
616 # only warn if ipythonrc-PROFNAME didn't exist
617 # only warn if ipythonrc-PROFNAME didn't exist
617 if opts.profile =='':
618 if opts.profile =='':
618 warn("Could not start with profile '%s'!\n ('%s/%s.py' does not exist?)" % (
619 warn("Could not start with profile '%s'!\n ('%s/%s.py' does not exist?)" % (
619 opts_all.profile, ipythondir, profmodname)
620 opts_all.profile, ipythondir, profmodname)
620
621
621 )
622 )
622 try:
623 try:
623 import ipy_user_conf
624 import ipy_user_conf
624 except ImportError:
625 except ImportError:
625 if opts_all.debug: IP.InteractiveTB()
626 if opts_all.debug: IP.InteractiveTB()
626 warn("Could not import user config!\n ('%s/ipy_user_conf.py' does not exist?)" %
627 warn("Could not import user config!\n ('%s/ipy_user_conf.py' does not exist?)" %
627 ipythondir)
628 ipythondir)
628
629
629 # release stdout and stderr and save config log into a global summary
630 # release stdout and stderr and save config log into a global summary
630 msg.config.release_all()
631 msg.config.release_all()
631 if IP_rc.messages:
632 if IP_rc.messages:
632 msg.summary += msg.config.summary_all()
633 msg.summary += msg.config.summary_all()
633
634
634 #------------------------------------------------------------------------
635 #------------------------------------------------------------------------
635 # Setup interactive session
636 # Setup interactive session
636
637
637 # Now we should be fully configured. We can then execute files or load
638 # Now we should be fully configured. We can then execute files or load
638 # things only needed for interactive use. Then we'll open the shell.
639 # things only needed for interactive use. Then we'll open the shell.
639
640
640 # Take a snapshot of the user namespace before opening the shell. That way
641 # Take a snapshot of the user namespace before opening the shell. That way
641 # we'll be able to identify which things were interactively defined and
642 # we'll be able to identify which things were interactively defined and
642 # which were defined through config files.
643 # which were defined through config files.
643 IP.user_config_ns = IP.user_ns.copy()
644 IP.user_config_ns = IP.user_ns.copy()
644
645
645 # Force reading a file as if it were a session log. Slower but safer.
646 # Force reading a file as if it were a session log. Slower but safer.
646 if load_logplay:
647 if load_logplay:
647 print 'Replaying log...'
648 print 'Replaying log...'
648 try:
649 try:
649 if IP_rc.debug:
650 if IP_rc.debug:
650 logplay_quiet = 0
651 logplay_quiet = 0
651 else:
652 else:
652 logplay_quiet = 1
653 logplay_quiet = 1
653
654
654 msg.logplay.trap_all()
655 msg.logplay.trap_all()
655 IP.safe_execfile(load_logplay,IP.user_ns,
656 IP.safe_execfile(load_logplay,IP.user_ns,
656 islog = 1, quiet = logplay_quiet)
657 islog = 1, quiet = logplay_quiet)
657 msg.logplay.release_all()
658 msg.logplay.release_all()
658 if IP_rc.messages:
659 if IP_rc.messages:
659 msg.summary += msg.logplay.summary_all()
660 msg.summary += msg.logplay.summary_all()
660 except:
661 except:
661 warn('Problems replaying logfile %s.' % load_logplay)
662 warn('Problems replaying logfile %s.' % load_logplay)
662 IP.InteractiveTB()
663 IP.InteractiveTB()
663
664
664 # Load remaining files in command line
665 # Load remaining files in command line
665 msg.user_exec.trap_all()
666 msg.user_exec.trap_all()
666
667
667 # Do NOT execute files named in the command line as scripts to be loaded
668 # Do NOT execute files named in the command line as scripts to be loaded
668 # by embedded instances. Doing so has the potential for an infinite
669 # by embedded instances. Doing so has the potential for an infinite
669 # recursion if there are exceptions thrown in the process.
670 # recursion if there are exceptions thrown in the process.
670
671
671 # XXX FIXME: the execution of user files should be moved out to after
672 # XXX FIXME: the execution of user files should be moved out to after
672 # ipython is fully initialized, just as if they were run via %run at the
673 # ipython is fully initialized, just as if they were run via %run at the
673 # ipython prompt. This would also give them the benefit of ipython's
674 # ipython prompt. This would also give them the benefit of ipython's
674 # nice tracebacks.
675 # nice tracebacks.
675
676
676 if not embedded and IP_rc.args:
677 if not embedded and IP_rc.args:
677 name_save = IP.user_ns['__name__']
678 name_save = IP.user_ns['__name__']
678 IP.user_ns['__name__'] = '__main__'
679 IP.user_ns['__name__'] = '__main__'
679 # Set our own excepthook in case the user code tries to call it
680 # Set our own excepthook in case the user code tries to call it
680 # directly. This prevents triggering the IPython crash handler.
681 # directly. This prevents triggering the IPython crash handler.
681 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
682 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
682
683
683 save_argv = sys.argv[:] # save it for later restoring
684 save_argv = sys.argv[:] # save it for later restoring
684
685
685 sys.argv = args
686 sys.argv = args
686
687
687 try:
688 try:
688 IP.safe_execfile(args[0], IP.user_ns)
689 IP.safe_execfile(args[0], IP.user_ns)
689 finally:
690 finally:
690 # Reset our crash handler in place
691 # Reset our crash handler in place
691 sys.excepthook = old_excepthook
692 sys.excepthook = old_excepthook
692 sys.argv = save_argv
693 sys.argv = save_argv
693 IP.user_ns['__name__'] = name_save
694 IP.user_ns['__name__'] = name_save
694
695
695 msg.user_exec.release_all()
696 msg.user_exec.release_all()
696 if IP_rc.messages:
697 if IP_rc.messages:
697 msg.summary += msg.user_exec.summary_all()
698 msg.summary += msg.user_exec.summary_all()
698
699
699 # since we can't specify a null string on the cmd line, 0 is the equivalent:
700 # since we can't specify a null string on the cmd line, 0 is the equivalent:
700 if IP_rc.nosep:
701 if IP_rc.nosep:
701 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
702 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
702 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
703 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
703 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
704 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
704 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
705 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
705 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
706 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
706 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
707 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
707 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
708 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
708
709
709 # Determine how many lines at the bottom of the screen are needed for
710 # Determine how many lines at the bottom of the screen are needed for
710 # showing prompts, so we can know wheter long strings are to be printed or
711 # showing prompts, so we can know wheter long strings are to be printed or
711 # paged:
712 # paged:
712 num_lines_bot = IP_rc.separate_in.count('\n')+1
713 num_lines_bot = IP_rc.separate_in.count('\n')+1
713 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
714 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
714
715
715 # configure startup banner
716 # configure startup banner
716 if IP_rc.c: # regular python doesn't print the banner with -c
717 if IP_rc.c: # regular python doesn't print the banner with -c
717 IP_rc.banner = 0
718 IP_rc.banner = 0
718 if IP_rc.banner:
719 if IP_rc.banner:
719 BANN_P = IP.BANNER_PARTS
720 BANN_P = IP.BANNER_PARTS
720 else:
721 else:
721 BANN_P = []
722 BANN_P = []
722
723
723 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
724 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
724
725
725 # add message log (possibly empty)
726 # add message log (possibly empty)
726 if msg.summary: BANN_P.append(msg.summary)
727 if msg.summary: BANN_P.append(msg.summary)
727 # Final banner is a string
728 # Final banner is a string
728 IP.BANNER = '\n'.join(BANN_P)
729 IP.BANNER = '\n'.join(BANN_P)
729
730
730 # Finalize the IPython instance. This assumes the rc structure is fully
731 # Finalize the IPython instance. This assumes the rc structure is fully
731 # in place.
732 # in place.
732 IP.post_config_initialization()
733 IP.post_config_initialization()
733
734
734 return IP
735 return IP
735 #************************ end of file <ipmaker.py> **************************
736 #************************ end of file <ipmaker.py> **************************
General Comments 0
You need to be logged in to leave comments. Login now