##// END OF EJS Templates
Wildcard system cleanup, ipmaker speedups, bugfix in globals handling...
fperez -
Show More

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

@@ -1,2510 +1,2563 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 922 2005-11-13 10:21:08Z fperez $"""
4 $Id: Magic.py 923 2005-11-15 08:51:15Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time
24 import os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time
25 try:
25 try:
26 import profile,pstats
26 import profile,pstats
27 except ImportError:
27 except ImportError:
28 profile = pstats = None
28 profile = pstats = None
29 from getopt import getopt
29 from getopt import getopt
30 from pprint import pprint, pformat
30 from pprint import pprint, pformat
31 from cStringIO import StringIO
31 from cStringIO import StringIO
32
32
33 # Homebrewed
33 # Homebrewed
34 from IPython.Struct import Struct
34 from IPython.Struct import Struct
35 from IPython.Itpl import Itpl, itpl, printpl,itplns
35 from IPython.Itpl import Itpl, itpl, printpl,itplns
36 from IPython.FakeModule import FakeModule
36 from IPython.FakeModule import FakeModule
37 from IPython.PyColorize import Parser
37 from IPython.PyColorize import Parser
38 from IPython import OInspect
38 from IPython import OInspect
39 from IPython import wildcard
39 from IPython import wildcard
40 from IPython.genutils import *
40 from IPython.genutils import *
41
41
42 # Globals to be set later by Magic constructor
42 # Globals to be set later by Magic constructor
43 MAGIC_PREFIX = ''
43 MAGIC_PREFIX = ''
44 MAGIC_ESCAPE = ''
44 MAGIC_ESCAPE = ''
45
45
46 #***************************************************************************
46 #***************************************************************************
47 # Utility functions
47 # Utility functions
48 def magic2python(cmd):
48 def magic2python(cmd):
49 """Convert a command string of magic syntax to valid Python code."""
49 """Convert a command string of magic syntax to valid Python code."""
50
50
51 if cmd.startswith('#'+MAGIC_ESCAPE) or \
51 if cmd.startswith('#'+MAGIC_ESCAPE) or \
52 cmd.startswith(MAGIC_ESCAPE):
52 cmd.startswith(MAGIC_ESCAPE):
53 if cmd[0]=='#':
53 if cmd[0]=='#':
54 cmd = cmd[1:]
54 cmd = cmd[1:]
55 # we need to return the proper line end later
55 # we need to return the proper line end later
56 if cmd[-1] == '\n':
56 if cmd[-1] == '\n':
57 endl = '\n'
57 endl = '\n'
58 else:
58 else:
59 endl = ''
59 endl = ''
60 try:
60 try:
61 func,args = cmd[1:].split(' ',1)
61 func,args = cmd[1:].split(' ',1)
62 except:
62 except:
63 func,args = cmd[1:].rstrip(),''
63 func,args = cmd[1:].rstrip(),''
64 args = args.replace('"','\\"').replace("'","\\'").rstrip()
64 args = args.replace('"','\\"').replace("'","\\'").rstrip()
65 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
65 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
66 else:
66 else:
67 return cmd
67 return cmd
68
68
69 def on_off(tag):
69 def on_off(tag):
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
71 return ['OFF','ON'][tag]
71 return ['OFF','ON'][tag]
72
72
73
73
74 #****************************************************************************
74 #****************************************************************************
75 # Utility classes
75 # Utility classes
76 class Macro:
76 class Macro:
77 """Simple class to store the value of macros as strings.
77 """Simple class to store the value of macros as strings.
78
78
79 This allows us to later exec them by checking when something is an
79 This allows us to later exec them by checking when something is an
80 instance of this class."""
80 instance of this class."""
81
81
82 def __init__(self,cmds):
82 def __init__(self,cmds):
83 """Build a macro from a list of commands."""
83 """Build a macro from a list of commands."""
84
84
85 # Since the list may include multi-line entries, first make sure that
85 # Since the list may include multi-line entries, first make sure that
86 # they've been all broken up before passing it to magic2python
86 # they've been all broken up before passing it to magic2python
87 cmdlist = map(magic2python,''.join(cmds).split('\n'))
87 cmdlist = map(magic2python,''.join(cmds).split('\n'))
88 self.value = '\n'.join(cmdlist)
88 self.value = '\n'.join(cmdlist)
89
89
90 def __str__(self):
90 def __str__(self):
91 return self.value
91 return self.value
92
92
93 #***************************************************************************
93 #***************************************************************************
94 # Main class implementing Magic functionality
94 # Main class implementing Magic functionality
95 class Magic:
95 class Magic:
96 """Magic functions for InteractiveShell.
96 """Magic functions for InteractiveShell.
97
97
98 Shell functions which can be reached as %function_name. All magic
98 Shell functions which can be reached as %function_name. All magic
99 functions should accept a string, which they can parse for their own
99 functions should accept a string, which they can parse for their own
100 needs. This can make some functions easier to type, eg `%cd ../`
100 needs. This can make some functions easier to type, eg `%cd ../`
101 vs. `%cd("../")`
101 vs. `%cd("../")`
102
102
103 ALL definitions MUST begin with the prefix magic_. The user won't need it
103 ALL definitions MUST begin with the prefix magic_. The user won't need it
104 at the command line, but it is is needed in the definition. """
104 at the command line, but it is is needed in the definition. """
105
105
106 # class globals
106 # class globals
107 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
107 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
108 'Automagic is ON, % prefix NOT needed for magic functions.']
108 'Automagic is ON, % prefix NOT needed for magic functions.']
109
109
110 #......................................................................
110 #......................................................................
111 # some utility functions
111 # some utility functions
112
112
113 def __init__(self,shell):
113 def __init__(self,shell):
114 # XXX This is hackish, clean up later to avoid these messy globals
114 # XXX This is hackish, clean up later to avoid these messy globals
115 global MAGIC_PREFIX, MAGIC_ESCAPE
115 global MAGIC_PREFIX, MAGIC_ESCAPE
116
116
117 self.options_table = {}
117 self.options_table = {}
118 MAGIC_PREFIX = shell.name+'.magic_'
118 MAGIC_PREFIX = shell.name+'.magic_'
119 MAGIC_ESCAPE = shell.ESC_MAGIC
119 MAGIC_ESCAPE = shell.ESC_MAGIC
120 if profile is None:
120 if profile is None:
121 self.magic_prun = self.profile_missing_notice
121 self.magic_prun = self.profile_missing_notice
122
122
123 def profile_missing_notice(self, *args, **kwargs):
123 def profile_missing_notice(self, *args, **kwargs):
124 error("""\
124 error("""\
125 The profile module could not be found. If you are a Debian user,
125 The profile module could not be found. If you are a Debian user,
126 it has been removed from the standard Debian package because of its non-free
126 it has been removed from the standard Debian package because of its non-free
127 license. To use profiling, please install"python2.3-profiler" from non-free.""")
127 license. To use profiling, please install"python2.3-profiler" from non-free.""")
128
128
129 def default_option(self,fn,optstr):
129 def default_option(self,fn,optstr):
130 """Make an entry in the options_table for fn, with value optstr"""
130 """Make an entry in the options_table for fn, with value optstr"""
131
131
132 if fn not in self.lsmagic():
132 if fn not in self.lsmagic():
133 error("%s is not a magic function" % fn)
133 error("%s is not a magic function" % fn)
134 self.options_table[fn] = optstr
134 self.options_table[fn] = optstr
135
135
136 def lsmagic(self):
136 def lsmagic(self):
137 """Return a list of currently available magic functions.
137 """Return a list of currently available magic functions.
138
138
139 Gives a list of the bare names after mangling (['ls','cd', ...], not
139 Gives a list of the bare names after mangling (['ls','cd', ...], not
140 ['magic_ls','magic_cd',...]"""
140 ['magic_ls','magic_cd',...]"""
141
141
142 # FIXME. This needs a cleanup, in the way the magics list is built.
142 # FIXME. This needs a cleanup, in the way the magics list is built.
143
143
144 # magics in class definition
144 # magics in class definition
145 class_magic = lambda fn: fn.startswith('magic_') and \
145 class_magic = lambda fn: fn.startswith('magic_') and \
146 callable(Magic.__dict__[fn])
146 callable(Magic.__dict__[fn])
147 # in instance namespace (run-time user additions)
147 # in instance namespace (run-time user additions)
148 inst_magic = lambda fn: fn.startswith('magic_') and \
148 inst_magic = lambda fn: fn.startswith('magic_') and \
149 callable(self.__dict__[fn])
149 callable(self.__dict__[fn])
150 # and bound magics by user (so they can access self):
150 # and bound magics by user (so they can access self):
151 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
151 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
152 callable(self.__class__.__dict__[fn])
152 callable(self.__class__.__dict__[fn])
153 magics = filter(class_magic,Magic.__dict__.keys()) + \
153 magics = filter(class_magic,Magic.__dict__.keys()) + \
154 filter(inst_magic,self.__dict__.keys()) + \
154 filter(inst_magic,self.__dict__.keys()) + \
155 filter(inst_bound_magic,self.__class__.__dict__.keys())
155 filter(inst_bound_magic,self.__class__.__dict__.keys())
156 out = []
156 out = []
157 for fn in magics:
157 for fn in magics:
158 out.append(fn.replace('magic_','',1))
158 out.append(fn.replace('magic_','',1))
159 out.sort()
159 out.sort()
160 return out
160 return out
161
161
162 def set_shell(self,shell):
162 def set_shell(self,shell):
163 self.shell = shell
163 self.shell = shell
164 self.alias_table = shell.alias_table
164 self.alias_table = shell.alias_table
165
165
166 def extract_input_slices(self,slices):
166 def extract_input_slices(self,slices):
167 """Return as a string a set of input history slices.
167 """Return as a string a set of input history slices.
168
168
169 The set of slices is given as a list of strings (like ['1','4:8','9'],
169 The set of slices is given as a list of strings (like ['1','4:8','9'],
170 since this function is for use by magic functions which get their
170 since this function is for use by magic functions which get their
171 arguments as strings."""
171 arguments as strings."""
172
172
173 cmds = []
173 cmds = []
174 for chunk in slices:
174 for chunk in slices:
175 if ':' in chunk:
175 if ':' in chunk:
176 ini,fin = map(int,chunk.split(':'))
176 ini,fin = map(int,chunk.split(':'))
177 else:
177 else:
178 ini = int(chunk)
178 ini = int(chunk)
179 fin = ini+1
179 fin = ini+1
180 cmds.append(self.shell.input_hist[ini:fin])
180 cmds.append(self.shell.input_hist[ini:fin])
181 return cmds
181 return cmds
182
182
183 def _ofind(self,oname):
183 def _ofind(self,oname):
184 """Find an object in the available namespaces.
184 """Find an object in the available namespaces.
185
185
186 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
186 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
187
187
188 Has special code to detect magic functions.
188 Has special code to detect magic functions.
189 """
189 """
190
190
191 oname = oname.strip()
191 oname = oname.strip()
192
192
193 # Namespaces to search in:
193 # Namespaces to search in:
194 user_ns = self.shell.user_ns
194 user_ns = self.shell.user_ns
195 internal_ns = self.shell.internal_ns
195 internal_ns = self.shell.internal_ns
196 builtin_ns = __builtin__.__dict__
196 builtin_ns = __builtin__.__dict__
197 alias_ns = self.shell.alias_table
197 alias_ns = self.shell.alias_table
198
198
199 # Put them in a list. The order is important so that we find things in
199 # Put them in a list. The order is important so that we find things in
200 # the same order that Python finds them.
200 # the same order that Python finds them.
201 namespaces = [ ('Interactive',user_ns),
201 namespaces = [ ('Interactive',user_ns),
202 ('IPython internal',internal_ns),
202 ('IPython internal',internal_ns),
203 ('Python builtin',builtin_ns),
203 ('Python builtin',builtin_ns),
204 ('Alias',alias_ns),
204 ('Alias',alias_ns),
205 ]
205 ]
206
206
207 # initialize results to 'null'
207 # initialize results to 'null'
208 found = 0; obj = None; ospace = None; ds = None;
208 found = 0; obj = None; ospace = None; ds = None;
209 ismagic = 0; isalias = 0
209 ismagic = 0; isalias = 0
210
210
211 # Look for the given name by splitting it in parts. If the head is
211 # Look for the given name by splitting it in parts. If the head is
212 # found, then we look for all the remaining parts as members, and only
212 # found, then we look for all the remaining parts as members, and only
213 # declare success if we can find them all.
213 # declare success if we can find them all.
214 oname_parts = oname.split('.')
214 oname_parts = oname.split('.')
215 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
215 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
216 for nsname,ns in namespaces:
216 for nsname,ns in namespaces:
217 try:
217 try:
218 obj = ns[oname_head]
218 obj = ns[oname_head]
219 except KeyError:
219 except KeyError:
220 continue
220 continue
221 else:
221 else:
222 for part in oname_rest:
222 for part in oname_rest:
223 try:
223 try:
224 obj = getattr(obj,part)
224 obj = getattr(obj,part)
225 except:
225 except:
226 # Blanket except b/c some badly implemented objects
226 # Blanket except b/c some badly implemented objects
227 # allow __getattr__ to raise exceptions other than
227 # allow __getattr__ to raise exceptions other than
228 # AttributeError, which then crashes IPython.
228 # AttributeError, which then crashes IPython.
229 break
229 break
230 else:
230 else:
231 # If we finish the for loop (no break), we got all members
231 # If we finish the for loop (no break), we got all members
232 found = 1
232 found = 1
233 ospace = nsname
233 ospace = nsname
234 if ns == alias_ns:
234 if ns == alias_ns:
235 isalias = 1
235 isalias = 1
236 break # namespace loop
236 break # namespace loop
237
237
238 # Try to see if it's magic
238 # Try to see if it's magic
239 if not found:
239 if not found:
240 if oname.startswith(self.shell.ESC_MAGIC):
240 if oname.startswith(self.shell.ESC_MAGIC):
241 oname = oname[1:]
241 oname = oname[1:]
242 obj = getattr(self,'magic_'+oname,None)
242 obj = getattr(self,'magic_'+oname,None)
243 if obj is not None:
243 if obj is not None:
244 found = 1
244 found = 1
245 ospace = 'IPython internal'
245 ospace = 'IPython internal'
246 ismagic = 1
246 ismagic = 1
247
247
248 # Last try: special-case some literals like '', [], {}, etc:
248 # Last try: special-case some literals like '', [], {}, etc:
249 if not found and oname_head in ["''",'""','[]','{}','()']:
249 if not found and oname_head in ["''",'""','[]','{}','()']:
250 obj = eval(oname_head)
250 obj = eval(oname_head)
251 found = 1
251 found = 1
252 ospace = 'Interactive'
252 ospace = 'Interactive'
253
253
254 return {'found':found, 'obj':obj, 'namespace':ospace,
254 return {'found':found, 'obj':obj, 'namespace':ospace,
255 'ismagic':ismagic, 'isalias':isalias}
255 'ismagic':ismagic, 'isalias':isalias}
256
256
257 def arg_err(self,func):
257 def arg_err(self,func):
258 """Print docstring if incorrect arguments were passed"""
258 """Print docstring if incorrect arguments were passed"""
259 print 'Error in arguments:'
259 print 'Error in arguments:'
260 print OInspect.getdoc(func)
260 print OInspect.getdoc(func)
261
261
262
262
263 def format_latex(self,str):
263 def format_latex(self,str):
264 """Format a string for latex inclusion."""
264 """Format a string for latex inclusion."""
265
265
266 # Characters that need to be escaped for latex:
266 # Characters that need to be escaped for latex:
267 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
267 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
268 # Magic command names as headers:
268 # Magic command names as headers:
269 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
269 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
270 re.MULTILINE)
270 re.MULTILINE)
271 # Magic commands
271 # Magic commands
272 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
272 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
273 re.MULTILINE)
273 re.MULTILINE)
274 # Paragraph continue
274 # Paragraph continue
275 par_re = re.compile(r'\\$',re.MULTILINE)
275 par_re = re.compile(r'\\$',re.MULTILINE)
276
276
277 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
277 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
278 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
278 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
279 str = par_re.sub(r'\\\\',str)
279 str = par_re.sub(r'\\\\',str)
280 str = escape_re.sub(r'\\\1',str)
280 str = escape_re.sub(r'\\\1',str)
281 return str
281 return str
282
282
283 def format_screen(self,str):
283 def format_screen(self,str):
284 """Format a string for screen printing.
284 """Format a string for screen printing.
285
285
286 This removes some latex-type format codes."""
286 This removes some latex-type format codes."""
287 # Paragraph continue
287 # Paragraph continue
288 par_re = re.compile(r'\\$',re.MULTILINE)
288 par_re = re.compile(r'\\$',re.MULTILINE)
289 str = par_re.sub('',str)
289 str = par_re.sub('',str)
290 return str
290 return str
291
291
292 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
292 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
293 """Parse options passed to an argument string.
293 """Parse options passed to an argument string.
294
294
295 The interface is similar to that of getopt(), but it returns back a
295 The interface is similar to that of getopt(), but it returns back a
296 Struct with the options as keys and the stripped argument string still
296 Struct with the options as keys and the stripped argument string still
297 as a string.
297 as a string.
298
298
299 arg_str is quoted as a true sys.argv vector by calling on the fly a
299 arg_str is quoted as a true sys.argv vector by using shlex.split.
300 python process in a subshell. This allows us to easily expand
300 This allows us to easily expand variables, glob files, quote
301 variables, glob files, quote arguments, etc, with all the power and
301 arguments, etc.
302 correctness of the underlying system shell.
303
302
304 Options:
303 Options:
305 -mode: default 'string'. If given as 'list', the argument string is
304 -mode: default 'string'. If given as 'list', the argument string is
306 returned as a list (split on whitespace) instead of a string.
305 returned as a list (split on whitespace) instead of a string.
307
306
308 -list_all: put all option values in lists. Normally only options
307 -list_all: put all option values in lists. Normally only options
309 appearing more than once are put in a list."""
308 appearing more than once are put in a list."""
310
309
311 # inject default options at the beginning of the input line
310 # inject default options at the beginning of the input line
312 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
311 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
313 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
312 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
314
313
315 mode = kw.get('mode','string')
314 mode = kw.get('mode','string')
316 if mode not in ['string','list']:
315 if mode not in ['string','list']:
317 raise ValueError,'incorrect mode given: %s' % mode
316 raise ValueError,'incorrect mode given: %s' % mode
318 # Get options
317 # Get options
319 list_all = kw.get('list_all',0)
318 list_all = kw.get('list_all',0)
320
319
321 # Check if we have more than one argument to warrant extra processing:
320 # Check if we have more than one argument to warrant extra processing:
322 odict = {} # Dictionary with options
321 odict = {} # Dictionary with options
323 args = arg_str.split()
322 args = arg_str.split()
324 if len(args) >= 1:
323 if len(args) >= 1:
325 # If the list of inputs only has 0 or 1 thing in it, there's no
324 # If the list of inputs only has 0 or 1 thing in it, there's no
326 # need to look for options
325 # need to look for options
327 argv = shlex_split(arg_str)
326 argv = shlex_split(arg_str)
328 # Do regular option processing
327 # Do regular option processing
329 opts,args = getopt(argv,opt_str,*long_opts)
328 opts,args = getopt(argv,opt_str,*long_opts)
330 for o,a in opts:
329 for o,a in opts:
331 if o.startswith('--'):
330 if o.startswith('--'):
332 o = o[2:]
331 o = o[2:]
333 else:
332 else:
334 o = o[1:]
333 o = o[1:]
335 try:
334 try:
336 odict[o].append(a)
335 odict[o].append(a)
337 except AttributeError:
336 except AttributeError:
338 odict[o] = [odict[o],a]
337 odict[o] = [odict[o],a]
339 except KeyError:
338 except KeyError:
340 if list_all:
339 if list_all:
341 odict[o] = [a]
340 odict[o] = [a]
342 else:
341 else:
343 odict[o] = a
342 odict[o] = a
344
343
345 # Prepare opts,args for return
344 # Prepare opts,args for return
346 opts = Struct(odict)
345 opts = Struct(odict)
347 if mode == 'string':
346 if mode == 'string':
348 args = ' '.join(args)
347 args = ' '.join(args)
349
348
350 return opts,args
349 return opts,args
351
350
352 #......................................................................
351 #......................................................................
353 # And now the actual magic functions
352 # And now the actual magic functions
354
353
355 # Functions for IPython shell work (vars,funcs, config, etc)
354 # Functions for IPython shell work (vars,funcs, config, etc)
356 def magic_lsmagic(self, parameter_s = ''):
355 def magic_lsmagic(self, parameter_s = ''):
357 """List currently available magic functions."""
356 """List currently available magic functions."""
358 mesc = self.shell.ESC_MAGIC
357 mesc = self.shell.ESC_MAGIC
359 print 'Available magic functions:\n'+mesc+\
358 print 'Available magic functions:\n'+mesc+\
360 (' '+mesc).join(self.lsmagic())
359 (' '+mesc).join(self.lsmagic())
361 print '\n' + Magic.auto_status[self.shell.rc.automagic]
360 print '\n' + Magic.auto_status[self.shell.rc.automagic]
362 return None
361 return None
363
362
364 def magic_magic(self, parameter_s = ''):
363 def magic_magic(self, parameter_s = ''):
365 """Print information about the magic function system."""
364 """Print information about the magic function system."""
366
365
367 mode = ''
366 mode = ''
368 try:
367 try:
369 if parameter_s.split()[0] == '-latex':
368 if parameter_s.split()[0] == '-latex':
370 mode = 'latex'
369 mode = 'latex'
371 except:
370 except:
372 pass
371 pass
373
372
374 magic_docs = []
373 magic_docs = []
375 for fname in self.lsmagic():
374 for fname in self.lsmagic():
376 mname = 'magic_' + fname
375 mname = 'magic_' + fname
377 for space in (Magic,self,self.__class__):
376 for space in (Magic,self,self.__class__):
378 try:
377 try:
379 fn = space.__dict__[mname]
378 fn = space.__dict__[mname]
380 except KeyError:
379 except KeyError:
381 pass
380 pass
382 else:
381 else:
383 break
382 break
384 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
383 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
385 fname,fn.__doc__))
384 fname,fn.__doc__))
386 magic_docs = ''.join(magic_docs)
385 magic_docs = ''.join(magic_docs)
387
386
388 if mode == 'latex':
387 if mode == 'latex':
389 print self.format_latex(magic_docs)
388 print self.format_latex(magic_docs)
390 return
389 return
391 else:
390 else:
392 magic_docs = self.format_screen(magic_docs)
391 magic_docs = self.format_screen(magic_docs)
393
392
394 outmsg = """
393 outmsg = """
395 IPython's 'magic' functions
394 IPython's 'magic' functions
396 ===========================
395 ===========================
397
396
398 The magic function system provides a series of functions which allow you to
397 The magic function system provides a series of functions which allow you to
399 control the behavior of IPython itself, plus a lot of system-type
398 control the behavior of IPython itself, plus a lot of system-type
400 features. All these functions are prefixed with a % character, but parameters
399 features. All these functions are prefixed with a % character, but parameters
401 are given without parentheses or quotes.
400 are given without parentheses or quotes.
402
401
403 NOTE: If you have 'automagic' enabled (via the command line option or with the
402 NOTE: If you have 'automagic' enabled (via the command line option or with the
404 %automagic function), you don't need to type in the % explicitly. By default,
403 %automagic function), you don't need to type in the % explicitly. By default,
405 IPython ships with automagic on, so you should only rarely need the % escape.
404 IPython ships with automagic on, so you should only rarely need the % escape.
406
405
407 Example: typing '%cd mydir' (without the quotes) changes you working directory
406 Example: typing '%cd mydir' (without the quotes) changes you working directory
408 to 'mydir', if it exists.
407 to 'mydir', if it exists.
409
408
410 You can define your own magic functions to extend the system. See the supplied
409 You can define your own magic functions to extend the system. See the supplied
411 ipythonrc and example-magic.py files for details (in your ipython
410 ipythonrc and example-magic.py files for details (in your ipython
412 configuration directory, typically $HOME/.ipython/).
411 configuration directory, typically $HOME/.ipython/).
413
412
414 You can also define your own aliased names for magic functions. In your
413 You can also define your own aliased names for magic functions. In your
415 ipythonrc file, placing a line like:
414 ipythonrc file, placing a line like:
416
415
417 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
416 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
418
417
419 will define %pf as a new name for %profile.
418 will define %pf as a new name for %profile.
420
419
421 You can also call magics in code using the ipmagic() function, which IPython
420 You can also call magics in code using the ipmagic() function, which IPython
422 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
421 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
423
422
424 For a list of the available magic functions, use %lsmagic. For a description
423 For a list of the available magic functions, use %lsmagic. For a description
425 of any of them, type %magic_name?, e.g. '%cd?'.
424 of any of them, type %magic_name?, e.g. '%cd?'.
426
425
427 Currently the magic system has the following functions:\n"""
426 Currently the magic system has the following functions:\n"""
428
427
429 mesc = self.shell.ESC_MAGIC
428 mesc = self.shell.ESC_MAGIC
430 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
429 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
431 "\n\n%s%s\n\n%s" % (outmsg,
430 "\n\n%s%s\n\n%s" % (outmsg,
432 magic_docs,mesc,mesc,
431 magic_docs,mesc,mesc,
433 (' '+mesc).join(self.lsmagic()),
432 (' '+mesc).join(self.lsmagic()),
434 Magic.auto_status[self.shell.rc.automagic] ) )
433 Magic.auto_status[self.shell.rc.automagic] ) )
435
434
436 page(outmsg,screen_lines=self.shell.rc.screen_length)
435 page(outmsg,screen_lines=self.shell.rc.screen_length)
437
436
438 def magic_automagic(self, parameter_s = ''):
437 def magic_automagic(self, parameter_s = ''):
439 """Make magic functions callable without having to type the initial %.
438 """Make magic functions callable without having to type the initial %.
440
439
441 Toggles on/off (when off, you must call it as %automagic, of
440 Toggles on/off (when off, you must call it as %automagic, of
442 course). Note that magic functions have lowest priority, so if there's
441 course). Note that magic functions have lowest priority, so if there's
443 a variable whose name collides with that of a magic fn, automagic
442 a variable whose name collides with that of a magic fn, automagic
444 won't work for that function (you get the variable instead). However,
443 won't work for that function (you get the variable instead). However,
445 if you delete the variable (del var), the previously shadowed magic
444 if you delete the variable (del var), the previously shadowed magic
446 function becomes visible to automagic again."""
445 function becomes visible to automagic again."""
447
446
448 rc = self.shell.rc
447 rc = self.shell.rc
449 rc.automagic = not rc.automagic
448 rc.automagic = not rc.automagic
450 print '\n' + Magic.auto_status[rc.automagic]
449 print '\n' + Magic.auto_status[rc.automagic]
451
450
452 def magic_autocall(self, parameter_s = ''):
451 def magic_autocall(self, parameter_s = ''):
453 """Make functions callable without having to type parentheses.
452 """Make functions callable without having to type parentheses.
454
453
455 This toggles the autocall command line option on and off."""
454 This toggles the autocall command line option on and off."""
456
455
457 rc = self.shell.rc
456 rc = self.shell.rc
458 rc.autocall = not rc.autocall
457 rc.autocall = not rc.autocall
459 print "Automatic calling is:",['OFF','ON'][rc.autocall]
458 print "Automatic calling is:",['OFF','ON'][rc.autocall]
460
459
461 def magic_autoindent(self, parameter_s = ''):
460 def magic_autoindent(self, parameter_s = ''):
462 """Toggle autoindent on/off (if available)."""
461 """Toggle autoindent on/off (if available)."""
463
462
464 self.shell.set_autoindent()
463 self.shell.set_autoindent()
465 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
464 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
466
465
467 def magic_system_verbose(self, parameter_s = ''):
466 def magic_system_verbose(self, parameter_s = ''):
468 """Toggle verbose printing of system calls on/off."""
467 """Toggle verbose printing of system calls on/off."""
469
468
470 self.shell.rc_set_toggle('system_verbose')
469 self.shell.rc_set_toggle('system_verbose')
471 print "System verbose printing is:",\
470 print "System verbose printing is:",\
472 ['OFF','ON'][self.shell.rc.system_verbose]
471 ['OFF','ON'][self.shell.rc.system_verbose]
473
472
474 def magic_history(self, parameter_s = ''):
473 def magic_history(self, parameter_s = ''):
475 """Print input history (_i<n> variables), with most recent last.
474 """Print input history (_i<n> variables), with most recent last.
476
475
477 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
476 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
478 %history [-n] n -> print at most n inputs\\
477 %history [-n] n -> print at most n inputs\\
479 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
478 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
480
479
481 Each input's number <n> is shown, and is accessible as the
480 Each input's number <n> is shown, and is accessible as the
482 automatically generated variable _i<n>. Multi-line statements are
481 automatically generated variable _i<n>. Multi-line statements are
483 printed starting at a new line for easy copy/paste.
482 printed starting at a new line for easy copy/paste.
484
483
485 If option -n is used, input numbers are not printed. This is useful if
484 If option -n is used, input numbers are not printed. This is useful if
486 you want to get a printout of many lines which can be directly pasted
485 you want to get a printout of many lines which can be directly pasted
487 into a text editor.
486 into a text editor.
488
487
489 This feature is only available if numbered prompts are in use."""
488 This feature is only available if numbered prompts are in use."""
490
489
491 if not self.do_full_cache:
490 if not self.do_full_cache:
492 print 'This feature is only available if numbered prompts are in use.'
491 print 'This feature is only available if numbered prompts are in use.'
493 return
492 return
494 opts,args = self.parse_options(parameter_s,'n',mode='list')
493 opts,args = self.parse_options(parameter_s,'n',mode='list')
495
494
496 default_length = 40
495 default_length = 40
497 if len(args) == 0:
496 if len(args) == 0:
498 final = self.outputcache.prompt_count
497 final = self.outputcache.prompt_count
499 init = max(1,final-default_length)
498 init = max(1,final-default_length)
500 elif len(args) == 1:
499 elif len(args) == 1:
501 final = self.outputcache.prompt_count
500 final = self.outputcache.prompt_count
502 init = max(1,final-int(args[0]))
501 init = max(1,final-int(args[0]))
503 elif len(args) == 2:
502 elif len(args) == 2:
504 init,final = map(int,args)
503 init,final = map(int,args)
505 else:
504 else:
506 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
505 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
507 print self.magic_hist.__doc__
506 print self.magic_hist.__doc__
508 return
507 return
509 width = len(str(final))
508 width = len(str(final))
510 line_sep = ['','\n']
509 line_sep = ['','\n']
511 input_hist = self.shell.input_hist
510 input_hist = self.shell.input_hist
512 print_nums = not opts.has_key('n')
511 print_nums = not opts.has_key('n')
513 for in_num in range(init,final):
512 for in_num in range(init,final):
514 inline = input_hist[in_num]
513 inline = input_hist[in_num]
515 multiline = inline.count('\n') > 1
514 multiline = inline.count('\n') > 1
516 if print_nums:
515 if print_nums:
517 print str(in_num).ljust(width)+':'+ line_sep[multiline],
516 print str(in_num).ljust(width)+':'+ line_sep[multiline],
518 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
517 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
519 inline.startswith('#!'):
518 inline.startswith('#!'):
520 print inline[1:],
519 print inline[1:],
521 else:
520 else:
522 print inline,
521 print inline,
523
522
524 def magic_hist(self, parameter_s=''):
523 def magic_hist(self, parameter_s=''):
525 """Alternate name for %history."""
524 """Alternate name for %history."""
526 return self.magic_history(parameter_s)
525 return self.magic_history(parameter_s)
527
526
528 def magic_p(self, parameter_s=''):
527 def magic_p(self, parameter_s=''):
529 """Just a short alias for Python's 'print'."""
528 """Just a short alias for Python's 'print'."""
530 exec 'print ' + parameter_s in self.shell.user_ns
529 exec 'print ' + parameter_s in self.shell.user_ns
531
530
532 def magic_r(self, parameter_s=''):
531 def magic_r(self, parameter_s=''):
533 """Repeat previous input.
532 """Repeat previous input.
534
533
535 If given an argument, repeats the previous command which starts with
534 If given an argument, repeats the previous command which starts with
536 the same string, otherwise it just repeats the previous input.
535 the same string, otherwise it just repeats the previous input.
537
536
538 Shell escaped commands (with ! as first character) are not recognized
537 Shell escaped commands (with ! as first character) are not recognized
539 by this system, only pure python code and magic commands.
538 by this system, only pure python code and magic commands.
540 """
539 """
541
540
542 start = parameter_s.strip()
541 start = parameter_s.strip()
543 esc_magic = self.shell.ESC_MAGIC
542 esc_magic = self.shell.ESC_MAGIC
544 # Identify magic commands even if automagic is on (which means
543 # Identify magic commands even if automagic is on (which means
545 # the in-memory version is different from that typed by the user).
544 # the in-memory version is different from that typed by the user).
546 if self.shell.rc.automagic:
545 if self.shell.rc.automagic:
547 start_magic = esc_magic+start
546 start_magic = esc_magic+start
548 else:
547 else:
549 start_magic = start
548 start_magic = start
550 # Look through the input history in reverse
549 # Look through the input history in reverse
551 for n in range(len(self.shell.input_hist)-2,0,-1):
550 for n in range(len(self.shell.input_hist)-2,0,-1):
552 input = self.shell.input_hist[n]
551 input = self.shell.input_hist[n]
553 # skip plain 'r' lines so we don't recurse to infinity
552 # skip plain 'r' lines so we don't recurse to infinity
554 if input != 'ipmagic("r")\n' and \
553 if input != 'ipmagic("r")\n' and \
555 (input.startswith(start) or input.startswith(start_magic)):
554 (input.startswith(start) or input.startswith(start_magic)):
556 #print 'match',`input` # dbg
555 #print 'match',`input` # dbg
557 if input.startswith(esc_magic):
556 if input.startswith(esc_magic):
558 input = magic2python(input)
557 input = magic2python(input)
559 #print 'modified',`input` # dbg
558 #print 'modified',`input` # dbg
560 print 'Executing:',input,
559 print 'Executing:',input,
561 exec input in self.shell.user_ns
560 exec input in self.shell.user_ns
562 return
561 return
563 print 'No previous input matching `%s` found.' % start
562 print 'No previous input matching `%s` found.' % start
564
563
565 def magic_page(self, parameter_s=''):
564 def magic_page(self, parameter_s=''):
566 """Pretty print the object and display it through a pager.
565 """Pretty print the object and display it through a pager.
567
566
568 If no parameter is given, use _ (last output)."""
567 If no parameter is given, use _ (last output)."""
569 # After a function contributed by Olivier Aubert, slightly modified.
568 # After a function contributed by Olivier Aubert, slightly modified.
570
569
571 oname = parameter_s and parameter_s or '_'
570 oname = parameter_s and parameter_s or '_'
572 info = self._ofind(oname)
571 info = self._ofind(oname)
573 if info['found']:
572 if info['found']:
574 page(pformat(info['obj']))
573 page(pformat(info['obj']))
575 else:
574 else:
576 print 'Object `%s` not found' % oname
575 print 'Object `%s` not found' % oname
577
576
578 def magic_profile(self, parameter_s=''):
577 def magic_profile(self, parameter_s=''):
579 """Print your currently active IPyhton profile."""
578 """Print your currently active IPyhton profile."""
580 if self.shell.rc.profile:
579 if self.shell.rc.profile:
581 printpl('Current IPython profile: $self.shell.rc.profile.')
580 printpl('Current IPython profile: $self.shell.rc.profile.')
582 else:
581 else:
583 print 'No profile active.'
582 print 'No profile active.'
584
583
585 def _inspect(self,meth,oname,**kw):
584 def _inspect(self,meth,oname,**kw):
586 """Generic interface to the inspector system.
585 """Generic interface to the inspector system.
587
586
588 This function is meant to be called by pdef, pdoc & friends."""
587 This function is meant to be called by pdef, pdoc & friends."""
589
588
590 oname = oname.strip()
589 oname = oname.strip()
591 info = Struct(self._ofind(oname))
590 info = Struct(self._ofind(oname))
592 if info.found:
591 if info.found:
593 pmethod = getattr(self.shell.inspector,meth)
592 pmethod = getattr(self.shell.inspector,meth)
594 formatter = info.ismagic and self.format_screen or None
593 formatter = info.ismagic and self.format_screen or None
595 if meth == 'pdoc':
594 if meth == 'pdoc':
596 pmethod(info.obj,oname,formatter)
595 pmethod(info.obj,oname,formatter)
597 elif meth == 'pinfo':
596 elif meth == 'pinfo':
598 pmethod(info.obj,oname,formatter,info,**kw)
597 pmethod(info.obj,oname,formatter,info,**kw)
599 else:
598 else:
600 pmethod(info.obj,oname)
599 pmethod(info.obj,oname)
601 else:
600 else:
602 print 'Object `%s` not found.' % oname
601 print 'Object `%s` not found.' % oname
603 return 'not found' # so callers can take other action
602 return 'not found' # so callers can take other action
604
603
605 def magic_pdef(self, parameter_s=''):
604 def magic_pdef(self, parameter_s=''):
606 """Print the definition header for any callable object.
605 """Print the definition header for any callable object.
607
606
608 If the object is a class, print the constructor information."""
607 If the object is a class, print the constructor information."""
609 self._inspect('pdef',parameter_s)
608 self._inspect('pdef',parameter_s)
610
609
611 def magic_pdoc(self, parameter_s=''):
610 def magic_pdoc(self, parameter_s=''):
612 """Print the docstring for an object.
611 """Print the docstring for an object.
613
612
614 If the given object is a class, it will print both the class and the
613 If the given object is a class, it will print both the class and the
615 constructor docstrings."""
614 constructor docstrings."""
616 self._inspect('pdoc',parameter_s)
615 self._inspect('pdoc',parameter_s)
617
616
618 def magic_psource(self, parameter_s=''):
617 def magic_psource(self, parameter_s=''):
619 """Print (or run through pager) the source code for an object."""
618 """Print (or run through pager) the source code for an object."""
620 self._inspect('psource',parameter_s)
619 self._inspect('psource',parameter_s)
621
620
622 def magic_pfile(self, parameter_s=''):
621 def magic_pfile(self, parameter_s=''):
623 """Print (or run through pager) the file where an object is defined.
622 """Print (or run through pager) the file where an object is defined.
624
623
625 The file opens at the line where the object definition begins. IPython
624 The file opens at the line where the object definition begins. IPython
626 will honor the environment variable PAGER if set, and otherwise will
625 will honor the environment variable PAGER if set, and otherwise will
627 do its best to print the file in a convenient form.
626 do its best to print the file in a convenient form.
628
627
629 If the given argument is not an object currently defined, IPython will
628 If the given argument is not an object currently defined, IPython will
630 try to interpret it as a filename (automatically adding a .py extension
629 try to interpret it as a filename (automatically adding a .py extension
631 if needed). You can thus use %pfile as a syntax highlighting code
630 if needed). You can thus use %pfile as a syntax highlighting code
632 viewer."""
631 viewer."""
633
632
634 # first interpret argument as an object name
633 # first interpret argument as an object name
635 out = self._inspect('pfile',parameter_s)
634 out = self._inspect('pfile',parameter_s)
636 # if not, try the input as a filename
635 # if not, try the input as a filename
637 if out == 'not found':
636 if out == 'not found':
638 try:
637 try:
639 filename = get_py_filename(parameter_s)
638 filename = get_py_filename(parameter_s)
640 except IOError,msg:
639 except IOError,msg:
641 print msg
640 print msg
642 return
641 return
643 page(self.shell.inspector.format(file(filename).read()))
642 page(self.shell.inspector.format(file(filename).read()))
644
643
645 def magic_pinfo(self, parameter_s=''):
644 def magic_pinfo(self, parameter_s=''):
646 """Provide detailed information about an object.
645 """Provide detailed information about an object.
647
646
648 '%pinfo object' is just a synonym for object? or ?object."""
647 '%pinfo object' is just a synonym for object? or ?object."""
649
648
650 #print 'pinfo par: <%s>' % parameter_s # dbg
649 #print 'pinfo par: <%s>' % parameter_s # dbg
651
650
652 # detail_level: 0 -> obj? , 1 -> obj??
651 # detail_level: 0 -> obj? , 1 -> obj??
653 detail_level = 0
652 detail_level = 0
654 # We need to detect if we got called as 'pinfo pinfo foo', which can
653 # We need to detect if we got called as 'pinfo pinfo foo', which can
655 # happen if the user types 'pinfo foo?' at the cmd line.
654 # happen if the user types 'pinfo foo?' at the cmd line.
656 pinfo,qmark1,oname,qmark2 = \
655 pinfo,qmark1,oname,qmark2 = \
657 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
656 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
658 if pinfo or qmark1 or qmark2:
657 if pinfo or qmark1 or qmark2:
659 detail_level = 1
658 detail_level = 1
660 if "*" in oname:
659 if "*" in oname:
661 self.magic_psearch(oname)
660 self.magic_psearch(oname)
662 else:
661 else:
663 self._inspect('pinfo',oname,detail_level=detail_level)
662 self._inspect('pinfo',oname,detail_level=detail_level)
664
663
665 def magic_psearch(self, parameter_s=''):
664 def magic_psearch(self, parameter_s=''):
666 """Search for object in namespaces by wildcard.
665 """Search for object in namespaces by wildcard.
667
666
668 %psearch PATTERN [OBJECT TYPE] [-NAMESPACE]* [+NAMESPACE]* [-a] [-c]
667 %psearch [options] PATTERN [OBJECT TYPE]
669
668
670 Note: ? can be used as a synonym for %psearch, at the beginning or at
669 Note: ? can be used as a synonym for %psearch, at the beginning or at
671 the end: both a*? and ?a* are equivalent to '%psearch a*'.
670 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
672
671 rest of the command line must be unchanged (options come first), so
673 PATTERN
672 for example the following forms are equivalent
674
673
675 where PATTERN is a string containing * as a wildcard similar to its
674 %psearch -i a* function
676 use in a shell. The pattern is matched in all namespaces on the
675 -i a* function?
677 search path. By default objects starting with a single _ are not
676 ?-i a* function
678 matched, many IPython generated objects have a single underscore. The
677
679 default is case insensitive matching. Matching is also done on the
678 Arguments:
680 attributes of objects and not only on the objects in a module.
679
681
680 PATTERN
682 [OBJECT TYPE]
681
683 Is the name of a python type from the types module. The name is given
682 where PATTERN is a string containing * as a wildcard similar to its
684 in lowercase without the ending type, ex. StringType is written
683 use in a shell. The pattern is matched in all namespaces on the
685 string. By adding a type here only objects matching the given type are
684 search path. By default objects starting with a single _ are not
686 matched. Using all here makes the pattern match all types (this is the
685 matched, many IPython generated objects have a single
687 default).
686 underscore. The default is case insensitive matching. Matching is
688
687 also done on the attributes of objects and not only on the objects
689 [-NAMESPACE]* [+NAMESPACE]*
688 in a module.
690 The possible namespaces are builtin, user, internal, alias. Where
689
691 builtin and user are default. Builtin contains the python module
690 [OBJECT TYPE]
692 builtin, user contains all imported namespaces, alias only contain the
691
693 shell aliases and no python objects, internal contains objects used by
692 Is the name of a python type from the types module. The name is
694 IPython. The namespaces on the search path are removed by -namespace
693 given in lowercase without the ending type, ex. StringType is
695 and added by +namespace.
694 written string. By adding a type here only objects matching the
696
695 given type are matched. Using all here makes the pattern match all
697 [-a] makes the pattern match even objects with a single underscore.
696 types (this is the default).
698 [-c] makes the pattern case sensitive.
697
698 Options:
699
700 -a: makes the pattern match even objects whose names start with a
701 single underscore. These names are normally ommitted from the
702 search.
703
704 -i/-c: make the pattern case insensitive/sensitive. If neither of
705 these options is given, the default is read from your ipythonrc
706 file. The option name which sets this value is
707 'wildcards_case_sensitive'. If this option is not specified in your
708 ipythonrc file, IPython's internal default is to do a case sensitive
709 search.
710
711 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
712 specifiy can be searched in any of the following namespaces:
713 'builtin', 'user', 'user_global','internal', 'alias', where
714 'builtin' and 'user' are the search defaults. Note that you should
715 not use quotes when specifying namespaces.
716
717 'Builtin' contains the python module builtin, 'user' contains all
718 user data, 'alias' only contain the shell aliases and no python
719 objects, 'internal' contains objects used by IPython. The
720 'user_global' namespace is only used by embedded IPython instances,
721 and it contains module-level globals. You can add namespaces to the
722 search with -s or exclude them with -e (these options can be given
723 more than once).
699
724
700 Examples:
725 Examples:
701
726
702 %psearch a* list objects beginning with an a
727 %psearch a* -> objects beginning with an a
703 %psearch a* function list all functions beginning with an a
728 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
704 %psearch re.e* list objects beginning with an e in module re
729 %psearch a* function -> all functions beginning with an a
705 %psearch r*.e* list objects that starts with e in modules starting in r
730 %psearch re.e* -> objects beginning with an e in module re
706 %psearch r*.* string list all strings in modules beginning with r
731 %psearch r*.e* -> objects that start with e in modules starting in r
732 %psearch r*.* string -> all strings in modules beginning with r
707
733
708 Case sensitve search:
734 Case sensitve search:
709
735
710 %psearch a* -c list all object beginning with lower case a
736 %psearch -c a* list all object beginning with lower case a
711
737
712 Show objects beginning with a single _:
738 Show objects beginning with a single _:
713
739
714 %psearch _* -a list objects beginning with underscore"""
740 %psearch -a _* list objects beginning with a single underscore"""
741
742 # default namespaces to be searched
743 def_search = ['user','builtin']
744
745 # Process options/args
746 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
747 opt = opts.get
748 shell = self.shell
749 psearch = shell.inspector.psearch
715
750
716 self.shell.inspector.psearch(parameter_s,shell=self.shell)
751 # select case options
752 if opts.has_key('i'):
753 ignore_case = True
754 elif opts.has_key('c'):
755 ignore_case = False
756 else:
757 ignore_case = not shell.rc.wildcards_case_sensitive
758
759 # Build list of namespaces to search from user options
760 def_search.extend(opt('s',[]))
761 ns_exclude = ns_exclude=opt('e',[])
762 ns_search = [nm for nm in def_search if nm not in ns_exclude]
763
764 # Call the actual search
765 try:
766 psearch(args,shell.ns_table,ns_search,
767 show_all=opt('a'),ignore_case=ignore_case)
768 except:
769 shell.showtraceback()
717
770
718 def magic_who_ls(self, parameter_s=''):
771 def magic_who_ls(self, parameter_s=''):
719 """Return a sorted list of all interactive variables.
772 """Return a sorted list of all interactive variables.
720
773
721 If arguments are given, only variables of types matching these
774 If arguments are given, only variables of types matching these
722 arguments are returned."""
775 arguments are returned."""
723
776
724 user_ns = self.shell.user_ns
777 user_ns = self.shell.user_ns
725 out = []
778 out = []
726 typelist = parameter_s.split()
779 typelist = parameter_s.split()
727 for i in self.shell.user_ns.keys():
780 for i in self.shell.user_ns.keys():
728 if not (i.startswith('_') or i.startswith('_i')) \
781 if not (i.startswith('_') or i.startswith('_i')) \
729 and not (self.internal_ns.has_key(i) or
782 and not (self.internal_ns.has_key(i) or
730 self.user_config_ns.has_key(i)):
783 self.user_config_ns.has_key(i)):
731 if typelist:
784 if typelist:
732 if type(user_ns[i]).__name__ in typelist:
785 if type(user_ns[i]).__name__ in typelist:
733 out.append(i)
786 out.append(i)
734 else:
787 else:
735 out.append(i)
788 out.append(i)
736 out.sort()
789 out.sort()
737 return out
790 return out
738
791
739 def magic_who(self, parameter_s=''):
792 def magic_who(self, parameter_s=''):
740 """Print all interactive variables, with some minimal formatting.
793 """Print all interactive variables, with some minimal formatting.
741
794
742 If any arguments are given, only variables whose type matches one of
795 If any arguments are given, only variables whose type matches one of
743 these are printed. For example:
796 these are printed. For example:
744
797
745 %who function str
798 %who function str
746
799
747 will only list functions and strings, excluding all other types of
800 will only list functions and strings, excluding all other types of
748 variables. To find the proper type names, simply use type(var) at a
801 variables. To find the proper type names, simply use type(var) at a
749 command line to see how python prints type names. For example:
802 command line to see how python prints type names. For example:
750
803
751 In [1]: type('hello')\\
804 In [1]: type('hello')\\
752 Out[1]: <type 'str'>
805 Out[1]: <type 'str'>
753
806
754 indicates that the type name for strings is 'str'.
807 indicates that the type name for strings is 'str'.
755
808
756 %who always excludes executed names loaded through your configuration
809 %who always excludes executed names loaded through your configuration
757 file and things which are internal to IPython.
810 file and things which are internal to IPython.
758
811
759 This is deliberate, as typically you may load many modules and the
812 This is deliberate, as typically you may load many modules and the
760 purpose of %who is to show you only what you've manually defined."""
813 purpose of %who is to show you only what you've manually defined."""
761
814
762 varlist = self.magic_who_ls(parameter_s)
815 varlist = self.magic_who_ls(parameter_s)
763 if not varlist:
816 if not varlist:
764 print 'Interactive namespace is empty.'
817 print 'Interactive namespace is empty.'
765 return
818 return
766
819
767 # if we have variables, move on...
820 # if we have variables, move on...
768
821
769 # stupid flushing problem: when prompts have no separators, stdout is
822 # stupid flushing problem: when prompts have no separators, stdout is
770 # getting lost. I'm starting to think this is a python bug. I'm having
823 # getting lost. I'm starting to think this is a python bug. I'm having
771 # to force a flush with a print because even a sys.stdout.flush
824 # to force a flush with a print because even a sys.stdout.flush
772 # doesn't seem to do anything!
825 # doesn't seem to do anything!
773
826
774 count = 0
827 count = 0
775 for i in varlist:
828 for i in varlist:
776 print i+'\t',
829 print i+'\t',
777 count += 1
830 count += 1
778 if count > 8:
831 if count > 8:
779 count = 0
832 count = 0
780 print
833 print
781 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
834 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
782
835
783 print # well, this does force a flush at the expense of an extra \n
836 print # well, this does force a flush at the expense of an extra \n
784
837
785 def magic_whos(self, parameter_s=''):
838 def magic_whos(self, parameter_s=''):
786 """Like %who, but gives some extra information about each variable.
839 """Like %who, but gives some extra information about each variable.
787
840
788 The same type filtering of %who can be applied here.
841 The same type filtering of %who can be applied here.
789
842
790 For all variables, the type is printed. Additionally it prints:
843 For all variables, the type is printed. Additionally it prints:
791
844
792 - For {},[],(): their length.
845 - For {},[],(): their length.
793
846
794 - For Numeric arrays, a summary with shape, number of elements,
847 - For Numeric arrays, a summary with shape, number of elements,
795 typecode and size in memory.
848 typecode and size in memory.
796
849
797 - Everything else: a string representation, snipping their middle if
850 - Everything else: a string representation, snipping their middle if
798 too long."""
851 too long."""
799
852
800 varnames = self.magic_who_ls(parameter_s)
853 varnames = self.magic_who_ls(parameter_s)
801 if not varnames:
854 if not varnames:
802 print 'Interactive namespace is empty.'
855 print 'Interactive namespace is empty.'
803 return
856 return
804
857
805 # if we have variables, move on...
858 # if we have variables, move on...
806
859
807 # for these types, show len() instead of data:
860 # for these types, show len() instead of data:
808 seq_types = [types.DictType,types.ListType,types.TupleType]
861 seq_types = [types.DictType,types.ListType,types.TupleType]
809
862
810 # for Numeric arrays, display summary info
863 # for Numeric arrays, display summary info
811 try:
864 try:
812 import Numeric
865 import Numeric
813 except ImportError:
866 except ImportError:
814 array_type = None
867 array_type = None
815 else:
868 else:
816 array_type = Numeric.ArrayType.__name__
869 array_type = Numeric.ArrayType.__name__
817
870
818 # Find all variable names and types so we can figure out column sizes
871 # Find all variable names and types so we can figure out column sizes
819 get_vars = lambda i: self.shell.user_ns[i]
872 get_vars = lambda i: self.shell.user_ns[i]
820 type_name = lambda v: type(v).__name__
873 type_name = lambda v: type(v).__name__
821 varlist = map(get_vars,varnames)
874 varlist = map(get_vars,varnames)
822 typelist = map(type_name,varlist)
875 typelist = map(type_name,varlist)
823 # column labels and # of spaces as separator
876 # column labels and # of spaces as separator
824 varlabel = 'Variable'
877 varlabel = 'Variable'
825 typelabel = 'Type'
878 typelabel = 'Type'
826 datalabel = 'Data/Info'
879 datalabel = 'Data/Info'
827 colsep = 3
880 colsep = 3
828 # variable format strings
881 # variable format strings
829 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
882 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
830 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
883 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
831 aformat = "%s: %s elems, type `%s`, %s bytes"
884 aformat = "%s: %s elems, type `%s`, %s bytes"
832 # find the size of the columns to format the output nicely
885 # find the size of the columns to format the output nicely
833 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
886 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
834 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
887 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
835 # table header
888 # table header
836 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
889 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
837 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
890 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
838 # and the table itself
891 # and the table itself
839 kb = 1024
892 kb = 1024
840 Mb = 1048576 # kb**2
893 Mb = 1048576 # kb**2
841 for vname,var,vtype in zip(varnames,varlist,typelist):
894 for vname,var,vtype in zip(varnames,varlist,typelist):
842 print itpl(vformat),
895 print itpl(vformat),
843 if vtype in seq_types:
896 if vtype in seq_types:
844 print len(var)
897 print len(var)
845 elif vtype==array_type:
898 elif vtype==array_type:
846 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
899 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
847 vsize = Numeric.size(var)
900 vsize = Numeric.size(var)
848 vbytes = vsize*var.itemsize()
901 vbytes = vsize*var.itemsize()
849 if vbytes < 100000:
902 if vbytes < 100000:
850 print aformat % (vshape,vsize,var.typecode(),vbytes)
903 print aformat % (vshape,vsize,var.typecode(),vbytes)
851 else:
904 else:
852 print aformat % (vshape,vsize,var.typecode(),vbytes),
905 print aformat % (vshape,vsize,var.typecode(),vbytes),
853 if vbytes < Mb:
906 if vbytes < Mb:
854 print '(%s kb)' % (vbytes/kb,)
907 print '(%s kb)' % (vbytes/kb,)
855 else:
908 else:
856 print '(%s Mb)' % (vbytes/Mb,)
909 print '(%s Mb)' % (vbytes/Mb,)
857 else:
910 else:
858 vstr = str(var)
911 vstr = str(var)
859 if len(vstr) < 50:
912 if len(vstr) < 50:
860 print vstr
913 print vstr
861 else:
914 else:
862 printpl(vfmt_short)
915 printpl(vfmt_short)
863
916
864 def magic_reset(self, parameter_s=''):
917 def magic_reset(self, parameter_s=''):
865 """Resets the namespace by removing all names defined by the user.
918 """Resets the namespace by removing all names defined by the user.
866
919
867 Input/Output history are left around in case you need them."""
920 Input/Output history are left around in case you need them."""
868
921
869 ans = raw_input(
922 ans = raw_input(
870 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
923 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
871 if not ans.lower() == 'y':
924 if not ans.lower() == 'y':
872 print 'Nothing done.'
925 print 'Nothing done.'
873 return
926 return
874 user_ns = self.shell.user_ns
927 user_ns = self.shell.user_ns
875 for i in self.magic_who_ls():
928 for i in self.magic_who_ls():
876 del(user_ns[i])
929 del(user_ns[i])
877
930
878 def magic_config(self,parameter_s=''):
931 def magic_config(self,parameter_s=''):
879 """Show IPython's internal configuration."""
932 """Show IPython's internal configuration."""
880
933
881 page('Current configuration structure:\n'+
934 page('Current configuration structure:\n'+
882 pformat(self.shell.rc.dict()))
935 pformat(self.shell.rc.dict()))
883
936
884 def magic_logstart(self,parameter_s=''):
937 def magic_logstart(self,parameter_s=''):
885 """Start logging anywhere in a session.
938 """Start logging anywhere in a session.
886
939
887 %logstart [log_name [log_mode]]
940 %logstart [log_name [log_mode]]
888
941
889 If no name is given, it defaults to a file named 'ipython.log' in your
942 If no name is given, it defaults to a file named 'ipython.log' in your
890 current directory, in 'rotate' mode (see below).
943 current directory, in 'rotate' mode (see below).
891
944
892 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
945 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
893 history up to that point and then continues logging.
946 history up to that point and then continues logging.
894
947
895 %logstart takes a second optional parameter: logging mode. This can be one
948 %logstart takes a second optional parameter: logging mode. This can be one
896 of (note that the modes are given unquoted):\\
949 of (note that the modes are given unquoted):\\
897 over: overwrite existing log.\\
950 over: overwrite existing log.\\
898 backup: rename (if exists) to name~ and start name.\\
951 backup: rename (if exists) to name~ and start name.\\
899 append: well, that says it.\\
952 append: well, that says it.\\
900 rotate: create rotating logs name.1~, name.2~, etc.
953 rotate: create rotating logs name.1~, name.2~, etc.
901 """
954 """
902
955
903 #FIXME. This function should all be moved to the Logger class.
956 #FIXME. This function should all be moved to the Logger class.
904
957
905 valid_modes = qw('over backup append rotate')
958 valid_modes = qw('over backup append rotate')
906 if self.LOG:
959 if self.LOG:
907 print 'Logging is already in place. Logfile:',self.LOG
960 print 'Logging is already in place. Logfile:',self.LOG
908 return
961 return
909
962
910 par = parameter_s.strip()
963 par = parameter_s.strip()
911 if not par:
964 if not par:
912 logname = self.LOGDEF
965 logname = self.LOGDEF
913 logmode = 'rotate' # use rotate for the auto-generated logs
966 logmode = 'rotate' # use rotate for the auto-generated logs
914 else:
967 else:
915 try:
968 try:
916 logname,logmode = par.split()
969 logname,logmode = par.split()
917 except:
970 except:
918 try:
971 try:
919 logname = par
972 logname = par
920 logmode = 'backup'
973 logmode = 'backup'
921 except:
974 except:
922 warn('Usage: %log [log_name [log_mode]]')
975 warn('Usage: %log [log_name [log_mode]]')
923 return
976 return
924 if not logmode in valid_modes:
977 if not logmode in valid_modes:
925 warn('Logging NOT activated.\n'
978 warn('Logging NOT activated.\n'
926 'Usage: %log [log_name [log_mode]]\n'
979 'Usage: %log [log_name [log_mode]]\n'
927 'Valid modes: '+str(valid_modes))
980 'Valid modes: '+str(valid_modes))
928 return
981 return
929
982
930 # If we made it this far, I think we're ok:
983 # If we made it this far, I think we're ok:
931 print 'Activating auto-logging.'
984 print 'Activating auto-logging.'
932 print 'Current session state plus future input saved to:',logname
985 print 'Current session state plus future input saved to:',logname
933 print 'Logging mode: ',logmode
986 print 'Logging mode: ',logmode
934 # put logname into rc struct as if it had been called on the command line,
987 # put logname into rc struct as if it had been called on the command line,
935 # so it ends up saved in the log header
988 # so it ends up saved in the log header
936 # Save it in case we need to restore it...
989 # Save it in case we need to restore it...
937 old_logfile = self.shell.rc.opts.get('logfile','')
990 old_logfile = self.shell.rc.opts.get('logfile','')
938 logname = os.path.expanduser(logname)
991 logname = os.path.expanduser(logname)
939 self.shell.rc.opts.logfile = logname
992 self.shell.rc.opts.logfile = logname
940 self.LOGMODE = logmode # FIXME: this should be set through a function.
993 self.LOGMODE = logmode # FIXME: this should be set through a function.
941 try:
994 try:
942 header = str(self.LOGHEAD)
995 header = str(self.LOGHEAD)
943 self.create_log(header,logname)
996 self.create_log(header,logname)
944 self.logstart(header,logname)
997 self.logstart(header,logname)
945 except:
998 except:
946 self.LOG = '' # we are NOT logging, something went wrong
999 self.LOG = '' # we are NOT logging, something went wrong
947 self.shell.rc.opts.logfile = old_logfile
1000 self.shell.rc.opts.logfile = old_logfile
948 warn("Couldn't start log: "+str(sys.exc_info()[1]))
1001 warn("Couldn't start log: "+str(sys.exc_info()[1]))
949 else: # log input history up to this point
1002 else: # log input history up to this point
950 self.logfile.write(self.shell.user_ns['_ih'][1:])
1003 self.logfile.write(self.shell.user_ns['_ih'][1:])
951 self.logfile.flush()
1004 self.logfile.flush()
952
1005
953 def magic_logoff(self,parameter_s=''):
1006 def magic_logoff(self,parameter_s=''):
954 """Temporarily stop logging.
1007 """Temporarily stop logging.
955
1008
956 You must have previously started logging."""
1009 You must have previously started logging."""
957 self.switch_log(0)
1010 self.switch_log(0)
958
1011
959 def magic_logon(self,parameter_s=''):
1012 def magic_logon(self,parameter_s=''):
960 """Restart logging.
1013 """Restart logging.
961
1014
962 This function is for restarting logging which you've temporarily
1015 This function is for restarting logging which you've temporarily
963 stopped with %logoff. For starting logging for the first time, you
1016 stopped with %logoff. For starting logging for the first time, you
964 must use the %logstart function, which allows you to specify an
1017 must use the %logstart function, which allows you to specify an
965 optional log filename."""
1018 optional log filename."""
966
1019
967 self.switch_log(1)
1020 self.switch_log(1)
968
1021
969 def magic_logstate(self,parameter_s=''):
1022 def magic_logstate(self,parameter_s=''):
970 """Print the status of the logging system."""
1023 """Print the status of the logging system."""
971
1024
972 self.logstate()
1025 self.logstate()
973
1026
974 def magic_pdb(self, parameter_s=''):
1027 def magic_pdb(self, parameter_s=''):
975 """Control the calling of the pdb interactive debugger.
1028 """Control the calling of the pdb interactive debugger.
976
1029
977 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1030 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
978 argument it works as a toggle.
1031 argument it works as a toggle.
979
1032
980 When an exception is triggered, IPython can optionally call the
1033 When an exception is triggered, IPython can optionally call the
981 interactive pdb debugger after the traceback printout. %pdb toggles
1034 interactive pdb debugger after the traceback printout. %pdb toggles
982 this feature on and off."""
1035 this feature on and off."""
983
1036
984 par = parameter_s.strip().lower()
1037 par = parameter_s.strip().lower()
985
1038
986 if par:
1039 if par:
987 try:
1040 try:
988 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1041 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
989 except KeyError:
1042 except KeyError:
990 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
1043 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
991 return
1044 return
992 else:
1045 else:
993 self.shell.InteractiveTB.call_pdb = pdb
1046 self.shell.InteractiveTB.call_pdb = pdb
994 else:
1047 else:
995 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
1048 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
996 print 'Automatic pdb calling has been turned',\
1049 print 'Automatic pdb calling has been turned',\
997 on_off(self.shell.InteractiveTB.call_pdb)
1050 on_off(self.shell.InteractiveTB.call_pdb)
998
1051
999
1052
1000 def magic_prun(self, parameter_s ='',user_mode=1,
1053 def magic_prun(self, parameter_s ='',user_mode=1,
1001 opts=None,arg_lst=None,prog_ns=None):
1054 opts=None,arg_lst=None,prog_ns=None):
1002
1055
1003 """Run a statement through the python code profiler.
1056 """Run a statement through the python code profiler.
1004
1057
1005 Usage:\\
1058 Usage:\\
1006 %prun [options] statement
1059 %prun [options] statement
1007
1060
1008 The given statement (which doesn't require quote marks) is run via the
1061 The given statement (which doesn't require quote marks) is run via the
1009 python profiler in a manner similar to the profile.run() function.
1062 python profiler in a manner similar to the profile.run() function.
1010 Namespaces are internally managed to work correctly; profile.run
1063 Namespaces are internally managed to work correctly; profile.run
1011 cannot be used in IPython because it makes certain assumptions about
1064 cannot be used in IPython because it makes certain assumptions about
1012 namespaces which do not hold under IPython.
1065 namespaces which do not hold under IPython.
1013
1066
1014 Options:
1067 Options:
1015
1068
1016 -l <limit>: you can place restrictions on what or how much of the
1069 -l <limit>: you can place restrictions on what or how much of the
1017 profile gets printed. The limit value can be:
1070 profile gets printed. The limit value can be:
1018
1071
1019 * A string: only information for function names containing this string
1072 * A string: only information for function names containing this string
1020 is printed.
1073 is printed.
1021
1074
1022 * An integer: only these many lines are printed.
1075 * An integer: only these many lines are printed.
1023
1076
1024 * A float (between 0 and 1): this fraction of the report is printed
1077 * A float (between 0 and 1): this fraction of the report is printed
1025 (for example, use a limit of 0.4 to see the topmost 40% only).
1078 (for example, use a limit of 0.4 to see the topmost 40% only).
1026
1079
1027 You can combine several limits with repeated use of the option. For
1080 You can combine several limits with repeated use of the option. For
1028 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1081 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1029 information about class constructors.
1082 information about class constructors.
1030
1083
1031 -r: return the pstats.Stats object generated by the profiling. This
1084 -r: return the pstats.Stats object generated by the profiling. This
1032 object has all the information about the profile in it, and you can
1085 object has all the information about the profile in it, and you can
1033 later use it for further analysis or in other functions.
1086 later use it for further analysis or in other functions.
1034
1087
1035 Since magic functions have a particular form of calling which prevents
1088 Since magic functions have a particular form of calling which prevents
1036 you from writing something like:\\
1089 you from writing something like:\\
1037 In [1]: p = %prun -r print 4 # invalid!\\
1090 In [1]: p = %prun -r print 4 # invalid!\\
1038 you must instead use IPython's automatic variables to assign this:\\
1091 you must instead use IPython's automatic variables to assign this:\\
1039 In [1]: %prun -r print 4 \\
1092 In [1]: %prun -r print 4 \\
1040 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1093 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1041 In [2]: stats = _
1094 In [2]: stats = _
1042
1095
1043 If you really need to assign this value via an explicit function call,
1096 If you really need to assign this value via an explicit function call,
1044 you can always tap directly into the true name of the magic function
1097 you can always tap directly into the true name of the magic function
1045 by using the ipmagic function (which IPython automatically adds to the
1098 by using the ipmagic function (which IPython automatically adds to the
1046 builtins):\\
1099 builtins):\\
1047 In [3]: stats = ipmagic('prun','-r print 4')
1100 In [3]: stats = ipmagic('prun','-r print 4')
1048
1101
1049 You can type ipmagic? for more details on ipmagic.
1102 You can type ipmagic? for more details on ipmagic.
1050
1103
1051 -s <key>: sort profile by given key. You can provide more than one key
1104 -s <key>: sort profile by given key. You can provide more than one key
1052 by using the option several times: '-s key1 -s key2 -s key3...'. The
1105 by using the option several times: '-s key1 -s key2 -s key3...'. The
1053 default sorting key is 'time'.
1106 default sorting key is 'time'.
1054
1107
1055 The following is copied verbatim from the profile documentation
1108 The following is copied verbatim from the profile documentation
1056 referenced below:
1109 referenced below:
1057
1110
1058 When more than one key is provided, additional keys are used as
1111 When more than one key is provided, additional keys are used as
1059 secondary criteria when the there is equality in all keys selected
1112 secondary criteria when the there is equality in all keys selected
1060 before them.
1113 before them.
1061
1114
1062 Abbreviations can be used for any key names, as long as the
1115 Abbreviations can be used for any key names, as long as the
1063 abbreviation is unambiguous. The following are the keys currently
1116 abbreviation is unambiguous. The following are the keys currently
1064 defined:
1117 defined:
1065
1118
1066 Valid Arg Meaning\\
1119 Valid Arg Meaning\\
1067 "calls" call count\\
1120 "calls" call count\\
1068 "cumulative" cumulative time\\
1121 "cumulative" cumulative time\\
1069 "file" file name\\
1122 "file" file name\\
1070 "module" file name\\
1123 "module" file name\\
1071 "pcalls" primitive call count\\
1124 "pcalls" primitive call count\\
1072 "line" line number\\
1125 "line" line number\\
1073 "name" function name\\
1126 "name" function name\\
1074 "nfl" name/file/line\\
1127 "nfl" name/file/line\\
1075 "stdname" standard name\\
1128 "stdname" standard name\\
1076 "time" internal time
1129 "time" internal time
1077
1130
1078 Note that all sorts on statistics are in descending order (placing
1131 Note that all sorts on statistics are in descending order (placing
1079 most time consuming items first), where as name, file, and line number
1132 most time consuming items first), where as name, file, and line number
1080 searches are in ascending order (i.e., alphabetical). The subtle
1133 searches are in ascending order (i.e., alphabetical). The subtle
1081 distinction between "nfl" and "stdname" is that the standard name is a
1134 distinction between "nfl" and "stdname" is that the standard name is a
1082 sort of the name as printed, which means that the embedded line
1135 sort of the name as printed, which means that the embedded line
1083 numbers get compared in an odd way. For example, lines 3, 20, and 40
1136 numbers get compared in an odd way. For example, lines 3, 20, and 40
1084 would (if the file names were the same) appear in the string order
1137 would (if the file names were the same) appear in the string order
1085 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1138 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1086 line numbers. In fact, sort_stats("nfl") is the same as
1139 line numbers. In fact, sort_stats("nfl") is the same as
1087 sort_stats("name", "file", "line").
1140 sort_stats("name", "file", "line").
1088
1141
1089 -T <filename>: save profile results as shown on screen to a text
1142 -T <filename>: save profile results as shown on screen to a text
1090 file. The profile is still shown on screen.
1143 file. The profile is still shown on screen.
1091
1144
1092 -D <filename>: save (via dump_stats) profile statistics to given
1145 -D <filename>: save (via dump_stats) profile statistics to given
1093 filename. This data is in a format understod by the pstats module, and
1146 filename. This data is in a format understod by the pstats module, and
1094 is generated by a call to the dump_stats() method of profile
1147 is generated by a call to the dump_stats() method of profile
1095 objects. The profile is still shown on screen.
1148 objects. The profile is still shown on screen.
1096
1149
1097 If you want to run complete programs under the profiler's control, use
1150 If you want to run complete programs under the profiler's control, use
1098 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1151 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1099 contains profiler specific options as described here.
1152 contains profiler specific options as described here.
1100
1153
1101 You can read the complete documentation for the profile module with:\\
1154 You can read the complete documentation for the profile module with:\\
1102 In [1]: import profile; profile.help() """
1155 In [1]: import profile; profile.help() """
1103
1156
1104 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1157 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1105 # protect user quote marks
1158 # protect user quote marks
1106 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1159 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1107
1160
1108 if user_mode: # regular user call
1161 if user_mode: # regular user call
1109 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1162 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1110 list_all=1)
1163 list_all=1)
1111 namespace = self.shell.user_ns
1164 namespace = self.shell.user_ns
1112 else: # called to run a program by %run -p
1165 else: # called to run a program by %run -p
1113 try:
1166 try:
1114 filename = get_py_filename(arg_lst[0])
1167 filename = get_py_filename(arg_lst[0])
1115 except IOError,msg:
1168 except IOError,msg:
1116 error(msg)
1169 error(msg)
1117 return
1170 return
1118
1171
1119 arg_str = 'execfile(filename,prog_ns)'
1172 arg_str = 'execfile(filename,prog_ns)'
1120 namespace = locals()
1173 namespace = locals()
1121
1174
1122 opts.merge(opts_def)
1175 opts.merge(opts_def)
1123
1176
1124 prof = profile.Profile()
1177 prof = profile.Profile()
1125 try:
1178 try:
1126 prof = prof.runctx(arg_str,namespace,namespace)
1179 prof = prof.runctx(arg_str,namespace,namespace)
1127 sys_exit = ''
1180 sys_exit = ''
1128 except SystemExit:
1181 except SystemExit:
1129 sys_exit = """*** SystemExit exception caught in code being profiled."""
1182 sys_exit = """*** SystemExit exception caught in code being profiled."""
1130
1183
1131 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1184 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1132
1185
1133 lims = opts.l
1186 lims = opts.l
1134 if lims:
1187 if lims:
1135 lims = [] # rebuild lims with ints/floats/strings
1188 lims = [] # rebuild lims with ints/floats/strings
1136 for lim in opts.l:
1189 for lim in opts.l:
1137 try:
1190 try:
1138 lims.append(int(lim))
1191 lims.append(int(lim))
1139 except ValueError:
1192 except ValueError:
1140 try:
1193 try:
1141 lims.append(float(lim))
1194 lims.append(float(lim))
1142 except ValueError:
1195 except ValueError:
1143 lims.append(lim)
1196 lims.append(lim)
1144
1197
1145 # trap output
1198 # trap output
1146 sys_stdout = sys.stdout
1199 sys_stdout = sys.stdout
1147 stdout_trap = StringIO()
1200 stdout_trap = StringIO()
1148 try:
1201 try:
1149 sys.stdout = stdout_trap
1202 sys.stdout = stdout_trap
1150 stats.print_stats(*lims)
1203 stats.print_stats(*lims)
1151 finally:
1204 finally:
1152 sys.stdout = sys_stdout
1205 sys.stdout = sys_stdout
1153 output = stdout_trap.getvalue()
1206 output = stdout_trap.getvalue()
1154 output = output.rstrip()
1207 output = output.rstrip()
1155
1208
1156 page(output,screen_lines=self.shell.rc.screen_length)
1209 page(output,screen_lines=self.shell.rc.screen_length)
1157 print sys_exit,
1210 print sys_exit,
1158
1211
1159 dump_file = opts.D[0]
1212 dump_file = opts.D[0]
1160 text_file = opts.T[0]
1213 text_file = opts.T[0]
1161 if dump_file:
1214 if dump_file:
1162 prof.dump_stats(dump_file)
1215 prof.dump_stats(dump_file)
1163 print '\n*** Profile stats marshalled to file',\
1216 print '\n*** Profile stats marshalled to file',\
1164 `dump_file`+'.',sys_exit
1217 `dump_file`+'.',sys_exit
1165 if text_file:
1218 if text_file:
1166 file(text_file,'w').write(output)
1219 file(text_file,'w').write(output)
1167 print '\n*** Profile printout saved to text file',\
1220 print '\n*** Profile printout saved to text file',\
1168 `text_file`+'.',sys_exit
1221 `text_file`+'.',sys_exit
1169
1222
1170 if opts.has_key('r'):
1223 if opts.has_key('r'):
1171 return stats
1224 return stats
1172 else:
1225 else:
1173 return None
1226 return None
1174
1227
1175 def magic_run(self, parameter_s ='',runner=None):
1228 def magic_run(self, parameter_s ='',runner=None):
1176 """Run the named file inside IPython as a program.
1229 """Run the named file inside IPython as a program.
1177
1230
1178 Usage:\\
1231 Usage:\\
1179 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1232 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1180
1233
1181 Parameters after the filename are passed as command-line arguments to
1234 Parameters after the filename are passed as command-line arguments to
1182 the program (put in sys.argv). Then, control returns to IPython's
1235 the program (put in sys.argv). Then, control returns to IPython's
1183 prompt.
1236 prompt.
1184
1237
1185 This is similar to running at a system prompt:\\
1238 This is similar to running at a system prompt:\\
1186 $ python file args\\
1239 $ python file args\\
1187 but with the advantage of giving you IPython's tracebacks, and of
1240 but with the advantage of giving you IPython's tracebacks, and of
1188 loading all variables into your interactive namespace for further use
1241 loading all variables into your interactive namespace for further use
1189 (unless -p is used, see below).
1242 (unless -p is used, see below).
1190
1243
1191 The file is executed in a namespace initially consisting only of
1244 The file is executed in a namespace initially consisting only of
1192 __name__=='__main__' and sys.argv constructed as indicated. It thus
1245 __name__=='__main__' and sys.argv constructed as indicated. It thus
1193 sees its environment as if it were being run as a stand-alone
1246 sees its environment as if it were being run as a stand-alone
1194 program. But after execution, the IPython interactive namespace gets
1247 program. But after execution, the IPython interactive namespace gets
1195 updated with all variables defined in the program (except for __name__
1248 updated with all variables defined in the program (except for __name__
1196 and sys.argv). This allows for very convenient loading of code for
1249 and sys.argv). This allows for very convenient loading of code for
1197 interactive work, while giving each program a 'clean sheet' to run in.
1250 interactive work, while giving each program a 'clean sheet' to run in.
1198
1251
1199 Options:
1252 Options:
1200
1253
1201 -n: __name__ is NOT set to '__main__', but to the running file's name
1254 -n: __name__ is NOT set to '__main__', but to the running file's name
1202 without extension (as python does under import). This allows running
1255 without extension (as python does under import). This allows running
1203 scripts and reloading the definitions in them without calling code
1256 scripts and reloading the definitions in them without calling code
1204 protected by an ' if __name__ == "__main__" ' clause.
1257 protected by an ' if __name__ == "__main__" ' clause.
1205
1258
1206 -i: run the file in IPython's namespace instead of an empty one. This
1259 -i: run the file in IPython's namespace instead of an empty one. This
1207 is useful if you are experimenting with code written in a text editor
1260 is useful if you are experimenting with code written in a text editor
1208 which depends on variables defined interactively.
1261 which depends on variables defined interactively.
1209
1262
1210 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1263 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1211 being run. This is particularly useful if IPython is being used to
1264 being run. This is particularly useful if IPython is being used to
1212 run unittests, which always exit with a sys.exit() call. In such
1265 run unittests, which always exit with a sys.exit() call. In such
1213 cases you are interested in the output of the test results, not in
1266 cases you are interested in the output of the test results, not in
1214 seeing a traceback of the unittest module.
1267 seeing a traceback of the unittest module.
1215
1268
1216 -t: print timing information at the end of the run. IPython will give
1269 -t: print timing information at the end of the run. IPython will give
1217 you an estimated CPU time consumption for your script, which under
1270 you an estimated CPU time consumption for your script, which under
1218 Unix uses the resource module to avoid the wraparound problems of
1271 Unix uses the resource module to avoid the wraparound problems of
1219 time.clock(). Under Unix, an estimate of time spent on system tasks
1272 time.clock(). Under Unix, an estimate of time spent on system tasks
1220 is also given (for Windows platforms this is reported as 0.0).
1273 is also given (for Windows platforms this is reported as 0.0).
1221
1274
1222 If -t is given, an additional -N<N> option can be given, where <N>
1275 If -t is given, an additional -N<N> option can be given, where <N>
1223 must be an integer indicating how many times you want the script to
1276 must be an integer indicating how many times you want the script to
1224 run. The final timing report will include total and per run results.
1277 run. The final timing report will include total and per run results.
1225
1278
1226 For example (testing the script uniq_stable.py):
1279 For example (testing the script uniq_stable.py):
1227
1280
1228 In [1]: run -t uniq_stable
1281 In [1]: run -t uniq_stable
1229
1282
1230 IPython CPU timings (estimated):\\
1283 IPython CPU timings (estimated):\\
1231 User : 0.19597 s.\\
1284 User : 0.19597 s.\\
1232 System: 0.0 s.\\
1285 System: 0.0 s.\\
1233
1286
1234 In [2]: run -t -N5 uniq_stable
1287 In [2]: run -t -N5 uniq_stable
1235
1288
1236 IPython CPU timings (estimated):\\
1289 IPython CPU timings (estimated):\\
1237 Total runs performed: 5\\
1290 Total runs performed: 5\\
1238 Times : Total Per run\\
1291 Times : Total Per run\\
1239 User : 0.910862 s, 0.1821724 s.\\
1292 User : 0.910862 s, 0.1821724 s.\\
1240 System: 0.0 s, 0.0 s.
1293 System: 0.0 s, 0.0 s.
1241
1294
1242 -d: run your program under the control of pdb, the Python debugger.
1295 -d: run your program under the control of pdb, the Python debugger.
1243 This allows you to execute your program step by step, watch variables,
1296 This allows you to execute your program step by step, watch variables,
1244 etc. Internally, what IPython does is similar to calling:
1297 etc. Internally, what IPython does is similar to calling:
1245
1298
1246 pdb.run('execfile("YOURFILENAME")')
1299 pdb.run('execfile("YOURFILENAME")')
1247
1300
1248 with a breakpoint set on line 1 of your file. You can change the line
1301 with a breakpoint set on line 1 of your file. You can change the line
1249 number for this automatic breakpoint to be <N> by using the -bN option
1302 number for this automatic breakpoint to be <N> by using the -bN option
1250 (where N must be an integer). For example:
1303 (where N must be an integer). For example:
1251
1304
1252 %run -d -b40 myscript
1305 %run -d -b40 myscript
1253
1306
1254 will set the first breakpoint at line 40 in myscript.py. Note that
1307 will set the first breakpoint at line 40 in myscript.py. Note that
1255 the first breakpoint must be set on a line which actually does
1308 the first breakpoint must be set on a line which actually does
1256 something (not a comment or docstring) for it to stop execution.
1309 something (not a comment or docstring) for it to stop execution.
1257
1310
1258 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1311 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1259 first enter 'c' (without qoutes) to start execution up to the first
1312 first enter 'c' (without qoutes) to start execution up to the first
1260 breakpoint.
1313 breakpoint.
1261
1314
1262 Entering 'help' gives information about the use of the debugger. You
1315 Entering 'help' gives information about the use of the debugger. You
1263 can easily see pdb's full documentation with "import pdb;pdb.help()"
1316 can easily see pdb's full documentation with "import pdb;pdb.help()"
1264 at a prompt.
1317 at a prompt.
1265
1318
1266 -p: run program under the control of the Python profiler module (which
1319 -p: run program under the control of the Python profiler module (which
1267 prints a detailed report of execution times, function calls, etc).
1320 prints a detailed report of execution times, function calls, etc).
1268
1321
1269 You can pass other options after -p which affect the behavior of the
1322 You can pass other options after -p which affect the behavior of the
1270 profiler itself. See the docs for %prun for details.
1323 profiler itself. See the docs for %prun for details.
1271
1324
1272 In this mode, the program's variables do NOT propagate back to the
1325 In this mode, the program's variables do NOT propagate back to the
1273 IPython interactive namespace (because they remain in the namespace
1326 IPython interactive namespace (because they remain in the namespace
1274 where the profiler executes them).
1327 where the profiler executes them).
1275
1328
1276 Internally this triggers a call to %prun, see its documentation for
1329 Internally this triggers a call to %prun, see its documentation for
1277 details on the options available specifically for profiling."""
1330 details on the options available specifically for profiling."""
1278
1331
1279 # get arguments and set sys.argv for program to be run.
1332 # get arguments and set sys.argv for program to be run.
1280 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1333 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1281 mode='list',list_all=1)
1334 mode='list',list_all=1)
1282
1335
1283 try:
1336 try:
1284 filename = get_py_filename(arg_lst[0])
1337 filename = get_py_filename(arg_lst[0])
1285 except IndexError:
1338 except IndexError:
1286 warn('you must provide at least a filename.')
1339 warn('you must provide at least a filename.')
1287 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1340 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1288 return
1341 return
1289 except IOError,msg:
1342 except IOError,msg:
1290 error(msg)
1343 error(msg)
1291 return
1344 return
1292
1345
1293 # Control the response to exit() calls made by the script being run
1346 # Control the response to exit() calls made by the script being run
1294 exit_ignore = opts.has_key('e')
1347 exit_ignore = opts.has_key('e')
1295
1348
1296 # Make sure that the running script gets a proper sys.argv as if it
1349 # Make sure that the running script gets a proper sys.argv as if it
1297 # were run from a system shell.
1350 # were run from a system shell.
1298 save_argv = sys.argv # save it for later restoring
1351 save_argv = sys.argv # save it for later restoring
1299 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1352 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1300
1353
1301 if opts.has_key('i'):
1354 if opts.has_key('i'):
1302 prog_ns = self.shell.user_ns
1355 prog_ns = self.shell.user_ns
1303 __name__save = self.shell.user_ns['__name__']
1356 __name__save = self.shell.user_ns['__name__']
1304 prog_ns['__name__'] = '__main__'
1357 prog_ns['__name__'] = '__main__'
1305 else:
1358 else:
1306 if opts.has_key('n'):
1359 if opts.has_key('n'):
1307 name = os.path.splitext(os.path.basename(filename))[0]
1360 name = os.path.splitext(os.path.basename(filename))[0]
1308 else:
1361 else:
1309 name = '__main__'
1362 name = '__main__'
1310 prog_ns = {'__name__':name}
1363 prog_ns = {'__name__':name}
1311
1364
1312 # pickle fix. See iplib for an explanation
1365 # pickle fix. See iplib for an explanation
1313 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1366 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1314
1367
1315 stats = None
1368 stats = None
1316 try:
1369 try:
1317 if opts.has_key('p'):
1370 if opts.has_key('p'):
1318 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1371 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1319 else:
1372 else:
1320 if opts.has_key('d'):
1373 if opts.has_key('d'):
1321 deb = pdb.Pdb()
1374 deb = pdb.Pdb()
1322 # reset Breakpoint state, which is moronically kept
1375 # reset Breakpoint state, which is moronically kept
1323 # in a class
1376 # in a class
1324 bdb.Breakpoint.next = 1
1377 bdb.Breakpoint.next = 1
1325 bdb.Breakpoint.bplist = {}
1378 bdb.Breakpoint.bplist = {}
1326 bdb.Breakpoint.bpbynumber = [None]
1379 bdb.Breakpoint.bpbynumber = [None]
1327 # Set an initial breakpoint to stop execution
1380 # Set an initial breakpoint to stop execution
1328 maxtries = 10
1381 maxtries = 10
1329 bp = int(opts.get('b',[1])[0])
1382 bp = int(opts.get('b',[1])[0])
1330 checkline = deb.checkline(filename,bp)
1383 checkline = deb.checkline(filename,bp)
1331 if not checkline:
1384 if not checkline:
1332 for bp in range(bp+1,bp+maxtries+1):
1385 for bp in range(bp+1,bp+maxtries+1):
1333 if deb.checkline(filename,bp):
1386 if deb.checkline(filename,bp):
1334 break
1387 break
1335 else:
1388 else:
1336 msg = ("\nI failed to find a valid line to set "
1389 msg = ("\nI failed to find a valid line to set "
1337 "a breakpoint\n"
1390 "a breakpoint\n"
1338 "after trying up to line: %s.\n"
1391 "after trying up to line: %s.\n"
1339 "Please set a valid breakpoint manually "
1392 "Please set a valid breakpoint manually "
1340 "with the -b option." % bp)
1393 "with the -b option." % bp)
1341 error(msg)
1394 error(msg)
1342 return
1395 return
1343 # if we find a good linenumber, set the breakpoint
1396 # if we find a good linenumber, set the breakpoint
1344 deb.do_break('%s:%s' % (filename,bp))
1397 deb.do_break('%s:%s' % (filename,bp))
1345 # Start file run
1398 # Start file run
1346 print "NOTE: Enter 'c' at the",
1399 print "NOTE: Enter 'c' at the",
1347 print "(Pdb) prompt to start your script."
1400 print "(Pdb) prompt to start your script."
1348 deb.run('execfile("%s")' % filename,prog_ns)
1401 deb.run('execfile("%s")' % filename,prog_ns)
1349 else:
1402 else:
1350 if runner is None:
1403 if runner is None:
1351 runner = self.shell.safe_execfile
1404 runner = self.shell.safe_execfile
1352 if opts.has_key('t'):
1405 if opts.has_key('t'):
1353 try:
1406 try:
1354 nruns = int(opts['N'][0])
1407 nruns = int(opts['N'][0])
1355 if nruns < 1:
1408 if nruns < 1:
1356 error('Number of runs must be >=1')
1409 error('Number of runs must be >=1')
1357 return
1410 return
1358 except (KeyError):
1411 except (KeyError):
1359 nruns = 1
1412 nruns = 1
1360 if nruns == 1:
1413 if nruns == 1:
1361 t0 = clock2()
1414 t0 = clock2()
1362 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1415 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1363 t1 = clock2()
1416 t1 = clock2()
1364 t_usr = t1[0]-t0[0]
1417 t_usr = t1[0]-t0[0]
1365 t_sys = t1[1]-t1[1]
1418 t_sys = t1[1]-t1[1]
1366 print "\nIPython CPU timings (estimated):"
1419 print "\nIPython CPU timings (estimated):"
1367 print " User : %10s s." % t_usr
1420 print " User : %10s s." % t_usr
1368 print " System: %10s s." % t_sys
1421 print " System: %10s s." % t_sys
1369 else:
1422 else:
1370 runs = range(nruns)
1423 runs = range(nruns)
1371 t0 = clock2()
1424 t0 = clock2()
1372 for nr in runs:
1425 for nr in runs:
1373 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1426 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1374 t1 = clock2()
1427 t1 = clock2()
1375 t_usr = t1[0]-t0[0]
1428 t_usr = t1[0]-t0[0]
1376 t_sys = t1[1]-t1[1]
1429 t_sys = t1[1]-t1[1]
1377 print "\nIPython CPU timings (estimated):"
1430 print "\nIPython CPU timings (estimated):"
1378 print "Total runs performed:",nruns
1431 print "Total runs performed:",nruns
1379 print " Times : %10s %10s" % ('Total','Per run')
1432 print " Times : %10s %10s" % ('Total','Per run')
1380 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1433 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1381 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1434 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1382
1435
1383 else:
1436 else:
1384 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1437 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1385 if opts.has_key('i'):
1438 if opts.has_key('i'):
1386 self.shell.user_ns['__name__'] = __name__save
1439 self.shell.user_ns['__name__'] = __name__save
1387 else:
1440 else:
1388 # update IPython interactive namespace
1441 # update IPython interactive namespace
1389 del prog_ns['__name__']
1442 del prog_ns['__name__']
1390 self.shell.user_ns.update(prog_ns)
1443 self.shell.user_ns.update(prog_ns)
1391 finally:
1444 finally:
1392 sys.argv = save_argv
1445 sys.argv = save_argv
1393 return stats
1446 return stats
1394
1447
1395 def magic_runlog(self, parameter_s =''):
1448 def magic_runlog(self, parameter_s =''):
1396 """Run files as logs.
1449 """Run files as logs.
1397
1450
1398 Usage:\\
1451 Usage:\\
1399 %runlog file1 file2 ...
1452 %runlog file1 file2 ...
1400
1453
1401 Run the named files (treating them as log files) in sequence inside
1454 Run the named files (treating them as log files) in sequence inside
1402 the interpreter, and return to the prompt. This is much slower than
1455 the interpreter, and return to the prompt. This is much slower than
1403 %run because each line is executed in a try/except block, but it
1456 %run because each line is executed in a try/except block, but it
1404 allows running files with syntax errors in them.
1457 allows running files with syntax errors in them.
1405
1458
1406 Normally IPython will guess when a file is one of its own logfiles, so
1459 Normally IPython will guess when a file is one of its own logfiles, so
1407 you can typically use %run even for logs. This shorthand allows you to
1460 you can typically use %run even for logs. This shorthand allows you to
1408 force any file to be treated as a log file."""
1461 force any file to be treated as a log file."""
1409
1462
1410 for f in parameter_s.split():
1463 for f in parameter_s.split():
1411 self.shell.safe_execfile(f,self.shell.user_ns,
1464 self.shell.safe_execfile(f,self.shell.user_ns,
1412 self.shell.user_ns,islog=1)
1465 self.shell.user_ns,islog=1)
1413
1466
1414 def magic_time(self,parameter_s = ''):
1467 def magic_time(self,parameter_s = ''):
1415 """Time execution of a Python statement or expression.
1468 """Time execution of a Python statement or expression.
1416
1469
1417 The CPU and wall clock times are printed, and the value of the
1470 The CPU and wall clock times are printed, and the value of the
1418 expression (if any) is returned. Note that under Win32, system time
1471 expression (if any) is returned. Note that under Win32, system time
1419 is always reported as 0, since it can not be measured.
1472 is always reported as 0, since it can not be measured.
1420
1473
1421 This function provides very basic timing functionality. In Python
1474 This function provides very basic timing functionality. In Python
1422 2.3, the timeit module offers more control and sophistication, but for
1475 2.3, the timeit module offers more control and sophistication, but for
1423 now IPython supports Python 2.2, so we can not rely on timeit being
1476 now IPython supports Python 2.2, so we can not rely on timeit being
1424 present.
1477 present.
1425
1478
1426 Some examples:
1479 Some examples:
1427
1480
1428 In [1]: time 2**128
1481 In [1]: time 2**128
1429 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1482 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1430 Wall time: 0.00
1483 Wall time: 0.00
1431 Out[1]: 340282366920938463463374607431768211456L
1484 Out[1]: 340282366920938463463374607431768211456L
1432
1485
1433 In [2]: n = 1000000
1486 In [2]: n = 1000000
1434
1487
1435 In [3]: time sum(range(n))
1488 In [3]: time sum(range(n))
1436 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1489 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1437 Wall time: 1.37
1490 Wall time: 1.37
1438 Out[3]: 499999500000L
1491 Out[3]: 499999500000L
1439
1492
1440 In [4]: time print 'hello world'
1493 In [4]: time print 'hello world'
1441 hello world
1494 hello world
1442 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1495 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1443 Wall time: 0.00
1496 Wall time: 0.00
1444 """
1497 """
1445
1498
1446 # fail immediately if the given expression can't be compiled
1499 # fail immediately if the given expression can't be compiled
1447 try:
1500 try:
1448 mode = 'eval'
1501 mode = 'eval'
1449 code = compile(parameter_s,'<timed eval>',mode)
1502 code = compile(parameter_s,'<timed eval>',mode)
1450 except SyntaxError:
1503 except SyntaxError:
1451 mode = 'exec'
1504 mode = 'exec'
1452 code = compile(parameter_s,'<timed exec>',mode)
1505 code = compile(parameter_s,'<timed exec>',mode)
1453 # skew measurement as little as possible
1506 # skew measurement as little as possible
1454 glob = self.shell.user_ns
1507 glob = self.shell.user_ns
1455 clk = clock2
1508 clk = clock2
1456 wtime = time.time
1509 wtime = time.time
1457 # time execution
1510 # time execution
1458 wall_st = wtime()
1511 wall_st = wtime()
1459 if mode=='eval':
1512 if mode=='eval':
1460 st = clk()
1513 st = clk()
1461 out = eval(code,glob)
1514 out = eval(code,glob)
1462 end = clk()
1515 end = clk()
1463 else:
1516 else:
1464 st = clk()
1517 st = clk()
1465 exec code in glob
1518 exec code in glob
1466 end = clk()
1519 end = clk()
1467 out = None
1520 out = None
1468 wall_end = wtime()
1521 wall_end = wtime()
1469 # Compute actual times and report
1522 # Compute actual times and report
1470 wall_time = wall_end-wall_st
1523 wall_time = wall_end-wall_st
1471 cpu_user = end[0]-st[0]
1524 cpu_user = end[0]-st[0]
1472 cpu_sys = end[1]-st[1]
1525 cpu_sys = end[1]-st[1]
1473 cpu_tot = cpu_user+cpu_sys
1526 cpu_tot = cpu_user+cpu_sys
1474 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1527 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1475 (cpu_user,cpu_sys,cpu_tot)
1528 (cpu_user,cpu_sys,cpu_tot)
1476 print "Wall time: %.2f" % wall_time
1529 print "Wall time: %.2f" % wall_time
1477 return out
1530 return out
1478
1531
1479 def magic_macro(self,parameter_s = ''):
1532 def magic_macro(self,parameter_s = ''):
1480 """Define a set of input lines as a macro for future re-execution.
1533 """Define a set of input lines as a macro for future re-execution.
1481
1534
1482 Usage:\\
1535 Usage:\\
1483 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1536 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1484
1537
1485 This will define a global variable called `name` which is a string
1538 This will define a global variable called `name` which is a string
1486 made of joining the slices and lines you specify (n1,n2,... numbers
1539 made of joining the slices and lines you specify (n1,n2,... numbers
1487 above) from your input history into a single string. This variable
1540 above) from your input history into a single string. This variable
1488 acts like an automatic function which re-executes those lines as if
1541 acts like an automatic function which re-executes those lines as if
1489 you had typed them. You just type 'name' at the prompt and the code
1542 you had typed them. You just type 'name' at the prompt and the code
1490 executes.
1543 executes.
1491
1544
1492 Note that the slices use the standard Python slicing notation (5:8
1545 Note that the slices use the standard Python slicing notation (5:8
1493 means include lines numbered 5,6,7).
1546 means include lines numbered 5,6,7).
1494
1547
1495 For example, if your history contains (%hist prints it):
1548 For example, if your history contains (%hist prints it):
1496
1549
1497 44: x=1\\
1550 44: x=1\\
1498 45: y=3\\
1551 45: y=3\\
1499 46: z=x+y\\
1552 46: z=x+y\\
1500 47: print x\\
1553 47: print x\\
1501 48: a=5\\
1554 48: a=5\\
1502 49: print 'x',x,'y',y\\
1555 49: print 'x',x,'y',y\\
1503
1556
1504 you can create a macro with lines 44 through 47 (included) and line 49
1557 you can create a macro with lines 44 through 47 (included) and line 49
1505 called my_macro with:
1558 called my_macro with:
1506
1559
1507 In [51]: %macro my_macro 44:48 49
1560 In [51]: %macro my_macro 44:48 49
1508
1561
1509 Now, typing `my_macro` (without quotes) will re-execute all this code
1562 Now, typing `my_macro` (without quotes) will re-execute all this code
1510 in one pass.
1563 in one pass.
1511
1564
1512 You don't need to give the line-numbers in order, and any given line
1565 You don't need to give the line-numbers in order, and any given line
1513 number can appear multiple times. You can assemble macros with any
1566 number can appear multiple times. You can assemble macros with any
1514 lines from your input history in any order.
1567 lines from your input history in any order.
1515
1568
1516 The macro is a simple object which holds its value in an attribute,
1569 The macro is a simple object which holds its value in an attribute,
1517 but IPython's display system checks for macros and executes them as
1570 but IPython's display system checks for macros and executes them as
1518 code instead of printing them when you type their name.
1571 code instead of printing them when you type their name.
1519
1572
1520 You can view a macro's contents by explicitly printing it with:
1573 You can view a macro's contents by explicitly printing it with:
1521
1574
1522 'print macro_name'.
1575 'print macro_name'.
1523
1576
1524 For one-off cases which DON'T contain magic function calls in them you
1577 For one-off cases which DON'T contain magic function calls in them you
1525 can obtain similar results by explicitly executing slices from your
1578 can obtain similar results by explicitly executing slices from your
1526 input history with:
1579 input history with:
1527
1580
1528 In [60]: exec In[44:48]+In[49]"""
1581 In [60]: exec In[44:48]+In[49]"""
1529
1582
1530 args = parameter_s.split()
1583 args = parameter_s.split()
1531 name,ranges = args[0], args[1:]
1584 name,ranges = args[0], args[1:]
1532 #print 'rng',ranges # dbg
1585 #print 'rng',ranges # dbg
1533 cmds = self.extract_input_slices(ranges)
1586 cmds = self.extract_input_slices(ranges)
1534 macro = Macro(cmds)
1587 macro = Macro(cmds)
1535 self.shell.user_ns.update({name:macro})
1588 self.shell.user_ns.update({name:macro})
1536 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1589 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1537 print 'Macro contents:'
1590 print 'Macro contents:'
1538 print str(macro).rstrip(),
1591 print str(macro).rstrip(),
1539
1592
1540 def magic_save(self,parameter_s = ''):
1593 def magic_save(self,parameter_s = ''):
1541 """Save a set of lines to a given filename.
1594 """Save a set of lines to a given filename.
1542
1595
1543 Usage:\\
1596 Usage:\\
1544 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1597 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1545
1598
1546 This function uses the same syntax as %macro for line extraction, but
1599 This function uses the same syntax as %macro for line extraction, but
1547 instead of creating a macro it saves the resulting string to the
1600 instead of creating a macro it saves the resulting string to the
1548 filename you specify.
1601 filename you specify.
1549
1602
1550 It adds a '.py' extension to the file if you don't do so yourself, and
1603 It adds a '.py' extension to the file if you don't do so yourself, and
1551 it asks for confirmation before overwriting existing files."""
1604 it asks for confirmation before overwriting existing files."""
1552
1605
1553 args = parameter_s.split()
1606 args = parameter_s.split()
1554 fname,ranges = args[0], args[1:]
1607 fname,ranges = args[0], args[1:]
1555 if not fname.endswith('.py'):
1608 if not fname.endswith('.py'):
1556 fname += '.py'
1609 fname += '.py'
1557 if os.path.isfile(fname):
1610 if os.path.isfile(fname):
1558 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1611 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1559 if ans.lower() not in ['y','yes']:
1612 if ans.lower() not in ['y','yes']:
1560 print 'Operation cancelled.'
1613 print 'Operation cancelled.'
1561 return
1614 return
1562 cmds = ''.join(self.extract_input_slices(ranges))
1615 cmds = ''.join(self.extract_input_slices(ranges))
1563 f = file(fname,'w')
1616 f = file(fname,'w')
1564 f.write(cmds)
1617 f.write(cmds)
1565 f.close()
1618 f.close()
1566 print 'The following commands were written to file `%s`:' % fname
1619 print 'The following commands were written to file `%s`:' % fname
1567 print cmds
1620 print cmds
1568
1621
1569 def magic_ed(self,parameter_s = ''):
1622 def magic_ed(self,parameter_s = ''):
1570 """Alias to %edit."""
1623 """Alias to %edit."""
1571 return self.magic_edit(parameter_s)
1624 return self.magic_edit(parameter_s)
1572
1625
1573 def magic_edit(self,parameter_s = '',last_call=['','']):
1626 def magic_edit(self,parameter_s = '',last_call=['','']):
1574 """Bring up an editor and execute the resulting code.
1627 """Bring up an editor and execute the resulting code.
1575
1628
1576 Usage:
1629 Usage:
1577 %edit [options] [args]
1630 %edit [options] [args]
1578
1631
1579 %edit runs IPython's editor hook. The default version of this hook is
1632 %edit runs IPython's editor hook. The default version of this hook is
1580 set to call the __IPYTHON__.rc.editor command. This is read from your
1633 set to call the __IPYTHON__.rc.editor command. This is read from your
1581 environment variable $EDITOR. If this isn't found, it will default to
1634 environment variable $EDITOR. If this isn't found, it will default to
1582 vi under Linux/Unix and to notepad under Windows. See the end of this
1635 vi under Linux/Unix and to notepad under Windows. See the end of this
1583 docstring for how to change the editor hook.
1636 docstring for how to change the editor hook.
1584
1637
1585 You can also set the value of this editor via the command line option
1638 You can also set the value of this editor via the command line option
1586 '-editor' or in your ipythonrc file. This is useful if you wish to use
1639 '-editor' or in your ipythonrc file. This is useful if you wish to use
1587 specifically for IPython an editor different from your typical default
1640 specifically for IPython an editor different from your typical default
1588 (and for Windows users who typically don't set environment variables).
1641 (and for Windows users who typically don't set environment variables).
1589
1642
1590 This command allows you to conveniently edit multi-line code right in
1643 This command allows you to conveniently edit multi-line code right in
1591 your IPython session.
1644 your IPython session.
1592
1645
1593 If called without arguments, %edit opens up an empty editor with a
1646 If called without arguments, %edit opens up an empty editor with a
1594 temporary file and will execute the contents of this file when you
1647 temporary file and will execute the contents of this file when you
1595 close it (don't forget to save it!).
1648 close it (don't forget to save it!).
1596
1649
1597 Options:
1650 Options:
1598
1651
1599 -p: this will call the editor with the same data as the previous time
1652 -p: this will call the editor with the same data as the previous time
1600 it was used, regardless of how long ago (in your current session) it
1653 it was used, regardless of how long ago (in your current session) it
1601 was.
1654 was.
1602
1655
1603 -x: do not execute the edited code immediately upon exit. This is
1656 -x: do not execute the edited code immediately upon exit. This is
1604 mainly useful if you are editing programs which need to be called with
1657 mainly useful if you are editing programs which need to be called with
1605 command line arguments, which you can then do using %run.
1658 command line arguments, which you can then do using %run.
1606
1659
1607 Arguments:
1660 Arguments:
1608
1661
1609 If arguments are given, the following possibilites exist:
1662 If arguments are given, the following possibilites exist:
1610
1663
1611 - The arguments are numbers or pairs of colon-separated numbers (like
1664 - The arguments are numbers or pairs of colon-separated numbers (like
1612 1 4:8 9). These are interpreted as lines of previous input to be
1665 1 4:8 9). These are interpreted as lines of previous input to be
1613 loaded into the editor. The syntax is the same of the %macro command.
1666 loaded into the editor. The syntax is the same of the %macro command.
1614
1667
1615 - If the argument doesn't start with a number, it is evaluated as a
1668 - If the argument doesn't start with a number, it is evaluated as a
1616 variable and its contents loaded into the editor. You can thus edit
1669 variable and its contents loaded into the editor. You can thus edit
1617 any string which contains python code (including the result of
1670 any string which contains python code (including the result of
1618 previous edits).
1671 previous edits).
1619
1672
1620 - If the argument is the name of an object (other than a string),
1673 - If the argument is the name of an object (other than a string),
1621 IPython will try to locate the file where it was defined and open the
1674 IPython will try to locate the file where it was defined and open the
1622 editor at the point where it is defined. You can use `%edit function`
1675 editor at the point where it is defined. You can use `%edit function`
1623 to load an editor exactly at the point where 'function' is defined,
1676 to load an editor exactly at the point where 'function' is defined,
1624 edit it and have the file be executed automatically.
1677 edit it and have the file be executed automatically.
1625
1678
1626 Note: opening at an exact line is only supported under Unix, and some
1679 Note: opening at an exact line is only supported under Unix, and some
1627 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1680 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1628 '+NUMBER' parameter necessary for this feature. Good editors like
1681 '+NUMBER' parameter necessary for this feature. Good editors like
1629 (X)Emacs, vi, jed, pico and joe all do.
1682 (X)Emacs, vi, jed, pico and joe all do.
1630
1683
1631 - If the argument is not found as a variable, IPython will look for a
1684 - If the argument is not found as a variable, IPython will look for a
1632 file with that name (adding .py if necessary) and load it into the
1685 file with that name (adding .py if necessary) and load it into the
1633 editor. It will execute its contents with execfile() when you exit,
1686 editor. It will execute its contents with execfile() when you exit,
1634 loading any code in the file into your interactive namespace.
1687 loading any code in the file into your interactive namespace.
1635
1688
1636 After executing your code, %edit will return as output the code you
1689 After executing your code, %edit will return as output the code you
1637 typed in the editor (except when it was an existing file). This way
1690 typed in the editor (except when it was an existing file). This way
1638 you can reload the code in further invocations of %edit as a variable,
1691 you can reload the code in further invocations of %edit as a variable,
1639 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1692 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1640 the output.
1693 the output.
1641
1694
1642 Note that %edit is also available through the alias %ed.
1695 Note that %edit is also available through the alias %ed.
1643
1696
1644 This is an example of creating a simple function inside the editor and
1697 This is an example of creating a simple function inside the editor and
1645 then modifying it. First, start up the editor:
1698 then modifying it. First, start up the editor:
1646
1699
1647 In [1]: ed\\
1700 In [1]: ed\\
1648 Editing... done. Executing edited code...\\
1701 Editing... done. Executing edited code...\\
1649 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1702 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1650
1703
1651 We can then call the function foo():
1704 We can then call the function foo():
1652
1705
1653 In [2]: foo()\\
1706 In [2]: foo()\\
1654 foo() was defined in an editing session
1707 foo() was defined in an editing session
1655
1708
1656 Now we edit foo. IPython automatically loads the editor with the
1709 Now we edit foo. IPython automatically loads the editor with the
1657 (temporary) file where foo() was previously defined:
1710 (temporary) file where foo() was previously defined:
1658
1711
1659 In [3]: ed foo\\
1712 In [3]: ed foo\\
1660 Editing... done. Executing edited code...
1713 Editing... done. Executing edited code...
1661
1714
1662 And if we call foo() again we get the modified version:
1715 And if we call foo() again we get the modified version:
1663
1716
1664 In [4]: foo()\\
1717 In [4]: foo()\\
1665 foo() has now been changed!
1718 foo() has now been changed!
1666
1719
1667 Here is an example of how to edit a code snippet successive
1720 Here is an example of how to edit a code snippet successive
1668 times. First we call the editor:
1721 times. First we call the editor:
1669
1722
1670 In [8]: ed\\
1723 In [8]: ed\\
1671 Editing... done. Executing edited code...\\
1724 Editing... done. Executing edited code...\\
1672 hello\\
1725 hello\\
1673 Out[8]: "print 'hello'\\n"
1726 Out[8]: "print 'hello'\\n"
1674
1727
1675 Now we call it again with the previous output (stored in _):
1728 Now we call it again with the previous output (stored in _):
1676
1729
1677 In [9]: ed _\\
1730 In [9]: ed _\\
1678 Editing... done. Executing edited code...\\
1731 Editing... done. Executing edited code...\\
1679 hello world\\
1732 hello world\\
1680 Out[9]: "print 'hello world'\\n"
1733 Out[9]: "print 'hello world'\\n"
1681
1734
1682 Now we call it with the output #8 (stored in _8, also as Out[8]):
1735 Now we call it with the output #8 (stored in _8, also as Out[8]):
1683
1736
1684 In [10]: ed _8\\
1737 In [10]: ed _8\\
1685 Editing... done. Executing edited code...\\
1738 Editing... done. Executing edited code...\\
1686 hello again\\
1739 hello again\\
1687 Out[10]: "print 'hello again'\\n"
1740 Out[10]: "print 'hello again'\\n"
1688
1741
1689
1742
1690 Changing the default editor hook:
1743 Changing the default editor hook:
1691
1744
1692 If you wish to write your own editor hook, you can put it in a
1745 If you wish to write your own editor hook, you can put it in a
1693 configuration file which you load at startup time. The default hook
1746 configuration file which you load at startup time. The default hook
1694 is defined in the IPython.hooks module, and you can use that as a
1747 is defined in the IPython.hooks module, and you can use that as a
1695 starting example for further modifications. That file also has
1748 starting example for further modifications. That file also has
1696 general instructions on how to set a new hook for use once you've
1749 general instructions on how to set a new hook for use once you've
1697 defined it."""
1750 defined it."""
1698
1751
1699 # FIXME: This function has become a convoluted mess. It needs a
1752 # FIXME: This function has become a convoluted mess. It needs a
1700 # ground-up rewrite with clean, simple logic.
1753 # ground-up rewrite with clean, simple logic.
1701
1754
1702 def make_filename(arg):
1755 def make_filename(arg):
1703 "Make a filename from the given args"
1756 "Make a filename from the given args"
1704 try:
1757 try:
1705 filename = get_py_filename(arg)
1758 filename = get_py_filename(arg)
1706 except IOError:
1759 except IOError:
1707 if args.endswith('.py'):
1760 if args.endswith('.py'):
1708 filename = arg
1761 filename = arg
1709 else:
1762 else:
1710 filename = None
1763 filename = None
1711 return filename
1764 return filename
1712
1765
1713 # custom exceptions
1766 # custom exceptions
1714 class DataIsObject(Exception): pass
1767 class DataIsObject(Exception): pass
1715
1768
1716 opts,args = self.parse_options(parameter_s,'px')
1769 opts,args = self.parse_options(parameter_s,'px')
1717
1770
1718 # Default line number value
1771 # Default line number value
1719 lineno = None
1772 lineno = None
1720 if opts.has_key('p'):
1773 if opts.has_key('p'):
1721 args = '_%s' % last_call[0]
1774 args = '_%s' % last_call[0]
1722 if not self.shell.user_ns.has_key(args):
1775 if not self.shell.user_ns.has_key(args):
1723 args = last_call[1]
1776 args = last_call[1]
1724
1777
1725 # use last_call to remember the state of the previous call, but don't
1778 # use last_call to remember the state of the previous call, but don't
1726 # let it be clobbered by successive '-p' calls.
1779 # let it be clobbered by successive '-p' calls.
1727 try:
1780 try:
1728 last_call[0] = self.shell.outputcache.prompt_count
1781 last_call[0] = self.shell.outputcache.prompt_count
1729 if not opts.has_key('p'):
1782 if not opts.has_key('p'):
1730 last_call[1] = parameter_s
1783 last_call[1] = parameter_s
1731 except:
1784 except:
1732 pass
1785 pass
1733
1786
1734 # by default this is done with temp files, except when the given
1787 # by default this is done with temp files, except when the given
1735 # arg is a filename
1788 # arg is a filename
1736 use_temp = 1
1789 use_temp = 1
1737
1790
1738 if re.match(r'\d',args):
1791 if re.match(r'\d',args):
1739 # Mode where user specifies ranges of lines, like in %macro.
1792 # Mode where user specifies ranges of lines, like in %macro.
1740 # This means that you can't edit files whose names begin with
1793 # This means that you can't edit files whose names begin with
1741 # numbers this way. Tough.
1794 # numbers this way. Tough.
1742 ranges = args.split()
1795 ranges = args.split()
1743 data = ''.join(self.extract_input_slices(ranges))
1796 data = ''.join(self.extract_input_slices(ranges))
1744 elif args.endswith('.py'):
1797 elif args.endswith('.py'):
1745 filename = make_filename(args)
1798 filename = make_filename(args)
1746 data = ''
1799 data = ''
1747 use_temp = 0
1800 use_temp = 0
1748 elif args:
1801 elif args:
1749 try:
1802 try:
1750 # Load the parameter given as a variable. If not a string,
1803 # Load the parameter given as a variable. If not a string,
1751 # process it as an object instead (below)
1804 # process it as an object instead (below)
1752
1805
1753 #print '*** args',args,'type',type(args) # dbg
1806 #print '*** args',args,'type',type(args) # dbg
1754 data = eval(args,self.shell.user_ns)
1807 data = eval(args,self.shell.user_ns)
1755 if not type(data) in StringTypes:
1808 if not type(data) in StringTypes:
1756 raise DataIsObject
1809 raise DataIsObject
1757 except (NameError,SyntaxError):
1810 except (NameError,SyntaxError):
1758 # given argument is not a variable, try as a filename
1811 # given argument is not a variable, try as a filename
1759 filename = make_filename(args)
1812 filename = make_filename(args)
1760 if filename is None:
1813 if filename is None:
1761 warn("Argument given (%s) can't be found as a variable "
1814 warn("Argument given (%s) can't be found as a variable "
1762 "or as a filename." % args)
1815 "or as a filename." % args)
1763 return
1816 return
1764 data = ''
1817 data = ''
1765 use_temp = 0
1818 use_temp = 0
1766 except DataIsObject:
1819 except DataIsObject:
1767 # For objects, try to edit the file where they are defined
1820 # For objects, try to edit the file where they are defined
1768 try:
1821 try:
1769 filename = inspect.getabsfile(data)
1822 filename = inspect.getabsfile(data)
1770 datafile = 1
1823 datafile = 1
1771 except TypeError:
1824 except TypeError:
1772 filename = make_filename(args)
1825 filename = make_filename(args)
1773 datafile = 1
1826 datafile = 1
1774 warn('Could not find file where `%s` is defined.\n'
1827 warn('Could not find file where `%s` is defined.\n'
1775 'Opening a file named `%s`' % (args,filename))
1828 'Opening a file named `%s`' % (args,filename))
1776 # Now, make sure we can actually read the source (if it was in
1829 # Now, make sure we can actually read the source (if it was in
1777 # a temp file it's gone by now).
1830 # a temp file it's gone by now).
1778 if datafile:
1831 if datafile:
1779 try:
1832 try:
1780 lineno = inspect.getsourcelines(data)[1]
1833 lineno = inspect.getsourcelines(data)[1]
1781 except IOError:
1834 except IOError:
1782 filename = make_filename(args)
1835 filename = make_filename(args)
1783 if filename is None:
1836 if filename is None:
1784 warn('The file `%s` where `%s` was defined cannot '
1837 warn('The file `%s` where `%s` was defined cannot '
1785 'be read.' % (filename,data))
1838 'be read.' % (filename,data))
1786 return
1839 return
1787 use_temp = 0
1840 use_temp = 0
1788 else:
1841 else:
1789 data = ''
1842 data = ''
1790
1843
1791 if use_temp:
1844 if use_temp:
1792 filename = tempfile.mktemp('.py')
1845 filename = tempfile.mktemp('.py')
1793 self.shell.tempfiles.append(filename)
1846 self.shell.tempfiles.append(filename)
1794
1847
1795 if data and use_temp:
1848 if data and use_temp:
1796 tmp_file = open(filename,'w')
1849 tmp_file = open(filename,'w')
1797 tmp_file.write(data)
1850 tmp_file.write(data)
1798 tmp_file.close()
1851 tmp_file.close()
1799
1852
1800 # do actual editing here
1853 # do actual editing here
1801 print 'Editing...',
1854 print 'Editing...',
1802 sys.stdout.flush()
1855 sys.stdout.flush()
1803 self.shell.hooks.editor(filename,lineno)
1856 self.shell.hooks.editor(filename,lineno)
1804 if opts.has_key('x'): # -x prevents actual execution
1857 if opts.has_key('x'): # -x prevents actual execution
1805 print
1858 print
1806 else:
1859 else:
1807 print 'done. Executing edited code...'
1860 print 'done. Executing edited code...'
1808 try:
1861 try:
1809 execfile(filename,self.shell.user_ns)
1862 execfile(filename,self.shell.user_ns)
1810 except IOError,msg:
1863 except IOError,msg:
1811 if msg.filename == filename:
1864 if msg.filename == filename:
1812 warn('File not found. Did you forget to save?')
1865 warn('File not found. Did you forget to save?')
1813 return
1866 return
1814 else:
1867 else:
1815 self.shell.showtraceback()
1868 self.shell.showtraceback()
1816 except:
1869 except:
1817 self.shell.showtraceback()
1870 self.shell.showtraceback()
1818 if use_temp:
1871 if use_temp:
1819 contents = open(filename).read()
1872 contents = open(filename).read()
1820 return contents
1873 return contents
1821
1874
1822 def magic_xmode(self,parameter_s = ''):
1875 def magic_xmode(self,parameter_s = ''):
1823 """Switch modes for the exception handlers.
1876 """Switch modes for the exception handlers.
1824
1877
1825 Valid modes: Plain, Context and Verbose.
1878 Valid modes: Plain, Context and Verbose.
1826
1879
1827 If called without arguments, acts as a toggle."""
1880 If called without arguments, acts as a toggle."""
1828
1881
1829 new_mode = parameter_s.strip().capitalize()
1882 new_mode = parameter_s.strip().capitalize()
1830 try:
1883 try:
1831 self.InteractiveTB.set_mode(mode = new_mode)
1884 self.InteractiveTB.set_mode(mode = new_mode)
1832 print 'Exception reporting mode:',self.InteractiveTB.mode
1885 print 'Exception reporting mode:',self.InteractiveTB.mode
1833 except:
1886 except:
1834 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1887 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1835
1888
1836 def magic_colors(self,parameter_s = ''):
1889 def magic_colors(self,parameter_s = ''):
1837 """Switch color scheme for prompts, info system and exception handlers.
1890 """Switch color scheme for prompts, info system and exception handlers.
1838
1891
1839 Currently implemented schemes: NoColor, Linux, LightBG.
1892 Currently implemented schemes: NoColor, Linux, LightBG.
1840
1893
1841 Color scheme names are not case-sensitive."""
1894 Color scheme names are not case-sensitive."""
1842
1895
1843 new_scheme = parameter_s.strip()
1896 new_scheme = parameter_s.strip()
1844 if not new_scheme:
1897 if not new_scheme:
1845 print 'You must specify a color scheme.'
1898 print 'You must specify a color scheme.'
1846 return
1899 return
1847 # Under Windows, check for Gary Bishop's readline, which is necessary
1900 # Under Windows, check for Gary Bishop's readline, which is necessary
1848 # for ANSI coloring
1901 # for ANSI coloring
1849 if os.name in ['nt','dos']:
1902 if os.name in ['nt','dos']:
1850 try:
1903 try:
1851 import readline
1904 import readline
1852 except ImportError:
1905 except ImportError:
1853 has_readline = 0
1906 has_readline = 0
1854 else:
1907 else:
1855 try:
1908 try:
1856 readline.GetOutputFile()
1909 readline.GetOutputFile()
1857 except AttributeError:
1910 except AttributeError:
1858 has_readline = 0
1911 has_readline = 0
1859 else:
1912 else:
1860 has_readline = 1
1913 has_readline = 1
1861 if not has_readline:
1914 if not has_readline:
1862 msg = """\
1915 msg = """\
1863 Proper color support under MS Windows requires Gary Bishop's readline library.
1916 Proper color support under MS Windows requires Gary Bishop's readline library.
1864 You can find it at:
1917 You can find it at:
1865 http://sourceforge.net/projects/uncpythontools
1918 http://sourceforge.net/projects/uncpythontools
1866 Gary's readline needs the ctypes module, from:
1919 Gary's readline needs the ctypes module, from:
1867 http://starship.python.net/crew/theller/ctypes
1920 http://starship.python.net/crew/theller/ctypes
1868
1921
1869 Defaulting color scheme to 'NoColor'"""
1922 Defaulting color scheme to 'NoColor'"""
1870 new_scheme = 'NoColor'
1923 new_scheme = 'NoColor'
1871 warn(msg)
1924 warn(msg)
1872
1925
1873 # Set prompt colors
1926 # Set prompt colors
1874 try:
1927 try:
1875 self.shell.outputcache.set_colors(new_scheme)
1928 self.shell.outputcache.set_colors(new_scheme)
1876 except:
1929 except:
1877 warn('Error changing prompt color schemes.\n'
1930 warn('Error changing prompt color schemes.\n'
1878 + str(sys.exc_info()[1]))
1931 + str(sys.exc_info()[1]))
1879 else:
1932 else:
1880 self.shell.rc.colors = \
1933 self.shell.rc.colors = \
1881 self.shell.outputcache.color_table.active_scheme_name
1934 self.shell.outputcache.color_table.active_scheme_name
1882 # Set exception colors
1935 # Set exception colors
1883 try:
1936 try:
1884 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1937 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1885 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1938 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1886 except:
1939 except:
1887 warn('Error changing exception color schemes.\n'
1940 warn('Error changing exception color schemes.\n'
1888 + str(sys.exc_info()[1]))
1941 + str(sys.exc_info()[1]))
1889 # Set info (for 'object?') colors
1942 # Set info (for 'object?') colors
1890 if self.shell.rc.color_info:
1943 if self.shell.rc.color_info:
1891 try:
1944 try:
1892 self.shell.inspector.set_active_scheme(new_scheme)
1945 self.shell.inspector.set_active_scheme(new_scheme)
1893 except:
1946 except:
1894 warn('Error changing object inspector color schemes.\n'
1947 warn('Error changing object inspector color schemes.\n'
1895 + str(sys.exc_info()[1]))
1948 + str(sys.exc_info()[1]))
1896 else:
1949 else:
1897 self.shell.inspector.set_active_scheme('NoColor')
1950 self.shell.inspector.set_active_scheme('NoColor')
1898
1951
1899 def magic_color_info(self,parameter_s = ''):
1952 def magic_color_info(self,parameter_s = ''):
1900 """Toggle color_info.
1953 """Toggle color_info.
1901
1954
1902 The color_info configuration parameter controls whether colors are
1955 The color_info configuration parameter controls whether colors are
1903 used for displaying object details (by things like %psource, %pfile or
1956 used for displaying object details (by things like %psource, %pfile or
1904 the '?' system). This function toggles this value with each call.
1957 the '?' system). This function toggles this value with each call.
1905
1958
1906 Note that unless you have a fairly recent pager (less works better
1959 Note that unless you have a fairly recent pager (less works better
1907 than more) in your system, using colored object information displays
1960 than more) in your system, using colored object information displays
1908 will not work properly. Test it and see."""
1961 will not work properly. Test it and see."""
1909
1962
1910 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1963 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1911 self.magic_colors(self.shell.rc.colors)
1964 self.magic_colors(self.shell.rc.colors)
1912 print 'Object introspection functions have now coloring:',
1965 print 'Object introspection functions have now coloring:',
1913 print ['OFF','ON'][self.shell.rc.color_info]
1966 print ['OFF','ON'][self.shell.rc.color_info]
1914
1967
1915 def magic_Pprint(self, parameter_s=''):
1968 def magic_Pprint(self, parameter_s=''):
1916 """Toggle pretty printing on/off."""
1969 """Toggle pretty printing on/off."""
1917
1970
1918 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1971 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1919 print 'Pretty printing has been turned', \
1972 print 'Pretty printing has been turned', \
1920 ['OFF','ON'][self.shell.outputcache.Pprint]
1973 ['OFF','ON'][self.shell.outputcache.Pprint]
1921
1974
1922 def magic_Exit(self, parameter_s=''):
1975 def magic_Exit(self, parameter_s=''):
1923 """Exit IPython without confirmation."""
1976 """Exit IPython without confirmation."""
1924
1977
1925 self.shell.exit_now = True
1978 self.shell.exit_now = True
1926
1979
1927 def magic_Quit(self, parameter_s=''):
1980 def magic_Quit(self, parameter_s=''):
1928 """Exit IPython without confirmation (like %Exit)."""
1981 """Exit IPython without confirmation (like %Exit)."""
1929
1982
1930 self.shell.exit_now = True
1983 self.shell.exit_now = True
1931
1984
1932 #......................................................................
1985 #......................................................................
1933 # Functions to implement unix shell-type things
1986 # Functions to implement unix shell-type things
1934
1987
1935 def magic_alias(self, parameter_s = ''):
1988 def magic_alias(self, parameter_s = ''):
1936 """Define an alias for a system command.
1989 """Define an alias for a system command.
1937
1990
1938 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1991 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1939
1992
1940 Then, typing 'alias_name params' will execute the system command 'cmd
1993 Then, typing 'alias_name params' will execute the system command 'cmd
1941 params' (from your underlying operating system).
1994 params' (from your underlying operating system).
1942
1995
1943 Aliases have lower precedence than magic functions and Python normal
1996 Aliases have lower precedence than magic functions and Python normal
1944 variables, so if 'foo' is both a Python variable and an alias, the
1997 variables, so if 'foo' is both a Python variable and an alias, the
1945 alias can not be executed until 'del foo' removes the Python variable.
1998 alias can not be executed until 'del foo' removes the Python variable.
1946
1999
1947 You can use the %l specifier in an alias definition to represent the
2000 You can use the %l specifier in an alias definition to represent the
1948 whole line when the alias is called. For example:
2001 whole line when the alias is called. For example:
1949
2002
1950 In [2]: alias all echo "Input in brackets: <%l>"\\
2003 In [2]: alias all echo "Input in brackets: <%l>"\\
1951 In [3]: all hello world\\
2004 In [3]: all hello world\\
1952 Input in brackets: <hello world>
2005 Input in brackets: <hello world>
1953
2006
1954 You can also define aliases with parameters using %s specifiers (one
2007 You can also define aliases with parameters using %s specifiers (one
1955 per parameter):
2008 per parameter):
1956
2009
1957 In [1]: alias parts echo first %s second %s\\
2010 In [1]: alias parts echo first %s second %s\\
1958 In [2]: %parts A B\\
2011 In [2]: %parts A B\\
1959 first A second B\\
2012 first A second B\\
1960 In [3]: %parts A\\
2013 In [3]: %parts A\\
1961 Incorrect number of arguments: 2 expected.\\
2014 Incorrect number of arguments: 2 expected.\\
1962 parts is an alias to: 'echo first %s second %s'
2015 parts is an alias to: 'echo first %s second %s'
1963
2016
1964 Note that %l and %s are mutually exclusive. You can only use one or
2017 Note that %l and %s are mutually exclusive. You can only use one or
1965 the other in your aliases.
2018 the other in your aliases.
1966
2019
1967 Aliases expand Python variables just like system calls using ! or !!
2020 Aliases expand Python variables just like system calls using ! or !!
1968 do: all expressions prefixed with '$' get expanded. For details of
2021 do: all expressions prefixed with '$' get expanded. For details of
1969 the semantic rules, see PEP-215:
2022 the semantic rules, see PEP-215:
1970 http://www.python.org/peps/pep-0215.html. This is the library used by
2023 http://www.python.org/peps/pep-0215.html. This is the library used by
1971 IPython for variable expansion. If you want to access a true shell
2024 IPython for variable expansion. If you want to access a true shell
1972 variable, an extra $ is necessary to prevent its expansion by IPython:
2025 variable, an extra $ is necessary to prevent its expansion by IPython:
1973
2026
1974 In [6]: alias show echo\\
2027 In [6]: alias show echo\\
1975 In [7]: PATH='A Python string'\\
2028 In [7]: PATH='A Python string'\\
1976 In [8]: show $PATH\\
2029 In [8]: show $PATH\\
1977 A Python string\\
2030 A Python string\\
1978 In [9]: show $$PATH\\
2031 In [9]: show $$PATH\\
1979 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2032 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1980
2033
1981 You can use the alias facility to acess all of $PATH. See the %rehash
2034 You can use the alias facility to acess all of $PATH. See the %rehash
1982 and %rehashx functions, which automatically create aliases for the
2035 and %rehashx functions, which automatically create aliases for the
1983 contents of your $PATH.
2036 contents of your $PATH.
1984
2037
1985 If called with no parameters, %alias prints the current alias table."""
2038 If called with no parameters, %alias prints the current alias table."""
1986
2039
1987 par = parameter_s.strip()
2040 par = parameter_s.strip()
1988 if not par:
2041 if not par:
1989 if self.shell.rc.automagic:
2042 if self.shell.rc.automagic:
1990 prechar = ''
2043 prechar = ''
1991 else:
2044 else:
1992 prechar = self.shell.ESC_MAGIC
2045 prechar = self.shell.ESC_MAGIC
1993 print 'Alias\t\tSystem Command\n'+'-'*30
2046 print 'Alias\t\tSystem Command\n'+'-'*30
1994 atab = self.shell.alias_table
2047 atab = self.shell.alias_table
1995 aliases = atab.keys()
2048 aliases = atab.keys()
1996 aliases.sort()
2049 aliases.sort()
1997 for alias in aliases:
2050 for alias in aliases:
1998 print prechar+alias+'\t\t'+atab[alias][1]
2051 print prechar+alias+'\t\t'+atab[alias][1]
1999 print '-'*30+'\nTotal number of aliases:',len(aliases)
2052 print '-'*30+'\nTotal number of aliases:',len(aliases)
2000 return
2053 return
2001 try:
2054 try:
2002 alias,cmd = par.split(None,1)
2055 alias,cmd = par.split(None,1)
2003 except:
2056 except:
2004 print OInspect.getdoc(self.magic_alias)
2057 print OInspect.getdoc(self.magic_alias)
2005 else:
2058 else:
2006 nargs = cmd.count('%s')
2059 nargs = cmd.count('%s')
2007 if nargs>0 and cmd.find('%l')>=0:
2060 if nargs>0 and cmd.find('%l')>=0:
2008 error('The %s and %l specifiers are mutually exclusive '
2061 error('The %s and %l specifiers are mutually exclusive '
2009 'in alias definitions.')
2062 'in alias definitions.')
2010 else: # all looks OK
2063 else: # all looks OK
2011 self.shell.alias_table[alias] = (nargs,cmd)
2064 self.shell.alias_table[alias] = (nargs,cmd)
2012 self.shell.alias_table_validate(verbose=1)
2065 self.shell.alias_table_validate(verbose=1)
2013 # end magic_alias
2066 # end magic_alias
2014
2067
2015 def magic_unalias(self, parameter_s = ''):
2068 def magic_unalias(self, parameter_s = ''):
2016 """Remove an alias"""
2069 """Remove an alias"""
2017
2070
2018 aname = parameter_s.strip()
2071 aname = parameter_s.strip()
2019 if aname in self.shell.alias_table:
2072 if aname in self.shell.alias_table:
2020 del self.shell.alias_table[aname]
2073 del self.shell.alias_table[aname]
2021
2074
2022 def magic_rehash(self, parameter_s = ''):
2075 def magic_rehash(self, parameter_s = ''):
2023 """Update the alias table with all entries in $PATH.
2076 """Update the alias table with all entries in $PATH.
2024
2077
2025 This version does no checks on execute permissions or whether the
2078 This version does no checks on execute permissions or whether the
2026 contents of $PATH are truly files (instead of directories or something
2079 contents of $PATH are truly files (instead of directories or something
2027 else). For such a safer (but slower) version, use %rehashx."""
2080 else). For such a safer (but slower) version, use %rehashx."""
2028
2081
2029 # This function (and rehashx) manipulate the alias_table directly
2082 # This function (and rehashx) manipulate the alias_table directly
2030 # rather than calling magic_alias, for speed reasons. A rehash on a
2083 # rather than calling magic_alias, for speed reasons. A rehash on a
2031 # typical Linux box involves several thousand entries, so efficiency
2084 # typical Linux box involves several thousand entries, so efficiency
2032 # here is a top concern.
2085 # here is a top concern.
2033
2086
2034 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2087 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2035 alias_table = self.shell.alias_table
2088 alias_table = self.shell.alias_table
2036 for pdir in path:
2089 for pdir in path:
2037 for ff in os.listdir(pdir):
2090 for ff in os.listdir(pdir):
2038 # each entry in the alias table must be (N,name), where
2091 # each entry in the alias table must be (N,name), where
2039 # N is the number of positional arguments of the alias.
2092 # N is the number of positional arguments of the alias.
2040 alias_table[ff] = (0,ff)
2093 alias_table[ff] = (0,ff)
2041 # Make sure the alias table doesn't contain keywords or builtins
2094 # Make sure the alias table doesn't contain keywords or builtins
2042 self.shell.alias_table_validate()
2095 self.shell.alias_table_validate()
2043 # Call again init_auto_alias() so we get 'rm -i' and other modified
2096 # Call again init_auto_alias() so we get 'rm -i' and other modified
2044 # aliases since %rehash will probably clobber them
2097 # aliases since %rehash will probably clobber them
2045 self.shell.init_auto_alias()
2098 self.shell.init_auto_alias()
2046
2099
2047 def magic_rehashx(self, parameter_s = ''):
2100 def magic_rehashx(self, parameter_s = ''):
2048 """Update the alias table with all executable files in $PATH.
2101 """Update the alias table with all executable files in $PATH.
2049
2102
2050 This version explicitly checks that every entry in $PATH is a file
2103 This version explicitly checks that every entry in $PATH is a file
2051 with execute access (os.X_OK), so it is much slower than %rehash.
2104 with execute access (os.X_OK), so it is much slower than %rehash.
2052
2105
2053 Under Windows, it checks executability as a match agains a
2106 Under Windows, it checks executability as a match agains a
2054 '|'-separated string of extensions, stored in the IPython config
2107 '|'-separated string of extensions, stored in the IPython config
2055 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2108 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2056
2109
2057 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2110 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2058 alias_table = self.shell.alias_table
2111 alias_table = self.shell.alias_table
2059
2112
2060 if os.name == 'posix':
2113 if os.name == 'posix':
2061 isexec = lambda fname:os.path.isfile(fname) and \
2114 isexec = lambda fname:os.path.isfile(fname) and \
2062 os.access(fname,os.X_OK)
2115 os.access(fname,os.X_OK)
2063 else:
2116 else:
2064
2117
2065 try:
2118 try:
2066 winext = os.environ['pathext'].replace(';','|').replace('.','')
2119 winext = os.environ['pathext'].replace(';','|').replace('.','')
2067 except KeyError:
2120 except KeyError:
2068 winext = 'exe|com|bat'
2121 winext = 'exe|com|bat'
2069
2122
2070 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2123 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2071 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2124 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2072 savedir = os.getcwd()
2125 savedir = os.getcwd()
2073 try:
2126 try:
2074 # write the whole loop for posix/Windows so we don't have an if in
2127 # write the whole loop for posix/Windows so we don't have an if in
2075 # the innermost part
2128 # the innermost part
2076 if os.name == 'posix':
2129 if os.name == 'posix':
2077 for pdir in path:
2130 for pdir in path:
2078 os.chdir(pdir)
2131 os.chdir(pdir)
2079 for ff in os.listdir(pdir):
2132 for ff in os.listdir(pdir):
2080 if isexec(ff):
2133 if isexec(ff):
2081 # each entry in the alias table must be (N,name),
2134 # each entry in the alias table must be (N,name),
2082 # where N is the number of positional arguments of the
2135 # where N is the number of positional arguments of the
2083 # alias.
2136 # alias.
2084 alias_table[ff] = (0,ff)
2137 alias_table[ff] = (0,ff)
2085 else:
2138 else:
2086 for pdir in path:
2139 for pdir in path:
2087 os.chdir(pdir)
2140 os.chdir(pdir)
2088 for ff in os.listdir(pdir):
2141 for ff in os.listdir(pdir):
2089 if isexec(ff):
2142 if isexec(ff):
2090 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2143 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2091 # Make sure the alias table doesn't contain keywords or builtins
2144 # Make sure the alias table doesn't contain keywords or builtins
2092 self.shell.alias_table_validate()
2145 self.shell.alias_table_validate()
2093 # Call again init_auto_alias() so we get 'rm -i' and other
2146 # Call again init_auto_alias() so we get 'rm -i' and other
2094 # modified aliases since %rehashx will probably clobber them
2147 # modified aliases since %rehashx will probably clobber them
2095 self.shell.init_auto_alias()
2148 self.shell.init_auto_alias()
2096 finally:
2149 finally:
2097 os.chdir(savedir)
2150 os.chdir(savedir)
2098
2151
2099 def magic_pwd(self, parameter_s = ''):
2152 def magic_pwd(self, parameter_s = ''):
2100 """Return the current working directory path."""
2153 """Return the current working directory path."""
2101 return os.getcwd()
2154 return os.getcwd()
2102
2155
2103 def magic_cd(self, parameter_s=''):
2156 def magic_cd(self, parameter_s=''):
2104 """Change the current working directory.
2157 """Change the current working directory.
2105
2158
2106 This command automatically maintains an internal list of directories
2159 This command automatically maintains an internal list of directories
2107 you visit during your IPython session, in the variable _dh. The
2160 you visit during your IPython session, in the variable _dh. The
2108 command %dhist shows this history nicely formatted.
2161 command %dhist shows this history nicely formatted.
2109
2162
2110 Usage:
2163 Usage:
2111
2164
2112 cd 'dir': changes to directory 'dir'.
2165 cd 'dir': changes to directory 'dir'.
2113
2166
2114 cd -: changes to the last visited directory.
2167 cd -: changes to the last visited directory.
2115
2168
2116 cd -<n>: changes to the n-th directory in the directory history.
2169 cd -<n>: changes to the n-th directory in the directory history.
2117
2170
2118 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2171 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2119 (note: cd <bookmark_name> is enough if there is no
2172 (note: cd <bookmark_name> is enough if there is no
2120 directory <bookmark_name>, but a bookmark with the name exists.)
2173 directory <bookmark_name>, but a bookmark with the name exists.)
2121
2174
2122 Options:
2175 Options:
2123
2176
2124 -q: quiet. Do not print the working directory after the cd command is
2177 -q: quiet. Do not print the working directory after the cd command is
2125 executed. By default IPython's cd command does print this directory,
2178 executed. By default IPython's cd command does print this directory,
2126 since the default prompts do not display path information.
2179 since the default prompts do not display path information.
2127
2180
2128 Note that !cd doesn't work for this purpose because the shell where
2181 Note that !cd doesn't work for this purpose because the shell where
2129 !command runs is immediately discarded after executing 'command'."""
2182 !command runs is immediately discarded after executing 'command'."""
2130
2183
2131 parameter_s = parameter_s.strip()
2184 parameter_s = parameter_s.strip()
2132 bkms = self.shell.persist.get("bookmarks",{})
2185 bkms = self.shell.persist.get("bookmarks",{})
2133
2186
2134 numcd = re.match(r'(-)(\d+)$',parameter_s)
2187 numcd = re.match(r'(-)(\d+)$',parameter_s)
2135 # jump in directory history by number
2188 # jump in directory history by number
2136 if numcd:
2189 if numcd:
2137 nn = int(numcd.group(2))
2190 nn = int(numcd.group(2))
2138 try:
2191 try:
2139 ps = self.shell.user_ns['_dh'][nn]
2192 ps = self.shell.user_ns['_dh'][nn]
2140 except IndexError:
2193 except IndexError:
2141 print 'The requested directory does not exist in history.'
2194 print 'The requested directory does not exist in history.'
2142 return
2195 return
2143 else:
2196 else:
2144 opts = {}
2197 opts = {}
2145 else:
2198 else:
2146 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2199 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2147 # jump to previous
2200 # jump to previous
2148 if ps == '-':
2201 if ps == '-':
2149 try:
2202 try:
2150 ps = self.shell.user_ns['_dh'][-2]
2203 ps = self.shell.user_ns['_dh'][-2]
2151 except IndexError:
2204 except IndexError:
2152 print 'No previous directory to change to.'
2205 print 'No previous directory to change to.'
2153 return
2206 return
2154 # jump to bookmark
2207 # jump to bookmark
2155 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2208 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2156 if bkms.has_key(ps):
2209 if bkms.has_key(ps):
2157 target = bkms[ps]
2210 target = bkms[ps]
2158 print '(bookmark:%s) -> %s' % (ps,target)
2211 print '(bookmark:%s) -> %s' % (ps,target)
2159 ps = target
2212 ps = target
2160 else:
2213 else:
2161 if bkms:
2214 if bkms:
2162 error("Bookmark '%s' not found. "
2215 error("Bookmark '%s' not found. "
2163 "Use '%bookmark -l' to see your bookmarks." % ps)
2216 "Use '%bookmark -l' to see your bookmarks." % ps)
2164 else:
2217 else:
2165 print "Bookmarks not set - use %bookmark <bookmarkname>"
2218 print "Bookmarks not set - use %bookmark <bookmarkname>"
2166 return
2219 return
2167
2220
2168 # at this point ps should point to the target dir
2221 # at this point ps should point to the target dir
2169 if ps:
2222 if ps:
2170 try:
2223 try:
2171 os.chdir(os.path.expanduser(ps))
2224 os.chdir(os.path.expanduser(ps))
2172 except OSError:
2225 except OSError:
2173 print sys.exc_info()[1]
2226 print sys.exc_info()[1]
2174 else:
2227 else:
2175 self.shell.user_ns['_dh'].append(os.getcwd())
2228 self.shell.user_ns['_dh'].append(os.getcwd())
2176 else:
2229 else:
2177 os.chdir(self.home_dir)
2230 os.chdir(self.home_dir)
2178 self.shell.user_ns['_dh'].append(os.getcwd())
2231 self.shell.user_ns['_dh'].append(os.getcwd())
2179 if not 'q' in opts:
2232 if not 'q' in opts:
2180 print self.shell.user_ns['_dh'][-1]
2233 print self.shell.user_ns['_dh'][-1]
2181
2234
2182 def magic_dhist(self, parameter_s=''):
2235 def magic_dhist(self, parameter_s=''):
2183 """Print your history of visited directories.
2236 """Print your history of visited directories.
2184
2237
2185 %dhist -> print full history\\
2238 %dhist -> print full history\\
2186 %dhist n -> print last n entries only\\
2239 %dhist n -> print last n entries only\\
2187 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2240 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2188
2241
2189 This history is automatically maintained by the %cd command, and
2242 This history is automatically maintained by the %cd command, and
2190 always available as the global list variable _dh. You can use %cd -<n>
2243 always available as the global list variable _dh. You can use %cd -<n>
2191 to go to directory number <n>."""
2244 to go to directory number <n>."""
2192
2245
2193 dh = self.shell.user_ns['_dh']
2246 dh = self.shell.user_ns['_dh']
2194 if parameter_s:
2247 if parameter_s:
2195 try:
2248 try:
2196 args = map(int,parameter_s.split())
2249 args = map(int,parameter_s.split())
2197 except:
2250 except:
2198 self.arg_err(Magic.magic_dhist)
2251 self.arg_err(Magic.magic_dhist)
2199 return
2252 return
2200 if len(args) == 1:
2253 if len(args) == 1:
2201 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2254 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2202 elif len(args) == 2:
2255 elif len(args) == 2:
2203 ini,fin = args
2256 ini,fin = args
2204 else:
2257 else:
2205 self.arg_err(Magic.magic_dhist)
2258 self.arg_err(Magic.magic_dhist)
2206 return
2259 return
2207 else:
2260 else:
2208 ini,fin = 0,len(dh)
2261 ini,fin = 0,len(dh)
2209 nlprint(dh,
2262 nlprint(dh,
2210 header = 'Directory history (kept in _dh)',
2263 header = 'Directory history (kept in _dh)',
2211 start=ini,stop=fin)
2264 start=ini,stop=fin)
2212
2265
2213 def magic_env(self, parameter_s=''):
2266 def magic_env(self, parameter_s=''):
2214 """List environment variables."""
2267 """List environment variables."""
2215
2268
2216 # environ is an instance of UserDict
2269 # environ is an instance of UserDict
2217 return os.environ.data
2270 return os.environ.data
2218
2271
2219 def magic_pushd(self, parameter_s=''):
2272 def magic_pushd(self, parameter_s=''):
2220 """Place the current dir on stack and change directory.
2273 """Place the current dir on stack and change directory.
2221
2274
2222 Usage:\\
2275 Usage:\\
2223 %pushd ['dirname']
2276 %pushd ['dirname']
2224
2277
2225 %pushd with no arguments does a %pushd to your home directory.
2278 %pushd with no arguments does a %pushd to your home directory.
2226 """
2279 """
2227 if parameter_s == '': parameter_s = '~'
2280 if parameter_s == '': parameter_s = '~'
2228 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2281 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2229 os.path.expanduser(self.dir_stack[0]):
2282 os.path.expanduser(self.dir_stack[0]):
2230 try:
2283 try:
2231 self.magic_cd(parameter_s)
2284 self.magic_cd(parameter_s)
2232 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2285 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2233 self.magic_dirs()
2286 self.magic_dirs()
2234 except:
2287 except:
2235 print 'Invalid directory'
2288 print 'Invalid directory'
2236 else:
2289 else:
2237 print 'You are already there!'
2290 print 'You are already there!'
2238
2291
2239 def magic_popd(self, parameter_s=''):
2292 def magic_popd(self, parameter_s=''):
2240 """Change to directory popped off the top of the stack.
2293 """Change to directory popped off the top of the stack.
2241 """
2294 """
2242 if len (self.dir_stack) > 1:
2295 if len (self.dir_stack) > 1:
2243 self.dir_stack.pop(0)
2296 self.dir_stack.pop(0)
2244 self.magic_cd(self.dir_stack[0])
2297 self.magic_cd(self.dir_stack[0])
2245 print self.dir_stack[0]
2298 print self.dir_stack[0]
2246 else:
2299 else:
2247 print "You can't remove the starting directory from the stack:",\
2300 print "You can't remove the starting directory from the stack:",\
2248 self.dir_stack
2301 self.dir_stack
2249
2302
2250 def magic_dirs(self, parameter_s=''):
2303 def magic_dirs(self, parameter_s=''):
2251 """Return the current directory stack."""
2304 """Return the current directory stack."""
2252
2305
2253 return self.dir_stack[:]
2306 return self.dir_stack[:]
2254
2307
2255 def magic_sc(self, parameter_s=''):
2308 def magic_sc(self, parameter_s=''):
2256 """Shell capture - execute a shell command and capture its output.
2309 """Shell capture - execute a shell command and capture its output.
2257
2310
2258 %sc [options] varname=command
2311 %sc [options] varname=command
2259
2312
2260 IPython will run the given command using commands.getoutput(), and
2313 IPython will run the given command using commands.getoutput(), and
2261 will then update the user's interactive namespace with a variable
2314 will then update the user's interactive namespace with a variable
2262 called varname, containing the value of the call. Your command can
2315 called varname, containing the value of the call. Your command can
2263 contain shell wildcards, pipes, etc.
2316 contain shell wildcards, pipes, etc.
2264
2317
2265 The '=' sign in the syntax is mandatory, and the variable name you
2318 The '=' sign in the syntax is mandatory, and the variable name you
2266 supply must follow Python's standard conventions for valid names.
2319 supply must follow Python's standard conventions for valid names.
2267
2320
2268 Options:
2321 Options:
2269
2322
2270 -l: list output. Split the output on newlines into a list before
2323 -l: list output. Split the output on newlines into a list before
2271 assigning it to the given variable. By default the output is stored
2324 assigning it to the given variable. By default the output is stored
2272 as a single string.
2325 as a single string.
2273
2326
2274 -v: verbose. Print the contents of the variable.
2327 -v: verbose. Print the contents of the variable.
2275
2328
2276 In most cases you should not need to split as a list, because the
2329 In most cases you should not need to split as a list, because the
2277 returned value is a special type of string which can automatically
2330 returned value is a special type of string which can automatically
2278 provide its contents either as a list (split on newlines) or as a
2331 provide its contents either as a list (split on newlines) or as a
2279 space-separated string. These are convenient, respectively, either
2332 space-separated string. These are convenient, respectively, either
2280 for sequential processing or to be passed to a shell command.
2333 for sequential processing or to be passed to a shell command.
2281
2334
2282 For example:
2335 For example:
2283
2336
2284 # Capture into variable a
2337 # Capture into variable a
2285 In [9]: sc a=ls *py
2338 In [9]: sc a=ls *py
2286
2339
2287 # a is a string with embedded newlines
2340 # a is a string with embedded newlines
2288 In [10]: a
2341 In [10]: a
2289 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2342 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2290
2343
2291 # which can be seen as a list:
2344 # which can be seen as a list:
2292 In [11]: a.l
2345 In [11]: a.l
2293 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2346 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2294
2347
2295 # or as a whitespace-separated string:
2348 # or as a whitespace-separated string:
2296 In [12]: a.s
2349 In [12]: a.s
2297 Out[12]: 'setup.py win32_manual_post_install.py'
2350 Out[12]: 'setup.py win32_manual_post_install.py'
2298
2351
2299 # a.s is useful to pass as a single command line:
2352 # a.s is useful to pass as a single command line:
2300 In [13]: !wc -l $a.s
2353 In [13]: !wc -l $a.s
2301 146 setup.py
2354 146 setup.py
2302 130 win32_manual_post_install.py
2355 130 win32_manual_post_install.py
2303 276 total
2356 276 total
2304
2357
2305 # while the list form is useful to loop over:
2358 # while the list form is useful to loop over:
2306 In [14]: for f in a.l:
2359 In [14]: for f in a.l:
2307 ....: !wc -l $f
2360 ....: !wc -l $f
2308 ....:
2361 ....:
2309 146 setup.py
2362 146 setup.py
2310 130 win32_manual_post_install.py
2363 130 win32_manual_post_install.py
2311
2364
2312 Similiarly, the lists returned by the -l option are also special, in
2365 Similiarly, the lists returned by the -l option are also special, in
2313 the sense that you can equally invoke the .s attribute on them to
2366 the sense that you can equally invoke the .s attribute on them to
2314 automatically get a whitespace-separated string from their contents:
2367 automatically get a whitespace-separated string from their contents:
2315
2368
2316 In [1]: sc -l b=ls *py
2369 In [1]: sc -l b=ls *py
2317
2370
2318 In [2]: b
2371 In [2]: b
2319 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2372 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2320
2373
2321 In [3]: b.s
2374 In [3]: b.s
2322 Out[3]: 'setup.py win32_manual_post_install.py'
2375 Out[3]: 'setup.py win32_manual_post_install.py'
2323
2376
2324 In summary, both the lists and strings used for ouptut capture have
2377 In summary, both the lists and strings used for ouptut capture have
2325 the following special attributes:
2378 the following special attributes:
2326
2379
2327 .l (or .list) : value as list.
2380 .l (or .list) : value as list.
2328 .n (or .nlstr): value as newline-separated string.
2381 .n (or .nlstr): value as newline-separated string.
2329 .s (or .spstr): value as space-separated string.
2382 .s (or .spstr): value as space-separated string.
2330 """
2383 """
2331
2384
2332 opts,args = self.parse_options(parameter_s,'lv')
2385 opts,args = self.parse_options(parameter_s,'lv')
2333 # Try to get a variable name and command to run
2386 # Try to get a variable name and command to run
2334 try:
2387 try:
2335 # the variable name must be obtained from the parse_options
2388 # the variable name must be obtained from the parse_options
2336 # output, which uses shlex.split to strip options out.
2389 # output, which uses shlex.split to strip options out.
2337 var,_ = args.split('=',1)
2390 var,_ = args.split('=',1)
2338 var = var.strip()
2391 var = var.strip()
2339 # But the the command has to be extracted from the original input
2392 # But the the command has to be extracted from the original input
2340 # parameter_s, not on what parse_options returns, to avoid the
2393 # parameter_s, not on what parse_options returns, to avoid the
2341 # quote stripping which shlex.split performs on it.
2394 # quote stripping which shlex.split performs on it.
2342 _,cmd = parameter_s.split('=',1)
2395 _,cmd = parameter_s.split('=',1)
2343 except ValueError:
2396 except ValueError:
2344 var,cmd = '',''
2397 var,cmd = '',''
2345 if not var:
2398 if not var:
2346 error('you must specify a variable to assign the command to.')
2399 error('you must specify a variable to assign the command to.')
2347 return
2400 return
2348 # If all looks ok, proceed
2401 # If all looks ok, proceed
2349 out,err = self.shell.getoutputerror(cmd)
2402 out,err = self.shell.getoutputerror(cmd)
2350 if err:
2403 if err:
2351 print >> Term.cerr,err
2404 print >> Term.cerr,err
2352 if opts.has_key('l'):
2405 if opts.has_key('l'):
2353 out = SList(out.split('\n'))
2406 out = SList(out.split('\n'))
2354 else:
2407 else:
2355 out = LSString(out)
2408 out = LSString(out)
2356 if opts.has_key('v'):
2409 if opts.has_key('v'):
2357 print '%s ==\n%s' % (var,pformat(out))
2410 print '%s ==\n%s' % (var,pformat(out))
2358 self.shell.user_ns.update({var:out})
2411 self.shell.user_ns.update({var:out})
2359
2412
2360 def magic_sx(self, parameter_s=''):
2413 def magic_sx(self, parameter_s=''):
2361 """Shell execute - run a shell command and capture its output.
2414 """Shell execute - run a shell command and capture its output.
2362
2415
2363 %sx command
2416 %sx command
2364
2417
2365 IPython will run the given command using commands.getoutput(), and
2418 IPython will run the given command using commands.getoutput(), and
2366 return the result formatted as a list (split on '\\n'). Since the
2419 return the result formatted as a list (split on '\\n'). Since the
2367 output is _returned_, it will be stored in ipython's regular output
2420 output is _returned_, it will be stored in ipython's regular output
2368 cache Out[N] and in the '_N' automatic variables.
2421 cache Out[N] and in the '_N' automatic variables.
2369
2422
2370 Notes:
2423 Notes:
2371
2424
2372 1) If an input line begins with '!!', then %sx is automatically
2425 1) If an input line begins with '!!', then %sx is automatically
2373 invoked. That is, while:
2426 invoked. That is, while:
2374 !ls
2427 !ls
2375 causes ipython to simply issue system('ls'), typing
2428 causes ipython to simply issue system('ls'), typing
2376 !!ls
2429 !!ls
2377 is a shorthand equivalent to:
2430 is a shorthand equivalent to:
2378 %sx ls
2431 %sx ls
2379
2432
2380 2) %sx differs from %sc in that %sx automatically splits into a list,
2433 2) %sx differs from %sc in that %sx automatically splits into a list,
2381 like '%sc -l'. The reason for this is to make it as easy as possible
2434 like '%sc -l'. The reason for this is to make it as easy as possible
2382 to process line-oriented shell output via further python commands.
2435 to process line-oriented shell output via further python commands.
2383 %sc is meant to provide much finer control, but requires more
2436 %sc is meant to provide much finer control, but requires more
2384 typing.
2437 typing.
2385
2438
2386 3) Just like %sc -l, this is a list with special attributes:
2439 3) Just like %sc -l, this is a list with special attributes:
2387
2440
2388 .l (or .list) : value as list.
2441 .l (or .list) : value as list.
2389 .n (or .nlstr): value as newline-separated string.
2442 .n (or .nlstr): value as newline-separated string.
2390 .s (or .spstr): value as whitespace-separated string.
2443 .s (or .spstr): value as whitespace-separated string.
2391
2444
2392 This is very useful when trying to use such lists as arguments to
2445 This is very useful when trying to use such lists as arguments to
2393 system commands."""
2446 system commands."""
2394
2447
2395 if parameter_s:
2448 if parameter_s:
2396 out,err = self.shell.getoutputerror(parameter_s)
2449 out,err = self.shell.getoutputerror(parameter_s)
2397 if err:
2450 if err:
2398 print >> Term.cerr,err
2451 print >> Term.cerr,err
2399 return SList(out.split('\n'))
2452 return SList(out.split('\n'))
2400
2453
2401 def magic_bg(self, parameter_s=''):
2454 def magic_bg(self, parameter_s=''):
2402 """Run a job in the background, in a separate thread.
2455 """Run a job in the background, in a separate thread.
2403
2456
2404 For example,
2457 For example,
2405
2458
2406 %bg myfunc(x,y,z=1)
2459 %bg myfunc(x,y,z=1)
2407
2460
2408 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2461 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2409 execution starts, a message will be printed indicating the job
2462 execution starts, a message will be printed indicating the job
2410 number. If your job number is 5, you can use
2463 number. If your job number is 5, you can use
2411
2464
2412 myvar = jobs.result(5) or myvar = jobs[5].result
2465 myvar = jobs.result(5) or myvar = jobs[5].result
2413
2466
2414 to assign this result to variable 'myvar'.
2467 to assign this result to variable 'myvar'.
2415
2468
2416 IPython has a job manager, accessible via the 'jobs' object. You can
2469 IPython has a job manager, accessible via the 'jobs' object. You can
2417 type jobs? to get more information about it, and use jobs.<TAB> to see
2470 type jobs? to get more information about it, and use jobs.<TAB> to see
2418 its attributes. All attributes not starting with an underscore are
2471 its attributes. All attributes not starting with an underscore are
2419 meant for public use.
2472 meant for public use.
2420
2473
2421 In particular, look at the jobs.new() method, which is used to create
2474 In particular, look at the jobs.new() method, which is used to create
2422 new jobs. This magic %bg function is just a convenience wrapper
2475 new jobs. This magic %bg function is just a convenience wrapper
2423 around jobs.new(), for expression-based jobs. If you want to create a
2476 around jobs.new(), for expression-based jobs. If you want to create a
2424 new job with an explicit function object and arguments, you must call
2477 new job with an explicit function object and arguments, you must call
2425 jobs.new() directly.
2478 jobs.new() directly.
2426
2479
2427 The jobs.new docstring also describes in detail several important
2480 The jobs.new docstring also describes in detail several important
2428 caveats associated with a thread-based model for background job
2481 caveats associated with a thread-based model for background job
2429 execution. Type jobs.new? for details.
2482 execution. Type jobs.new? for details.
2430
2483
2431 You can check the status of all jobs with jobs.status().
2484 You can check the status of all jobs with jobs.status().
2432
2485
2433 The jobs variable is set by IPython into the Python builtin namespace.
2486 The jobs variable is set by IPython into the Python builtin namespace.
2434 If you ever declare a variable named 'jobs', you will shadow this
2487 If you ever declare a variable named 'jobs', you will shadow this
2435 name. You can either delete your global jobs variable to regain
2488 name. You can either delete your global jobs variable to regain
2436 access to the job manager, or make a new name and assign it manually
2489 access to the job manager, or make a new name and assign it manually
2437 to the manager (stored in IPython's namespace). For example, to
2490 to the manager (stored in IPython's namespace). For example, to
2438 assign the job manager to the Jobs name, use:
2491 assign the job manager to the Jobs name, use:
2439
2492
2440 Jobs = __builtins__.jobs"""
2493 Jobs = __builtins__.jobs"""
2441
2494
2442 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2495 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2443
2496
2444 def magic_bookmark(self, parameter_s=''):
2497 def magic_bookmark(self, parameter_s=''):
2445 """Manage IPython's bookmark system.
2498 """Manage IPython's bookmark system.
2446
2499
2447 %bookmark <name> - set bookmark to current dir
2500 %bookmark <name> - set bookmark to current dir
2448 %bookmark <name> <dir> - set bookmark to <dir>
2501 %bookmark <name> <dir> - set bookmark to <dir>
2449 %bookmark -l - list all bookmarks
2502 %bookmark -l - list all bookmarks
2450 %bookmark -d <name> - remove bookmark
2503 %bookmark -d <name> - remove bookmark
2451 %bookmark -r - remove all bookmarks
2504 %bookmark -r - remove all bookmarks
2452
2505
2453 You can later on access a bookmarked folder with:
2506 You can later on access a bookmarked folder with:
2454 %cd -b <name>
2507 %cd -b <name>
2455 or simply '%cd <name>' if there is no directory called <name> AND
2508 or simply '%cd <name>' if there is no directory called <name> AND
2456 there is such a bookmark defined.
2509 there is such a bookmark defined.
2457
2510
2458 Your bookmarks persist through IPython sessions, but they are
2511 Your bookmarks persist through IPython sessions, but they are
2459 associated with each profile."""
2512 associated with each profile."""
2460
2513
2461 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2514 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2462 if len(args) > 2:
2515 if len(args) > 2:
2463 error('You can only give at most two arguments')
2516 error('You can only give at most two arguments')
2464 return
2517 return
2465
2518
2466 bkms = self.shell.persist.get('bookmarks',{})
2519 bkms = self.shell.persist.get('bookmarks',{})
2467
2520
2468 if opts.has_key('d'):
2521 if opts.has_key('d'):
2469 try:
2522 try:
2470 todel = args[0]
2523 todel = args[0]
2471 except IndexError:
2524 except IndexError:
2472 error('You must provide a bookmark to delete')
2525 error('You must provide a bookmark to delete')
2473 else:
2526 else:
2474 try:
2527 try:
2475 del bkms[todel]
2528 del bkms[todel]
2476 except:
2529 except:
2477 error("Can't delete bookmark '%s'" % todel)
2530 error("Can't delete bookmark '%s'" % todel)
2478 elif opts.has_key('r'):
2531 elif opts.has_key('r'):
2479 bkms = {}
2532 bkms = {}
2480 elif opts.has_key('l'):
2533 elif opts.has_key('l'):
2481 bks = bkms.keys()
2534 bks = bkms.keys()
2482 bks.sort()
2535 bks.sort()
2483 if bks:
2536 if bks:
2484 size = max(map(len,bks))
2537 size = max(map(len,bks))
2485 else:
2538 else:
2486 size = 0
2539 size = 0
2487 fmt = '%-'+str(size)+'s -> %s'
2540 fmt = '%-'+str(size)+'s -> %s'
2488 print 'Current bookmarks:'
2541 print 'Current bookmarks:'
2489 for bk in bks:
2542 for bk in bks:
2490 print fmt % (bk,bkms[bk])
2543 print fmt % (bk,bkms[bk])
2491 else:
2544 else:
2492 if not args:
2545 if not args:
2493 error("You must specify the bookmark name")
2546 error("You must specify the bookmark name")
2494 elif len(args)==1:
2547 elif len(args)==1:
2495 bkms[args[0]] = os.getcwd()
2548 bkms[args[0]] = os.getcwd()
2496 elif len(args)==2:
2549 elif len(args)==2:
2497 bkms[args[0]] = args[1]
2550 bkms[args[0]] = args[1]
2498 self.persist['bookmarks'] = bkms
2551 self.persist['bookmarks'] = bkms
2499
2552
2500 def magic_pycat(self, parameter_s=''):
2553 def magic_pycat(self, parameter_s=''):
2501 """Show a syntax-highlighted file through a pager.
2554 """Show a syntax-highlighted file through a pager.
2502
2555
2503 This magic is similar to the cat utility, but it will assume the file
2556 This magic is similar to the cat utility, but it will assume the file
2504 to be Python source and will show it with syntax highlighting. """
2557 to be Python source and will show it with syntax highlighting. """
2505
2558
2506 filename = get_py_filename(parameter_s)
2559 filename = get_py_filename(parameter_s)
2507 page(self.shell.colorize(file_read(filename)),
2560 page(self.shell.colorize(file_read(filename)),
2508 screen_lines=self.shell.rc.screen_length)
2561 screen_lines=self.shell.rc.screen_length)
2509
2562
2510 # end Magic
2563 # end Magic
@@ -1,442 +1,455 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for inspecting Python objects.
2 """Tools for inspecting Python objects.
3
3
4 Uses syntax highlighting for presenting the various information elements.
4 Uses syntax highlighting for presenting the various information elements.
5
5
6 Similar in spirit to the inspect module, but all calls take a name argument to
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
7 reference the name under which an object is being read.
8
8
9 $Id: OInspect.py 922 2005-11-13 10:21:08Z fperez $
9 $Id: OInspect.py 923 2005-11-15 08:51:15Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
13 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #*****************************************************************************
17 #*****************************************************************************
18
18
19 from IPython import Release
19 from IPython import Release
20 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
21 __license__ = Release.license
22
22
23 __all__ = ['Inspector','InspectColors']
23 __all__ = ['Inspector','InspectColors']
24
24
25 # stdlib modules
25 # stdlib modules
26 import __builtin__
26 import inspect,linecache,types,StringIO,string
27 import inspect,linecache,types,StringIO,string
27
28
28 # IPython's own
29 # IPython's own
29 from IPython import PyColorize
30 from IPython import PyColorize
30 from IPython.Itpl import itpl
31 from IPython.Itpl import itpl
31 from IPython.wildcard import choose_namespaces,list_namespace
32 from IPython.wildcard import list_namespace
32 from IPython.genutils import page,indent,Term
33 from IPython.genutils import page,indent,Term,mkdict
33 from IPython.ColorANSI import *
34 from IPython.ColorANSI import *
34
35
35 #****************************************************************************
36 #****************************************************************************
36 # Builtin color schemes
37 # Builtin color schemes
37
38
38 Colors = TermColors # just a shorthand
39 Colors = TermColors # just a shorthand
39
40
40 # Build a few color schemes
41 # Build a few color schemes
41 NoColor = ColorScheme(
42 NoColor = ColorScheme(
42 'NoColor',{
43 'NoColor',{
43 'header' : Colors.NoColor,
44 'header' : Colors.NoColor,
44 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
45 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
45 } )
46 } )
46
47
47 LinuxColors = ColorScheme(
48 LinuxColors = ColorScheme(
48 'Linux',{
49 'Linux',{
49 'header' : Colors.LightRed,
50 'header' : Colors.LightRed,
50 'normal' : Colors.Normal # color off (usu. Colors.Normal)
51 'normal' : Colors.Normal # color off (usu. Colors.Normal)
51 } )
52 } )
52
53
53 LightBGColors = ColorScheme(
54 LightBGColors = ColorScheme(
54 'LightBG',{
55 'LightBG',{
55 'header' : Colors.Red,
56 'header' : Colors.Red,
56 'normal' : Colors.Normal # color off (usu. Colors.Normal)
57 'normal' : Colors.Normal # color off (usu. Colors.Normal)
57 } )
58 } )
58
59
59 # Build table of color schemes (needed by the parser)
60 # Build table of color schemes (needed by the parser)
60 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
61 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
61 'Linux')
62 'Linux')
62
63
63 #****************************************************************************
64 #****************************************************************************
64 # Auxiliary functions
65 # Auxiliary functions
65 def getdoc(obj):
66 def getdoc(obj):
66 """Stable wrapper around inspect.getdoc.
67 """Stable wrapper around inspect.getdoc.
67
68
68 This can't crash because of attribute problems.
69 This can't crash because of attribute problems.
69
70
70 It also attempts to call a getdoc() method on the given object. This
71 It also attempts to call a getdoc() method on the given object. This
71 allows objects which provide their docstrings via non-standard mechanisms
72 allows objects which provide their docstrings via non-standard mechanisms
72 (like Pyro proxies) to still be inspected by ipython's ? system."""
73 (like Pyro proxies) to still be inspected by ipython's ? system."""
73
74
74 ds = None # default return value
75 ds = None # default return value
75 try:
76 try:
76 ds = inspect.getdoc(obj)
77 ds = inspect.getdoc(obj)
77 except:
78 except:
78 # Harden against an inspect failure, which can occur with
79 # Harden against an inspect failure, which can occur with
79 # SWIG-wrapped extensions.
80 # SWIG-wrapped extensions.
80 pass
81 pass
81 # Allow objects to offer customized documentation via a getdoc method:
82 # Allow objects to offer customized documentation via a getdoc method:
82 try:
83 try:
83 ds2 = obj.getdoc()
84 ds2 = obj.getdoc()
84 except:
85 except:
85 pass
86 pass
86 else:
87 else:
87 # if we get extra info, we add it to the normal docstring.
88 # if we get extra info, we add it to the normal docstring.
88 if ds is None:
89 if ds is None:
89 ds = ds2
90 ds = ds2
90 else:
91 else:
91 ds = '%s\n%s' % (ds,ds2)
92 ds = '%s\n%s' % (ds,ds2)
92 return ds
93 return ds
93
94
94 #****************************************************************************
95 #****************************************************************************
95 # Class definitions
96 # Class definitions
96
97
97 class myStringIO(StringIO.StringIO):
98 class myStringIO(StringIO.StringIO):
98 """Adds a writeln method to normal StringIO."""
99 """Adds a writeln method to normal StringIO."""
99 def writeln(self,*arg,**kw):
100 def writeln(self,*arg,**kw):
100 """Does a write() and then a write('\n')"""
101 """Does a write() and then a write('\n')"""
101 self.write(*arg,**kw)
102 self.write(*arg,**kw)
102 self.write('\n')
103 self.write('\n')
103
104
104 class Inspector:
105 class Inspector:
105 def __init__(self,color_table,code_color_table,scheme):
106 def __init__(self,color_table,code_color_table,scheme):
106 self.color_table = color_table
107 self.color_table = color_table
107 self.parser = PyColorize.Parser(code_color_table,out='str')
108 self.parser = PyColorize.Parser(code_color_table,out='str')
108 self.format = self.parser.format
109 self.format = self.parser.format
109 self.set_active_scheme(scheme)
110 self.set_active_scheme(scheme)
110
111
111 def __getargspec(self,obj):
112 def __getargspec(self,obj):
112 """Get the names and default values of a function's arguments.
113 """Get the names and default values of a function's arguments.
113
114
114 A tuple of four things is returned: (args, varargs, varkw, defaults).
115 A tuple of four things is returned: (args, varargs, varkw, defaults).
115 'args' is a list of the argument names (it may contain nested lists).
116 'args' is a list of the argument names (it may contain nested lists).
116 'varargs' and 'varkw' are the names of the * and ** arguments or None.
117 'varargs' and 'varkw' are the names of the * and ** arguments or None.
117 'defaults' is an n-tuple of the default values of the last n arguments.
118 'defaults' is an n-tuple of the default values of the last n arguments.
118
119
119 Modified version of inspect.getargspec from the Python Standard
120 Modified version of inspect.getargspec from the Python Standard
120 Library."""
121 Library."""
121
122
122 if inspect.isfunction(obj):
123 if inspect.isfunction(obj):
123 func_obj = obj
124 func_obj = obj
124 elif inspect.ismethod(obj):
125 elif inspect.ismethod(obj):
125 func_obj = obj.im_func
126 func_obj = obj.im_func
126 else:
127 else:
127 raise TypeError, 'arg is not a Python function'
128 raise TypeError, 'arg is not a Python function'
128 args, varargs, varkw = inspect.getargs(func_obj.func_code)
129 args, varargs, varkw = inspect.getargs(func_obj.func_code)
129 return args, varargs, varkw, func_obj.func_defaults
130 return args, varargs, varkw, func_obj.func_defaults
130
131
131 def __getdef(self,obj,oname=''):
132 def __getdef(self,obj,oname=''):
132 """Return the definition header for any callable object.
133 """Return the definition header for any callable object.
133
134
134 If any exception is generated, None is returned instead and the
135 If any exception is generated, None is returned instead and the
135 exception is suppressed."""
136 exception is suppressed."""
136
137
137 try:
138 try:
138 return oname + inspect.formatargspec(*self.__getargspec(obj))
139 return oname + inspect.formatargspec(*self.__getargspec(obj))
139 except:
140 except:
140 return None
141 return None
141
142
142 def __head(self,h):
143 def __head(self,h):
143 """Return a header string with proper colors."""
144 """Return a header string with proper colors."""
144 return '%s%s%s' % (self.color_table.active_colors.header,h,
145 return '%s%s%s' % (self.color_table.active_colors.header,h,
145 self.color_table.active_colors.normal)
146 self.color_table.active_colors.normal)
146
147
147 def set_active_scheme(self,scheme):
148 def set_active_scheme(self,scheme):
148 self.color_table.set_active_scheme(scheme)
149 self.color_table.set_active_scheme(scheme)
149 self.parser.color_table.set_active_scheme(scheme)
150 self.parser.color_table.set_active_scheme(scheme)
150
151
151 def noinfo(self,msg,oname):
152 def noinfo(self,msg,oname):
152 """Generic message when no information is found."""
153 """Generic message when no information is found."""
153 print 'No %s found' % msg,
154 print 'No %s found' % msg,
154 if oname:
155 if oname:
155 print 'for %s' % oname
156 print 'for %s' % oname
156 else:
157 else:
157 print
158 print
158
159
159 def pdef(self,obj,oname=''):
160 def pdef(self,obj,oname=''):
160 """Print the definition header for any callable object.
161 """Print the definition header for any callable object.
161
162
162 If the object is a class, print the constructor information."""
163 If the object is a class, print the constructor information."""
163
164
164 if not callable(obj):
165 if not callable(obj):
165 print 'Object is not callable.'
166 print 'Object is not callable.'
166 return
167 return
167
168
168 header = ''
169 header = ''
169 if type(obj) is types.ClassType:
170 if type(obj) is types.ClassType:
170 header = self.__head('Class constructor information:\n')
171 header = self.__head('Class constructor information:\n')
171 obj = obj.__init__
172 obj = obj.__init__
172 elif type(obj) is types.InstanceType:
173 elif type(obj) is types.InstanceType:
173 obj = obj.__call__
174 obj = obj.__call__
174
175
175 output = self.__getdef(obj,oname)
176 output = self.__getdef(obj,oname)
176 if output is None:
177 if output is None:
177 self.noinfo('definition header',oname)
178 self.noinfo('definition header',oname)
178 else:
179 else:
179 print >>Term.cout, header,self.format(output),
180 print >>Term.cout, header,self.format(output),
180
181
181 def pdoc(self,obj,oname='',formatter = None):
182 def pdoc(self,obj,oname='',formatter = None):
182 """Print the docstring for any object.
183 """Print the docstring for any object.
183
184
184 Optional:
185 Optional:
185 -formatter: a function to run the docstring through for specially
186 -formatter: a function to run the docstring through for specially
186 formatted docstrings."""
187 formatted docstrings."""
187
188
188 head = self.__head # so that itpl can find it even if private
189 head = self.__head # so that itpl can find it even if private
189 ds = getdoc(obj)
190 ds = getdoc(obj)
190 if formatter:
191 if formatter:
191 ds = formatter(ds)
192 ds = formatter(ds)
192 if type(obj) is types.ClassType:
193 if type(obj) is types.ClassType:
193 init_ds = getdoc(obj.__init__)
194 init_ds = getdoc(obj.__init__)
194 output = itpl('$head("Class Docstring:")\n'
195 output = itpl('$head("Class Docstring:")\n'
195 '$indent(ds)\n'
196 '$indent(ds)\n'
196 '$head("Constructor Docstring"):\n'
197 '$head("Constructor Docstring"):\n'
197 '$indent(init_ds)')
198 '$indent(init_ds)')
198 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
199 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
199 call_ds = getdoc(obj.__call__)
200 call_ds = getdoc(obj.__call__)
200 if call_ds:
201 if call_ds:
201 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
202 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
202 '$head("Calling Docstring:")\n$indent(call_ds)')
203 '$head("Calling Docstring:")\n$indent(call_ds)')
203 else:
204 else:
204 output = ds
205 output = ds
205 else:
206 else:
206 output = ds
207 output = ds
207 if output is None:
208 if output is None:
208 self.noinfo('documentation',oname)
209 self.noinfo('documentation',oname)
209 return
210 return
210 page(output)
211 page(output)
211
212
212 def psource(self,obj,oname=''):
213 def psource(self,obj,oname=''):
213 """Print the source code for an object."""
214 """Print the source code for an object."""
214
215
215 # Flush the source cache because inspect can return out-of-date source
216 # Flush the source cache because inspect can return out-of-date source
216 linecache.checkcache()
217 linecache.checkcache()
217 try:
218 try:
218 src = inspect.getsource(obj)
219 src = inspect.getsource(obj)
219 except:
220 except:
220 self.noinfo('source',oname)
221 self.noinfo('source',oname)
221 else:
222 else:
222 page(self.format(src))
223 page(self.format(src))
223
224
224 def pfile(self,obj,oname=''):
225 def pfile(self,obj,oname=''):
225 """Show the whole file where an object was defined."""
226 """Show the whole file where an object was defined."""
226 try:
227 try:
227 sourcelines,lineno = inspect.getsourcelines(obj)
228 sourcelines,lineno = inspect.getsourcelines(obj)
228 except:
229 except:
229 self.noinfo('file',oname)
230 self.noinfo('file',oname)
230 else:
231 else:
231 # run contents of file through pager starting at line
232 # run contents of file through pager starting at line
232 # where the object is defined
233 # where the object is defined
233 page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
234 page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
234
235
235 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
236 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
236 """Show detailed information about an object.
237 """Show detailed information about an object.
237
238
238 Optional arguments:
239 Optional arguments:
239
240
240 - oname: name of the variable pointing to the object.
241 - oname: name of the variable pointing to the object.
241
242
242 - formatter: special formatter for docstrings (see pdoc)
243 - formatter: special formatter for docstrings (see pdoc)
243
244
244 - info: a structure with some information fields which may have been
245 - info: a structure with some information fields which may have been
245 precomputed already.
246 precomputed already.
246
247
247 - detail_level: if set to 1, more information is given.
248 - detail_level: if set to 1, more information is given.
248 """
249 """
249
250
250 obj_type = type(obj)
251 obj_type = type(obj)
251
252
252 header = self.__head
253 header = self.__head
253 if info is None:
254 if info is None:
254 ismagic = 0
255 ismagic = 0
255 isalias = 0
256 isalias = 0
256 ospace = ''
257 ospace = ''
257 else:
258 else:
258 ismagic = info.ismagic
259 ismagic = info.ismagic
259 isalias = info.isalias
260 isalias = info.isalias
260 ospace = info.namespace
261 ospace = info.namespace
261 # Get docstring, special-casing aliases:
262 # Get docstring, special-casing aliases:
262 if isalias:
263 if isalias:
263 ds = "Alias to the system command:\n %s" % obj[1]
264 ds = "Alias to the system command:\n %s" % obj[1]
264 else:
265 else:
265 ds = getdoc(obj)
266 ds = getdoc(obj)
266 if formatter is not None:
267 if formatter is not None:
267 ds = formatter(ds)
268 ds = formatter(ds)
268
269
269 # store output in a list which gets joined with \n at the end.
270 # store output in a list which gets joined with \n at the end.
270 out = myStringIO()
271 out = myStringIO()
271
272
272 string_max = 200 # max size of strings to show (snipped if longer)
273 string_max = 200 # max size of strings to show (snipped if longer)
273 shalf = int((string_max -5)/2)
274 shalf = int((string_max -5)/2)
274
275
275 if ismagic:
276 if ismagic:
276 obj_type_name = 'Magic function'
277 obj_type_name = 'Magic function'
277 elif isalias:
278 elif isalias:
278 obj_type_name = 'System alias'
279 obj_type_name = 'System alias'
279 else:
280 else:
280 obj_type_name = obj_type.__name__
281 obj_type_name = obj_type.__name__
281 out.writeln(header('Type:\t\t')+obj_type_name)
282 out.writeln(header('Type:\t\t')+obj_type_name)
282
283
283 try:
284 try:
284 bclass = obj.__class__
285 bclass = obj.__class__
285 out.writeln(header('Base Class:\t')+str(bclass))
286 out.writeln(header('Base Class:\t')+str(bclass))
286 except: pass
287 except: pass
287
288
288 # String form, but snip if too long in ? form (full in ??)
289 # String form, but snip if too long in ? form (full in ??)
289 try:
290 try:
290 ostr = str(obj)
291 ostr = str(obj)
291 str_head = 'String Form:'
292 str_head = 'String Form:'
292 if not detail_level and len(ostr)>string_max:
293 if not detail_level and len(ostr)>string_max:
293 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
294 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
294 ostr = ("\n" + " " * len(str_head.expandtabs())).\
295 ostr = ("\n" + " " * len(str_head.expandtabs())).\
295 join(map(string.strip,ostr.split("\n")))
296 join(map(string.strip,ostr.split("\n")))
296 if ostr.find('\n') > -1:
297 if ostr.find('\n') > -1:
297 # Print multi-line strings starting at the next line.
298 # Print multi-line strings starting at the next line.
298 str_sep = '\n'
299 str_sep = '\n'
299 else:
300 else:
300 str_sep = '\t'
301 str_sep = '\t'
301 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
302 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
302 except:
303 except:
303 pass
304 pass
304
305
305 if ospace:
306 if ospace:
306 out.writeln(header('Namespace:\t')+ospace)
307 out.writeln(header('Namespace:\t')+ospace)
307
308
308 # Length (for strings and lists)
309 # Length (for strings and lists)
309 try:
310 try:
310 length = str(len(obj))
311 length = str(len(obj))
311 out.writeln(header('Length:\t\t')+length)
312 out.writeln(header('Length:\t\t')+length)
312 except: pass
313 except: pass
313
314
314 # Filename where object was defined
315 # Filename where object was defined
315 try:
316 try:
316 file = inspect.getabsfile(obj)
317 file = inspect.getabsfile(obj)
317 if file.endswith('<string>'):
318 if file.endswith('<string>'):
318 file = 'Dynamically generated function. No source code available.'
319 file = 'Dynamically generated function. No source code available.'
319 out.writeln(header('File:\t\t')+file)
320 out.writeln(header('File:\t\t')+file)
320 except: pass
321 except: pass
321
322
322 # reconstruct the function definition and print it:
323 # reconstruct the function definition and print it:
323 defln = self.__getdef(obj,oname)
324 defln = self.__getdef(obj,oname)
324 if defln:
325 if defln:
325 out.write(header('Definition:\t')+self.format(defln))
326 out.write(header('Definition:\t')+self.format(defln))
326
327
327 # Docstrings only in detail 0 mode, since source contains them (we
328 # Docstrings only in detail 0 mode, since source contains them (we
328 # avoid repetitions). If source fails, we add them back, see below.
329 # avoid repetitions). If source fails, we add them back, see below.
329 if ds and detail_level == 0:
330 if ds and detail_level == 0:
330 out.writeln(header('Docstring:\n') + indent(ds))
331 out.writeln(header('Docstring:\n') + indent(ds))
331
332
332 # Original source code for any callable
333 # Original source code for any callable
333 if detail_level:
334 if detail_level:
334 # Flush the source cache because inspect can return out-of-date source
335 # Flush the source cache because inspect can return out-of-date source
335 linecache.checkcache()
336 linecache.checkcache()
336 try:
337 try:
337 source = self.format(inspect.getsource(obj))
338 source = self.format(inspect.getsource(obj))
338 out.write(header('Source:\n')+source.rstrip())
339 out.write(header('Source:\n')+source.rstrip())
339 except:
340 except:
340 if ds:
341 if ds:
341 out.writeln(header('Docstring:\n') + indent(ds))
342 out.writeln(header('Docstring:\n') + indent(ds))
342
343
343 # Constructor docstring for classes
344 # Constructor docstring for classes
344 if obj_type is types.ClassType:
345 if obj_type is types.ClassType:
345 # reconstruct the function definition and print it:
346 # reconstruct the function definition and print it:
346 try:
347 try:
347 obj_init = obj.__init__
348 obj_init = obj.__init__
348 except AttributeError:
349 except AttributeError:
349 init_def = init_ds = None
350 init_def = init_ds = None
350 else:
351 else:
351 init_def = self.__getdef(obj_init,oname)
352 init_def = self.__getdef(obj_init,oname)
352 init_ds = getdoc(obj_init)
353 init_ds = getdoc(obj_init)
353
354
354 if init_def or init_ds:
355 if init_def or init_ds:
355 out.writeln(header('\nConstructor information:'))
356 out.writeln(header('\nConstructor information:'))
356 if init_def:
357 if init_def:
357 out.write(header('Definition:\t')+ self.format(init_def))
358 out.write(header('Definition:\t')+ self.format(init_def))
358 if init_ds:
359 if init_ds:
359 out.writeln(header('Docstring:\n') + indent(init_ds))
360 out.writeln(header('Docstring:\n') + indent(init_ds))
360 # and class docstring for instances:
361 # and class docstring for instances:
361 elif obj_type is types.InstanceType:
362 elif obj_type is types.InstanceType:
362
363
363 # First, check whether the instance docstring is identical to the
364 # First, check whether the instance docstring is identical to the
364 # class one, and print it separately if they don't coincide. In
365 # class one, and print it separately if they don't coincide. In
365 # most cases they will, but it's nice to print all the info for
366 # most cases they will, but it's nice to print all the info for
366 # objects which use instance-customized docstrings.
367 # objects which use instance-customized docstrings.
367 if ds:
368 if ds:
368 class_ds = getdoc(obj.__class__)
369 class_ds = getdoc(obj.__class__)
369 if class_ds and ds != class_ds:
370 if class_ds and ds != class_ds:
370 out.writeln(header('Class Docstring:\n') +
371 out.writeln(header('Class Docstring:\n') +
371 indent(class_ds))
372 indent(class_ds))
372
373
373 # Next, try to show constructor docstrings
374 # Next, try to show constructor docstrings
374 try:
375 try:
375 init_ds = getdoc(obj.__init__)
376 init_ds = getdoc(obj.__init__)
376 except AttributeError:
377 except AttributeError:
377 init_ds = None
378 init_ds = None
378 if init_ds:
379 if init_ds:
379 out.writeln(header('Constructor Docstring:\n') +
380 out.writeln(header('Constructor Docstring:\n') +
380 indent(init_ds))
381 indent(init_ds))
381
382
382 # Call form docstring for callable instances
383 # Call form docstring for callable instances
383 if hasattr(obj,'__call__'):
384 if hasattr(obj,'__call__'):
384 out.writeln(header('Callable:\t')+'Yes')
385 out.writeln(header('Callable:\t')+'Yes')
385 call_def = self.__getdef(obj.__call__,oname)
386 call_def = self.__getdef(obj.__call__,oname)
386 if call_def is None:
387 if call_def is None:
387 out.write(header('Call def:\t')+
388 out.write(header('Call def:\t')+
388 'Calling definition not available.')
389 'Calling definition not available.')
389 else:
390 else:
390 out.write(header('Call def:\t')+self.format(call_def))
391 out.write(header('Call def:\t')+self.format(call_def))
391 call_ds = getdoc(obj.__call__)
392 call_ds = getdoc(obj.__call__)
392 if call_ds:
393 if call_ds:
393 out.writeln(header('Call docstring:\n') + indent(call_ds))
394 out.writeln(header('Call docstring:\n') + indent(call_ds))
394
395
395 # Finally send to printer/pager
396 # Finally send to printer/pager
396 output = out.getvalue()
397 output = out.getvalue()
397 if output:
398 if output:
398 page(output)
399 page(output)
399 # end pinfo
400 # end pinfo
400
401
401 def psearch(self,oname='',formatter=None,shell=None):
402 def psearch(self,pattern,ns_table,ns_search=[],
403 ignore_case=False,show_all=False):
402 """Search namespaces with wildcards for objects.
404 """Search namespaces with wildcards for objects.
403
405
406 Arguments:
407
408 - pattern: string containing shell-like wildcards to use in namespace
409 searches and optionally a type specification to narrow the search to
410 objects of that type.
411
412 - ns_table: dict of name->namespaces for search.
413
404 Optional arguments:
414 Optional arguments:
405
415
406 - oname: rest of the commandline containging pattern and options.
416 - ns_search: list of namespace names to include in search.
407
417
408 - formatter: Not used.
418 - ignore_case(False): make the search case-insensitive.
409
419
410 - shell: The shell object from the Magic class. Needed to access
420 - show_all(False): show all names, including those starting with
411 the namespaces.
421 underscores.
412 """
422 """
413 option_list = ['-c','-a']
423 # defaults
414 cmds = oname.split()
415 filter = ''
416 type_pattern = 'all'
424 type_pattern = 'all'
417 options = [x for x in cmds if x in option_list]
425 filter = ''
418 ignorecase = '-c' not in options
426
419 showhidden = '-a' in options
427 cmds = pattern.split()
420 ns_cmds = [x for x in cmds if x[0] in '-+' and x not in option_list]
421 cmds = [x for x in cmds if x[0] not in '-+']
422 len_cmds = len(cmds)
428 len_cmds = len(cmds)
423 if len_cmds == 1:
429 if len_cmds == 1:
424 filter = cmds[0].strip()
430 # Only filter pattern given
431 filter = cmds[0]
425 elif len_cmds == 2:
432 elif len_cmds == 2:
433 # Both filter and type specified
426 filter,type_pattern = cmds
434 filter,type_pattern = cmds
427 elif len_cmds>2:
435 else:
428 # assume we want to choose name spaces. Rather poor design forces
436 raise ValueError('invalid argument string for psearch: <%s>' %
429 #the use of a typepattern in order to choose name spaces
437 pattern)
430 cmds = cmds[:2]
431
438
432 do_list = choose_namespaces(shell,ns_cmds)
439 # filter search namespaces
440 for name in ns_search:
441 if name not in ns_table:
442 raise ValueError('invalid namespace <%s>. Valid names: %s' %
443 (name,ns_table.keys()))
433
444
445 #print 'type_pattern:',type_pattern # dbg
434 search_result = []
446 search_result = []
435 for ns in do_list:
447 for ns_name in ns_search:
448 ns = ns_table[ns_name]
436 tmp_res = list(list_namespace(ns,type_pattern,filter,
449 tmp_res = list(list_namespace(ns,type_pattern,filter,
437 ignorecase=ignorecase,
450 ignore_case=ignore_case,
438 showhidden=showhidden))
451 show_all=show_all))
439 search_result.extend(tmp_res)
452 search_result.extend(tmp_res)
440 search_result.sort()
453 search_result.sort()
441
454
442 page('\n'.join(search_result))
455 page('\n'.join(search_result))
@@ -1,880 +1,877 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Shell classes.
2 """IPython Shell classes.
3
3
4 All the matplotlib support code was co-developed with John Hunter,
4 All the matplotlib support code was co-developed with John Hunter,
5 matplotlib's author.
5 matplotlib's author.
6
6
7 $Id: Shell.py 921 2005-11-13 06:51:34Z fperez $"""
7 $Id: Shell.py 923 2005-11-15 08:51:15Z fperez $"""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 from IPython import Release
16 from IPython import Release
17 __author__ = '%s <%s>' % Release.authors['Fernando']
17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __license__ = Release.license
18 __license__ = Release.license
19
19
20 # Code begins
20 # Code begins
21 import __main__
21 import __main__
22 import __builtin__
22 import __builtin__
23 import sys
23 import sys
24 import os
24 import os
25 import code
25 import code
26 import threading
26 import threading
27 import signal
27 import signal
28
28
29 import IPython
29 import IPython
30 from IPython.iplib import InteractiveShell
30 from IPython.iplib import InteractiveShell
31 from IPython.ipmaker import make_IPython
31 from IPython.ipmaker import make_IPython
32 from IPython.genutils import Term,warn,error,flag_calls
32 from IPython.genutils import Term,warn,error,flag_calls
33 from IPython.Struct import Struct
33 from IPython.Struct import Struct
34 from IPython.Magic import Magic
34 from IPython.Magic import Magic
35 from IPython import ultraTB
35 from IPython import ultraTB
36
36
37 # global flag to pass around information about Ctrl-C without exceptions
37 # global flag to pass around information about Ctrl-C without exceptions
38 KBINT = False
38 KBINT = False
39
39
40 # global flag to turn on/off Tk support.
40 # global flag to turn on/off Tk support.
41 USE_TK = False
41 USE_TK = False
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # This class is trivial now, but I want to have it in to publish a clean
44 # This class is trivial now, but I want to have it in to publish a clean
45 # interface. Later when the internals are reorganized, code that uses this
45 # interface. Later when the internals are reorganized, code that uses this
46 # shouldn't have to change.
46 # shouldn't have to change.
47
47
48 class IPShell:
48 class IPShell:
49 """Create an IPython instance."""
49 """Create an IPython instance."""
50
50
51 def __init__(self,argv=None,user_ns=None,debug=1,
51 def __init__(self,argv=None,user_ns=None,debug=1,
52 shell_class=InteractiveShell):
52 shell_class=InteractiveShell):
53 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
53 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
54 shell_class=shell_class)
54 shell_class=shell_class)
55
55
56 def mainloop(self,sys_exit=0,banner=None):
56 def mainloop(self,sys_exit=0,banner=None):
57 self.IP.mainloop(banner)
57 self.IP.mainloop(banner)
58 if sys_exit:
58 if sys_exit:
59 sys.exit()
59 sys.exit()
60
60
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62 class IPShellEmbed:
62 class IPShellEmbed:
63 """Allow embedding an IPython shell into a running program.
63 """Allow embedding an IPython shell into a running program.
64
64
65 Instances of this class are callable, with the __call__ method being an
65 Instances of this class are callable, with the __call__ method being an
66 alias to the embed() method of an InteractiveShell instance.
66 alias to the embed() method of an InteractiveShell instance.
67
67
68 Usage (see also the example-embed.py file for a running example):
68 Usage (see also the example-embed.py file for a running example):
69
69
70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
71
71
72 - argv: list containing valid command-line options for IPython, as they
72 - argv: list containing valid command-line options for IPython, as they
73 would appear in sys.argv[1:].
73 would appear in sys.argv[1:].
74
74
75 For example, the following command-line options:
75 For example, the following command-line options:
76
76
77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
78
78
79 would be passed in the argv list as:
79 would be passed in the argv list as:
80
80
81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
82
82
83 - banner: string which gets printed every time the interpreter starts.
83 - banner: string which gets printed every time the interpreter starts.
84
84
85 - exit_msg: string which gets printed every time the interpreter exits.
85 - exit_msg: string which gets printed every time the interpreter exits.
86
86
87 - rc_override: a dict or Struct of configuration options such as those
87 - rc_override: a dict or Struct of configuration options such as those
88 used by IPython. These options are read from your ~/.ipython/ipythonrc
88 used by IPython. These options are read from your ~/.ipython/ipythonrc
89 file when the Shell object is created. Passing an explicit rc_override
89 file when the Shell object is created. Passing an explicit rc_override
90 dict with any options you want allows you to override those values at
90 dict with any options you want allows you to override those values at
91 creation time without having to modify the file. This way you can create
91 creation time without having to modify the file. This way you can create
92 embeddable instances configured in any way you want without editing any
92 embeddable instances configured in any way you want without editing any
93 global files (thus keeping your interactive IPython configuration
93 global files (thus keeping your interactive IPython configuration
94 unchanged).
94 unchanged).
95
95
96 Then the ipshell instance can be called anywhere inside your code:
96 Then the ipshell instance can be called anywhere inside your code:
97
97
98 ipshell(header='') -> Opens up an IPython shell.
98 ipshell(header='') -> Opens up an IPython shell.
99
99
100 - header: string printed by the IPython shell upon startup. This can let
100 - header: string printed by the IPython shell upon startup. This can let
101 you know where in your code you are when dropping into the shell. Note
101 you know where in your code you are when dropping into the shell. Note
102 that 'banner' gets prepended to all calls, so header is used for
102 that 'banner' gets prepended to all calls, so header is used for
103 location-specific information.
103 location-specific information.
104
104
105 For more details, see the __call__ method below.
105 For more details, see the __call__ method below.
106
106
107 When the IPython shell is exited with Ctrl-D, normal program execution
107 When the IPython shell is exited with Ctrl-D, normal program execution
108 resumes.
108 resumes.
109
109
110 This functionality was inspired by a posting on comp.lang.python by cmkl
110 This functionality was inspired by a posting on comp.lang.python by cmkl
111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
112 by the IDL stop/continue commands."""
112 by the IDL stop/continue commands."""
113
113
114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
115 """Note that argv here is a string, NOT a list."""
115 """Note that argv here is a string, NOT a list."""
116 self.set_banner(banner)
116 self.set_banner(banner)
117 self.set_exit_msg(exit_msg)
117 self.set_exit_msg(exit_msg)
118 self.set_dummy_mode(0)
118 self.set_dummy_mode(0)
119
119
120 # sys.displayhook is a global, we need to save the user's original
120 # sys.displayhook is a global, we need to save the user's original
121 # Don't rely on __displayhook__, as the user may have changed that.
121 # Don't rely on __displayhook__, as the user may have changed that.
122 self.sys_displayhook_ori = sys.displayhook
122 self.sys_displayhook_ori = sys.displayhook
123
123
124 # save readline completer status
124 # save readline completer status
125 try:
125 try:
126 #print 'Save completer',sys.ipcompleter # dbg
126 #print 'Save completer',sys.ipcompleter # dbg
127 self.sys_ipcompleter_ori = sys.ipcompleter
127 self.sys_ipcompleter_ori = sys.ipcompleter
128 except:
128 except:
129 pass # not nested with IPython
129 pass # not nested with IPython
130
130
131 # FIXME. Passing user_ns breaks namespace handling.
131 # FIXME. Passing user_ns breaks namespace handling.
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134
134
135 # mark this as an embedded instance so we know if we get a crash
136 # post-mortem
137 self.IP.rc.embedded = 1
138 # copy our own displayhook also
135 # copy our own displayhook also
139 self.sys_displayhook_embed = sys.displayhook
136 self.sys_displayhook_embed = sys.displayhook
140 # and leave the system's display hook clean
137 # and leave the system's display hook clean
141 sys.displayhook = self.sys_displayhook_ori
138 sys.displayhook = self.sys_displayhook_ori
142 # don't use the ipython crash handler so that user exceptions aren't
139 # don't use the ipython crash handler so that user exceptions aren't
143 # trapped
140 # trapped
144 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
141 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
145 mode = self.IP.rc.xmode,
142 mode = self.IP.rc.xmode,
146 call_pdb = self.IP.rc.pdb)
143 call_pdb = self.IP.rc.pdb)
147 self.restore_system_completer()
144 self.restore_system_completer()
148
145
149 def restore_system_completer(self):
146 def restore_system_completer(self):
150 """Restores the readline completer which was in place.
147 """Restores the readline completer which was in place.
151
148
152 This allows embedded IPython within IPython not to disrupt the
149 This allows embedded IPython within IPython not to disrupt the
153 parent's completion.
150 parent's completion.
154 """
151 """
155
152
156 try:
153 try:
157 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
154 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
158 sys.ipcompleter = self.sys_ipcompleter_ori
155 sys.ipcompleter = self.sys_ipcompleter_ori
159 except:
156 except:
160 pass
157 pass
161
158
162 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
159 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
163 """Activate the interactive interpreter.
160 """Activate the interactive interpreter.
164
161
165 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
162 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
166 the interpreter shell with the given local and global namespaces, and
163 the interpreter shell with the given local and global namespaces, and
167 optionally print a header string at startup.
164 optionally print a header string at startup.
168
165
169 The shell can be globally activated/deactivated using the
166 The shell can be globally activated/deactivated using the
170 set/get_dummy_mode methods. This allows you to turn off a shell used
167 set/get_dummy_mode methods. This allows you to turn off a shell used
171 for debugging globally.
168 for debugging globally.
172
169
173 However, *each* time you call the shell you can override the current
170 However, *each* time you call the shell you can override the current
174 state of dummy_mode with the optional keyword parameter 'dummy'. For
171 state of dummy_mode with the optional keyword parameter 'dummy'. For
175 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
172 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
176 can still have a specific call work by making it as IPShell(dummy=0).
173 can still have a specific call work by making it as IPShell(dummy=0).
177
174
178 The optional keyword parameter dummy controls whether the call
175 The optional keyword parameter dummy controls whether the call
179 actually does anything. """
176 actually does anything. """
180
177
181 # Allow the dummy parameter to override the global __dummy_mode
178 # Allow the dummy parameter to override the global __dummy_mode
182 if dummy or (dummy != 0 and self.__dummy_mode):
179 if dummy or (dummy != 0 and self.__dummy_mode):
183 return
180 return
184
181
185 # Set global subsystems (display,completions) to our values
182 # Set global subsystems (display,completions) to our values
186 sys.displayhook = self.sys_displayhook_embed
183 sys.displayhook = self.sys_displayhook_embed
187 if self.IP.has_readline:
184 if self.IP.has_readline:
188 self.IP.readline.set_completer(self.IP.Completer.complete)
185 self.IP.readline.set_completer(self.IP.Completer.complete)
189
186
190 if self.banner and header:
187 if self.banner and header:
191 format = '%s\n%s\n'
188 format = '%s\n%s\n'
192 else:
189 else:
193 format = '%s%s\n'
190 format = '%s%s\n'
194 banner = format % (self.banner,header)
191 banner = format % (self.banner,header)
195
192
196 # Call the embedding code with a stack depth of 1 so it can skip over
193 # Call the embedding code with a stack depth of 1 so it can skip over
197 # our call and get the original caller's namespaces.
194 # our call and get the original caller's namespaces.
198 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
195 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
199
196
200 if self.exit_msg:
197 if self.exit_msg:
201 print self.exit_msg
198 print self.exit_msg
202
199
203 # Restore global systems (display, completion)
200 # Restore global systems (display, completion)
204 sys.displayhook = self.sys_displayhook_ori
201 sys.displayhook = self.sys_displayhook_ori
205 self.restore_system_completer()
202 self.restore_system_completer()
206
203
207 def set_dummy_mode(self,dummy):
204 def set_dummy_mode(self,dummy):
208 """Sets the embeddable shell's dummy mode parameter.
205 """Sets the embeddable shell's dummy mode parameter.
209
206
210 set_dummy_mode(dummy): dummy = 0 or 1.
207 set_dummy_mode(dummy): dummy = 0 or 1.
211
208
212 This parameter is persistent and makes calls to the embeddable shell
209 This parameter is persistent and makes calls to the embeddable shell
213 silently return without performing any action. This allows you to
210 silently return without performing any action. This allows you to
214 globally activate or deactivate a shell you're using with a single call.
211 globally activate or deactivate a shell you're using with a single call.
215
212
216 If you need to manually"""
213 If you need to manually"""
217
214
218 if dummy not in [0,1]:
215 if dummy not in [0,1]:
219 raise ValueError,'dummy parameter must be 0 or 1'
216 raise ValueError,'dummy parameter must be 0 or 1'
220 self.__dummy_mode = dummy
217 self.__dummy_mode = dummy
221
218
222 def get_dummy_mode(self):
219 def get_dummy_mode(self):
223 """Return the current value of the dummy mode parameter.
220 """Return the current value of the dummy mode parameter.
224 """
221 """
225 return self.__dummy_mode
222 return self.__dummy_mode
226
223
227 def set_banner(self,banner):
224 def set_banner(self,banner):
228 """Sets the global banner.
225 """Sets the global banner.
229
226
230 This banner gets prepended to every header printed when the shell
227 This banner gets prepended to every header printed when the shell
231 instance is called."""
228 instance is called."""
232
229
233 self.banner = banner
230 self.banner = banner
234
231
235 def set_exit_msg(self,exit_msg):
232 def set_exit_msg(self,exit_msg):
236 """Sets the global exit_msg.
233 """Sets the global exit_msg.
237
234
238 This exit message gets printed upon exiting every time the embedded
235 This exit message gets printed upon exiting every time the embedded
239 shell is called. It is None by default. """
236 shell is called. It is None by default. """
240
237
241 self.exit_msg = exit_msg
238 self.exit_msg = exit_msg
242
239
243 #-----------------------------------------------------------------------------
240 #-----------------------------------------------------------------------------
244 def sigint_handler (signum,stack_frame):
241 def sigint_handler (signum,stack_frame):
245 """Sigint handler for threaded apps.
242 """Sigint handler for threaded apps.
246
243
247 This is a horrible hack to pass information about SIGINT _without_ using
244 This is a horrible hack to pass information about SIGINT _without_ using
248 exceptions, since I haven't been able to properly manage cross-thread
245 exceptions, since I haven't been able to properly manage cross-thread
249 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
246 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
250 that's my understanding from a c.l.py thread where this was discussed)."""
247 that's my understanding from a c.l.py thread where this was discussed)."""
251
248
252 global KBINT
249 global KBINT
253
250
254 print '\nKeyboardInterrupt - Press <Enter> to continue.',
251 print '\nKeyboardInterrupt - Press <Enter> to continue.',
255 Term.cout.flush()
252 Term.cout.flush()
256 # Set global flag so that runsource can know that Ctrl-C was hit
253 # Set global flag so that runsource can know that Ctrl-C was hit
257 KBINT = True
254 KBINT = True
258
255
259 class MTInteractiveShell(InteractiveShell):
256 class MTInteractiveShell(InteractiveShell):
260 """Simple multi-threaded shell."""
257 """Simple multi-threaded shell."""
261
258
262 # Threading strategy taken from:
259 # Threading strategy taken from:
263 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
260 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
264 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
261 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
265 # from the pygtk mailing list, to avoid lockups with system calls.
262 # from the pygtk mailing list, to avoid lockups with system calls.
266
263
267 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
264 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
268 user_ns = None, banner2='',**kw):
265 user_ns = None, banner2='',**kw):
269 """Similar to the normal InteractiveShell, but with threading control"""
266 """Similar to the normal InteractiveShell, but with threading control"""
270
267
271 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
268 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
272
269
273 # Locking control variable
270 # Locking control variable
274 self.thread_ready = threading.Condition()
271 self.thread_ready = threading.Condition()
275
272
276 # Stuff to do at closing time
273 # Stuff to do at closing time
277 self._kill = False
274 self._kill = False
278 on_kill = kw.get('on_kill')
275 on_kill = kw.get('on_kill')
279 if on_kill is None:
276 if on_kill is None:
280 on_kill = []
277 on_kill = []
281 # Check that all things to kill are callable:
278 # Check that all things to kill are callable:
282 for t in on_kill:
279 for t in on_kill:
283 if not callable(t):
280 if not callable(t):
284 raise TypeError,'on_kill must be a list of callables'
281 raise TypeError,'on_kill must be a list of callables'
285 self.on_kill = on_kill
282 self.on_kill = on_kill
286
283
287 def runsource(self, source, filename="<input>", symbol="single"):
284 def runsource(self, source, filename="<input>", symbol="single"):
288 """Compile and run some source in the interpreter.
285 """Compile and run some source in the interpreter.
289
286
290 Modified version of code.py's runsource(), to handle threading issues.
287 Modified version of code.py's runsource(), to handle threading issues.
291 See the original for full docstring details."""
288 See the original for full docstring details."""
292
289
293 global KBINT
290 global KBINT
294
291
295 # If Ctrl-C was typed, we reset the flag and return right away
292 # If Ctrl-C was typed, we reset the flag and return right away
296 if KBINT:
293 if KBINT:
297 KBINT = False
294 KBINT = False
298 return False
295 return False
299
296
300 try:
297 try:
301 code = self.compile(source, filename, symbol)
298 code = self.compile(source, filename, symbol)
302 except (OverflowError, SyntaxError, ValueError):
299 except (OverflowError, SyntaxError, ValueError):
303 # Case 1
300 # Case 1
304 self.showsyntaxerror(filename)
301 self.showsyntaxerror(filename)
305 return False
302 return False
306
303
307 if code is None:
304 if code is None:
308 # Case 2
305 # Case 2
309 return True
306 return True
310
307
311 # Case 3
308 # Case 3
312 # Store code in self, so the execution thread can handle it
309 # Store code in self, so the execution thread can handle it
313 self.thread_ready.acquire()
310 self.thread_ready.acquire()
314 self.code_to_run = code
311 self.code_to_run = code
315 self.thread_ready.wait() # Wait until processed in timeout interval
312 self.thread_ready.wait() # Wait until processed in timeout interval
316 self.thread_ready.release()
313 self.thread_ready.release()
317
314
318 return False
315 return False
319
316
320 def runcode(self):
317 def runcode(self):
321 """Execute a code object.
318 """Execute a code object.
322
319
323 Multithreaded wrapper around IPython's runcode()."""
320 Multithreaded wrapper around IPython's runcode()."""
324
321
325 # lock thread-protected stuff
322 # lock thread-protected stuff
326 self.thread_ready.acquire()
323 self.thread_ready.acquire()
327
324
328 # Install sigint handler
325 # Install sigint handler
329 try:
326 try:
330 signal.signal(signal.SIGINT, sigint_handler)
327 signal.signal(signal.SIGINT, sigint_handler)
331 except SystemError:
328 except SystemError:
332 # This happens under Windows, which seems to have all sorts
329 # This happens under Windows, which seems to have all sorts
333 # of problems with signal handling. Oh well...
330 # of problems with signal handling. Oh well...
334 pass
331 pass
335
332
336 if self._kill:
333 if self._kill:
337 print >>Term.cout, 'Closing threads...',
334 print >>Term.cout, 'Closing threads...',
338 Term.cout.flush()
335 Term.cout.flush()
339 for tokill in self.on_kill:
336 for tokill in self.on_kill:
340 tokill()
337 tokill()
341 print >>Term.cout, 'Done.'
338 print >>Term.cout, 'Done.'
342
339
343 # Run pending code by calling parent class
340 # Run pending code by calling parent class
344 if self.code_to_run is not None:
341 if self.code_to_run is not None:
345 self.thread_ready.notify()
342 self.thread_ready.notify()
346 InteractiveShell.runcode(self,self.code_to_run)
343 InteractiveShell.runcode(self,self.code_to_run)
347
344
348 # We're done with thread-protected variables
345 # We're done with thread-protected variables
349 self.thread_ready.release()
346 self.thread_ready.release()
350 # This MUST return true for gtk threading to work
347 # This MUST return true for gtk threading to work
351 return True
348 return True
352
349
353 def kill (self):
350 def kill (self):
354 """Kill the thread, returning when it has been shut down."""
351 """Kill the thread, returning when it has been shut down."""
355 self.thread_ready.acquire()
352 self.thread_ready.acquire()
356 self._kill = True
353 self._kill = True
357 self.thread_ready.release()
354 self.thread_ready.release()
358
355
359 class MatplotlibShellBase:
356 class MatplotlibShellBase:
360 """Mixin class to provide the necessary modifications to regular IPython
357 """Mixin class to provide the necessary modifications to regular IPython
361 shell classes for matplotlib support.
358 shell classes for matplotlib support.
362
359
363 Given Python's MRO, this should be used as the FIRST class in the
360 Given Python's MRO, this should be used as the FIRST class in the
364 inheritance hierarchy, so that it overrides the relevant methods."""
361 inheritance hierarchy, so that it overrides the relevant methods."""
365
362
366 def _matplotlib_config(self,name):
363 def _matplotlib_config(self,name):
367 """Return various items needed to setup the user's shell with matplotlib"""
364 """Return various items needed to setup the user's shell with matplotlib"""
368
365
369 # Initialize matplotlib to interactive mode always
366 # Initialize matplotlib to interactive mode always
370 import matplotlib
367 import matplotlib
371 from matplotlib import backends
368 from matplotlib import backends
372 matplotlib.interactive(True)
369 matplotlib.interactive(True)
373
370
374 def use(arg):
371 def use(arg):
375 """IPython wrapper for matplotlib's backend switcher.
372 """IPython wrapper for matplotlib's backend switcher.
376
373
377 In interactive use, we can not allow switching to a different
374 In interactive use, we can not allow switching to a different
378 interactive backend, since thread conflicts will most likely crash
375 interactive backend, since thread conflicts will most likely crash
379 the python interpreter. This routine does a safety check first,
376 the python interpreter. This routine does a safety check first,
380 and refuses to perform a dangerous switch. It still allows
377 and refuses to perform a dangerous switch. It still allows
381 switching to non-interactive backends."""
378 switching to non-interactive backends."""
382
379
383 if arg in backends.interactive_bk and arg != self.mpl_backend:
380 if arg in backends.interactive_bk and arg != self.mpl_backend:
384 m=('invalid matplotlib backend switch.\n'
381 m=('invalid matplotlib backend switch.\n'
385 'This script attempted to switch to the interactive '
382 'This script attempted to switch to the interactive '
386 'backend: `%s`\n'
383 'backend: `%s`\n'
387 'Your current choice of interactive backend is: `%s`\n\n'
384 'Your current choice of interactive backend is: `%s`\n\n'
388 'Switching interactive matplotlib backends at runtime\n'
385 'Switching interactive matplotlib backends at runtime\n'
389 'would crash the python interpreter, '
386 'would crash the python interpreter, '
390 'and IPython has blocked it.\n\n'
387 'and IPython has blocked it.\n\n'
391 'You need to either change your choice of matplotlib backend\n'
388 'You need to either change your choice of matplotlib backend\n'
392 'by editing your .matplotlibrc file, or run this script as a \n'
389 'by editing your .matplotlibrc file, or run this script as a \n'
393 'standalone file from the command line, not using IPython.\n' %
390 'standalone file from the command line, not using IPython.\n' %
394 (arg,self.mpl_backend) )
391 (arg,self.mpl_backend) )
395 raise RuntimeError, m
392 raise RuntimeError, m
396 else:
393 else:
397 self.mpl_use(arg)
394 self.mpl_use(arg)
398 self.mpl_use._called = True
395 self.mpl_use._called = True
399
396
400 self.matplotlib = matplotlib
397 self.matplotlib = matplotlib
401 self.mpl_backend = matplotlib.rcParams['backend']
398 self.mpl_backend = matplotlib.rcParams['backend']
402
399
403 # we also need to block switching of interactive backends by use()
400 # we also need to block switching of interactive backends by use()
404 self.mpl_use = matplotlib.use
401 self.mpl_use = matplotlib.use
405 self.mpl_use._called = False
402 self.mpl_use._called = False
406 # overwrite the original matplotlib.use with our wrapper
403 # overwrite the original matplotlib.use with our wrapper
407 matplotlib.use = use
404 matplotlib.use = use
408
405
409
406
410 # This must be imported last in the matplotlib series, after
407 # This must be imported last in the matplotlib series, after
411 # backend/interactivity choices have been made
408 # backend/interactivity choices have been made
412 try:
409 try:
413 import matplotlib.pylab as pylab
410 import matplotlib.pylab as pylab
414 self.pylab = pylab
411 self.pylab = pylab
415 self.pylab_name = 'pylab'
412 self.pylab_name = 'pylab'
416 except ImportError:
413 except ImportError:
417 import matplotlib.matlab as matlab
414 import matplotlib.matlab as matlab
418 self.pylab = matlab
415 self.pylab = matlab
419 self.pylab_name = 'matlab'
416 self.pylab_name = 'matlab'
420
417
421 self.pylab.show._needmain = False
418 self.pylab.show._needmain = False
422 # We need to detect at runtime whether show() is called by the user.
419 # We need to detect at runtime whether show() is called by the user.
423 # For this, we wrap it into a decorator which adds a 'called' flag.
420 # For this, we wrap it into a decorator which adds a 'called' flag.
424 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
421 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
425
422
426 # Build a user namespace initialized with matplotlib/matlab features.
423 # Build a user namespace initialized with matplotlib/matlab features.
427 user_ns = {'__name__':'__main__',
424 user_ns = {'__name__':'__main__',
428 '__builtins__' : __builtin__ }
425 '__builtins__' : __builtin__ }
429
426
430 # Be careful not to remove the final \n in the code string below, or
427 # Be careful not to remove the final \n in the code string below, or
431 # things will break badly with py22 (I think it's a python bug, 2.3 is
428 # things will break badly with py22 (I think it's a python bug, 2.3 is
432 # OK).
429 # OK).
433 pname = self.pylab_name # Python can't interpolate dotted var names
430 pname = self.pylab_name # Python can't interpolate dotted var names
434 exec ("import matplotlib\n"
431 exec ("import matplotlib\n"
435 "import matplotlib.%(pname)s as %(pname)s\n"
432 "import matplotlib.%(pname)s as %(pname)s\n"
436 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
433 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
437
434
438 # Build matplotlib info banner
435 # Build matplotlib info banner
439 b="""
436 b="""
440 Welcome to pylab, a matplotlib-based Python environment.
437 Welcome to pylab, a matplotlib-based Python environment.
441 For more information, type 'help(pylab)'.
438 For more information, type 'help(pylab)'.
442 """
439 """
443 return user_ns,b
440 return user_ns,b
444
441
445 def mplot_exec(self,fname,*where,**kw):
442 def mplot_exec(self,fname,*where,**kw):
446 """Execute a matplotlib script.
443 """Execute a matplotlib script.
447
444
448 This is a call to execfile(), but wrapped in safeties to properly
445 This is a call to execfile(), but wrapped in safeties to properly
449 handle interactive rendering and backend switching."""
446 handle interactive rendering and backend switching."""
450
447
451 #print '*** Matplotlib runner ***' # dbg
448 #print '*** Matplotlib runner ***' # dbg
452 # turn off rendering until end of script
449 # turn off rendering until end of script
453 isInteractive = self.matplotlib.rcParams['interactive']
450 isInteractive = self.matplotlib.rcParams['interactive']
454 self.matplotlib.interactive(False)
451 self.matplotlib.interactive(False)
455 self.safe_execfile(fname,*where,**kw)
452 self.safe_execfile(fname,*where,**kw)
456 self.matplotlib.interactive(isInteractive)
453 self.matplotlib.interactive(isInteractive)
457 # make rendering call now, if the user tried to do it
454 # make rendering call now, if the user tried to do it
458 if self.pylab.draw_if_interactive.called:
455 if self.pylab.draw_if_interactive.called:
459 self.pylab.draw()
456 self.pylab.draw()
460 self.pylab.draw_if_interactive.called = False
457 self.pylab.draw_if_interactive.called = False
461
458
462 # if a backend switch was performed, reverse it now
459 # if a backend switch was performed, reverse it now
463 if self.mpl_use._called:
460 if self.mpl_use._called:
464 self.matplotlib.rcParams['backend'] = self.mpl_backend
461 self.matplotlib.rcParams['backend'] = self.mpl_backend
465
462
466 def magic_run(self,parameter_s=''):
463 def magic_run(self,parameter_s=''):
467 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
464 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
468
465
469 # Fix the docstring so users see the original as well
466 # Fix the docstring so users see the original as well
470 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
467 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
471 "\n *** Modified %run for Matplotlib,"
468 "\n *** Modified %run for Matplotlib,"
472 " with proper interactive handling ***")
469 " with proper interactive handling ***")
473
470
474 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
471 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
475 # and multithreaded. Note that these are meant for internal use, the IPShell*
472 # and multithreaded. Note that these are meant for internal use, the IPShell*
476 # classes below are the ones meant for public consumption.
473 # classes below are the ones meant for public consumption.
477
474
478 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
475 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
479 """Single-threaded shell with matplotlib support."""
476 """Single-threaded shell with matplotlib support."""
480
477
481 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
478 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
482 user_ns = None, **kw):
479 user_ns = None, **kw):
483 user_ns,b2 = self._matplotlib_config(name)
480 user_ns,b2 = self._matplotlib_config(name)
484 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
481 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
485
482
486 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
483 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
487 """Multi-threaded shell with matplotlib support."""
484 """Multi-threaded shell with matplotlib support."""
488
485
489 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
486 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
490 user_ns = None, **kw):
487 user_ns = None, **kw):
491 user_ns,b2 = self._matplotlib_config(name)
488 user_ns,b2 = self._matplotlib_config(name)
492 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
489 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
493
490
494 #-----------------------------------------------------------------------------
491 #-----------------------------------------------------------------------------
495 # Utility functions for the different GUI enabled IPShell* classes.
492 # Utility functions for the different GUI enabled IPShell* classes.
496
493
497 def get_tk():
494 def get_tk():
498 """Tries to import Tkinter and returns a withdrawn Tkinter root
495 """Tries to import Tkinter and returns a withdrawn Tkinter root
499 window. If Tkinter is already imported or not available, this
496 window. If Tkinter is already imported or not available, this
500 returns None. This function calls `hijack_tk` underneath.
497 returns None. This function calls `hijack_tk` underneath.
501 """
498 """
502 if not USE_TK or sys.modules.has_key('Tkinter'):
499 if not USE_TK or sys.modules.has_key('Tkinter'):
503 return None
500 return None
504 else:
501 else:
505 try:
502 try:
506 import Tkinter
503 import Tkinter
507 except ImportError:
504 except ImportError:
508 return None
505 return None
509 else:
506 else:
510 hijack_tk()
507 hijack_tk()
511 r = Tkinter.Tk()
508 r = Tkinter.Tk()
512 r.withdraw()
509 r.withdraw()
513 return r
510 return r
514
511
515 def hijack_tk():
512 def hijack_tk():
516 """Modifies Tkinter's mainloop with a dummy so when a module calls
513 """Modifies Tkinter's mainloop with a dummy so when a module calls
517 mainloop, it does not block.
514 mainloop, it does not block.
518
515
519 """
516 """
520 def misc_mainloop(self, n=0):
517 def misc_mainloop(self, n=0):
521 pass
518 pass
522 def tkinter_mainloop(n=0):
519 def tkinter_mainloop(n=0):
523 pass
520 pass
524
521
525 import Tkinter
522 import Tkinter
526 Tkinter.Misc.mainloop = misc_mainloop
523 Tkinter.Misc.mainloop = misc_mainloop
527 Tkinter.mainloop = tkinter_mainloop
524 Tkinter.mainloop = tkinter_mainloop
528
525
529 def update_tk(tk):
526 def update_tk(tk):
530 """Updates the Tkinter event loop. This is typically called from
527 """Updates the Tkinter event loop. This is typically called from
531 the respective WX or GTK mainloops.
528 the respective WX or GTK mainloops.
532 """
529 """
533 if tk:
530 if tk:
534 tk.update()
531 tk.update()
535
532
536 def hijack_wx():
533 def hijack_wx():
537 """Modifies wxPython's MainLoop with a dummy so user code does not
534 """Modifies wxPython's MainLoop with a dummy so user code does not
538 block IPython. The hijacked mainloop function is returned.
535 block IPython. The hijacked mainloop function is returned.
539 """
536 """
540 def dummy_mainloop(*args, **kw):
537 def dummy_mainloop(*args, **kw):
541 pass
538 pass
542 import wxPython
539 import wxPython
543 ver = wxPython.__version__
540 ver = wxPython.__version__
544 orig_mainloop = None
541 orig_mainloop = None
545 if ver[:3] >= '2.5':
542 if ver[:3] >= '2.5':
546 import wx
543 import wx
547 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
544 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
548 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
545 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
549 else: raise AttributeError('Could not find wx core module')
546 else: raise AttributeError('Could not find wx core module')
550 orig_mainloop = core.PyApp_MainLoop
547 orig_mainloop = core.PyApp_MainLoop
551 core.PyApp_MainLoop = dummy_mainloop
548 core.PyApp_MainLoop = dummy_mainloop
552 elif ver[:3] == '2.4':
549 elif ver[:3] == '2.4':
553 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
550 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
554 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
551 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
555 else:
552 else:
556 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
553 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
557 return orig_mainloop
554 return orig_mainloop
558
555
559 def hijack_gtk():
556 def hijack_gtk():
560 """Modifies pyGTK's mainloop with a dummy so user code does not
557 """Modifies pyGTK's mainloop with a dummy so user code does not
561 block IPython. This function returns the original `gtk.mainloop`
558 block IPython. This function returns the original `gtk.mainloop`
562 function that has been hijacked.
559 function that has been hijacked.
563 """
560 """
564 def dummy_mainloop(*args, **kw):
561 def dummy_mainloop(*args, **kw):
565 pass
562 pass
566 import gtk
563 import gtk
567 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
564 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
568 else: orig_mainloop = gtk.mainloop
565 else: orig_mainloop = gtk.mainloop
569 gtk.mainloop = dummy_mainloop
566 gtk.mainloop = dummy_mainloop
570 gtk.main = dummy_mainloop
567 gtk.main = dummy_mainloop
571 return orig_mainloop
568 return orig_mainloop
572
569
573 #-----------------------------------------------------------------------------
570 #-----------------------------------------------------------------------------
574 # The IPShell* classes below are the ones meant to be run by external code as
571 # The IPShell* classes below are the ones meant to be run by external code as
575 # IPython instances. Note that unless a specific threading strategy is
572 # IPython instances. Note that unless a specific threading strategy is
576 # desired, the factory function start() below should be used instead (it
573 # desired, the factory function start() below should be used instead (it
577 # selects the proper threaded class).
574 # selects the proper threaded class).
578
575
579 class IPShellGTK(threading.Thread):
576 class IPShellGTK(threading.Thread):
580 """Run a gtk mainloop() in a separate thread.
577 """Run a gtk mainloop() in a separate thread.
581
578
582 Python commands can be passed to the thread where they will be executed.
579 Python commands can be passed to the thread where they will be executed.
583 This is implemented by periodically checking for passed code using a
580 This is implemented by periodically checking for passed code using a
584 GTK timeout callback."""
581 GTK timeout callback."""
585
582
586 TIMEOUT = 100 # Millisecond interval between timeouts.
583 TIMEOUT = 100 # Millisecond interval between timeouts.
587
584
588 def __init__(self,argv=None,user_ns=None,debug=1,
585 def __init__(self,argv=None,user_ns=None,debug=1,
589 shell_class=MTInteractiveShell):
586 shell_class=MTInteractiveShell):
590
587
591 import gtk
588 import gtk
592
589
593 self.gtk = gtk
590 self.gtk = gtk
594 self.gtk_mainloop = hijack_gtk()
591 self.gtk_mainloop = hijack_gtk()
595
592
596 # Allows us to use both Tk and GTK.
593 # Allows us to use both Tk and GTK.
597 self.tk = get_tk()
594 self.tk = get_tk()
598
595
599 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
596 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
600 else: mainquit = self.gtk.mainquit
597 else: mainquit = self.gtk.mainquit
601
598
602 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
599 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
603 shell_class=shell_class,
600 shell_class=shell_class,
604 on_kill=[mainquit])
601 on_kill=[mainquit])
605 threading.Thread.__init__(self)
602 threading.Thread.__init__(self)
606
603
607 def run(self):
604 def run(self):
608 self.IP.mainloop()
605 self.IP.mainloop()
609 self.IP.kill()
606 self.IP.kill()
610
607
611 def mainloop(self):
608 def mainloop(self):
612
609
613 if self.gtk.pygtk_version >= (2,4,0):
610 if self.gtk.pygtk_version >= (2,4,0):
614 import gobject
611 import gobject
615 gobject.idle_add(self.on_timer)
612 gobject.idle_add(self.on_timer)
616 else:
613 else:
617 self.gtk.idle_add(self.on_timer)
614 self.gtk.idle_add(self.on_timer)
618
615
619 if sys.platform != 'win32':
616 if sys.platform != 'win32':
620 try:
617 try:
621 if self.gtk.gtk_version[0] >= 2:
618 if self.gtk.gtk_version[0] >= 2:
622 self.gtk.threads_init()
619 self.gtk.threads_init()
623 except AttributeError:
620 except AttributeError:
624 pass
621 pass
625 except RuntimeError:
622 except RuntimeError:
626 error('Your pyGTK likely has not been compiled with '
623 error('Your pyGTK likely has not been compiled with '
627 'threading support.\n'
624 'threading support.\n'
628 'The exception printout is below.\n'
625 'The exception printout is below.\n'
629 'You can either rebuild pyGTK with threads, or '
626 'You can either rebuild pyGTK with threads, or '
630 'try using \n'
627 'try using \n'
631 'matplotlib with a different backend (like Tk or WX).\n'
628 'matplotlib with a different backend (like Tk or WX).\n'
632 'Note that matplotlib will most likely not work in its '
629 'Note that matplotlib will most likely not work in its '
633 'current state!')
630 'current state!')
634 self.IP.InteractiveTB()
631 self.IP.InteractiveTB()
635 self.start()
632 self.start()
636 self.gtk.threads_enter()
633 self.gtk.threads_enter()
637 self.gtk_mainloop()
634 self.gtk_mainloop()
638 self.gtk.threads_leave()
635 self.gtk.threads_leave()
639 self.join()
636 self.join()
640
637
641 def on_timer(self):
638 def on_timer(self):
642 update_tk(self.tk)
639 update_tk(self.tk)
643 return self.IP.runcode()
640 return self.IP.runcode()
644
641
645
642
646 class IPShellWX(threading.Thread):
643 class IPShellWX(threading.Thread):
647 """Run a wx mainloop() in a separate thread.
644 """Run a wx mainloop() in a separate thread.
648
645
649 Python commands can be passed to the thread where they will be executed.
646 Python commands can be passed to the thread where they will be executed.
650 This is implemented by periodically checking for passed code using a
647 This is implemented by periodically checking for passed code using a
651 GTK timeout callback."""
648 GTK timeout callback."""
652
649
653 TIMEOUT = 100 # Millisecond interval between timeouts.
650 TIMEOUT = 100 # Millisecond interval between timeouts.
654
651
655 def __init__(self,argv=None,user_ns=None,debug=1,
652 def __init__(self,argv=None,user_ns=None,debug=1,
656 shell_class=MTInteractiveShell):
653 shell_class=MTInteractiveShell):
657
654
658 import wxPython.wx as wx
655 import wxPython.wx as wx
659
656
660 threading.Thread.__init__(self)
657 threading.Thread.__init__(self)
661 self.wx = wx
658 self.wx = wx
662 self.wx_mainloop = hijack_wx()
659 self.wx_mainloop = hijack_wx()
663
660
664 # Allows us to use both Tk and GTK.
661 # Allows us to use both Tk and GTK.
665 self.tk = get_tk()
662 self.tk = get_tk()
666
663
667 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
664 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
668 shell_class=shell_class,
665 shell_class=shell_class,
669 on_kill=[self.wxexit])
666 on_kill=[self.wxexit])
670 self.app = None
667 self.app = None
671
668
672 def wxexit(self, *args):
669 def wxexit(self, *args):
673 if self.app is not None:
670 if self.app is not None:
674 self.app.agent.timer.Stop()
671 self.app.agent.timer.Stop()
675 self.app.ExitMainLoop()
672 self.app.ExitMainLoop()
676
673
677 def run(self):
674 def run(self):
678 self.IP.mainloop()
675 self.IP.mainloop()
679 self.IP.kill()
676 self.IP.kill()
680
677
681 def mainloop(self):
678 def mainloop(self):
682
679
683 self.start()
680 self.start()
684
681
685 class TimerAgent(self.wx.wxMiniFrame):
682 class TimerAgent(self.wx.wxMiniFrame):
686 wx = self.wx
683 wx = self.wx
687 IP = self.IP
684 IP = self.IP
688 tk = self.tk
685 tk = self.tk
689 def __init__(self, parent, interval):
686 def __init__(self, parent, interval):
690 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
687 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
691 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
688 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
692 size=(100, 100),style=style)
689 size=(100, 100),style=style)
693 self.Show(False)
690 self.Show(False)
694 self.interval = interval
691 self.interval = interval
695 self.timerId = self.wx.wxNewId()
692 self.timerId = self.wx.wxNewId()
696
693
697 def StartWork(self):
694 def StartWork(self):
698 self.timer = self.wx.wxTimer(self, self.timerId)
695 self.timer = self.wx.wxTimer(self, self.timerId)
699 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
696 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
700 self.timer.Start(self.interval)
697 self.timer.Start(self.interval)
701
698
702 def OnTimer(self, event):
699 def OnTimer(self, event):
703 update_tk(self.tk)
700 update_tk(self.tk)
704 self.IP.runcode()
701 self.IP.runcode()
705
702
706 class App(self.wx.wxApp):
703 class App(self.wx.wxApp):
707 wx = self.wx
704 wx = self.wx
708 TIMEOUT = self.TIMEOUT
705 TIMEOUT = self.TIMEOUT
709 def OnInit(self):
706 def OnInit(self):
710 'Create the main window and insert the custom frame'
707 'Create the main window and insert the custom frame'
711 self.agent = TimerAgent(None, self.TIMEOUT)
708 self.agent = TimerAgent(None, self.TIMEOUT)
712 self.agent.Show(self.wx.false)
709 self.agent.Show(self.wx.false)
713 self.agent.StartWork()
710 self.agent.StartWork()
714 return self.wx.true
711 return self.wx.true
715
712
716 self.app = App(redirect=False)
713 self.app = App(redirect=False)
717 self.wx_mainloop(self.app)
714 self.wx_mainloop(self.app)
718 self.join()
715 self.join()
719
716
720
717
721 class IPShellQt(threading.Thread):
718 class IPShellQt(threading.Thread):
722 """Run a Qt event loop in a separate thread.
719 """Run a Qt event loop in a separate thread.
723
720
724 Python commands can be passed to the thread where they will be executed.
721 Python commands can be passed to the thread where they will be executed.
725 This is implemented by periodically checking for passed code using a
722 This is implemented by periodically checking for passed code using a
726 Qt timer / slot."""
723 Qt timer / slot."""
727
724
728 TIMEOUT = 100 # Millisecond interval between timeouts.
725 TIMEOUT = 100 # Millisecond interval between timeouts.
729
726
730 def __init__(self,argv=None,user_ns=None,debug=0,
727 def __init__(self,argv=None,user_ns=None,debug=0,
731 shell_class=MTInteractiveShell):
728 shell_class=MTInteractiveShell):
732
729
733 import qt
730 import qt
734
731
735 class newQApplication:
732 class newQApplication:
736 def __init__( self ):
733 def __init__( self ):
737 self.QApplication = qt.QApplication
734 self.QApplication = qt.QApplication
738
735
739 def __call__( *args, **kwargs ):
736 def __call__( *args, **kwargs ):
740 return qt.qApp
737 return qt.qApp
741
738
742 def exec_loop( *args, **kwargs ):
739 def exec_loop( *args, **kwargs ):
743 pass
740 pass
744
741
745 def __getattr__( self, name ):
742 def __getattr__( self, name ):
746 return getattr( self.QApplication, name )
743 return getattr( self.QApplication, name )
747
744
748 qt.QApplication = newQApplication()
745 qt.QApplication = newQApplication()
749
746
750 # Allows us to use both Tk and QT.
747 # Allows us to use both Tk and QT.
751 self.tk = get_tk()
748 self.tk = get_tk()
752
749
753 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
750 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
754 shell_class=shell_class,
751 shell_class=shell_class,
755 on_kill=[qt.qApp.exit])
752 on_kill=[qt.qApp.exit])
756
753
757 threading.Thread.__init__(self)
754 threading.Thread.__init__(self)
758
755
759 def run(self):
756 def run(self):
760 #sys.excepthook = self.IP.excepthook # dbg
757 #sys.excepthook = self.IP.excepthook # dbg
761 self.IP.mainloop()
758 self.IP.mainloop()
762 self.IP.kill()
759 self.IP.kill()
763
760
764 def mainloop(self):
761 def mainloop(self):
765 import qt, sys
762 import qt, sys
766 if qt.QApplication.startingUp():
763 if qt.QApplication.startingUp():
767 a = qt.QApplication.QApplication( sys.argv )
764 a = qt.QApplication.QApplication( sys.argv )
768 self.timer = qt.QTimer()
765 self.timer = qt.QTimer()
769 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
766 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
770
767
771 self.start()
768 self.start()
772 self.timer.start( self.TIMEOUT, True )
769 self.timer.start( self.TIMEOUT, True )
773 while True:
770 while True:
774 if self.IP._kill: break
771 if self.IP._kill: break
775 qt.qApp.exec_loop()
772 qt.qApp.exec_loop()
776 self.join()
773 self.join()
777
774
778 def on_timer(self):
775 def on_timer(self):
779 update_tk(self.tk)
776 update_tk(self.tk)
780 result = self.IP.runcode()
777 result = self.IP.runcode()
781 self.timer.start( self.TIMEOUT, True )
778 self.timer.start( self.TIMEOUT, True )
782 return result
779 return result
783
780
784 # A set of matplotlib public IPython shell classes, for single-threaded
781 # A set of matplotlib public IPython shell classes, for single-threaded
785 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
782 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
786 class IPShellMatplotlib(IPShell):
783 class IPShellMatplotlib(IPShell):
787 """Subclass IPShell with MatplotlibShell as the internal shell.
784 """Subclass IPShell with MatplotlibShell as the internal shell.
788
785
789 Single-threaded class, meant for the Tk* and FLTK* backends.
786 Single-threaded class, meant for the Tk* and FLTK* backends.
790
787
791 Having this on a separate class simplifies the external driver code."""
788 Having this on a separate class simplifies the external driver code."""
792
789
793 def __init__(self,argv=None,user_ns=None,debug=1):
790 def __init__(self,argv=None,user_ns=None,debug=1):
794 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
791 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
795
792
796 class IPShellMatplotlibGTK(IPShellGTK):
793 class IPShellMatplotlibGTK(IPShellGTK):
797 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
794 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
798
795
799 Multi-threaded class, meant for the GTK* backends."""
796 Multi-threaded class, meant for the GTK* backends."""
800
797
801 def __init__(self,argv=None,user_ns=None,debug=1):
798 def __init__(self,argv=None,user_ns=None,debug=1):
802 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
799 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
803
800
804 class IPShellMatplotlibWX(IPShellWX):
801 class IPShellMatplotlibWX(IPShellWX):
805 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
802 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
806
803
807 Multi-threaded class, meant for the WX* backends."""
804 Multi-threaded class, meant for the WX* backends."""
808
805
809 def __init__(self,argv=None,user_ns=None,debug=1):
806 def __init__(self,argv=None,user_ns=None,debug=1):
810 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
807 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
811
808
812 class IPShellMatplotlibQt(IPShellQt):
809 class IPShellMatplotlibQt(IPShellQt):
813 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
810 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
814
811
815 Multi-threaded class, meant for the Qt* backends."""
812 Multi-threaded class, meant for the Qt* backends."""
816
813
817 def __init__(self,argv=None,user_ns=None,debug=1):
814 def __init__(self,argv=None,user_ns=None,debug=1):
818 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
815 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
819
816
820 #-----------------------------------------------------------------------------
817 #-----------------------------------------------------------------------------
821 # Factory functions to actually start the proper thread-aware shell
818 # Factory functions to actually start the proper thread-aware shell
822
819
823 def _matplotlib_shell_class():
820 def _matplotlib_shell_class():
824 """Factory function to handle shell class selection for matplotlib.
821 """Factory function to handle shell class selection for matplotlib.
825
822
826 The proper shell class to use depends on the matplotlib backend, since
823 The proper shell class to use depends on the matplotlib backend, since
827 each backend requires a different threading strategy."""
824 each backend requires a different threading strategy."""
828
825
829 try:
826 try:
830 import matplotlib
827 import matplotlib
831 except ImportError:
828 except ImportError:
832 error('matplotlib could NOT be imported! Starting normal IPython.')
829 error('matplotlib could NOT be imported! Starting normal IPython.')
833 sh_class = IPShell
830 sh_class = IPShell
834 else:
831 else:
835 backend = matplotlib.rcParams['backend']
832 backend = matplotlib.rcParams['backend']
836 if backend.startswith('GTK'):
833 if backend.startswith('GTK'):
837 sh_class = IPShellMatplotlibGTK
834 sh_class = IPShellMatplotlibGTK
838 elif backend.startswith('WX'):
835 elif backend.startswith('WX'):
839 sh_class = IPShellMatplotlibWX
836 sh_class = IPShellMatplotlibWX
840 elif backend.startswith('Qt'):
837 elif backend.startswith('Qt'):
841 sh_class = IPShellMatplotlibQt
838 sh_class = IPShellMatplotlibQt
842 else:
839 else:
843 sh_class = IPShellMatplotlib
840 sh_class = IPShellMatplotlib
844 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
841 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
845 return sh_class
842 return sh_class
846
843
847 # This is the one which should be called by external code.
844 # This is the one which should be called by external code.
848 def start():
845 def start():
849 """Return a running shell instance, dealing with threading options.
846 """Return a running shell instance, dealing with threading options.
850
847
851 This is a factory function which will instantiate the proper IPython shell
848 This is a factory function which will instantiate the proper IPython shell
852 based on the user's threading choice. Such a selector is needed because
849 based on the user's threading choice. Such a selector is needed because
853 different GUI toolkits require different thread handling details."""
850 different GUI toolkits require different thread handling details."""
854
851
855 global USE_TK
852 global USE_TK
856 # Crude sys.argv hack to extract the threading options.
853 # Crude sys.argv hack to extract the threading options.
857 if len(sys.argv) > 1:
854 if len(sys.argv) > 1:
858 if len(sys.argv) > 2:
855 if len(sys.argv) > 2:
859 arg2 = sys.argv[2]
856 arg2 = sys.argv[2]
860 if arg2.endswith('-tk'):
857 if arg2.endswith('-tk'):
861 USE_TK = True
858 USE_TK = True
862 arg1 = sys.argv[1]
859 arg1 = sys.argv[1]
863 if arg1.endswith('-gthread'):
860 if arg1.endswith('-gthread'):
864 shell = IPShellGTK
861 shell = IPShellGTK
865 elif arg1.endswith( '-qthread' ):
862 elif arg1.endswith( '-qthread' ):
866 shell = IPShellQt
863 shell = IPShellQt
867 elif arg1.endswith('-wthread'):
864 elif arg1.endswith('-wthread'):
868 shell = IPShellWX
865 shell = IPShellWX
869 elif arg1.endswith('-pylab'):
866 elif arg1.endswith('-pylab'):
870 shell = _matplotlib_shell_class()
867 shell = _matplotlib_shell_class()
871 else:
868 else:
872 shell = IPShell
869 shell = IPShell
873 else:
870 else:
874 shell = IPShell
871 shell = IPShell
875 return shell()
872 return shell()
876
873
877 # Some aliases for backwards compatibility
874 # Some aliases for backwards compatibility
878 IPythonShell = IPShell
875 IPythonShell = IPShell
879 IPythonShellEmbed = IPShellEmbed
876 IPythonShellEmbed = IPShellEmbed
880 #************************ End of file <Shell.py> ***************************
877 #************************ End of file <Shell.py> ***************************
@@ -1,550 +1,558 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 633 2005-07-17 01:03:15Z tzanko $
2 # $Id: ipythonrc 923 2005-11-15 08:51:15Z fperez $
3
3
4 #***************************************************************************
4 #***************************************************************************
5 #
5 #
6 # Configuration file for IPython -- ipythonrc format
6 # Configuration file for IPython -- ipythonrc format
7 #
7 #
8 # The format of this file is simply one of 'key value' lines.
8 # The format of this file is simply one of 'key value' lines.
9 # Lines containing only whitespace at the beginning and then a # are ignored
9 # Lines containing only whitespace at the beginning and then a # are ignored
10 # as comments. But comments can NOT be put on lines with data.
10 # as comments. But comments can NOT be put on lines with data.
11
11
12 # The meaning and use of each key are explained below.
12 # The meaning and use of each key are explained below.
13
13
14 #---------------------------------------------------------------------------
14 #---------------------------------------------------------------------------
15 # Section: included files
15 # Section: included files
16
16
17 # Put one or more *config* files (with the syntax of this file) you want to
17 # Put one or more *config* files (with the syntax of this file) you want to
18 # include. For keys with a unique value the outermost file has precedence. For
18 # include. For keys with a unique value the outermost file has precedence. For
19 # keys with multiple values, they all get assembled into a list which then
19 # keys with multiple values, they all get assembled into a list which then
20 # gets loaded by IPython.
20 # gets loaded by IPython.
21
21
22 # In this file, all lists of things should simply be space-separated.
22 # In this file, all lists of things should simply be space-separated.
23
23
24 # This allows you to build hierarchies of files which recursively load
24 # This allows you to build hierarchies of files which recursively load
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 # should only keep here basic things you always want available. Then you can
26 # should only keep here basic things you always want available. Then you can
27 # include it in every other special-purpose config file you create.
27 # include it in every other special-purpose config file you create.
28 include
28 include
29
29
30 #---------------------------------------------------------------------------
30 #---------------------------------------------------------------------------
31 # Section: startup setup
31 # Section: startup setup
32
32
33 # These are mostly things which parallel a command line option of the same
33 # These are mostly things which parallel a command line option of the same
34 # name.
34 # name.
35
35
36 # Keys in this section should only appear once. If any key from this section
36 # Keys in this section should only appear once. If any key from this section
37 # is encountered more than once, the last value remains, all earlier ones get
37 # is encountered more than once, the last value remains, all earlier ones get
38 # discarded.
38 # discarded.
39
39
40 # Automatic calling of callable objects. If set to true, callable objects are
40 # Automatic calling of callable objects. If set to true, callable objects are
41 # automatically called when invoked at the command line, even if you don't
41 # automatically called when invoked at the command line, even if you don't
42 # type parentheses. IPython adds the parentheses for you. For example:
42 # type parentheses. IPython adds the parentheses for you. For example:
43
43
44 #In [1]: str 45
44 #In [1]: str 45
45 #------> str(45)
45 #------> str(45)
46 #Out[1]: '45'
46 #Out[1]: '45'
47
47
48 # IPython reprints your line with '---->' indicating that it added
48 # IPython reprints your line with '---->' indicating that it added
49 # parentheses. While this option is very convenient for interactive use, it
49 # parentheses. While this option is very convenient for interactive use, it
50 # may occasionally cause problems with objects which have side-effects if
50 # may occasionally cause problems with objects which have side-effects if
51 # called unexpectedly. Set it to 0 if you want to disable it.
51 # called unexpectedly. Set it to 0 if you want to disable it.
52
52
53 # Note that even with autocall off, you can still use '/' at the start of a
53 # Note that even with autocall off, you can still use '/' at the start of a
54 # line to treat the first argument on the command line as a function and add
54 # line to treat the first argument on the command line as a function and add
55 # parentheses to it:
55 # parentheses to it:
56
56
57 #In [8]: /str 43
57 #In [8]: /str 43
58 #------> str(43)
58 #------> str(43)
59 #Out[8]: '43'
59 #Out[8]: '43'
60
60
61 autocall 1
61 autocall 1
62
62
63 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
63 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
64 # line, while also un-indenting automatically after 'raise' or 'return'.
64 # line, while also un-indenting automatically after 'raise' or 'return'.
65
65
66 # This feature uses the readline library, so it will honor your ~/.inputrc
66 # This feature uses the readline library, so it will honor your ~/.inputrc
67 # configuration (or whatever file your INPUTRC variable points to). Adding
67 # configuration (or whatever file your INPUTRC variable points to). Adding
68 # the following lines to your .inputrc file can make indent/unindenting more
68 # the following lines to your .inputrc file can make indent/unindenting more
69 # convenient (M-i indents, M-u unindents):
69 # convenient (M-i indents, M-u unindents):
70
70
71 # $if Python
71 # $if Python
72 # "\M-i": " "
72 # "\M-i": " "
73 # "\M-u": "\d\d\d\d"
73 # "\M-u": "\d\d\d\d"
74 # $endif
74 # $endif
75
75
76 # The feature is potentially a bit dangerous, because it can cause problems
76 # The feature is potentially a bit dangerous, because it can cause problems
77 # with pasting of indented code (the pasted code gets re-indented on each
77 # with pasting of indented code (the pasted code gets re-indented on each
78 # line). But it's a huge time-saver when working interactively. The magic
78 # line). But it's a huge time-saver when working interactively. The magic
79 # function @autoindent allows you to toggle it on/off at runtime.
79 # function @autoindent allows you to toggle it on/off at runtime.
80
80
81 autoindent 1
81 autoindent 1
82
82
83 # Auto-magic. This gives you access to all the magic functions without having
83 # Auto-magic. This gives you access to all the magic functions without having
84 # to prepend them with an @ sign. If you define a variable with the same name
84 # to prepend them with an @ sign. If you define a variable with the same name
85 # as a magic function (say who=1), you will need to access the magic function
85 # as a magic function (say who=1), you will need to access the magic function
86 # with @ (@who in this example). However, if later you delete your variable
86 # with @ (@who in this example). However, if later you delete your variable
87 # (del who), you'll recover the automagic calling form.
87 # (del who), you'll recover the automagic calling form.
88
88
89 # Considering that many magic functions provide a lot of shell-like
89 # Considering that many magic functions provide a lot of shell-like
90 # functionality, automagic gives you something close to a full Python+system
90 # functionality, automagic gives you something close to a full Python+system
91 # shell environment (and you can extend it further if you want).
91 # shell environment (and you can extend it further if you want).
92
92
93 automagic 1
93 automagic 1
94
94
95 # Size of the output cache. After this many entries are stored, the cache will
95 # Size of the output cache. After this many entries are stored, the cache will
96 # get flushed. Depending on the size of your intermediate calculations, you
96 # get flushed. Depending on the size of your intermediate calculations, you
97 # may have memory problems if you make it too big, since keeping things in the
97 # may have memory problems if you make it too big, since keeping things in the
98 # cache prevents Python from reclaiming the memory for old results. Experiment
98 # cache prevents Python from reclaiming the memory for old results. Experiment
99 # with a value that works well for you.
99 # with a value that works well for you.
100
100
101 # If you choose cache_size 0 IPython will revert to python's regular >>>
101 # If you choose cache_size 0 IPython will revert to python's regular >>>
102 # unnumbered prompt. You will still have _, __ and ___ for your last three
102 # unnumbered prompt. You will still have _, __ and ___ for your last three
103 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
103 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
104 # you are running on a slow machine or with very limited memory, this may
104 # you are running on a slow machine or with very limited memory, this may
105 # help.
105 # help.
106
106
107 cache_size 1000
107 cache_size 1000
108
108
109 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
109 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
110 # but that's your choice! Classic 1 -> same as IPython -classic.
110 # but that's your choice! Classic 1 -> same as IPython -classic.
111 # Note that this is _not_ the normal python interpreter, it's simply
111 # Note that this is _not_ the normal python interpreter, it's simply
112 # IPython emulating most of the classic interpreter's behavior.
112 # IPython emulating most of the classic interpreter's behavior.
113 classic 0
113 classic 0
114
114
115 # colors - Coloring option for prompts and traceback printouts.
115 # colors - Coloring option for prompts and traceback printouts.
116
116
117 # Currently available schemes: NoColor, Linux, LightBG.
117 # Currently available schemes: NoColor, Linux, LightBG.
118
118
119 # This option allows coloring the prompts and traceback printouts. This
119 # This option allows coloring the prompts and traceback printouts. This
120 # requires a terminal which can properly handle color escape sequences. If you
120 # requires a terminal which can properly handle color escape sequences. If you
121 # are having problems with this, use the NoColor scheme (uses no color escapes
121 # are having problems with this, use the NoColor scheme (uses no color escapes
122 # at all).
122 # at all).
123
123
124 # The Linux option works well in linux console type environments: dark
124 # The Linux option works well in linux console type environments: dark
125 # background with light fonts.
125 # background with light fonts.
126
126
127 # LightBG is similar to Linux but swaps dark/light colors to be more readable
127 # LightBG is similar to Linux but swaps dark/light colors to be more readable
128 # in light background terminals.
128 # in light background terminals.
129
129
130 # keep uncommented only the one you want:
130 # keep uncommented only the one you want:
131 colors Linux
131 colors Linux
132 #colors LightBG
132 #colors LightBG
133 #colors NoColor
133 #colors NoColor
134
134
135 ########################
135 ########################
136 # Note to Windows users
136 # Note to Windows users
137 #
137 #
138 # Color and readline support is avaialble to Windows users via Gary Bishop's
138 # Color and readline support is avaialble to Windows users via Gary Bishop's
139 # readline library. You can find Gary's tools at
139 # readline library. You can find Gary's tools at
140 # http://sourceforge.net/projects/uncpythontools.
140 # http://sourceforge.net/projects/uncpythontools.
141 # Note that his readline module requires in turn the ctypes library, available
141 # Note that his readline module requires in turn the ctypes library, available
142 # at http://starship.python.net/crew/theller/ctypes.
142 # at http://starship.python.net/crew/theller/ctypes.
143 ########################
143 ########################
144
144
145 # color_info: IPython can display information about objects via a set of
145 # color_info: IPython can display information about objects via a set of
146 # functions, and optionally can use colors for this, syntax highlighting
146 # functions, and optionally can use colors for this, syntax highlighting
147 # source code and various other elements. This information is passed through a
147 # source code and various other elements. This information is passed through a
148 # pager (it defaults to 'less' if $PAGER is not set).
148 # pager (it defaults to 'less' if $PAGER is not set).
149
149
150 # If your pager has problems, try to setting it to properly handle escapes
150 # If your pager has problems, try to setting it to properly handle escapes
151 # (see the less manpage for detail), or disable this option. The magic
151 # (see the less manpage for detail), or disable this option. The magic
152 # function @color_info allows you to toggle this interactively for testing.
152 # function @color_info allows you to toggle this interactively for testing.
153
153
154 color_info 1
154 color_info 1
155
155
156 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
156 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
157 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
157 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
158 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
158 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
159 # any confirmation.
159 # any confirmation.
160
160
161 confirm_exit 1
161 confirm_exit 1
162
162
163 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
163 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
164 # still available as dreload() and appears as a builtin.
164 # still available as dreload() and appears as a builtin.
165
165
166 deep_reload 0
166 deep_reload 0
167
167
168 # Which editor to use with the @edit command. If you leave this at 0, IPython
168 # Which editor to use with the @edit command. If you leave this at 0, IPython
169 # will honor your EDITOR environment variable. Since this editor is invoked on
169 # will honor your EDITOR environment variable. Since this editor is invoked on
170 # the fly by ipython and is meant for editing small code snippets, you may
170 # the fly by ipython and is meant for editing small code snippets, you may
171 # want to use a small, lightweight editor here.
171 # want to use a small, lightweight editor here.
172
172
173 # For Emacs users, setting up your Emacs server properly as described in the
173 # For Emacs users, setting up your Emacs server properly as described in the
174 # manual is a good idea. An alternative is to use jed, a very light editor
174 # manual is a good idea. An alternative is to use jed, a very light editor
175 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
175 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
176
176
177 editor 0
177 editor 0
178
178
179 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
179 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
180 log 0
180 log 0
181
181
182 # Same as ipython -Logfile YourLogfileName.
182 # Same as ipython -Logfile YourLogfileName.
183 # Don't use with log 1 (use one or the other)
183 # Don't use with log 1 (use one or the other)
184 logfile ''
184 logfile ''
185
185
186 # banner 0 -> same as ipython -nobanner
186 # banner 0 -> same as ipython -nobanner
187 banner 1
187 banner 1
188
188
189 # messages 0 -> same as ipython -nomessages
189 # messages 0 -> same as ipython -nomessages
190 messages 1
190 messages 1
191
191
192 # Automatically call the pdb debugger after every uncaught exception. If you
192 # Automatically call the pdb debugger after every uncaught exception. If you
193 # are used to debugging using pdb, this puts you automatically inside of it
193 # are used to debugging using pdb, this puts you automatically inside of it
194 # after any call (either in IPython or in code called by it) which triggers an
194 # after any call (either in IPython or in code called by it) which triggers an
195 # exception which goes uncaught.
195 # exception which goes uncaught.
196 pdb 0
196 pdb 0
197
197
198 # Enable the pprint module for printing. pprint tends to give a more readable
198 # Enable the pprint module for printing. pprint tends to give a more readable
199 # display (than print) for complex nested data structures.
199 # display (than print) for complex nested data structures.
200 pprint 1
200 pprint 1
201
201
202 # Prompt strings
202 # Prompt strings
203
203
204 # Most bash-like escapes can be used to customize IPython's prompts, as well as
204 # Most bash-like escapes can be used to customize IPython's prompts, as well as
205 # a few additional ones which are IPython-specific. All valid prompt escapes
205 # a few additional ones which are IPython-specific. All valid prompt escapes
206 # are described in detail in the Customization section of the IPython HTML/PDF
206 # are described in detail in the Customization section of the IPython HTML/PDF
207 # manual.
207 # manual.
208
208
209 # Use \# to represent the current prompt number, and quote them to protect
209 # Use \# to represent the current prompt number, and quote them to protect
210 # spaces.
210 # spaces.
211 prompt_in1 'In [\#]: '
211 prompt_in1 'In [\#]: '
212
212
213 # \D is replaced by as many dots as there are digits in the
213 # \D is replaced by as many dots as there are digits in the
214 # current value of \#.
214 # current value of \#.
215 prompt_in2 ' .\D.: '
215 prompt_in2 ' .\D.: '
216
216
217 prompt_out 'Out[\#]: '
217 prompt_out 'Out[\#]: '
218
218
219 # Select whether to left-pad the output prompts to match the length of the
219 # Select whether to left-pad the output prompts to match the length of the
220 # input ones. This allows you for example to use a simple '>' as an output
220 # input ones. This allows you for example to use a simple '>' as an output
221 # prompt, and yet have the output line up with the input. If set to false,
221 # prompt, and yet have the output line up with the input. If set to false,
222 # the output prompts will be unpadded (flush left).
222 # the output prompts will be unpadded (flush left).
223 prompts_pad_left 1
223 prompts_pad_left 1
224
224
225 # quick 1 -> same as ipython -quick
225 # quick 1 -> same as ipython -quick
226 quick 0
226 quick 0
227
227
228 # Use the readline library (1) or not (0). Most users will want this on, but
228 # Use the readline library (1) or not (0). Most users will want this on, but
229 # if you experience strange problems with line management (mainly when using
229 # if you experience strange problems with line management (mainly when using
230 # IPython inside Emacs buffers) you may try disabling it. Not having it on
230 # IPython inside Emacs buffers) you may try disabling it. Not having it on
231 # prevents you from getting command history with the arrow keys, searching and
231 # prevents you from getting command history with the arrow keys, searching and
232 # name completion using TAB.
232 # name completion using TAB.
233
233
234 readline 1
234 readline 1
235
235
236 # Screen Length: number of lines of your screen. This is used to control
236 # Screen Length: number of lines of your screen. This is used to control
237 # printing of very long strings. Strings longer than this number of lines will
237 # printing of very long strings. Strings longer than this number of lines will
238 # be paged with the less command instead of directly printed.
238 # be paged with the less command instead of directly printed.
239
239
240 # The default value for this is 0, which means IPython will auto-detect your
240 # The default value for this is 0, which means IPython will auto-detect your
241 # screen size every time it needs to print. If for some reason this isn't
241 # screen size every time it needs to print. If for some reason this isn't
242 # working well (it needs curses support), specify it yourself. Otherwise don't
242 # working well (it needs curses support), specify it yourself. Otherwise don't
243 # change the default.
243 # change the default.
244
244
245 screen_length 0
245 screen_length 0
246
246
247 # Prompt separators for input and output.
247 # Prompt separators for input and output.
248 # Use \n for newline explicitly, without quotes.
248 # Use \n for newline explicitly, without quotes.
249 # Use 0 (like at the cmd line) to turn off a given separator.
249 # Use 0 (like at the cmd line) to turn off a given separator.
250
250
251 # The structure of prompt printing is:
251 # The structure of prompt printing is:
252 # (SeparateIn)Input....
252 # (SeparateIn)Input....
253 # (SeparateOut)Output...
253 # (SeparateOut)Output...
254 # (SeparateOut2), # that is, no newline is printed after Out2
254 # (SeparateOut2), # that is, no newline is printed after Out2
255 # By choosing these you can organize your output any way you want.
255 # By choosing these you can organize your output any way you want.
256
256
257 separate_in \n
257 separate_in \n
258 separate_out 0
258 separate_out 0
259 separate_out2 0
259 separate_out2 0
260
260
261 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
261 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
262 # Simply removes all input/output separators, overriding the choices above.
262 # Simply removes all input/output separators, overriding the choices above.
263 nosep 0
263 nosep 0
264
264
265 # Wildcard searches - IPython has a system for searching names using
266 # shell-like wildcards; type %psearch? for details. This variables sets
267 # whether by default such searches should be case sensitive or not. You can
268 # always override the default at the system command line or the IPython
269 # prompt.
270
271 wildcards_case_sensitive 1
272
265 # xmode - Exception reporting mode.
273 # xmode - Exception reporting mode.
266
274
267 # Valid modes: Plain, Context and Verbose.
275 # Valid modes: Plain, Context and Verbose.
268
276
269 # Plain: similar to python's normal traceback printing.
277 # Plain: similar to python's normal traceback printing.
270
278
271 # Context: prints 5 lines of context source code around each line in the
279 # Context: prints 5 lines of context source code around each line in the
272 # traceback.
280 # traceback.
273
281
274 # Verbose: similar to Context, but additionally prints the variables currently
282 # Verbose: similar to Context, but additionally prints the variables currently
275 # visible where the exception happened (shortening their strings if too
283 # visible where the exception happened (shortening their strings if too
276 # long). This can potentially be very slow, if you happen to have a huge data
284 # long). This can potentially be very slow, if you happen to have a huge data
277 # structure whose string representation is complex to compute. Your computer
285 # structure whose string representation is complex to compute. Your computer
278 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
286 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
279 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
287 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
280
288
281 #xmode Plain
289 #xmode Plain
282 xmode Context
290 xmode Context
283 #xmode Verbose
291 #xmode Verbose
284
292
285 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
293 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
286 # !cmd) to be used in multi-line input (like for loops). For example, if you
294 # !cmd) to be used in multi-line input (like for loops). For example, if you
287 # have this active, the following is valid in IPython:
295 # have this active, the following is valid in IPython:
288 #
296 #
289 #In [17]: for i in range(3):
297 #In [17]: for i in range(3):
290 # ....: mkdir $i
298 # ....: mkdir $i
291 # ....: !touch $i/hello
299 # ....: !touch $i/hello
292 # ....: ls -l $i
300 # ....: ls -l $i
293
301
294 multi_line_specials 1
302 multi_line_specials 1
295
303
296 #---------------------------------------------------------------------------
304 #---------------------------------------------------------------------------
297 # Section: Readline configuration (readline is not available for MS-Windows)
305 # Section: Readline configuration (readline is not available for MS-Windows)
298
306
299 # This is done via the following options:
307 # This is done via the following options:
300
308
301 # (i) readline_parse_and_bind: this option can appear as many times as you
309 # (i) readline_parse_and_bind: this option can appear as many times as you
302 # want, each time defining a string to be executed via a
310 # want, each time defining a string to be executed via a
303 # readline.parse_and_bind() command. The syntax for valid commands of this
311 # readline.parse_and_bind() command. The syntax for valid commands of this
304 # kind can be found by reading the documentation for the GNU readline library,
312 # kind can be found by reading the documentation for the GNU readline library,
305 # as these commands are of the kind which readline accepts in its
313 # as these commands are of the kind which readline accepts in its
306 # configuration file.
314 # configuration file.
307
315
308 # The TAB key can be used to complete names at the command line in one of two
316 # The TAB key can be used to complete names at the command line in one of two
309 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
317 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
310 # completes as much as possible while 'menu-complete' cycles through all
318 # completes as much as possible while 'menu-complete' cycles through all
311 # possible completions. Leave the one you prefer uncommented.
319 # possible completions. Leave the one you prefer uncommented.
312
320
313 readline_parse_and_bind tab: complete
321 readline_parse_and_bind tab: complete
314 #readline_parse_and_bind tab: menu-complete
322 #readline_parse_and_bind tab: menu-complete
315
323
316 # This binds Control-l to printing the list of all possible completions when
324 # This binds Control-l to printing the list of all possible completions when
317 # there is more than one (what 'complete' does when hitting TAB twice, or at
325 # there is more than one (what 'complete' does when hitting TAB twice, or at
318 # the first TAB if show-all-if-ambiguous is on)
326 # the first TAB if show-all-if-ambiguous is on)
319 readline_parse_and_bind "\C-l": possible-completions
327 readline_parse_and_bind "\C-l": possible-completions
320
328
321 # This forces readline to automatically print the above list when tab
329 # This forces readline to automatically print the above list when tab
322 # completion is set to 'complete'. You can still get this list manually by
330 # completion is set to 'complete'. You can still get this list manually by
323 # using the key bound to 'possible-completions' (Control-l by default) or by
331 # using the key bound to 'possible-completions' (Control-l by default) or by
324 # hitting TAB twice. Turning this on makes the printing happen at the first
332 # hitting TAB twice. Turning this on makes the printing happen at the first
325 # TAB.
333 # TAB.
326 readline_parse_and_bind set show-all-if-ambiguous on
334 readline_parse_and_bind set show-all-if-ambiguous on
327
335
328 # If you have TAB set to complete names, you can rebind any key (Control-o by
336 # If you have TAB set to complete names, you can rebind any key (Control-o by
329 # default) to insert a true TAB character.
337 # default) to insert a true TAB character.
330 readline_parse_and_bind "\C-o": tab-insert
338 readline_parse_and_bind "\C-o": tab-insert
331
339
332 # These commands allow you to indent/unindent easily, with the 4-space
340 # These commands allow you to indent/unindent easily, with the 4-space
333 # convention of the Python coding standards. Since IPython's internal
341 # convention of the Python coding standards. Since IPython's internal
334 # auto-indent system also uses 4 spaces, you should not change the number of
342 # auto-indent system also uses 4 spaces, you should not change the number of
335 # spaces in the code below.
343 # spaces in the code below.
336 readline_parse_and_bind "\M-i": " "
344 readline_parse_and_bind "\M-i": " "
337 readline_parse_and_bind "\M-o": "\d\d\d\d"
345 readline_parse_and_bind "\M-o": "\d\d\d\d"
338 readline_parse_and_bind "\M-I": "\d\d\d\d"
346 readline_parse_and_bind "\M-I": "\d\d\d\d"
339
347
340 # Bindings for incremental searches in the history. These searches use the
348 # Bindings for incremental searches in the history. These searches use the
341 # string typed so far on the command line and search anything in the previous
349 # string typed so far on the command line and search anything in the previous
342 # input history containing them.
350 # input history containing them.
343 readline_parse_and_bind "\C-r": reverse-search-history
351 readline_parse_and_bind "\C-r": reverse-search-history
344 readline_parse_and_bind "\C-s": forward-search-history
352 readline_parse_and_bind "\C-s": forward-search-history
345
353
346 # Bindings for completing the current line in the history of previous
354 # Bindings for completing the current line in the history of previous
347 # commands. This allows you to recall any previous command by typing its first
355 # commands. This allows you to recall any previous command by typing its first
348 # few letters and hitting Control-p, bypassing all intermediate commands which
356 # few letters and hitting Control-p, bypassing all intermediate commands which
349 # may be in the history (much faster than hitting up-arrow 50 times!)
357 # may be in the history (much faster than hitting up-arrow 50 times!)
350 readline_parse_and_bind "\C-p": history-search-backward
358 readline_parse_and_bind "\C-p": history-search-backward
351 readline_parse_and_bind "\C-n": history-search-forward
359 readline_parse_and_bind "\C-n": history-search-forward
352
360
353 # I also like to have the same functionality on the plain arrow keys. If you'd
361 # I also like to have the same functionality on the plain arrow keys. If you'd
354 # rather have the arrows use all the history (and not just match what you've
362 # rather have the arrows use all the history (and not just match what you've
355 # typed so far), comment out or delete the next two lines.
363 # typed so far), comment out or delete the next two lines.
356 readline_parse_and_bind "\e[A": history-search-backward
364 readline_parse_and_bind "\e[A": history-search-backward
357 readline_parse_and_bind "\e[B": history-search-forward
365 readline_parse_and_bind "\e[B": history-search-forward
358
366
359 # These are typically on by default under *nix, but not win32.
367 # These are typically on by default under *nix, but not win32.
360 readline_parse_and_bind "\C-k": kill-line
368 readline_parse_and_bind "\C-k": kill-line
361 readline_parse_and_bind "\C-u": unix-line-discard
369 readline_parse_and_bind "\C-u": unix-line-discard
362
370
363 # (ii) readline_remove_delims: a string of characters to be removed from the
371 # (ii) readline_remove_delims: a string of characters to be removed from the
364 # default word-delimiters list used by readline, so that completions may be
372 # default word-delimiters list used by readline, so that completions may be
365 # performed on strings which contain them.
373 # performed on strings which contain them.
366
374
367 readline_remove_delims -/~
375 readline_remove_delims -/~
368
376
369 # (iii) readline_merge_completions: whether to merge the result of all
377 # (iii) readline_merge_completions: whether to merge the result of all
370 # possible completions or not. If true, IPython will complete filenames,
378 # possible completions or not. If true, IPython will complete filenames,
371 # python names and aliases and return all possible completions. If you set it
379 # python names and aliases and return all possible completions. If you set it
372 # to false, each completer is used at a time, and only if it doesn't return
380 # to false, each completer is used at a time, and only if it doesn't return
373 # any completions is the next one used.
381 # any completions is the next one used.
374
382
375 # The default order is: [python_matches, file_matches, alias_matches]
383 # The default order is: [python_matches, file_matches, alias_matches]
376
384
377 readline_merge_completions 1
385 readline_merge_completions 1
378
386
379 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
387 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
380 # will complete all attributes of an object, including all the special methods
388 # will complete all attributes of an object, including all the special methods
381 # whose names start with single or double underscores (like __getitem__ or
389 # whose names start with single or double underscores (like __getitem__ or
382 # __class__).
390 # __class__).
383
391
384 # This variable allows you to control this completion behavior:
392 # This variable allows you to control this completion behavior:
385
393
386 # readline_omit__names 1 -> completion will omit showing any names starting
394 # readline_omit__names 1 -> completion will omit showing any names starting
387 # with two __, but it will still show names starting with one _.
395 # with two __, but it will still show names starting with one _.
388
396
389 # readline_omit__names 2 -> completion will omit all names beginning with one
397 # readline_omit__names 2 -> completion will omit all names beginning with one
390 # _ (which obviously means filtering out the double __ ones).
398 # _ (which obviously means filtering out the double __ ones).
391
399
392 # Even when this option is set, you can still see those names by explicitly
400 # Even when this option is set, you can still see those names by explicitly
393 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
401 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
394 # complete attribute names starting with '_'.
402 # complete attribute names starting with '_'.
395
403
396 # This option is off by default so that new users see all attributes of any
404 # This option is off by default so that new users see all attributes of any
397 # objects they are dealing with.
405 # objects they are dealing with.
398
406
399 readline_omit__names 0
407 readline_omit__names 0
400
408
401 #---------------------------------------------------------------------------
409 #---------------------------------------------------------------------------
402 # Section: modules to be loaded with 'import ...'
410 # Section: modules to be loaded with 'import ...'
403
411
404 # List, separated by spaces, the names of the modules you want to import
412 # List, separated by spaces, the names of the modules you want to import
405
413
406 # Example:
414 # Example:
407 # import_mod sys os
415 # import_mod sys os
408 # will produce internally the statements
416 # will produce internally the statements
409 # import sys
417 # import sys
410 # import os
418 # import os
411
419
412 # Each import is executed in its own try/except block, so if one module
420 # Each import is executed in its own try/except block, so if one module
413 # fails to load the others will still be ok.
421 # fails to load the others will still be ok.
414
422
415 import_mod
423 import_mod
416
424
417 #---------------------------------------------------------------------------
425 #---------------------------------------------------------------------------
418 # Section: modules to import some functions from: 'from ... import ...'
426 # Section: modules to import some functions from: 'from ... import ...'
419
427
420 # List, one per line, the modules for which you want only to import some
428 # List, one per line, the modules for which you want only to import some
421 # functions. Give the module name first and then the name of functions to be
429 # functions. Give the module name first and then the name of functions to be
422 # imported from that module.
430 # imported from that module.
423
431
424 # Example:
432 # Example:
425
433
426 # import_some IPython.genutils timing timings
434 # import_some IPython.genutils timing timings
427 # will produce internally the statement
435 # will produce internally the statement
428 # from IPython.genutils import timing, timings
436 # from IPython.genutils import timing, timings
429
437
430 # timing() and timings() are two IPython utilities for timing the execution of
438 # timing() and timings() are two IPython utilities for timing the execution of
431 # your own functions, which you may find useful. Just commment out the above
439 # your own functions, which you may find useful. Just commment out the above
432 # line if you want to test them.
440 # line if you want to test them.
433
441
434 # If you have more than one modules_some line, each gets its own try/except
442 # If you have more than one modules_some line, each gets its own try/except
435 # block (like modules, see above).
443 # block (like modules, see above).
436
444
437 import_some
445 import_some
438
446
439 #---------------------------------------------------------------------------
447 #---------------------------------------------------------------------------
440 # Section: modules to import all from : 'from ... import *'
448 # Section: modules to import all from : 'from ... import *'
441
449
442 # List (same syntax as import_mod above) those modules for which you want to
450 # List (same syntax as import_mod above) those modules for which you want to
443 # import all functions. Remember, this is a potentially dangerous thing to do,
451 # import all functions. Remember, this is a potentially dangerous thing to do,
444 # since it is very easy to overwrite names of things you need. Use with
452 # since it is very easy to overwrite names of things you need. Use with
445 # caution.
453 # caution.
446
454
447 # Example:
455 # Example:
448 # import_all sys os
456 # import_all sys os
449 # will produce internally the statements
457 # will produce internally the statements
450 # from sys import *
458 # from sys import *
451 # from os import *
459 # from os import *
452
460
453 # As before, each will be called in a separate try/except block.
461 # As before, each will be called in a separate try/except block.
454
462
455 import_all
463 import_all
456
464
457 #---------------------------------------------------------------------------
465 #---------------------------------------------------------------------------
458 # Section: Python code to execute.
466 # Section: Python code to execute.
459
467
460 # Put here code to be explicitly executed (keep it simple!)
468 # Put here code to be explicitly executed (keep it simple!)
461 # Put one line of python code per line. All whitespace is removed (this is a
469 # Put one line of python code per line. All whitespace is removed (this is a
462 # feature, not a bug), so don't get fancy building loops here.
470 # feature, not a bug), so don't get fancy building loops here.
463 # This is just for quick convenient creation of things you want available.
471 # This is just for quick convenient creation of things you want available.
464
472
465 # Example:
473 # Example:
466 # execute x = 1
474 # execute x = 1
467 # execute print 'hello world'; y = z = 'a'
475 # execute print 'hello world'; y = z = 'a'
468 # will produce internally
476 # will produce internally
469 # x = 1
477 # x = 1
470 # print 'hello world'; y = z = 'a'
478 # print 'hello world'; y = z = 'a'
471 # and each *line* (not each statement, we don't do python syntax parsing) is
479 # and each *line* (not each statement, we don't do python syntax parsing) is
472 # executed in its own try/except block.
480 # executed in its own try/except block.
473
481
474 execute
482 execute
475
483
476 # Note for the adventurous: you can use this to define your own names for the
484 # Note for the adventurous: you can use this to define your own names for the
477 # magic functions, by playing some namespace tricks:
485 # magic functions, by playing some namespace tricks:
478
486
479 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
487 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
480
488
481 # defines @pf as a new name for @profile.
489 # defines @pf as a new name for @profile.
482
490
483 #---------------------------------------------------------------------------
491 #---------------------------------------------------------------------------
484 # Section: Pyhton files to load and execute.
492 # Section: Pyhton files to load and execute.
485
493
486 # Put here the full names of files you want executed with execfile(file). If
494 # Put here the full names of files you want executed with execfile(file). If
487 # you want complicated initialization, just write whatever you want in a
495 # you want complicated initialization, just write whatever you want in a
488 # regular python file and load it from here.
496 # regular python file and load it from here.
489
497
490 # Filenames defined here (which *must* include the extension) are searched for
498 # Filenames defined here (which *must* include the extension) are searched for
491 # through all of sys.path. Since IPython adds your .ipython directory to
499 # through all of sys.path. Since IPython adds your .ipython directory to
492 # sys.path, they can also be placed in your .ipython dir and will be
500 # sys.path, they can also be placed in your .ipython dir and will be
493 # found. Otherwise (if you want to execute things not in .ipyton nor in
501 # found. Otherwise (if you want to execute things not in .ipyton nor in
494 # sys.path) give a full path (you can use ~, it gets expanded)
502 # sys.path) give a full path (you can use ~, it gets expanded)
495
503
496 # Example:
504 # Example:
497 # execfile file1.py ~/file2.py
505 # execfile file1.py ~/file2.py
498 # will generate
506 # will generate
499 # execfile('file1.py')
507 # execfile('file1.py')
500 # execfile('_path_to_your_home/file2.py')
508 # execfile('_path_to_your_home/file2.py')
501
509
502 # As before, each file gets its own try/except block.
510 # As before, each file gets its own try/except block.
503
511
504 execfile
512 execfile
505
513
506 # If you are feeling adventurous, you can even add functionality to IPython
514 # If you are feeling adventurous, you can even add functionality to IPython
507 # through here. IPython works through a global variable called __ip which
515 # through here. IPython works through a global variable called __ip which
508 # exists at the time when these files are read. If you know what you are doing
516 # exists at the time when these files are read. If you know what you are doing
509 # (read the source) you can add functions to __ip in files loaded here.
517 # (read the source) you can add functions to __ip in files loaded here.
510
518
511 # The file example-magic.py contains a simple but correct example. Try it:
519 # The file example-magic.py contains a simple but correct example. Try it:
512
520
513 # execfile example-magic.py
521 # execfile example-magic.py
514
522
515 # Look at the examples in IPython/iplib.py for more details on how these magic
523 # Look at the examples in IPython/iplib.py for more details on how these magic
516 # functions need to process their arguments.
524 # functions need to process their arguments.
517
525
518 #---------------------------------------------------------------------------
526 #---------------------------------------------------------------------------
519 # Section: aliases for system shell commands
527 # Section: aliases for system shell commands
520
528
521 # Here you can define your own names for system commands. The syntax is
529 # Here you can define your own names for system commands. The syntax is
522 # similar to that of the builtin @alias function:
530 # similar to that of the builtin @alias function:
523
531
524 # alias alias_name command_string
532 # alias alias_name command_string
525
533
526 # The resulting aliases are auto-generated magic functions (hence usable as
534 # The resulting aliases are auto-generated magic functions (hence usable as
527 # @alias_name)
535 # @alias_name)
528
536
529 # For example:
537 # For example:
530
538
531 # alias myls ls -la
539 # alias myls ls -la
532
540
533 # will define 'myls' as an alias for executing the system command 'ls -la'.
541 # will define 'myls' as an alias for executing the system command 'ls -la'.
534 # This allows you to customize IPython's environment to have the same aliases
542 # This allows you to customize IPython's environment to have the same aliases
535 # you are accustomed to from your own shell.
543 # you are accustomed to from your own shell.
536
544
537 # You can also define aliases with parameters using %s specifiers (one per
545 # You can also define aliases with parameters using %s specifiers (one per
538 # parameter):
546 # parameter):
539
547
540 # alias parts echo first %s second %s
548 # alias parts echo first %s second %s
541
549
542 # will give you in IPython:
550 # will give you in IPython:
543 # >>> @parts A B
551 # >>> @parts A B
544 # first A second B
552 # first A second B
545
553
546 # Use one 'alias' statement per alias you wish to define.
554 # Use one 'alias' statement per alias you wish to define.
547
555
548 # alias
556 # alias
549
557
550 #************************* end of file <ipythonrc> ************************
558 #************************* end of file <ipythonrc> ************************
@@ -1,2062 +1,2098 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or newer.
5 Requires Python 2.1 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 921 2005-11-13 06:51:34Z fperez $
9 $Id: iplib.py 923 2005-11-15 08:51:15Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2004 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, much of that class has been copied
20 # Python standard library. Over time, much 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. The Python License (sec. 2) allows for this, but it's always
22 # subclassing. The Python License (sec. 2) allows for this, but it's always
23 # nice to acknowledge credit where credit is due.
23 # nice to acknowledge credit where credit is due.
24 #*****************************************************************************
24 #*****************************************************************************
25
25
26 #****************************************************************************
26 #****************************************************************************
27 # Modules and globals
27 # Modules and globals
28
28
29 from __future__ import generators # for 2.2 backwards-compatibility
29 from __future__ import generators # for 2.2 backwards-compatibility
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import exceptions
40 import exceptions
41 import keyword
41 import keyword
42 import new
42 import new
43 import os, sys, shutil
43 import os, sys, shutil
44 import code, glob, types, re
44 import code, glob, types, re
45 import string, StringIO
45 import string, StringIO
46 import inspect, pydoc
46 import inspect, pydoc
47 import bdb, pdb
47 import bdb, pdb
48 import UserList # don't subclass list so this works with Python2.1
48 import UserList # don't subclass list so this works with Python2.1
49 from pprint import pprint, pformat
49 from pprint import pprint, pformat
50 import cPickle as pickle
50 import cPickle as pickle
51 import traceback
51 import traceback
52 from codeop import CommandCompiler
52 from codeop import CommandCompiler
53
53
54 # IPython's own modules
54 # IPython's own modules
55 import IPython
55 import IPython
56 from IPython import OInspect,PyColorize,ultraTB
56 from IPython import OInspect,PyColorize,ultraTB
57 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
57 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
58 from IPython.Logger import Logger
58 from IPython.Logger import Logger
59 from IPython.Magic import Magic,magic2python,shlex_split
59 from IPython.Magic import Magic,magic2python,shlex_split
60 from IPython.usage import cmd_line_usage,interactive_usage
60 from IPython.usage import cmd_line_usage,interactive_usage
61 from IPython.Struct import Struct
61 from IPython.Struct import Struct
62 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
63 from IPython.FakeModule import FakeModule
63 from IPython.FakeModule import FakeModule
64 from IPython.background_jobs import BackgroundJobManager
64 from IPython.background_jobs import BackgroundJobManager
65 from IPython.PyColorize import Parser
65 from IPython.PyColorize import Parser
66 from IPython.genutils import *
66 from IPython.genutils import *
67
67
68 # Global pointer to the running
68 # Global pointer to the running
69
69
70 # store the builtin raw_input globally, and use this always, in case user code
70 # store the builtin raw_input globally, and use this always, in case user code
71 # overwrites it (like wx.py.PyShell does)
71 # overwrites it (like wx.py.PyShell does)
72 raw_input_original = raw_input
72 raw_input_original = raw_input
73
73
74 #****************************************************************************
74 #****************************************************************************
75 # Some utility function definitions
75 # Some utility function definitions
76
76
77 class Bunch: pass
77 class Bunch: pass
78
78
79 def esc_quotes(strng):
79 def esc_quotes(strng):
80 """Return the input string with single and double quotes escaped out"""
80 """Return the input string with single and double quotes escaped out"""
81
81
82 return strng.replace('"','\\"').replace("'","\\'")
82 return strng.replace('"','\\"').replace("'","\\'")
83
83
84 def import_fail_info(mod_name,fns=None):
84 def import_fail_info(mod_name,fns=None):
85 """Inform load failure for a module."""
85 """Inform load failure for a module."""
86
86
87 if fns == None:
87 if fns == None:
88 warn("Loading of %s failed.\n" % (mod_name,))
88 warn("Loading of %s failed.\n" % (mod_name,))
89 else:
89 else:
90 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
90 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
91
91
92 def qw_lol(indata):
92 def qw_lol(indata):
93 """qw_lol('a b') -> [['a','b']],
93 """qw_lol('a b') -> [['a','b']],
94 otherwise it's just a call to qw().
94 otherwise it's just a call to qw().
95
95
96 We need this to make sure the modules_some keys *always* end up as a
96 We need this to make sure the modules_some keys *always* end up as a
97 list of lists."""
97 list of lists."""
98
98
99 if type(indata) in StringTypes:
99 if type(indata) in StringTypes:
100 return [qw(indata)]
100 return [qw(indata)]
101 else:
101 else:
102 return qw(indata)
102 return qw(indata)
103
103
104 def ipmagic(arg_s):
104 def ipmagic(arg_s):
105 """Call a magic function by name.
105 """Call a magic function by name.
106
106
107 Input: a string containing the name of the magic function to call and any
107 Input: a string containing the name of the magic function to call and any
108 additional arguments to be passed to the magic.
108 additional arguments to be passed to the magic.
109
109
110 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
110 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
111 prompt:
111 prompt:
112
112
113 In[1]: %name -opt foo bar
113 In[1]: %name -opt foo bar
114
114
115 To call a magic without arguments, simply use ipmagic('name').
115 To call a magic without arguments, simply use ipmagic('name').
116
116
117 This provides a proper Python function to call IPython's magics in any
117 This provides a proper Python function to call IPython's magics in any
118 valid Python code you can type at the interpreter, including loops and
118 valid Python code you can type at the interpreter, including loops and
119 compound statements. It is added by IPython to the Python builtin
119 compound statements. It is added by IPython to the Python builtin
120 namespace upon initialization."""
120 namespace upon initialization."""
121
121
122 args = arg_s.split(' ',1)
122 args = arg_s.split(' ',1)
123 magic_name = args[0]
123 magic_name = args[0]
124 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
124 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
125 magic_name = magic_name[1:]
125 magic_name = magic_name[1:]
126 try:
126 try:
127 magic_args = args[1]
127 magic_args = args[1]
128 except IndexError:
128 except IndexError:
129 magic_args = ''
129 magic_args = ''
130 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
130 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
131 if fn is None:
131 if fn is None:
132 error("Magic function `%s` not found." % magic_name)
132 error("Magic function `%s` not found." % magic_name)
133 else:
133 else:
134 magic_args = __IPYTHON__.var_expand(magic_args)
134 magic_args = __IPYTHON__.var_expand(magic_args)
135 return fn(magic_args)
135 return fn(magic_args)
136
136
137 def ipalias(arg_s):
137 def ipalias(arg_s):
138 """Call an alias by name.
138 """Call an alias by name.
139
139
140 Input: a string containing the name of the alias to call and any
140 Input: a string containing the name of the alias to call and any
141 additional arguments to be passed to the magic.
141 additional arguments to be passed to the magic.
142
142
143 ipalias('name -opt foo bar') is equivalent to typing at the ipython
143 ipalias('name -opt foo bar') is equivalent to typing at the ipython
144 prompt:
144 prompt:
145
145
146 In[1]: name -opt foo bar
146 In[1]: name -opt foo bar
147
147
148 To call an alias without arguments, simply use ipalias('name').
148 To call an alias without arguments, simply use ipalias('name').
149
149
150 This provides a proper Python function to call IPython's aliases in any
150 This provides a proper Python function to call IPython's aliases in any
151 valid Python code you can type at the interpreter, including loops and
151 valid Python code you can type at the interpreter, including loops and
152 compound statements. It is added by IPython to the Python builtin
152 compound statements. It is added by IPython to the Python builtin
153 namespace upon initialization."""
153 namespace upon initialization."""
154
154
155 args = arg_s.split(' ',1)
155 args = arg_s.split(' ',1)
156 alias_name = args[0]
156 alias_name = args[0]
157 try:
157 try:
158 alias_args = args[1]
158 alias_args = args[1]
159 except IndexError:
159 except IndexError:
160 alias_args = ''
160 alias_args = ''
161 if alias_name in __IPYTHON__.alias_table:
161 if alias_name in __IPYTHON__.alias_table:
162 __IPYTHON__.call_alias(alias_name,alias_args)
162 __IPYTHON__.call_alias(alias_name,alias_args)
163 else:
163 else:
164 error("Alias `%s` not found." % alias_name)
164 error("Alias `%s` not found." % alias_name)
165
165
166 #-----------------------------------------------------------------------------
166 #-----------------------------------------------------------------------------
167 # Local use classes
167 # Local use classes
168 try:
168 try:
169 from IPython import FlexCompleter
169 from IPython import FlexCompleter
170
170
171 class MagicCompleter(FlexCompleter.Completer):
171 class MagicCompleter(FlexCompleter.Completer):
172 """Extension of the completer class to work on %-prefixed lines."""
172 """Extension of the completer class to work on %-prefixed lines."""
173
173
174 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
174 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
175 """MagicCompleter() -> completer
175 """MagicCompleter() -> completer
176
176
177 Return a completer object suitable for use by the readline library
177 Return a completer object suitable for use by the readline library
178 via readline.set_completer().
178 via readline.set_completer().
179
179
180 Inputs:
180 Inputs:
181
181
182 - shell: a pointer to the ipython shell itself. This is needed
182 - shell: a pointer to the ipython shell itself. This is needed
183 because this completer knows about magic functions, and those can
183 because this completer knows about magic functions, and those can
184 only be accessed via the ipython instance.
184 only be accessed via the ipython instance.
185
185
186 - namespace: an optional dict where completions are performed.
186 - namespace: an optional dict where completions are performed.
187
187
188 - The optional omit__names parameter sets the completer to omit the
188 - The optional omit__names parameter sets the completer to omit the
189 'magic' names (__magicname__) for python objects unless the text
189 'magic' names (__magicname__) for python objects unless the text
190 to be completed explicitly starts with one or more underscores.
190 to be completed explicitly starts with one or more underscores.
191
191
192 - If alias_table is supplied, it should be a dictionary of aliases
192 - If alias_table is supplied, it should be a dictionary of aliases
193 to complete. """
193 to complete. """
194
194
195 FlexCompleter.Completer.__init__(self,namespace)
195 FlexCompleter.Completer.__init__(self,namespace)
196 self.magic_prefix = shell.name+'.magic_'
196 self.magic_prefix = shell.name+'.magic_'
197 self.magic_escape = shell.ESC_MAGIC
197 self.magic_escape = shell.ESC_MAGIC
198 self.readline = FlexCompleter.readline
198 self.readline = FlexCompleter.readline
199 delims = self.readline.get_completer_delims()
199 delims = self.readline.get_completer_delims()
200 delims = delims.replace(self.magic_escape,'')
200 delims = delims.replace(self.magic_escape,'')
201 self.readline.set_completer_delims(delims)
201 self.readline.set_completer_delims(delims)
202 self.get_line_buffer = self.readline.get_line_buffer
202 self.get_line_buffer = self.readline.get_line_buffer
203 self.omit__names = omit__names
203 self.omit__names = omit__names
204 self.merge_completions = shell.rc.readline_merge_completions
204 self.merge_completions = shell.rc.readline_merge_completions
205
205
206 if alias_table is None:
206 if alias_table is None:
207 alias_table = {}
207 alias_table = {}
208 self.alias_table = alias_table
208 self.alias_table = alias_table
209 # Regexp to split filenames with spaces in them
209 # Regexp to split filenames with spaces in them
210 self.space_name_re = re.compile(r'([^\\] )')
210 self.space_name_re = re.compile(r'([^\\] )')
211 # Hold a local ref. to glob.glob for speed
211 # Hold a local ref. to glob.glob for speed
212 self.glob = glob.glob
212 self.glob = glob.glob
213 # Special handling of backslashes needed in win32 platforms
213 # Special handling of backslashes needed in win32 platforms
214 if sys.platform == "win32":
214 if sys.platform == "win32":
215 self.clean_glob = self._clean_glob_win32
215 self.clean_glob = self._clean_glob_win32
216 else:
216 else:
217 self.clean_glob = self._clean_glob
217 self.clean_glob = self._clean_glob
218 self.matchers = [self.python_matches,
218 self.matchers = [self.python_matches,
219 self.file_matches,
219 self.file_matches,
220 self.alias_matches,
220 self.alias_matches,
221 self.python_func_kw_matches]
221 self.python_func_kw_matches]
222
222
223 # Code contributed by Alex Schmolck, for ipython/emacs integration
223 # Code contributed by Alex Schmolck, for ipython/emacs integration
224 def all_completions(self, text):
224 def all_completions(self, text):
225 """Return all possible completions for the benefit of emacs."""
225 """Return all possible completions for the benefit of emacs."""
226
226
227 completions = []
227 completions = []
228 try:
228 try:
229 for i in xrange(sys.maxint):
229 for i in xrange(sys.maxint):
230 res = self.complete(text, i)
230 res = self.complete(text, i)
231
231
232 if not res: break
232 if not res: break
233
233
234 completions.append(res)
234 completions.append(res)
235 #XXX workaround for ``notDefined.<tab>``
235 #XXX workaround for ``notDefined.<tab>``
236 except NameError:
236 except NameError:
237 pass
237 pass
238 return completions
238 return completions
239 # /end Alex Schmolck code.
239 # /end Alex Schmolck code.
240
240
241 def _clean_glob(self,text):
241 def _clean_glob(self,text):
242 return self.glob("%s*" % text)
242 return self.glob("%s*" % text)
243
243
244 def _clean_glob_win32(self,text):
244 def _clean_glob_win32(self,text):
245 return [f.replace("\\","/")
245 return [f.replace("\\","/")
246 for f in self.glob("%s*" % text)]
246 for f in self.glob("%s*" % text)]
247
247
248 def file_matches(self, text):
248 def file_matches(self, text):
249 """Match filneames, expanding ~USER type strings.
249 """Match filneames, expanding ~USER type strings.
250
250
251 Most of the seemingly convoluted logic in this completer is an
251 Most of the seemingly convoluted logic in this completer is an
252 attempt to handle filenames with spaces in them. And yet it's not
252 attempt to handle filenames with spaces in them. And yet it's not
253 quite perfect, because Python's readline doesn't expose all of the
253 quite perfect, because Python's readline doesn't expose all of the
254 GNU readline details needed for this to be done correctly.
254 GNU readline details needed for this to be done correctly.
255
255
256 For a filename with a space in it, the printed completions will be
256 For a filename with a space in it, the printed completions will be
257 only the parts after what's already been typed (instead of the
257 only the parts after what's already been typed (instead of the
258 full completions, as is normally done). I don't think with the
258 full completions, as is normally done). I don't think with the
259 current (as of Python 2.3) Python readline it's possible to do
259 current (as of Python 2.3) Python readline it's possible to do
260 better."""
260 better."""
261
261
262 #print 'Completer->file_matches: <%s>' % text # dbg
262 #print 'Completer->file_matches: <%s>' % text # dbg
263
263
264 # chars that require escaping with backslash - i.e. chars
264 # chars that require escaping with backslash - i.e. chars
265 # that readline treats incorrectly as delimiters, but we
265 # that readline treats incorrectly as delimiters, but we
266 # don't want to treat as delimiters in filename matching
266 # don't want to treat as delimiters in filename matching
267 # when escaped with backslash
267 # when escaped with backslash
268
268
269 protectables = ' ()[]{}'
269 protectables = ' ()[]{}'
270
270
271 def protect_filename(s):
271 def protect_filename(s):
272 return "".join([(ch in protectables and '\\' + ch or ch)
272 return "".join([(ch in protectables and '\\' + ch or ch)
273 for ch in s])
273 for ch in s])
274
274
275 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
275 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
276 open_quotes = 0 # track strings with open quotes
276 open_quotes = 0 # track strings with open quotes
277 try:
277 try:
278 lsplit = shlex_split(lbuf)[-1]
278 lsplit = shlex_split(lbuf)[-1]
279 except ValueError:
279 except ValueError:
280 # typically an unmatched ", or backslash without escaped char.
280 # typically an unmatched ", or backslash without escaped char.
281 if lbuf.count('"')==1:
281 if lbuf.count('"')==1:
282 open_quotes = 1
282 open_quotes = 1
283 lsplit = lbuf.split('"')[-1]
283 lsplit = lbuf.split('"')[-1]
284 elif lbuf.count("'")==1:
284 elif lbuf.count("'")==1:
285 open_quotes = 1
285 open_quotes = 1
286 lsplit = lbuf.split("'")[-1]
286 lsplit = lbuf.split("'")[-1]
287 else:
287 else:
288 return None
288 return None
289 except IndexError:
289 except IndexError:
290 # tab pressed on empty line
290 # tab pressed on empty line
291 lsplit = ""
291 lsplit = ""
292
292
293 if lsplit != protect_filename(lsplit):
293 if lsplit != protect_filename(lsplit):
294 # if protectables are found, do matching on the whole escaped
294 # if protectables are found, do matching on the whole escaped
295 # name
295 # name
296 has_protectables = 1
296 has_protectables = 1
297 text0,text = text,lsplit
297 text0,text = text,lsplit
298 else:
298 else:
299 has_protectables = 0
299 has_protectables = 0
300 text = os.path.expanduser(text)
300 text = os.path.expanduser(text)
301
301
302 if text == "":
302 if text == "":
303 return [protect_filename(f) for f in self.glob("*")]
303 return [protect_filename(f) for f in self.glob("*")]
304
304
305 m0 = self.clean_glob(text.replace('\\',''))
305 m0 = self.clean_glob(text.replace('\\',''))
306 if has_protectables:
306 if has_protectables:
307 # If we had protectables, we need to revert our changes to the
307 # If we had protectables, we need to revert our changes to the
308 # beginning of filename so that we don't double-write the part
308 # beginning of filename so that we don't double-write the part
309 # of the filename we have so far
309 # of the filename we have so far
310 len_lsplit = len(lsplit)
310 len_lsplit = len(lsplit)
311 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
311 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
312 else:
312 else:
313 if open_quotes:
313 if open_quotes:
314 # if we have a string with an open quote, we don't need to
314 # if we have a string with an open quote, we don't need to
315 # protect the names at all (and we _shouldn't_, as it
315 # protect the names at all (and we _shouldn't_, as it
316 # would cause bugs when the filesystem call is made).
316 # would cause bugs when the filesystem call is made).
317 matches = m0
317 matches = m0
318 else:
318 else:
319 matches = [protect_filename(f) for f in m0]
319 matches = [protect_filename(f) for f in m0]
320 if len(matches) == 1 and os.path.isdir(matches[0]):
320 if len(matches) == 1 and os.path.isdir(matches[0]):
321 # Takes care of links to directories also. Use '/'
321 # Takes care of links to directories also. Use '/'
322 # explicitly, even under Windows, so that name completions
322 # explicitly, even under Windows, so that name completions
323 # don't end up escaped.
323 # don't end up escaped.
324 matches[0] += '/'
324 matches[0] += '/'
325 return matches
325 return matches
326
326
327 def alias_matches(self, text):
327 def alias_matches(self, text):
328 """Match internal system aliases"""
328 """Match internal system aliases"""
329 #print 'Completer->alias_matches:',text # dbg
329 #print 'Completer->alias_matches:',text # dbg
330 text = os.path.expanduser(text)
330 text = os.path.expanduser(text)
331 aliases = self.alias_table.keys()
331 aliases = self.alias_table.keys()
332 if text == "":
332 if text == "":
333 return aliases
333 return aliases
334 else:
334 else:
335 return [alias for alias in aliases if alias.startswith(text)]
335 return [alias for alias in aliases if alias.startswith(text)]
336
336
337 def python_matches(self,text):
337 def python_matches(self,text):
338 """Match attributes or global python names"""
338 """Match attributes or global python names"""
339 #print 'Completer->python_matches' # dbg
339 #print 'Completer->python_matches' # dbg
340 if "." in text:
340 if "." in text:
341 try:
341 try:
342 matches = self.attr_matches(text)
342 matches = self.attr_matches(text)
343 if text.endswith('.') and self.omit__names:
343 if text.endswith('.') and self.omit__names:
344 if self.omit__names == 1:
344 if self.omit__names == 1:
345 # true if txt is _not_ a __ name, false otherwise:
345 # true if txt is _not_ a __ name, false otherwise:
346 no__name = (lambda txt:
346 no__name = (lambda txt:
347 re.match(r'.*\.__.*?__',txt) is None)
347 re.match(r'.*\.__.*?__',txt) is None)
348 else:
348 else:
349 # true if txt is _not_ a _ name, false otherwise:
349 # true if txt is _not_ a _ name, false otherwise:
350 no__name = (lambda txt:
350 no__name = (lambda txt:
351 re.match(r'.*\._.*?',txt) is None)
351 re.match(r'.*\._.*?',txt) is None)
352 matches = filter(no__name, matches)
352 matches = filter(no__name, matches)
353 except NameError:
353 except NameError:
354 # catches <undefined attributes>.<tab>
354 # catches <undefined attributes>.<tab>
355 matches = []
355 matches = []
356 else:
356 else:
357 matches = self.global_matches(text)
357 matches = self.global_matches(text)
358 # this is so completion finds magics when automagic is on:
358 # this is so completion finds magics when automagic is on:
359 if matches == [] and not text.startswith(os.sep):
359 if matches == [] and not text.startswith(os.sep):
360 matches = self.attr_matches(self.magic_prefix+text)
360 matches = self.attr_matches(self.magic_prefix+text)
361 return matches
361 return matches
362
362
363 def _default_arguments(self, obj):
363 def _default_arguments(self, obj):
364 """Return the list of default arguments of obj if it is callable,
364 """Return the list of default arguments of obj if it is callable,
365 or empty list otherwise."""
365 or empty list otherwise."""
366
366
367 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
367 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
368 # for classes, check for __init__,__new__
368 # for classes, check for __init__,__new__
369 if inspect.isclass(obj):
369 if inspect.isclass(obj):
370 obj = (getattr(obj,'__init__',None) or
370 obj = (getattr(obj,'__init__',None) or
371 getattr(obj,'__new__',None))
371 getattr(obj,'__new__',None))
372 # for all others, check if they are __call__able
372 # for all others, check if they are __call__able
373 elif hasattr(obj, '__call__'):
373 elif hasattr(obj, '__call__'):
374 obj = obj.__call__
374 obj = obj.__call__
375 # XXX: is there a way to handle the builtins ?
375 # XXX: is there a way to handle the builtins ?
376 try:
376 try:
377 args,_,_1,defaults = inspect.getargspec(obj)
377 args,_,_1,defaults = inspect.getargspec(obj)
378 if defaults:
378 if defaults:
379 return args[-len(defaults):]
379 return args[-len(defaults):]
380 except TypeError: pass
380 except TypeError: pass
381 return []
381 return []
382
382
383 def python_func_kw_matches(self,text):
383 def python_func_kw_matches(self,text):
384 """Match named parameters (kwargs) of the last open function"""
384 """Match named parameters (kwargs) of the last open function"""
385
385
386 if "." in text: # a parameter cannot be dotted
386 if "." in text: # a parameter cannot be dotted
387 return []
387 return []
388 try: regexp = self.__funcParamsRegex
388 try: regexp = self.__funcParamsRegex
389 except AttributeError:
389 except AttributeError:
390 regexp = self.__funcParamsRegex = re.compile(r'''
390 regexp = self.__funcParamsRegex = re.compile(r'''
391 '.*?' | # single quoted strings or
391 '.*?' | # single quoted strings or
392 ".*?" | # double quoted strings or
392 ".*?" | # double quoted strings or
393 \w+ | # identifier
393 \w+ | # identifier
394 \S # other characters
394 \S # other characters
395 ''', re.VERBOSE | re.DOTALL)
395 ''', re.VERBOSE | re.DOTALL)
396 # 1. find the nearest identifier that comes before an unclosed
396 # 1. find the nearest identifier that comes before an unclosed
397 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
397 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
398 tokens = regexp.findall(self.get_line_buffer())
398 tokens = regexp.findall(self.get_line_buffer())
399 tokens.reverse()
399 tokens.reverse()
400 iterTokens = iter(tokens); openPar = 0
400 iterTokens = iter(tokens); openPar = 0
401 for token in iterTokens:
401 for token in iterTokens:
402 if token == ')':
402 if token == ')':
403 openPar -= 1
403 openPar -= 1
404 elif token == '(':
404 elif token == '(':
405 openPar += 1
405 openPar += 1
406 if openPar > 0:
406 if openPar > 0:
407 # found the last unclosed parenthesis
407 # found the last unclosed parenthesis
408 break
408 break
409 else:
409 else:
410 return []
410 return []
411 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
411 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
412 ids = []
412 ids = []
413 isId = re.compile(r'\w+$').match
413 isId = re.compile(r'\w+$').match
414 while True:
414 while True:
415 try:
415 try:
416 ids.append(iterTokens.next())
416 ids.append(iterTokens.next())
417 if not isId(ids[-1]):
417 if not isId(ids[-1]):
418 ids.pop(); break
418 ids.pop(); break
419 if not iterTokens.next() == '.':
419 if not iterTokens.next() == '.':
420 break
420 break
421 except StopIteration:
421 except StopIteration:
422 break
422 break
423 # lookup the candidate callable matches either using global_matches
423 # lookup the candidate callable matches either using global_matches
424 # or attr_matches for dotted names
424 # or attr_matches for dotted names
425 if len(ids) == 1:
425 if len(ids) == 1:
426 callableMatches = self.global_matches(ids[0])
426 callableMatches = self.global_matches(ids[0])
427 else:
427 else:
428 callableMatches = self.attr_matches('.'.join(ids[::-1]))
428 callableMatches = self.attr_matches('.'.join(ids[::-1]))
429 argMatches = []
429 argMatches = []
430 for callableMatch in callableMatches:
430 for callableMatch in callableMatches:
431 try: namedArgs = self._default_arguments(eval(callableMatch,
431 try: namedArgs = self._default_arguments(eval(callableMatch,
432 self.namespace))
432 self.namespace))
433 except: continue
433 except: continue
434 for namedArg in namedArgs:
434 for namedArg in namedArgs:
435 if namedArg.startswith(text):
435 if namedArg.startswith(text):
436 argMatches.append("%s=" %namedArg)
436 argMatches.append("%s=" %namedArg)
437 return argMatches
437 return argMatches
438
438
439 def complete(self, text, state):
439 def complete(self, text, state):
440 """Return the next possible completion for 'text'.
440 """Return the next possible completion for 'text'.
441
441
442 This is called successively with state == 0, 1, 2, ... until it
442 This is called successively with state == 0, 1, 2, ... until it
443 returns None. The completion should begin with 'text'. """
443 returns None. The completion should begin with 'text'. """
444
444
445 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
445 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
446 magic_escape = self.magic_escape
446 magic_escape = self.magic_escape
447 magic_prefix = self.magic_prefix
447 magic_prefix = self.magic_prefix
448
448
449 try:
449 try:
450 if text.startswith(magic_escape):
450 if text.startswith(magic_escape):
451 text = text.replace(magic_escape,magic_prefix)
451 text = text.replace(magic_escape,magic_prefix)
452 elif text.startswith('~'):
452 elif text.startswith('~'):
453 text = os.path.expanduser(text)
453 text = os.path.expanduser(text)
454 if state == 0:
454 if state == 0:
455 # Extend the list of completions with the results of each
455 # Extend the list of completions with the results of each
456 # matcher, so we return results to the user from all
456 # matcher, so we return results to the user from all
457 # namespaces.
457 # namespaces.
458 if self.merge_completions:
458 if self.merge_completions:
459 self.matches = []
459 self.matches = []
460 for matcher in self.matchers:
460 for matcher in self.matchers:
461 self.matches.extend(matcher(text))
461 self.matches.extend(matcher(text))
462 else:
462 else:
463 for matcher in self.matchers:
463 for matcher in self.matchers:
464 self.matches = matcher(text)
464 self.matches = matcher(text)
465 if self.matches:
465 if self.matches:
466 break
466 break
467
467
468 try:
468 try:
469 return self.matches[state].replace(magic_prefix,magic_escape)
469 return self.matches[state].replace(magic_prefix,magic_escape)
470 except IndexError:
470 except IndexError:
471 return None
471 return None
472 except:
472 except:
473 # If completion fails, don't annoy the user.
473 # If completion fails, don't annoy the user.
474 pass
474 pass
475
475
476 except ImportError:
476 except ImportError:
477 pass # no readline support
477 pass # no readline support
478
478
479 except KeyError:
479 except KeyError:
480 pass # Windows doesn't set TERM, it doesn't matter
480 pass # Windows doesn't set TERM, it doesn't matter
481
481
482
482
483 class InputList(UserList.UserList):
483 class InputList(UserList.UserList):
484 """Class to store user input.
484 """Class to store user input.
485
485
486 It's basically a list, but slices return a string instead of a list, thus
486 It's basically a list, but slices return a string instead of a list, thus
487 allowing things like (assuming 'In' is an instance):
487 allowing things like (assuming 'In' is an instance):
488
488
489 exec In[4:7]
489 exec In[4:7]
490
490
491 or
491 or
492
492
493 exec In[5:9] + In[14] + In[21:25]"""
493 exec In[5:9] + In[14] + In[21:25]"""
494
494
495 def __getslice__(self,i,j):
495 def __getslice__(self,i,j):
496 return ''.join(UserList.UserList.__getslice__(self,i,j))
496 return ''.join(UserList.UserList.__getslice__(self,i,j))
497
497
498 #****************************************************************************
498 #****************************************************************************
499 # Local use exceptions
499 # Local use exceptions
500 class SpaceInInput(exceptions.Exception):
500 class SpaceInInput(exceptions.Exception):
501 pass
501 pass
502
502
503 #****************************************************************************
503 #****************************************************************************
504 # Main IPython class
504 # Main IPython class
505
505
506 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
506 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
507 """An enhanced console for Python."""
507 """An enhanced console for Python."""
508
508
509 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
509 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
510 user_ns = None,user_global_ns=None,banner2='',
510 user_ns = None,user_global_ns=None,banner2='',
511 custom_exceptions=((),None)):
511 custom_exceptions=((),None),embedded=False):
512
512
513 # Put a reference to self in builtins so that any form of embedded or
513 # Put a reference to self in builtins so that any form of embedded or
514 # imported code can test for being inside IPython.
514 # imported code can test for being inside IPython.
515 __builtin__.__IPYTHON__ = self
515 __builtin__.__IPYTHON__ = self
516
516
517 # And load into builtins ipmagic/ipalias as well
517 # And load into builtins ipmagic/ipalias as well
518 __builtin__.ipmagic = ipmagic
518 __builtin__.ipmagic = ipmagic
519 __builtin__.ipalias = ipalias
519 __builtin__.ipalias = ipalias
520
520
521 # Add to __builtin__ other parts of IPython's public API
521 # Add to __builtin__ other parts of IPython's public API
522 __builtin__.ip_set_hook = self.set_hook
522 __builtin__.ip_set_hook = self.set_hook
523
523
524 # Keep in the builtins a flag for when IPython is active. We set it
524 # Keep in the builtins a flag for when IPython is active. We set it
525 # with setdefault so that multiple nested IPythons don't clobber one
525 # with setdefault so that multiple nested IPythons don't clobber one
526 # another. Each will increase its value by one upon being activated,
526 # another. Each will increase its value by one upon being activated,
527 # which also gives us a way to determine the nesting level.
527 # which also gives us a way to determine the nesting level.
528 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
528 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
529
529
530 # Inform the user of ipython's fast exit magics.
530 # Inform the user of ipython's fast exit magics.
531 _exit = ' Use %Exit or %Quit to exit without confirmation.'
531 _exit = ' Use %Exit or %Quit to exit without confirmation.'
532 __builtin__.exit += _exit
532 __builtin__.exit += _exit
533 __builtin__.quit += _exit
533 __builtin__.quit += _exit
534
534
535 # We need to know whether the instance is meant for embedding, since
536 # global/local namespaces need to be handled differently in that case
537 self.embedded = embedded
538
535 # compiler command
539 # compiler command
536 self.compile = CommandCompiler()
540 self.compile = CommandCompiler()
537
541
538 # User input buffer
542 # User input buffer
539 self.buffer = []
543 self.buffer = []
540
544
541 # Default name given in compilation of code
545 # Default name given in compilation of code
542 self.filename = '<ipython console>'
546 self.filename = '<ipython console>'
543
547
544 # Create the namespace where the user will operate. user_ns is
548 # Create the namespace where the user will operate. user_ns is
545 # normally the only one used, and it is passed to the exec calls as
549 # normally the only one used, and it is passed to the exec calls as
546 # the locals argument. But we do carry a user_global_ns namespace
550 # the locals argument. But we do carry a user_global_ns namespace
547 # given as the exec 'globals' argument, This is useful in embedding
551 # given as the exec 'globals' argument, This is useful in embedding
548 # situations where the ipython shell opens in a context where the
552 # situations where the ipython shell opens in a context where the
549 # distinction between locals and globals is meaningful.
553 # distinction between locals and globals is meaningful.
550
554
551 # FIXME. For some strange reason, __builtins__ is showing up at user
555 # FIXME. For some strange reason, __builtins__ is showing up at user
552 # level as a dict instead of a module. This is a manual fix, but I
556 # level as a dict instead of a module. This is a manual fix, but I
553 # should really track down where the problem is coming from. Alex
557 # should really track down where the problem is coming from. Alex
554 # Schmolck reported this problem first.
558 # Schmolck reported this problem first.
555
559
556 # A useful post by Alex Martelli on this topic:
560 # A useful post by Alex Martelli on this topic:
557 # Re: inconsistent value from __builtins__
561 # Re: inconsistent value from __builtins__
558 # Von: Alex Martelli <aleaxit@yahoo.com>
562 # Von: Alex Martelli <aleaxit@yahoo.com>
559 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
563 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
560 # Gruppen: comp.lang.python
564 # Gruppen: comp.lang.python
561 # Referenzen: 1
565 # Referenzen: 1
562
566
563 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
567 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
564 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
568 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
565 # > <type 'dict'>
569 # > <type 'dict'>
566 # > >>> print type(__builtins__)
570 # > >>> print type(__builtins__)
567 # > <type 'module'>
571 # > <type 'module'>
568 # > Is this difference in return value intentional?
572 # > Is this difference in return value intentional?
569
573
570 # Well, it's documented that '__builtins__' can be either a dictionary
574 # Well, it's documented that '__builtins__' can be either a dictionary
571 # or a module, and it's been that way for a long time. Whether it's
575 # or a module, and it's been that way for a long time. Whether it's
572 # intentional (or sensible), I don't know. In any case, the idea is that
576 # intentional (or sensible), I don't know. In any case, the idea is that
573 # if you need to access the built-in namespace directly, you should start
577 # if you need to access the built-in namespace directly, you should start
574 # with "import __builtin__" (note, no 's') which will definitely give you
578 # with "import __builtin__" (note, no 's') which will definitely give you
575 # a module. Yeah, it's somewhat confusing:-(.
579 # a module. Yeah, it's somewhat confusing:-(.
576
580
577 if user_ns is None:
581 if user_ns is None:
578 # Set __name__ to __main__ to better match the behavior of the
582 # Set __name__ to __main__ to better match the behavior of the
579 # normal interpreter.
583 # normal interpreter.
580 user_ns = {'__name__' :'__main__',
584 user_ns = {'__name__' :'__main__',
581 '__builtins__' : __builtin__,
585 '__builtins__' : __builtin__,
582 }
586 }
583
587
584 if user_global_ns is None:
588 if user_global_ns is None:
585 user_global_ns = {}
589 user_global_ns = {}
586
590
587 # assign namespaces
591 # Assign namespaces
592 # This is the namespace where all normal user variables live
588 self.user_ns = user_ns
593 self.user_ns = user_ns
594 # Embedded instances require a separate namespace for globals.
595 # Normally this one is unused by non-embedded instances.
589 self.user_global_ns = user_global_ns
596 self.user_global_ns = user_global_ns
597 # A namespace to keep track of internal data structures to prevent
598 # them from cluttering user-visible stuff. Will be updated later
599 self.internal_ns = {}
600
601 # Namespace of system aliases. Each entry in the alias
602 # table must be a 2-tuple of the form (N,name), where N is the number
603 # of positional arguments of the alias.
604 self.alias_table = {}
605
606 # A table holding all the namespaces IPython deals with, so that
607 # introspection facilities can search easily.
608 self.ns_table = {'user':user_ns,
609 'user_global':user_global_ns,
610 'alias':self.alias_table,
611 'internal':self.internal_ns,
612 'builtin':__builtin__.__dict__
613 }
590
614
591 # The user namespace MUST have a pointer to the shell itself.
615 # The user namespace MUST have a pointer to the shell itself.
592 self.user_ns[name] = self
616 self.user_ns[name] = self
593
617
594 # We need to insert into sys.modules something that looks like a
618 # We need to insert into sys.modules something that looks like a
595 # module but which accesses the IPython namespace, for shelve and
619 # module but which accesses the IPython namespace, for shelve and
596 # pickle to work interactively. Normally they rely on getting
620 # pickle to work interactively. Normally they rely on getting
597 # everything out of __main__, but for embedding purposes each IPython
621 # everything out of __main__, but for embedding purposes each IPython
598 # instance has its own private namespace, so we can't go shoving
622 # instance has its own private namespace, so we can't go shoving
599 # everything into __main__.
623 # everything into __main__.
600
624
601 try:
625 try:
602 main_name = self.user_ns['__name__']
626 main_name = self.user_ns['__name__']
603 except KeyError:
627 except KeyError:
604 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
628 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
605 else:
629 else:
606 #print "pickle hack in place" # dbg
630 #print "pickle hack in place" # dbg
607 sys.modules[main_name] = FakeModule(self.user_ns)
631 sys.modules[main_name] = FakeModule(self.user_ns)
608
632
609 # List of input with multi-line handling.
633 # List of input with multi-line handling.
610 # Fill its zero entry, user counter starts at 1
634 # Fill its zero entry, user counter starts at 1
611 self.input_hist = InputList(['\n'])
635 self.input_hist = InputList(['\n'])
612
636
613 # list of visited directories
637 # list of visited directories
614 try:
638 try:
615 self.dir_hist = [os.getcwd()]
639 self.dir_hist = [os.getcwd()]
616 except IOError, e:
640 except IOError, e:
617 self.dir_hist = []
641 self.dir_hist = []
618
642
619 # dict of output history
643 # dict of output history
620 self.output_hist = {}
644 self.output_hist = {}
621
645
622 # dict of names to be treated as system aliases. Each entry in the
623 # alias table must be a 2-tuple of the form (N,name), where N is the
624 # number of positional arguments of the alias.
625 self.alias_table = {}
626
627 # dict of things NOT to alias (keywords, builtins and some special magics)
646 # dict of things NOT to alias (keywords, builtins and some special magics)
628 no_alias = {}
647 no_alias = {}
629 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
648 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
630 for key in keyword.kwlist + no_alias_magics:
649 for key in keyword.kwlist + no_alias_magics:
631 no_alias[key] = 1
650 no_alias[key] = 1
632 no_alias.update(__builtin__.__dict__)
651 no_alias.update(__builtin__.__dict__)
633 self.no_alias = no_alias
652 self.no_alias = no_alias
634
653
635 # make global variables for user access to these
654 # make global variables for user access to these
636 self.user_ns['_ih'] = self.input_hist
655 self.user_ns['_ih'] = self.input_hist
637 self.user_ns['_oh'] = self.output_hist
656 self.user_ns['_oh'] = self.output_hist
638 self.user_ns['_dh'] = self.dir_hist
657 self.user_ns['_dh'] = self.dir_hist
639
658
640 # user aliases to input and output histories
659 # user aliases to input and output histories
641 self.user_ns['In'] = self.input_hist
660 self.user_ns['In'] = self.input_hist
642 self.user_ns['Out'] = self.output_hist
661 self.user_ns['Out'] = self.output_hist
643
662
644 # Store the actual shell's name
663 # Store the actual shell's name
645 self.name = name
664 self.name = name
646
665
647 # Object variable to store code object waiting execution. This is
666 # Object variable to store code object waiting execution. This is
648 # used mainly by the multithreaded shells, but it can come in handy in
667 # used mainly by the multithreaded shells, but it can come in handy in
649 # other situations. No need to use a Queue here, since it's a single
668 # other situations. No need to use a Queue here, since it's a single
650 # item which gets cleared once run.
669 # item which gets cleared once run.
651 self.code_to_run = None
670 self.code_to_run = None
652
671
653 # Job manager (for jobs run as background threads)
672 # Job manager (for jobs run as background threads)
654 self.jobs = BackgroundJobManager()
673 self.jobs = BackgroundJobManager()
655 # Put the job manager into builtins so it's always there.
674 # Put the job manager into builtins so it's always there.
656 __builtin__.jobs = self.jobs
675 __builtin__.jobs = self.jobs
657
676
658 # escapes for automatic behavior on the command line
677 # escapes for automatic behavior on the command line
659 self.ESC_SHELL = '!'
678 self.ESC_SHELL = '!'
660 self.ESC_HELP = '?'
679 self.ESC_HELP = '?'
661 self.ESC_MAGIC = '%'
680 self.ESC_MAGIC = '%'
662 self.ESC_QUOTE = ','
681 self.ESC_QUOTE = ','
663 self.ESC_QUOTE2 = ';'
682 self.ESC_QUOTE2 = ';'
664 self.ESC_PAREN = '/'
683 self.ESC_PAREN = '/'
665
684
666 # And their associated handlers
685 # And their associated handlers
667 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
686 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
668 self.ESC_QUOTE:self.handle_auto,
687 self.ESC_QUOTE:self.handle_auto,
669 self.ESC_QUOTE2:self.handle_auto,
688 self.ESC_QUOTE2:self.handle_auto,
670 self.ESC_MAGIC:self.handle_magic,
689 self.ESC_MAGIC:self.handle_magic,
671 self.ESC_HELP:self.handle_help,
690 self.ESC_HELP:self.handle_help,
672 self.ESC_SHELL:self.handle_shell_escape,
691 self.ESC_SHELL:self.handle_shell_escape,
673 }
692 }
674
693
675 # class initializations
694 # class initializations
676 Logger.__init__(self,log_ns = self.user_ns)
695 Logger.__init__(self,log_ns = self.user_ns)
677 Magic.__init__(self,self)
696 Magic.__init__(self,self)
678
697
679 # an ugly hack to get a pointer to the shell, so I can start writing
698 # an ugly hack to get a pointer to the shell, so I can start writing
680 # magic code via this pointer instead of the current mixin salad.
699 # magic code via this pointer instead of the current mixin salad.
681 Magic.set_shell(self,self)
700 Magic.set_shell(self,self)
682
701
683 # Python source parser/formatter for syntax highlighting
702 # Python source parser/formatter for syntax highlighting
684 pyformat = Parser().format
703 pyformat = Parser().format
685 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
704 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
686
705
687 # hooks holds pointers used for user-side customizations
706 # hooks holds pointers used for user-side customizations
688 self.hooks = Struct()
707 self.hooks = Struct()
689
708
690 # Set all default hooks, defined in the IPython.hooks module.
709 # Set all default hooks, defined in the IPython.hooks module.
691 hooks = IPython.hooks
710 hooks = IPython.hooks
692 for hook_name in hooks.__all__:
711 for hook_name in hooks.__all__:
693 self.set_hook(hook_name,getattr(hooks,hook_name))
712 self.set_hook(hook_name,getattr(hooks,hook_name))
694
713
695 # Flag to mark unconditional exit
714 # Flag to mark unconditional exit
696 self.exit_now = False
715 self.exit_now = False
697
716
698 self.usage_min = """\
717 self.usage_min = """\
699 An enhanced console for Python.
718 An enhanced console for Python.
700 Some of its features are:
719 Some of its features are:
701 - Readline support if the readline library is present.
720 - Readline support if the readline library is present.
702 - Tab completion in the local namespace.
721 - Tab completion in the local namespace.
703 - Logging of input, see command-line options.
722 - Logging of input, see command-line options.
704 - System shell escape via ! , eg !ls.
723 - System shell escape via ! , eg !ls.
705 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
724 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
706 - Keeps track of locally defined variables via %who, %whos.
725 - Keeps track of locally defined variables via %who, %whos.
707 - Show object information with a ? eg ?x or x? (use ?? for more info).
726 - Show object information with a ? eg ?x or x? (use ?? for more info).
708 """
727 """
709 if usage: self.usage = usage
728 if usage: self.usage = usage
710 else: self.usage = self.usage_min
729 else: self.usage = self.usage_min
711
730
712 # Storage
731 # Storage
713 self.rc = rc # This will hold all configuration information
732 self.rc = rc # This will hold all configuration information
714 self.inputcache = []
733 self.inputcache = []
715 self._boundcache = []
734 self._boundcache = []
716 self.pager = 'less'
735 self.pager = 'less'
717 # temporary files used for various purposes. Deleted at exit.
736 # temporary files used for various purposes. Deleted at exit.
718 self.tempfiles = []
737 self.tempfiles = []
719
738
720 # Keep track of readline usage (later set by init_readline)
739 # Keep track of readline usage (later set by init_readline)
721 self.has_readline = 0
740 self.has_readline = 0
722
741
723 # for pushd/popd management
742 # for pushd/popd management
724 try:
743 try:
725 self.home_dir = get_home_dir()
744 self.home_dir = get_home_dir()
726 except HomeDirError,msg:
745 except HomeDirError,msg:
727 fatal(msg)
746 fatal(msg)
728
747
729 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
748 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
730
749
731 # Functions to call the underlying shell.
750 # Functions to call the underlying shell.
732
751
733 # utility to expand user variables via Itpl
752 # utility to expand user variables via Itpl
734 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
753 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
735 self.user_ns))
754 self.user_ns))
736 # The first is similar to os.system, but it doesn't return a value,
755 # The first is similar to os.system, but it doesn't return a value,
737 # and it allows interpolation of variables in the user's namespace.
756 # and it allows interpolation of variables in the user's namespace.
738 self.system = lambda cmd: shell(self.var_expand(cmd),
757 self.system = lambda cmd: shell(self.var_expand(cmd),
739 header='IPython system call: ',
758 header='IPython system call: ',
740 verbose=self.rc.system_verbose)
759 verbose=self.rc.system_verbose)
741 # These are for getoutput and getoutputerror:
760 # These are for getoutput and getoutputerror:
742 self.getoutput = lambda cmd: \
761 self.getoutput = lambda cmd: \
743 getoutput(self.var_expand(cmd),
762 getoutput(self.var_expand(cmd),
744 header='IPython system call: ',
763 header='IPython system call: ',
745 verbose=self.rc.system_verbose)
764 verbose=self.rc.system_verbose)
746 self.getoutputerror = lambda cmd: \
765 self.getoutputerror = lambda cmd: \
747 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
766 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
748 self.user_ns)),
767 self.user_ns)),
749 header='IPython system call: ',
768 header='IPython system call: ',
750 verbose=self.rc.system_verbose)
769 verbose=self.rc.system_verbose)
751
770
752 # RegExp for splitting line contents into pre-char//first
771 # RegExp for splitting line contents into pre-char//first
753 # word-method//rest. For clarity, each group in on one line.
772 # word-method//rest. For clarity, each group in on one line.
754
773
755 # WARNING: update the regexp if the above escapes are changed, as they
774 # WARNING: update the regexp if the above escapes are changed, as they
756 # are hardwired in.
775 # are hardwired in.
757
776
758 # Don't get carried away with trying to make the autocalling catch too
777 # Don't get carried away with trying to make the autocalling catch too
759 # much: it's better to be conservative rather than to trigger hidden
778 # much: it's better to be conservative rather than to trigger hidden
760 # evals() somewhere and end up causing side effects.
779 # evals() somewhere and end up causing side effects.
761
780
762 self.line_split = re.compile(r'^([\s*,;/])'
781 self.line_split = re.compile(r'^([\s*,;/])'
763 r'([\?\w\.]+\w*\s*)'
782 r'([\?\w\.]+\w*\s*)'
764 r'(\(?.*$)')
783 r'(\(?.*$)')
765
784
766 # Original re, keep around for a while in case changes break something
785 # Original re, keep around for a while in case changes break something
767 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
786 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
768 # r'(\s*[\?\w\.]+\w*\s*)'
787 # r'(\s*[\?\w\.]+\w*\s*)'
769 # r'(\(?.*$)')
788 # r'(\(?.*$)')
770
789
771 # RegExp to identify potential function names
790 # RegExp to identify potential function names
772 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
791 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
773 # RegExp to exclude strings with this start from autocalling
792 # RegExp to exclude strings with this start from autocalling
774 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
793 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
775 # try to catch also methods for stuff in lists/tuples/dicts: off
794 # try to catch also methods for stuff in lists/tuples/dicts: off
776 # (experimental). For this to work, the line_split regexp would need
795 # (experimental). For this to work, the line_split regexp would need
777 # to be modified so it wouldn't break things at '['. That line is
796 # to be modified so it wouldn't break things at '['. That line is
778 # nasty enough that I shouldn't change it until I can test it _well_.
797 # nasty enough that I shouldn't change it until I can test it _well_.
779 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
798 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
780
799
781 # keep track of where we started running (mainly for crash post-mortem)
800 # keep track of where we started running (mainly for crash post-mortem)
782 self.starting_dir = os.getcwd()
801 self.starting_dir = os.getcwd()
783
802
784 # Attributes for Logger mixin class, make defaults here
803 # Attributes for Logger mixin class, make defaults here
785 self._dolog = 0
804 self._dolog = 0
786 self.LOG = ''
805 self.LOG = ''
787 self.LOGDEF = '.InteractiveShell.log'
806 self.LOGDEF = '.InteractiveShell.log'
788 self.LOGMODE = 'over'
807 self.LOGMODE = 'over'
789 self.LOGHEAD = Itpl(
808 self.LOGHEAD = Itpl(
790 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
809 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
791 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
810 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
792 #log# opts = $self.rc.opts
811 #log# opts = $self.rc.opts
793 #log# args = $self.rc.args
812 #log# args = $self.rc.args
794 #log# It is safe to make manual edits below here.
813 #log# It is safe to make manual edits below here.
795 #log#-----------------------------------------------------------------------
814 #log#-----------------------------------------------------------------------
796 """)
815 """)
797 # Various switches which can be set
816 # Various switches which can be set
798 self.CACHELENGTH = 5000 # this is cheap, it's just text
817 self.CACHELENGTH = 5000 # this is cheap, it's just text
799 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
818 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
800 self.banner2 = banner2
819 self.banner2 = banner2
801
820
802 # TraceBack handlers:
821 # TraceBack handlers:
803 # Need two, one for syntax errors and one for other exceptions.
822 # Need two, one for syntax errors and one for other exceptions.
804 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
823 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
805 # This one is initialized with an offset, meaning we always want to
824 # This one is initialized with an offset, meaning we always want to
806 # remove the topmost item in the traceback, which is our own internal
825 # remove the topmost item in the traceback, which is our own internal
807 # code. Valid modes: ['Plain','Context','Verbose']
826 # code. Valid modes: ['Plain','Context','Verbose']
808 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
827 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
809 color_scheme='NoColor',
828 color_scheme='NoColor',
810 tb_offset = 1)
829 tb_offset = 1)
811 # and add any custom exception handlers the user may have specified
830 # and add any custom exception handlers the user may have specified
812 self.set_custom_exc(*custom_exceptions)
831 self.set_custom_exc(*custom_exceptions)
813
832
814 # Object inspector
833 # Object inspector
815 ins_colors = OInspect.InspectColors
834 ins_colors = OInspect.InspectColors
816 code_colors = PyColorize.ANSICodeColors
835 code_colors = PyColorize.ANSICodeColors
817 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
836 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
818 self.autoindent = 0
837 self.autoindent = 0
819
838
820 # Make some aliases automatically
839 # Make some aliases automatically
821 # Prepare list of shell aliases to auto-define
840 # Prepare list of shell aliases to auto-define
822 if os.name == 'posix':
841 if os.name == 'posix':
823 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
842 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
824 'mv mv -i','rm rm -i','cp cp -i',
843 'mv mv -i','rm rm -i','cp cp -i',
825 'cat cat','less less','clear clear',
844 'cat cat','less less','clear clear',
826 # a better ls
845 # a better ls
827 'ls ls -F',
846 'ls ls -F',
828 # long ls
847 # long ls
829 'll ls -lF',
848 'll ls -lF',
830 # color ls
849 # color ls
831 'lc ls -F -o --color',
850 'lc ls -F -o --color',
832 # ls normal files only
851 # ls normal files only
833 'lf ls -F -o --color %l | grep ^-',
852 'lf ls -F -o --color %l | grep ^-',
834 # ls symbolic links
853 # ls symbolic links
835 'lk ls -F -o --color %l | grep ^l',
854 'lk ls -F -o --color %l | grep ^l',
836 # directories or links to directories,
855 # directories or links to directories,
837 'ldir ls -F -o --color %l | grep /$',
856 'ldir ls -F -o --color %l | grep /$',
838 # things which are executable
857 # things which are executable
839 'lx ls -F -o --color %l | grep ^-..x',
858 'lx ls -F -o --color %l | grep ^-..x',
840 )
859 )
841 elif os.name in ['nt','dos']:
860 elif os.name in ['nt','dos']:
842 auto_alias = ('dir dir /on', 'ls dir /on',
861 auto_alias = ('dir dir /on', 'ls dir /on',
843 'ddir dir /ad /on', 'ldir dir /ad /on',
862 'ddir dir /ad /on', 'ldir dir /ad /on',
844 'mkdir mkdir','rmdir rmdir','echo echo',
863 'mkdir mkdir','rmdir rmdir','echo echo',
845 'ren ren','cls cls','copy copy')
864 'ren ren','cls cls','copy copy')
846 else:
865 else:
847 auto_alias = ()
866 auto_alias = ()
848 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
867 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
849 # Call the actual (public) initializer
868 # Call the actual (public) initializer
850 self.init_auto_alias()
869 self.init_auto_alias()
851 # end __init__
870 # end __init__
852
871
853 def set_hook(self,name,hook):
872 def set_hook(self,name,hook):
854 """set_hook(name,hook) -> sets an internal IPython hook.
873 """set_hook(name,hook) -> sets an internal IPython hook.
855
874
856 IPython exposes some of its internal API as user-modifiable hooks. By
875 IPython exposes some of its internal API as user-modifiable hooks. By
857 resetting one of these hooks, you can modify IPython's behavior to
876 resetting one of these hooks, you can modify IPython's behavior to
858 call at runtime your own routines."""
877 call at runtime your own routines."""
859
878
860 # At some point in the future, this should validate the hook before it
879 # At some point in the future, this should validate the hook before it
861 # accepts it. Probably at least check that the hook takes the number
880 # accepts it. Probably at least check that the hook takes the number
862 # of args it's supposed to.
881 # of args it's supposed to.
863 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
882 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
864
883
865 def set_custom_exc(self,exc_tuple,handler):
884 def set_custom_exc(self,exc_tuple,handler):
866 """set_custom_exc(exc_tuple,handler)
885 """set_custom_exc(exc_tuple,handler)
867
886
868 Set a custom exception handler, which will be called if any of the
887 Set a custom exception handler, which will be called if any of the
869 exceptions in exc_tuple occur in the mainloop (specifically, in the
888 exceptions in exc_tuple occur in the mainloop (specifically, in the
870 runcode() method.
889 runcode() method.
871
890
872 Inputs:
891 Inputs:
873
892
874 - exc_tuple: a *tuple* of valid exceptions to call the defined
893 - exc_tuple: a *tuple* of valid exceptions to call the defined
875 handler for. It is very important that you use a tuple, and NOT A
894 handler for. It is very important that you use a tuple, and NOT A
876 LIST here, because of the way Python's except statement works. If
895 LIST here, because of the way Python's except statement works. If
877 you only want to trap a single exception, use a singleton tuple:
896 you only want to trap a single exception, use a singleton tuple:
878
897
879 exc_tuple == (MyCustomException,)
898 exc_tuple == (MyCustomException,)
880
899
881 - handler: this must be defined as a function with the following
900 - handler: this must be defined as a function with the following
882 basic interface: def my_handler(self,etype,value,tb).
901 basic interface: def my_handler(self,etype,value,tb).
883
902
884 This will be made into an instance method (via new.instancemethod)
903 This will be made into an instance method (via new.instancemethod)
885 of IPython itself, and it will be called if any of the exceptions
904 of IPython itself, and it will be called if any of the exceptions
886 listed in the exc_tuple are caught. If the handler is None, an
905 listed in the exc_tuple are caught. If the handler is None, an
887 internal basic one is used, which just prints basic info.
906 internal basic one is used, which just prints basic info.
888
907
889 WARNING: by putting in your own exception handler into IPython's main
908 WARNING: by putting in your own exception handler into IPython's main
890 execution loop, you run a very good chance of nasty crashes. This
909 execution loop, you run a very good chance of nasty crashes. This
891 facility should only be used if you really know what you are doing."""
910 facility should only be used if you really know what you are doing."""
892
911
893 assert type(exc_tuple)==type(()) , \
912 assert type(exc_tuple)==type(()) , \
894 "The custom exceptions must be given AS A TUPLE."
913 "The custom exceptions must be given AS A TUPLE."
895
914
896 def dummy_handler(self,etype,value,tb):
915 def dummy_handler(self,etype,value,tb):
897 print '*** Simple custom exception handler ***'
916 print '*** Simple custom exception handler ***'
898 print 'Exception type :',etype
917 print 'Exception type :',etype
899 print 'Exception value:',value
918 print 'Exception value:',value
900 print 'Traceback :',tb
919 print 'Traceback :',tb
901 print 'Source code :','\n'.join(self.buffer)
920 print 'Source code :','\n'.join(self.buffer)
902
921
903 if handler is None: handler = dummy_handler
922 if handler is None: handler = dummy_handler
904
923
905 self.CustomTB = new.instancemethod(handler,self,self.__class__)
924 self.CustomTB = new.instancemethod(handler,self,self.__class__)
906 self.custom_exceptions = exc_tuple
925 self.custom_exceptions = exc_tuple
907
926
908 def set_custom_completer(self,completer,pos=0):
927 def set_custom_completer(self,completer,pos=0):
909 """set_custom_completer(completer,pos=0)
928 """set_custom_completer(completer,pos=0)
910
929
911 Adds a new custom completer function.
930 Adds a new custom completer function.
912
931
913 The position argument (defaults to 0) is the index in the completers
932 The position argument (defaults to 0) is the index in the completers
914 list where you want the completer to be inserted."""
933 list where you want the completer to be inserted."""
915
934
916 newcomp = new.instancemethod(completer,self.Completer,
935 newcomp = new.instancemethod(completer,self.Completer,
917 self.Completer.__class__)
936 self.Completer.__class__)
918 self.Completer.matchers.insert(pos,newcomp)
937 self.Completer.matchers.insert(pos,newcomp)
919
938
920 def complete(self,text):
939 def complete(self,text):
921 """Return a sorted list of all possible completions on text.
940 """Return a sorted list of all possible completions on text.
922
941
923 Inputs:
942 Inputs:
924
943
925 - text: a string of text to be completed on.
944 - text: a string of text to be completed on.
926
945
927 This is a wrapper around the completion mechanism, similar to what
946 This is a wrapper around the completion mechanism, similar to what
928 readline does at the command line when the TAB key is hit. By
947 readline does at the command line when the TAB key is hit. By
929 exposing it as a method, it can be used by other non-readline
948 exposing it as a method, it can be used by other non-readline
930 environments (such as GUIs) for text completion.
949 environments (such as GUIs) for text completion.
931
950
932 Simple usage example:
951 Simple usage example:
933
952
934 In [1]: x = 'hello'
953 In [1]: x = 'hello'
935
954
936 In [2]: __IP.complete('x.l')
955 In [2]: __IP.complete('x.l')
937 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
956 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
938
957
939 complete = self.Completer.complete
958 complete = self.Completer.complete
940 state = 0
959 state = 0
941 # use a dict so we get unique keys, since ipyhton's multiple
960 # use a dict so we get unique keys, since ipyhton's multiple
942 # completers can return duplicates.
961 # completers can return duplicates.
943 comps = {}
962 comps = {}
944 while True:
963 while True:
945 newcomp = complete(text,state)
964 newcomp = complete(text,state)
946 if newcomp is None:
965 if newcomp is None:
947 break
966 break
948 comps[newcomp] = 1
967 comps[newcomp] = 1
949 state += 1
968 state += 1
950 outcomps = comps.keys()
969 outcomps = comps.keys()
951 outcomps.sort()
970 outcomps.sort()
952 return outcomps
971 return outcomps
953
972
954 def post_config_initialization(self):
973 def post_config_initialization(self):
955 """Post configuration init method
974 """Post configuration init method
956
975
957 This is called after the configuration files have been processed to
976 This is called after the configuration files have been processed to
958 'finalize' the initialization."""
977 'finalize' the initialization."""
959
978
979 # Load readline proper
980 if self.rc.readline:
981 self.init_readline()
982
983 # Set user colors (don't do it in the constructor above so that it doesn't
984 # crash if colors option is invalid)
985 self.magic_colors(self.rc.colors)
986
960 # dynamic data that survives through sessions
987 # dynamic data that survives through sessions
961 # XXX make the filename a config option?
988 # XXX make the filename a config option?
962 persist_base = 'persist'
989 persist_base = 'persist'
963 if self.rc.profile:
990 if self.rc.profile:
964 persist_base += '_%s' % self.rc.profile
991 persist_base += '_%s' % self.rc.profile
965 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
992 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
966
993
967 try:
994 try:
968 self.persist = pickle.load(file(self.persist_fname))
995 self.persist = pickle.load(file(self.persist_fname))
969 except:
996 except:
970 self.persist = {}
997 self.persist = {}
971
998
972 def init_auto_alias(self):
999 def init_auto_alias(self):
973 """Define some aliases automatically.
1000 """Define some aliases automatically.
974
1001
975 These are ALL parameter-less aliases"""
1002 These are ALL parameter-less aliases"""
976 for alias,cmd in self.auto_alias:
1003 for alias,cmd in self.auto_alias:
977 self.alias_table[alias] = (0,cmd)
1004 self.alias_table[alias] = (0,cmd)
978
1005
979 def alias_table_validate(self,verbose=0):
1006 def alias_table_validate(self,verbose=0):
980 """Update information about the alias table.
1007 """Update information about the alias table.
981
1008
982 In particular, make sure no Python keywords/builtins are in it."""
1009 In particular, make sure no Python keywords/builtins are in it."""
983
1010
984 no_alias = self.no_alias
1011 no_alias = self.no_alias
985 for k in self.alias_table.keys():
1012 for k in self.alias_table.keys():
986 if k in no_alias:
1013 if k in no_alias:
987 del self.alias_table[k]
1014 del self.alias_table[k]
988 if verbose:
1015 if verbose:
989 print ("Deleting alias <%s>, it's a Python "
1016 print ("Deleting alias <%s>, it's a Python "
990 "keyword or builtin." % k)
1017 "keyword or builtin." % k)
991
1018
992 def set_autoindent(self,value=None):
1019 def set_autoindent(self,value=None):
993 """Set the autoindent flag, checking for readline support.
1020 """Set the autoindent flag, checking for readline support.
994
1021
995 If called with no arguments, it acts as a toggle."""
1022 If called with no arguments, it acts as a toggle."""
996
1023
997 if not self.has_readline:
1024 if not self.has_readline:
998 if os.name == 'posix':
1025 if os.name == 'posix':
999 warn("The auto-indent feature requires the readline library")
1026 warn("The auto-indent feature requires the readline library")
1000 self.autoindent = 0
1027 self.autoindent = 0
1001 return
1028 return
1002 if value is None:
1029 if value is None:
1003 self.autoindent = not self.autoindent
1030 self.autoindent = not self.autoindent
1004 else:
1031 else:
1005 self.autoindent = value
1032 self.autoindent = value
1006
1033
1007 def rc_set_toggle(self,rc_field,value=None):
1034 def rc_set_toggle(self,rc_field,value=None):
1008 """Set or toggle a field in IPython's rc config. structure.
1035 """Set or toggle a field in IPython's rc config. structure.
1009
1036
1010 If called with no arguments, it acts as a toggle.
1037 If called with no arguments, it acts as a toggle.
1011
1038
1012 If called with a non-existent field, the resulting AttributeError
1039 If called with a non-existent field, the resulting AttributeError
1013 exception will propagate out."""
1040 exception will propagate out."""
1014
1041
1015 rc_val = getattr(self.rc,rc_field)
1042 rc_val = getattr(self.rc,rc_field)
1016 if value is None:
1043 if value is None:
1017 value = not rc_val
1044 value = not rc_val
1018 setattr(self.rc,rc_field,value)
1045 setattr(self.rc,rc_field,value)
1019
1046
1020 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1047 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1021 """Install the user configuration directory.
1048 """Install the user configuration directory.
1022
1049
1023 Can be called when running for the first time or to upgrade the user's
1050 Can be called when running for the first time or to upgrade the user's
1024 .ipython/ directory with the mode parameter. Valid modes are 'install'
1051 .ipython/ directory with the mode parameter. Valid modes are 'install'
1025 and 'upgrade'."""
1052 and 'upgrade'."""
1026
1053
1027 def wait():
1054 def wait():
1028 try:
1055 try:
1029 raw_input("Please press <RETURN> to start IPython.")
1056 raw_input("Please press <RETURN> to start IPython.")
1030 except EOFError:
1057 except EOFError:
1031 print >> Term.cout
1058 print >> Term.cout
1032 print '*'*70
1059 print '*'*70
1033
1060
1034 cwd = os.getcwd() # remember where we started
1061 cwd = os.getcwd() # remember where we started
1035 glb = glob.glob
1062 glb = glob.glob
1036 print '*'*70
1063 print '*'*70
1037 if mode == 'install':
1064 if mode == 'install':
1038 print \
1065 print \
1039 """Welcome to IPython. I will try to create a personal configuration directory
1066 """Welcome to IPython. I will try to create a personal configuration directory
1040 where you can customize many aspects of IPython's functionality in:\n"""
1067 where you can customize many aspects of IPython's functionality in:\n"""
1041 else:
1068 else:
1042 print 'I am going to upgrade your configuration in:'
1069 print 'I am going to upgrade your configuration in:'
1043
1070
1044 print ipythondir
1071 print ipythondir
1045
1072
1046 rcdirend = os.path.join('IPython','UserConfig')
1073 rcdirend = os.path.join('IPython','UserConfig')
1047 cfg = lambda d: os.path.join(d,rcdirend)
1074 cfg = lambda d: os.path.join(d,rcdirend)
1048 try:
1075 try:
1049 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1076 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1050 except IOError:
1077 except IOError:
1051 warning = """
1078 warning = """
1052 Installation error. IPython's directory was not found.
1079 Installation error. IPython's directory was not found.
1053
1080
1054 Check the following:
1081 Check the following:
1055
1082
1056 The ipython/IPython directory should be in a directory belonging to your
1083 The ipython/IPython directory should be in a directory belonging to your
1057 PYTHONPATH environment variable (that is, it should be in a directory
1084 PYTHONPATH environment variable (that is, it should be in a directory
1058 belonging to sys.path). You can copy it explicitly there or just link to it.
1085 belonging to sys.path). You can copy it explicitly there or just link to it.
1059
1086
1060 IPython will proceed with builtin defaults.
1087 IPython will proceed with builtin defaults.
1061 """
1088 """
1062 warn(warning)
1089 warn(warning)
1063 wait()
1090 wait()
1064 return
1091 return
1065
1092
1066 if mode == 'install':
1093 if mode == 'install':
1067 try:
1094 try:
1068 shutil.copytree(rcdir,ipythondir)
1095 shutil.copytree(rcdir,ipythondir)
1069 os.chdir(ipythondir)
1096 os.chdir(ipythondir)
1070 rc_files = glb("ipythonrc*")
1097 rc_files = glb("ipythonrc*")
1071 for rc_file in rc_files:
1098 for rc_file in rc_files:
1072 os.rename(rc_file,rc_file+rc_suffix)
1099 os.rename(rc_file,rc_file+rc_suffix)
1073 except:
1100 except:
1074 warning = """
1101 warning = """
1075
1102
1076 There was a problem with the installation:
1103 There was a problem with the installation:
1077 %s
1104 %s
1078 Try to correct it or contact the developers if you think it's a bug.
1105 Try to correct it or contact the developers if you think it's a bug.
1079 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1106 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1080 warn(warning)
1107 warn(warning)
1081 wait()
1108 wait()
1082 return
1109 return
1083
1110
1084 elif mode == 'upgrade':
1111 elif mode == 'upgrade':
1085 try:
1112 try:
1086 os.chdir(ipythondir)
1113 os.chdir(ipythondir)
1087 except:
1114 except:
1088 print """
1115 print """
1089 Can not upgrade: changing to directory %s failed. Details:
1116 Can not upgrade: changing to directory %s failed. Details:
1090 %s
1117 %s
1091 """ % (ipythondir,sys.exc_info()[1])
1118 """ % (ipythondir,sys.exc_info()[1])
1092 wait()
1119 wait()
1093 return
1120 return
1094 else:
1121 else:
1095 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1122 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1096 for new_full_path in sources:
1123 for new_full_path in sources:
1097 new_filename = os.path.basename(new_full_path)
1124 new_filename = os.path.basename(new_full_path)
1098 if new_filename.startswith('ipythonrc'):
1125 if new_filename.startswith('ipythonrc'):
1099 new_filename = new_filename + rc_suffix
1126 new_filename = new_filename + rc_suffix
1100 # The config directory should only contain files, skip any
1127 # The config directory should only contain files, skip any
1101 # directories which may be there (like CVS)
1128 # directories which may be there (like CVS)
1102 if os.path.isdir(new_full_path):
1129 if os.path.isdir(new_full_path):
1103 continue
1130 continue
1104 if os.path.exists(new_filename):
1131 if os.path.exists(new_filename):
1105 old_file = new_filename+'.old'
1132 old_file = new_filename+'.old'
1106 if os.path.exists(old_file):
1133 if os.path.exists(old_file):
1107 os.remove(old_file)
1134 os.remove(old_file)
1108 os.rename(new_filename,old_file)
1135 os.rename(new_filename,old_file)
1109 shutil.copy(new_full_path,new_filename)
1136 shutil.copy(new_full_path,new_filename)
1110 else:
1137 else:
1111 raise ValueError,'unrecognized mode for install:',`mode`
1138 raise ValueError,'unrecognized mode for install:',`mode`
1112
1139
1113 # Fix line-endings to those native to each platform in the config
1140 # Fix line-endings to those native to each platform in the config
1114 # directory.
1141 # directory.
1115 try:
1142 try:
1116 os.chdir(ipythondir)
1143 os.chdir(ipythondir)
1117 except:
1144 except:
1118 print """
1145 print """
1119 Problem: changing to directory %s failed.
1146 Problem: changing to directory %s failed.
1120 Details:
1147 Details:
1121 %s
1148 %s
1122
1149
1123 Some configuration files may have incorrect line endings. This should not
1150 Some configuration files may have incorrect line endings. This should not
1124 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1151 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1125 wait()
1152 wait()
1126 else:
1153 else:
1127 for fname in glb('ipythonrc*'):
1154 for fname in glb('ipythonrc*'):
1128 try:
1155 try:
1129 native_line_ends(fname,backup=0)
1156 native_line_ends(fname,backup=0)
1130 except IOError:
1157 except IOError:
1131 pass
1158 pass
1132
1159
1133 if mode == 'install':
1160 if mode == 'install':
1134 print """
1161 print """
1135 Successful installation!
1162 Successful installation!
1136
1163
1137 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1164 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1138 IPython manual (there are both HTML and PDF versions supplied with the
1165 IPython manual (there are both HTML and PDF versions supplied with the
1139 distribution) to make sure that your system environment is properly configured
1166 distribution) to make sure that your system environment is properly configured
1140 to take advantage of IPython's features."""
1167 to take advantage of IPython's features."""
1141 else:
1168 else:
1142 print """
1169 print """
1143 Successful upgrade!
1170 Successful upgrade!
1144
1171
1145 All files in your directory:
1172 All files in your directory:
1146 %(ipythondir)s
1173 %(ipythondir)s
1147 which would have been overwritten by the upgrade were backed up with a .old
1174 which would have been overwritten by the upgrade were backed up with a .old
1148 extension. If you had made particular customizations in those files you may
1175 extension. If you had made particular customizations in those files you may
1149 want to merge them back into the new files.""" % locals()
1176 want to merge them back into the new files.""" % locals()
1150 wait()
1177 wait()
1151 os.chdir(cwd)
1178 os.chdir(cwd)
1152 # end user_setup()
1179 # end user_setup()
1153
1180
1154 def atexit_operations(self):
1181 def atexit_operations(self):
1155 """This will be executed at the time of exit.
1182 """This will be executed at the time of exit.
1156
1183
1157 Saving of persistent data should be performed here. """
1184 Saving of persistent data should be performed here. """
1158
1185
1159 # input history
1186 # input history
1160 self.savehist()
1187 self.savehist()
1161
1188
1162 # Cleanup all tempfiles left around
1189 # Cleanup all tempfiles left around
1163 for tfile in self.tempfiles:
1190 for tfile in self.tempfiles:
1164 try:
1191 try:
1165 os.unlink(tfile)
1192 os.unlink(tfile)
1166 except OSError:
1193 except OSError:
1167 pass
1194 pass
1168
1195
1169 # save the "persistent data" catch-all dictionary
1196 # save the "persistent data" catch-all dictionary
1170 try:
1197 try:
1171 pickle.dump(self.persist, open(self.persist_fname,"w"))
1198 pickle.dump(self.persist, open(self.persist_fname,"w"))
1172 except:
1199 except:
1173 print "*** ERROR *** persistent data saving failed."
1200 print "*** ERROR *** persistent data saving failed."
1174
1201
1175 def savehist(self):
1202 def savehist(self):
1176 """Save input history to a file (via readline library)."""
1203 """Save input history to a file (via readline library)."""
1177 try:
1204 try:
1178 self.readline.write_history_file(self.histfile)
1205 self.readline.write_history_file(self.histfile)
1179 except:
1206 except:
1180 print 'Unable to save IPython command history to file: ' + \
1207 print 'Unable to save IPython command history to file: ' + \
1181 `self.histfile`
1208 `self.histfile`
1182
1209
1183 def pre_readline(self):
1210 def pre_readline(self):
1184 """readline hook to be used at the start of each line.
1211 """readline hook to be used at the start of each line.
1185
1212
1186 Currently it handles auto-indent only."""
1213 Currently it handles auto-indent only."""
1187
1214
1188 self.readline.insert_text(' '* self.readline_indent)
1215 self.readline.insert_text(' '* self.readline_indent)
1189
1216
1190 def init_readline(self):
1217 def init_readline(self):
1191 """Command history completion/saving/reloading."""
1218 """Command history completion/saving/reloading."""
1192 try:
1219 try:
1193 import readline
1220 import readline
1194 self.Completer = MagicCompleter(self,
1221 self.Completer = MagicCompleter(self,
1195 self.user_ns,
1222 self.user_ns,
1196 self.rc.readline_omit__names,
1223 self.rc.readline_omit__names,
1197 self.alias_table)
1224 self.alias_table)
1198 except ImportError,NameError:
1225 except ImportError,NameError:
1199 # If FlexCompleter failed to import, MagicCompleter won't be
1226 # If FlexCompleter failed to import, MagicCompleter won't be
1200 # defined. This can happen because of a problem with readline
1227 # defined. This can happen because of a problem with readline
1201 self.has_readline = 0
1228 self.has_readline = 0
1202 # no point in bugging windows users with this every time:
1229 # no point in bugging windows users with this every time:
1203 if os.name == 'posix':
1230 if os.name == 'posix':
1204 warn('Readline services not available on this platform.')
1231 warn('Readline services not available on this platform.')
1205 else:
1232 else:
1206 import atexit
1233 import atexit
1207
1234
1208 # Platform-specific configuration
1235 # Platform-specific configuration
1209 if os.name == 'nt':
1236 if os.name == 'nt':
1210 # readline under Windows modifies the default exit behavior
1237 # readline under Windows modifies the default exit behavior
1211 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1238 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1212 __builtin__.exit = __builtin__.quit = \
1239 __builtin__.exit = __builtin__.quit = \
1213 ('Use Ctrl-D (i.e. EOF) to exit. '
1240 ('Use Ctrl-D (i.e. EOF) to exit. '
1214 'Use %Exit or %Quit to exit without confirmation.')
1241 'Use %Exit or %Quit to exit without confirmation.')
1215 self.readline_startup_hook = readline.set_pre_input_hook
1242 self.readline_startup_hook = readline.set_pre_input_hook
1216 else:
1243 else:
1217 self.readline_startup_hook = readline.set_startup_hook
1244 self.readline_startup_hook = readline.set_startup_hook
1218
1245
1219 # Load user's initrc file (readline config)
1246 # Load user's initrc file (readline config)
1220 inputrc_name = os.environ.get('INPUTRC')
1247 inputrc_name = os.environ.get('INPUTRC')
1221 if inputrc_name is None:
1248 if inputrc_name is None:
1222 home_dir = get_home_dir()
1249 home_dir = get_home_dir()
1223 if home_dir is not None:
1250 if home_dir is not None:
1224 inputrc_name = os.path.join(home_dir,'.inputrc')
1251 inputrc_name = os.path.join(home_dir,'.inputrc')
1225 if os.path.isfile(inputrc_name):
1252 if os.path.isfile(inputrc_name):
1226 try:
1253 try:
1227 readline.read_init_file(inputrc_name)
1254 readline.read_init_file(inputrc_name)
1228 except:
1255 except:
1229 warn('Problems reading readline initialization file <%s>'
1256 warn('Problems reading readline initialization file <%s>'
1230 % inputrc_name)
1257 % inputrc_name)
1231
1258
1232 self.has_readline = 1
1259 self.has_readline = 1
1233 self.readline = readline
1260 self.readline = readline
1234 self.readline_indent = 0 # for auto-indenting via readline
1261 self.readline_indent = 0 # for auto-indenting via readline
1235 # save this in sys so embedded copies can restore it properly
1262 # save this in sys so embedded copies can restore it properly
1236 sys.ipcompleter = self.Completer.complete
1263 sys.ipcompleter = self.Completer.complete
1237 readline.set_completer(self.Completer.complete)
1264 readline.set_completer(self.Completer.complete)
1238
1265
1239 # Configure readline according to user's prefs
1266 # Configure readline according to user's prefs
1240 for rlcommand in self.rc.readline_parse_and_bind:
1267 for rlcommand in self.rc.readline_parse_and_bind:
1241 readline.parse_and_bind(rlcommand)
1268 readline.parse_and_bind(rlcommand)
1242
1269
1243 # remove some chars from the delimiters list
1270 # remove some chars from the delimiters list
1244 delims = readline.get_completer_delims()
1271 delims = readline.get_completer_delims()
1245 delims = delims.translate(string._idmap,
1272 delims = delims.translate(string._idmap,
1246 self.rc.readline_remove_delims)
1273 self.rc.readline_remove_delims)
1247 readline.set_completer_delims(delims)
1274 readline.set_completer_delims(delims)
1248 # otherwise we end up with a monster history after a while:
1275 # otherwise we end up with a monster history after a while:
1249 readline.set_history_length(1000)
1276 readline.set_history_length(1000)
1250 try:
1277 try:
1251 #print '*** Reading readline history' # dbg
1278 #print '*** Reading readline history' # dbg
1252 readline.read_history_file(self.histfile)
1279 readline.read_history_file(self.histfile)
1253 except IOError:
1280 except IOError:
1254 pass # It doesn't exist yet.
1281 pass # It doesn't exist yet.
1255
1282
1256 atexit.register(self.atexit_operations)
1283 atexit.register(self.atexit_operations)
1257 del atexit
1284 del atexit
1258
1285
1259 # Configure auto-indent for all platforms
1286 # Configure auto-indent for all platforms
1260 self.set_autoindent(self.rc.autoindent)
1287 self.set_autoindent(self.rc.autoindent)
1261
1288
1262 def showsyntaxerror(self, filename=None):
1289 def showsyntaxerror(self, filename=None):
1263 """Display the syntax error that just occurred.
1290 """Display the syntax error that just occurred.
1264
1291
1265 This doesn't display a stack trace because there isn't one.
1292 This doesn't display a stack trace because there isn't one.
1266
1293
1267 If a filename is given, it is stuffed in the exception instead
1294 If a filename is given, it is stuffed in the exception instead
1268 of what was there before (because Python's parser always uses
1295 of what was there before (because Python's parser always uses
1269 "<string>" when reading from a string).
1296 "<string>" when reading from a string).
1270 """
1297 """
1271 type, value, sys.last_traceback = sys.exc_info()
1298 type, value, sys.last_traceback = sys.exc_info()
1272 sys.last_type = type
1299 sys.last_type = type
1273 sys.last_value = value
1300 sys.last_value = value
1274 if filename and type is SyntaxError:
1301 if filename and type is SyntaxError:
1275 # Work hard to stuff the correct filename in the exception
1302 # Work hard to stuff the correct filename in the exception
1276 try:
1303 try:
1277 msg, (dummy_filename, lineno, offset, line) = value
1304 msg, (dummy_filename, lineno, offset, line) = value
1278 except:
1305 except:
1279 # Not the format we expect; leave it alone
1306 # Not the format we expect; leave it alone
1280 pass
1307 pass
1281 else:
1308 else:
1282 # Stuff in the right filename
1309 # Stuff in the right filename
1283 try:
1310 try:
1284 # Assume SyntaxError is a class exception
1311 # Assume SyntaxError is a class exception
1285 value = SyntaxError(msg, (filename, lineno, offset, line))
1312 value = SyntaxError(msg, (filename, lineno, offset, line))
1286 except:
1313 except:
1287 # If that failed, assume SyntaxError is a string
1314 # If that failed, assume SyntaxError is a string
1288 value = msg, (filename, lineno, offset, line)
1315 value = msg, (filename, lineno, offset, line)
1289 self.SyntaxTB(type,value,[])
1316 self.SyntaxTB(type,value,[])
1290
1317
1291 def debugger(self):
1318 def debugger(self):
1292 """Call the pdb debugger."""
1319 """Call the pdb debugger."""
1293
1320
1294 if not self.rc.pdb:
1321 if not self.rc.pdb:
1295 return
1322 return
1296 pdb.pm()
1323 pdb.pm()
1297
1324
1298 def showtraceback(self,exc_tuple = None,filename=None):
1325 def showtraceback(self,exc_tuple = None,filename=None):
1299 """Display the exception that just occurred."""
1326 """Display the exception that just occurred."""
1300
1327
1301 # Though this won't be called by syntax errors in the input line,
1328 # Though this won't be called by syntax errors in the input line,
1302 # there may be SyntaxError cases whith imported code.
1329 # there may be SyntaxError cases whith imported code.
1303 if exc_tuple is None:
1330 if exc_tuple is None:
1304 type, value, tb = sys.exc_info()
1331 type, value, tb = sys.exc_info()
1305 else:
1332 else:
1306 type, value, tb = exc_tuple
1333 type, value, tb = exc_tuple
1307 if type is SyntaxError:
1334 if type is SyntaxError:
1308 self.showsyntaxerror(filename)
1335 self.showsyntaxerror(filename)
1309 else:
1336 else:
1310 sys.last_type = type
1337 sys.last_type = type
1311 sys.last_value = value
1338 sys.last_value = value
1312 sys.last_traceback = tb
1339 sys.last_traceback = tb
1313 self.InteractiveTB()
1340 self.InteractiveTB()
1314 if self.InteractiveTB.call_pdb and self.has_readline:
1341 if self.InteractiveTB.call_pdb and self.has_readline:
1315 # pdb mucks up readline, fix it back
1342 # pdb mucks up readline, fix it back
1316 self.readline.set_completer(self.Completer.complete)
1343 self.readline.set_completer(self.Completer.complete)
1317
1344
1318 def update_cache(self, line):
1345 def update_cache(self, line):
1319 """puts line into cache"""
1346 """puts line into cache"""
1320 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1347 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1321 if len(self.inputcache) >= self.CACHELENGTH:
1348 if len(self.inputcache) >= self.CACHELENGTH:
1322 self.inputcache.pop() # This not :-)
1349 self.inputcache.pop() # This not :-)
1323
1350
1324 def mainloop(self,banner=None):
1351 def mainloop(self,banner=None):
1325 """Creates the local namespace and starts the mainloop.
1352 """Creates the local namespace and starts the mainloop.
1326
1353
1327 If an optional banner argument is given, it will override the
1354 If an optional banner argument is given, it will override the
1328 internally created default banner."""
1355 internally created default banner."""
1329
1356
1330 if self.rc.c: # Emulate Python's -c option
1357 if self.rc.c: # Emulate Python's -c option
1331 self.exec_init_cmd()
1358 self.exec_init_cmd()
1332 if banner is None:
1359 if banner is None:
1333 if self.rc.banner:
1360 if self.rc.banner:
1334 banner = self.BANNER+self.banner2
1361 banner = self.BANNER+self.banner2
1335 else:
1362 else:
1336 banner = ''
1363 banner = ''
1337 self.interact(banner)
1364 self.interact(banner)
1338
1365
1339 def exec_init_cmd(self):
1366 def exec_init_cmd(self):
1340 """Execute a command given at the command line.
1367 """Execute a command given at the command line.
1341
1368
1342 This emulates Python's -c option."""
1369 This emulates Python's -c option."""
1343
1370
1344 sys.argv = ['-c']
1371 sys.argv = ['-c']
1345 self.push(self.rc.c)
1372 self.push(self.rc.c)
1346
1373
1347 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1374 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1348 """Embeds IPython into a running python program.
1375 """Embeds IPython into a running python program.
1349
1376
1350 Input:
1377 Input:
1351
1378
1352 - header: An optional header message can be specified.
1379 - header: An optional header message can be specified.
1353
1380
1354 - local_ns, global_ns: working namespaces. If given as None, the
1381 - local_ns, global_ns: working namespaces. If given as None, the
1355 IPython-initialized one is updated with __main__.__dict__, so that
1382 IPython-initialized one is updated with __main__.__dict__, so that
1356 program variables become visible but user-specific configuration
1383 program variables become visible but user-specific configuration
1357 remains possible.
1384 remains possible.
1358
1385
1359 - stack_depth: specifies how many levels in the stack to go to
1386 - stack_depth: specifies how many levels in the stack to go to
1360 looking for namespaces (when local_ns and global_ns are None). This
1387 looking for namespaces (when local_ns and global_ns are None). This
1361 allows an intermediate caller to make sure that this function gets
1388 allows an intermediate caller to make sure that this function gets
1362 the namespace from the intended level in the stack. By default (0)
1389 the namespace from the intended level in the stack. By default (0)
1363 it will get its locals and globals from the immediate caller.
1390 it will get its locals and globals from the immediate caller.
1364
1391
1365 Warning: it's possible to use this in a program which is being run by
1392 Warning: it's possible to use this in a program which is being run by
1366 IPython itself (via %run), but some funny things will happen (a few
1393 IPython itself (via %run), but some funny things will happen (a few
1367 globals get overwritten). In the future this will be cleaned up, as
1394 globals get overwritten). In the future this will be cleaned up, as
1368 there is no fundamental reason why it can't work perfectly."""
1395 there is no fundamental reason why it can't work perfectly."""
1369
1396
1370 # Get locals and globals from caller
1397 # Get locals and globals from caller
1371 if local_ns is None or global_ns is None:
1398 if local_ns is None or global_ns is None:
1372 call_frame = sys._getframe(stack_depth).f_back
1399 call_frame = sys._getframe(stack_depth).f_back
1373
1400
1374 if local_ns is None:
1401 if local_ns is None:
1375 local_ns = call_frame.f_locals
1402 local_ns = call_frame.f_locals
1376 if global_ns is None:
1403 if global_ns is None:
1377 global_ns = call_frame.f_globals
1404 global_ns = call_frame.f_globals
1378
1405
1379 # Update namespaces and fire up interpreter
1406 # Update namespaces and fire up interpreter
1380 self.user_ns = local_ns
1407 self.user_ns = local_ns
1381 self.user_global_ns = global_ns
1408 self.user_global_ns = global_ns
1382
1409
1383 # Patch for global embedding to make sure that things don't overwrite
1410 # Patch for global embedding to make sure that things don't overwrite
1384 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1411 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1385 # FIXME. Test this a bit more carefully (the if.. is new)
1412 # FIXME. Test this a bit more carefully (the if.. is new)
1386 if local_ns is None and global_ns is None:
1413 if local_ns is None and global_ns is None:
1387 self.user_global_ns.update(__main__.__dict__)
1414 self.user_global_ns.update(__main__.__dict__)
1388
1415
1389 self.interact(header)
1416 self.interact(header)
1390
1417
1391 def interact(self, banner=None):
1418 def interact(self, banner=None):
1392 """Closely emulate the interactive Python console.
1419 """Closely emulate the interactive Python console.
1393
1420
1394 The optional banner argument specify the banner to print
1421 The optional banner argument specify the banner to print
1395 before the first interaction; by default it prints a banner
1422 before the first interaction; by default it prints a banner
1396 similar to the one printed by the real Python interpreter,
1423 similar to the one printed by the real Python interpreter,
1397 followed by the current class name in parentheses (so as not
1424 followed by the current class name in parentheses (so as not
1398 to confuse this with the real interpreter -- since it's so
1425 to confuse this with the real interpreter -- since it's so
1399 close!).
1426 close!).
1400
1427
1401 """
1428 """
1402 cprt = 'Type "copyright", "credits" or "license" for more information.'
1429 cprt = 'Type "copyright", "credits" or "license" for more information.'
1403 if banner is None:
1430 if banner is None:
1404 self.write("Python %s on %s\n%s\n(%s)\n" %
1431 self.write("Python %s on %s\n%s\n(%s)\n" %
1405 (sys.version, sys.platform, cprt,
1432 (sys.version, sys.platform, cprt,
1406 self.__class__.__name__))
1433 self.__class__.__name__))
1407 else:
1434 else:
1408 self.write(banner)
1435 self.write(banner)
1409
1436
1410 more = 0
1437 more = 0
1411
1438
1412 # Mark activity in the builtins
1439 # Mark activity in the builtins
1413 __builtin__.__dict__['__IPYTHON__active'] += 1
1440 __builtin__.__dict__['__IPYTHON__active'] += 1
1414
1441
1415 # exit_now is set by a call to %Exit or %Quit
1442 # exit_now is set by a call to %Exit or %Quit
1416 while not self.exit_now:
1443 while not self.exit_now:
1417 try:
1444 try:
1418 if more:
1445 if more:
1419 prompt = self.outputcache.prompt2
1446 prompt = self.outputcache.prompt2
1420 if self.autoindent:
1447 if self.autoindent:
1421 self.readline_startup_hook(self.pre_readline)
1448 self.readline_startup_hook(self.pre_readline)
1422 else:
1449 else:
1423 prompt = self.outputcache.prompt1
1450 prompt = self.outputcache.prompt1
1424 try:
1451 try:
1425 line = self.raw_input(prompt)
1452 line = self.raw_input(prompt)
1426 if self.autoindent:
1453 if self.autoindent:
1427 self.readline_startup_hook(None)
1454 self.readline_startup_hook(None)
1428 except EOFError:
1455 except EOFError:
1429 if self.autoindent:
1456 if self.autoindent:
1430 self.readline_startup_hook(None)
1457 self.readline_startup_hook(None)
1431 self.write("\n")
1458 self.write("\n")
1432 if self.rc.confirm_exit:
1459 if self.rc.confirm_exit:
1433 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1460 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1434 break
1461 break
1435 else:
1462 else:
1436 break
1463 break
1437 else:
1464 else:
1438 more = self.push(line)
1465 more = self.push(line)
1439 # Auto-indent management
1466 # Auto-indent management
1440 if self.autoindent:
1467 if self.autoindent:
1441 if line:
1468 if line:
1442 ini_spaces = re.match('^(\s+)',line)
1469 ini_spaces = re.match('^(\s+)',line)
1443 if ini_spaces:
1470 if ini_spaces:
1444 nspaces = ini_spaces.end()
1471 nspaces = ini_spaces.end()
1445 else:
1472 else:
1446 nspaces = 0
1473 nspaces = 0
1447 self.readline_indent = nspaces
1474 self.readline_indent = nspaces
1448
1475
1449 if line[-1] == ':':
1476 if line[-1] == ':':
1450 self.readline_indent += 4
1477 self.readline_indent += 4
1451 elif re.match(r'^\s+raise|^\s+return',line):
1478 elif re.match(r'^\s+raise|^\s+return',line):
1452 self.readline_indent -= 4
1479 self.readline_indent -= 4
1453 else:
1480 else:
1454 self.readline_indent = 0
1481 self.readline_indent = 0
1455
1482
1456 except KeyboardInterrupt:
1483 except KeyboardInterrupt:
1457 self.write("\nKeyboardInterrupt\n")
1484 self.write("\nKeyboardInterrupt\n")
1458 self.resetbuffer()
1485 self.resetbuffer()
1459 more = 0
1486 more = 0
1460 # keep cache in sync with the prompt counter:
1487 # keep cache in sync with the prompt counter:
1461 self.outputcache.prompt_count -= 1
1488 self.outputcache.prompt_count -= 1
1462
1489
1463 if self.autoindent:
1490 if self.autoindent:
1464 self.readline_indent = 0
1491 self.readline_indent = 0
1465
1492
1466 except bdb.BdbQuit:
1493 except bdb.BdbQuit:
1467 warn("The Python debugger has exited with a BdbQuit exception.\n"
1494 warn("The Python debugger has exited with a BdbQuit exception.\n"
1468 "Because of how pdb handles the stack, it is impossible\n"
1495 "Because of how pdb handles the stack, it is impossible\n"
1469 "for IPython to properly format this particular exception.\n"
1496 "for IPython to properly format this particular exception.\n"
1470 "IPython will resume normal operation.")
1497 "IPython will resume normal operation.")
1471
1498
1472 # We are off again...
1499 # We are off again...
1473 __builtin__.__dict__['__IPYTHON__active'] -= 1
1500 __builtin__.__dict__['__IPYTHON__active'] -= 1
1474
1501
1475 def excepthook(self, type, value, tb):
1502 def excepthook(self, type, value, tb):
1476 """One more defense for GUI apps that call sys.excepthook.
1503 """One more defense for GUI apps that call sys.excepthook.
1477
1504
1478 GUI frameworks like wxPython trap exceptions and call
1505 GUI frameworks like wxPython trap exceptions and call
1479 sys.excepthook themselves. I guess this is a feature that
1506 sys.excepthook themselves. I guess this is a feature that
1480 enables them to keep running after exceptions that would
1507 enables them to keep running after exceptions that would
1481 otherwise kill their mainloop. This is a bother for IPython
1508 otherwise kill their mainloop. This is a bother for IPython
1482 which excepts to catch all of the program exceptions with a try:
1509 which excepts to catch all of the program exceptions with a try:
1483 except: statement.
1510 except: statement.
1484
1511
1485 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1512 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1486 any app directly invokes sys.excepthook, it will look to the user like
1513 any app directly invokes sys.excepthook, it will look to the user like
1487 IPython crashed. In order to work around this, we can disable the
1514 IPython crashed. In order to work around this, we can disable the
1488 CrashHandler and replace it with this excepthook instead, which prints a
1515 CrashHandler and replace it with this excepthook instead, which prints a
1489 regular traceback using our InteractiveTB. In this fashion, apps which
1516 regular traceback using our InteractiveTB. In this fashion, apps which
1490 call sys.excepthook will generate a regular-looking exception from
1517 call sys.excepthook will generate a regular-looking exception from
1491 IPython, and the CrashHandler will only be triggered by real IPython
1518 IPython, and the CrashHandler will only be triggered by real IPython
1492 crashes.
1519 crashes.
1493
1520
1494 This hook should be used sparingly, only in places which are not likely
1521 This hook should be used sparingly, only in places which are not likely
1495 to be true IPython errors.
1522 to be true IPython errors.
1496 """
1523 """
1497
1524
1498 self.InteractiveTB(type, value, tb, tb_offset=0)
1525 self.InteractiveTB(type, value, tb, tb_offset=0)
1499 if self.InteractiveTB.call_pdb and self.has_readline:
1526 if self.InteractiveTB.call_pdb and self.has_readline:
1500 self.readline.set_completer(self.Completer.complete)
1527 self.readline.set_completer(self.Completer.complete)
1501
1528
1502 def call_alias(self,alias,rest=''):
1529 def call_alias(self,alias,rest=''):
1503 """Call an alias given its name and the rest of the line.
1530 """Call an alias given its name and the rest of the line.
1504
1531
1505 This function MUST be given a proper alias, because it doesn't make
1532 This function MUST be given a proper alias, because it doesn't make
1506 any checks when looking up into the alias table. The caller is
1533 any checks when looking up into the alias table. The caller is
1507 responsible for invoking it only with a valid alias."""
1534 responsible for invoking it only with a valid alias."""
1508
1535
1509 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1536 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1510 nargs,cmd = self.alias_table[alias]
1537 nargs,cmd = self.alias_table[alias]
1511 # Expand the %l special to be the user's input line
1538 # Expand the %l special to be the user's input line
1512 if cmd.find('%l') >= 0:
1539 if cmd.find('%l') >= 0:
1513 cmd = cmd.replace('%l',rest)
1540 cmd = cmd.replace('%l',rest)
1514 rest = ''
1541 rest = ''
1515 if nargs==0:
1542 if nargs==0:
1516 # Simple, argument-less aliases
1543 # Simple, argument-less aliases
1517 cmd = '%s %s' % (cmd,rest)
1544 cmd = '%s %s' % (cmd,rest)
1518 else:
1545 else:
1519 # Handle aliases with positional arguments
1546 # Handle aliases with positional arguments
1520 args = rest.split(None,nargs)
1547 args = rest.split(None,nargs)
1521 if len(args)< nargs:
1548 if len(args)< nargs:
1522 error('Alias <%s> requires %s arguments, %s given.' %
1549 error('Alias <%s> requires %s arguments, %s given.' %
1523 (alias,nargs,len(args)))
1550 (alias,nargs,len(args)))
1524 return
1551 return
1525 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1552 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1526 # Now call the macro, evaluating in the user's namespace
1553 # Now call the macro, evaluating in the user's namespace
1527 try:
1554 try:
1528 self.system(cmd)
1555 self.system(cmd)
1529 except:
1556 except:
1530 self.showtraceback()
1557 self.showtraceback()
1531
1558
1532 def runlines(self,lines):
1559 def runlines(self,lines):
1533 """Run a string of one or more lines of source.
1560 """Run a string of one or more lines of source.
1534
1561
1535 This method is capable of running a string containing multiple source
1562 This method is capable of running a string containing multiple source
1536 lines, as if they had been entered at the IPython prompt. Since it
1563 lines, as if they had been entered at the IPython prompt. Since it
1537 exposes IPython's processing machinery, the given strings can contain
1564 exposes IPython's processing machinery, the given strings can contain
1538 magic calls (%magic), special shell access (!cmd), etc."""
1565 magic calls (%magic), special shell access (!cmd), etc."""
1539
1566
1540 # We must start with a clean buffer, in case this is run from an
1567 # We must start with a clean buffer, in case this is run from an
1541 # interactive IPython session (via a magic, for example).
1568 # interactive IPython session (via a magic, for example).
1542 self.resetbuffer()
1569 self.resetbuffer()
1543 lines = lines.split('\n')
1570 lines = lines.split('\n')
1544 more = 0
1571 more = 0
1545 for line in lines:
1572 for line in lines:
1546 # skip blank lines so we don't mess up the prompt counter, but do
1573 # skip blank lines so we don't mess up the prompt counter, but do
1547 # NOT skip even a blank line if we are in a code block (more is
1574 # NOT skip even a blank line if we are in a code block (more is
1548 # true)
1575 # true)
1549 if line or more:
1576 if line or more:
1550 more = self.push((self.prefilter(line,more)))
1577 more = self.push((self.prefilter(line,more)))
1551 # IPython's runsource returns None if there was an error
1578 # IPython's runsource returns None if there was an error
1552 # compiling the code. This allows us to stop processing right
1579 # compiling the code. This allows us to stop processing right
1553 # away, so the user gets the error message at the right place.
1580 # away, so the user gets the error message at the right place.
1554 if more is None:
1581 if more is None:
1555 break
1582 break
1556 # final newline in case the input didn't have it, so that the code
1583 # final newline in case the input didn't have it, so that the code
1557 # actually does get executed
1584 # actually does get executed
1558 if more:
1585 if more:
1559 self.push('\n')
1586 self.push('\n')
1560
1587
1561 def runsource(self, source, filename="<input>", symbol="single"):
1588 def runsource(self, source, filename="<input>", symbol="single"):
1562 """Compile and run some source in the interpreter.
1589 """Compile and run some source in the interpreter.
1563
1590
1564 Arguments are as for compile_command().
1591 Arguments are as for compile_command().
1565
1592
1566 One several things can happen:
1593 One several things can happen:
1567
1594
1568 1) The input is incorrect; compile_command() raised an
1595 1) The input is incorrect; compile_command() raised an
1569 exception (SyntaxError or OverflowError). A syntax traceback
1596 exception (SyntaxError or OverflowError). A syntax traceback
1570 will be printed by calling the showsyntaxerror() method.
1597 will be printed by calling the showsyntaxerror() method.
1571
1598
1572 2) The input is incomplete, and more input is required;
1599 2) The input is incomplete, and more input is required;
1573 compile_command() returned None. Nothing happens.
1600 compile_command() returned None. Nothing happens.
1574
1601
1575 3) The input is complete; compile_command() returned a code
1602 3) The input is complete; compile_command() returned a code
1576 object. The code is executed by calling self.runcode() (which
1603 object. The code is executed by calling self.runcode() (which
1577 also handles run-time exceptions, except for SystemExit).
1604 also handles run-time exceptions, except for SystemExit).
1578
1605
1579 The return value is:
1606 The return value is:
1580
1607
1581 - True in case 2
1608 - True in case 2
1582
1609
1583 - False in the other cases, unless an exception is raised, where
1610 - False in the other cases, unless an exception is raised, where
1584 None is returned instead. This can be used by external callers to
1611 None is returned instead. This can be used by external callers to
1585 know whether to continue feeding input or not.
1612 know whether to continue feeding input or not.
1586
1613
1587 The return value can be used to decide whether to use sys.ps1 or
1614 The return value can be used to decide whether to use sys.ps1 or
1588 sys.ps2 to prompt the next line."""
1615 sys.ps2 to prompt the next line."""
1589
1616
1590 try:
1617 try:
1591 code = self.compile(source, filename, symbol)
1618 code = self.compile(source, filename, symbol)
1592 except (OverflowError, SyntaxError, ValueError):
1619 except (OverflowError, SyntaxError, ValueError):
1593 # Case 1
1620 # Case 1
1594 self.showsyntaxerror(filename)
1621 self.showsyntaxerror(filename)
1595 return None
1622 return None
1596
1623
1597 if code is None:
1624 if code is None:
1598 # Case 2
1625 # Case 2
1599 return True
1626 return True
1600
1627
1601 # Case 3
1628 # Case 3
1602 # We store the code object so that threaded shells and
1629 # We store the code object so that threaded shells and
1603 # custom exception handlers can access all this info if needed.
1630 # custom exception handlers can access all this info if needed.
1604 # The source corresponding to this can be obtained from the
1631 # The source corresponding to this can be obtained from the
1605 # buffer attribute as '\n'.join(self.buffer).
1632 # buffer attribute as '\n'.join(self.buffer).
1606 self.code_to_run = code
1633 self.code_to_run = code
1607 # now actually execute the code object
1634 # now actually execute the code object
1608 if self.runcode(code) == 0:
1635 if self.runcode(code) == 0:
1609 return False
1636 return False
1610 else:
1637 else:
1611 return None
1638 return None
1612
1639
1613 def runcode(self,code_obj):
1640 def runcode(self,code_obj):
1614 """Execute a code object.
1641 """Execute a code object.
1615
1642
1616 When an exception occurs, self.showtraceback() is called to display a
1643 When an exception occurs, self.showtraceback() is called to display a
1617 traceback.
1644 traceback.
1618
1645
1619 Return value: a flag indicating whether the code to be run completed
1646 Return value: a flag indicating whether the code to be run completed
1620 successfully:
1647 successfully:
1621
1648
1622 - 0: successful execution.
1649 - 0: successful execution.
1623 - 1: an error occurred.
1650 - 1: an error occurred.
1624 """
1651 """
1625
1652
1626 # Set our own excepthook in case the user code tries to call it
1653 # Set our own excepthook in case the user code tries to call it
1627 # directly, so that the IPython crash handler doesn't get triggered
1654 # directly, so that the IPython crash handler doesn't get triggered
1628 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1655 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1629 outflag = 1 # happens in more places, so it's easier as default
1656 outflag = 1 # happens in more places, so it's easier as default
1630 try:
1657 try:
1631 try:
1658 try:
1632 exec code_obj in self.user_global_ns, self.user_ns
1659 # Embedded instances require separate global/local namespaces
1660 # so they can see both the surrounding (local) namespace and
1661 # the module-level globals when called inside another function.
1662 if self.embedded:
1663 exec code_obj in self.user_global_ns, self.user_ns
1664 # Normal (non-embedded) instances should only have a single
1665 # namespace for user code execution, otherwise functions won't
1666 # see interactive top-level globals.
1667 else:
1668 exec code_obj in self.user_ns
1633 finally:
1669 finally:
1634 # Reset our crash handler in place
1670 # Reset our crash handler in place
1635 sys.excepthook = old_excepthook
1671 sys.excepthook = old_excepthook
1636 except SystemExit:
1672 except SystemExit:
1637 self.resetbuffer()
1673 self.resetbuffer()
1638 self.showtraceback()
1674 self.showtraceback()
1639 warn( __builtin__.exit,level=1)
1675 warn( __builtin__.exit,level=1)
1640 except self.custom_exceptions:
1676 except self.custom_exceptions:
1641 etype,value,tb = sys.exc_info()
1677 etype,value,tb = sys.exc_info()
1642 self.CustomTB(etype,value,tb)
1678 self.CustomTB(etype,value,tb)
1643 except:
1679 except:
1644 self.showtraceback()
1680 self.showtraceback()
1645 else:
1681 else:
1646 outflag = 0
1682 outflag = 0
1647 if code.softspace(sys.stdout, 0):
1683 if code.softspace(sys.stdout, 0):
1648 print
1684 print
1649 # Flush out code object which has been run (and source)
1685 # Flush out code object which has been run (and source)
1650 self.code_to_run = None
1686 self.code_to_run = None
1651 return outflag
1687 return outflag
1652
1688
1653 def raw_input(self, prompt=""):
1689 def raw_input(self, prompt=""):
1654 """Write a prompt and read a line.
1690 """Write a prompt and read a line.
1655
1691
1656 The returned line does not include the trailing newline.
1692 The returned line does not include the trailing newline.
1657 When the user enters the EOF key sequence, EOFError is raised.
1693 When the user enters the EOF key sequence, EOFError is raised.
1658
1694
1659 The base implementation uses the built-in function
1695 The base implementation uses the built-in function
1660 raw_input(); a subclass may replace this with a different
1696 raw_input(); a subclass may replace this with a different
1661 implementation.
1697 implementation.
1662 """
1698 """
1663 return self.prefilter(raw_input_original(prompt),
1699 return self.prefilter(raw_input_original(prompt),
1664 prompt==self.outputcache.prompt2)
1700 prompt==self.outputcache.prompt2)
1665
1701
1666 def split_user_input(self,line):
1702 def split_user_input(self,line):
1667 """Split user input into pre-char, function part and rest."""
1703 """Split user input into pre-char, function part and rest."""
1668
1704
1669 lsplit = self.line_split.match(line)
1705 lsplit = self.line_split.match(line)
1670 if lsplit is None: # no regexp match returns None
1706 if lsplit is None: # no regexp match returns None
1671 try:
1707 try:
1672 iFun,theRest = line.split(None,1)
1708 iFun,theRest = line.split(None,1)
1673 except ValueError:
1709 except ValueError:
1674 iFun,theRest = line,''
1710 iFun,theRest = line,''
1675 pre = re.match('^(\s*)(.*)',line).groups()[0]
1711 pre = re.match('^(\s*)(.*)',line).groups()[0]
1676 else:
1712 else:
1677 pre,iFun,theRest = lsplit.groups()
1713 pre,iFun,theRest = lsplit.groups()
1678
1714
1679 #print 'line:<%s>' % line # dbg
1715 #print 'line:<%s>' % line # dbg
1680 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1716 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1681 return pre,iFun.strip(),theRest
1717 return pre,iFun.strip(),theRest
1682
1718
1683 def _prefilter(self, line, continue_prompt):
1719 def _prefilter(self, line, continue_prompt):
1684 """Calls different preprocessors, depending on the form of line."""
1720 """Calls different preprocessors, depending on the form of line."""
1685
1721
1686 # All handlers *must* return a value, even if it's blank ('').
1722 # All handlers *must* return a value, even if it's blank ('').
1687
1723
1688 # Lines are NOT logged here. Handlers should process the line as
1724 # Lines are NOT logged here. Handlers should process the line as
1689 # needed, update the cache AND log it (so that the input cache array
1725 # needed, update the cache AND log it (so that the input cache array
1690 # stays synced).
1726 # stays synced).
1691
1727
1692 # This function is _very_ delicate, and since it's also the one which
1728 # This function is _very_ delicate, and since it's also the one which
1693 # determines IPython's response to user input, it must be as efficient
1729 # determines IPython's response to user input, it must be as efficient
1694 # as possible. For this reason it has _many_ returns in it, trying
1730 # as possible. For this reason it has _many_ returns in it, trying
1695 # always to exit as quickly as it can figure out what it needs to do.
1731 # always to exit as quickly as it can figure out what it needs to do.
1696
1732
1697 # This function is the main responsible for maintaining IPython's
1733 # This function is the main responsible for maintaining IPython's
1698 # behavior respectful of Python's semantics. So be _very_ careful if
1734 # behavior respectful of Python's semantics. So be _very_ careful if
1699 # making changes to anything here.
1735 # making changes to anything here.
1700
1736
1701 #.....................................................................
1737 #.....................................................................
1702 # Code begins
1738 # Code begins
1703
1739
1704 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1740 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1705
1741
1706 # save the line away in case we crash, so the post-mortem handler can
1742 # save the line away in case we crash, so the post-mortem handler can
1707 # record it
1743 # record it
1708 self._last_input_line = line
1744 self._last_input_line = line
1709
1745
1710 #print '***line: <%s>' % line # dbg
1746 #print '***line: <%s>' % line # dbg
1711
1747
1712 # the input history needs to track even empty lines
1748 # the input history needs to track even empty lines
1713 if not line.strip():
1749 if not line.strip():
1714 if not continue_prompt:
1750 if not continue_prompt:
1715 self.outputcache.prompt_count -= 1
1751 self.outputcache.prompt_count -= 1
1716 return self.handle_normal('',continue_prompt)
1752 return self.handle_normal('',continue_prompt)
1717
1753
1718 # print '***cont',continue_prompt # dbg
1754 # print '***cont',continue_prompt # dbg
1719 # special handlers are only allowed for single line statements
1755 # special handlers are only allowed for single line statements
1720 if continue_prompt and not self.rc.multi_line_specials:
1756 if continue_prompt and not self.rc.multi_line_specials:
1721 return self.handle_normal(line,continue_prompt)
1757 return self.handle_normal(line,continue_prompt)
1722
1758
1723 # For the rest, we need the structure of the input
1759 # For the rest, we need the structure of the input
1724 pre,iFun,theRest = self.split_user_input(line)
1760 pre,iFun,theRest = self.split_user_input(line)
1725 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1761 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1726
1762
1727 # First check for explicit escapes in the last/first character
1763 # First check for explicit escapes in the last/first character
1728 handler = None
1764 handler = None
1729 if line[-1] == self.ESC_HELP:
1765 if line[-1] == self.ESC_HELP:
1730 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1766 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1731 if handler is None:
1767 if handler is None:
1732 # look at the first character of iFun, NOT of line, so we skip
1768 # look at the first character of iFun, NOT of line, so we skip
1733 # leading whitespace in multiline input
1769 # leading whitespace in multiline input
1734 handler = self.esc_handlers.get(iFun[0:1])
1770 handler = self.esc_handlers.get(iFun[0:1])
1735 if handler is not None:
1771 if handler is not None:
1736 return handler(line,continue_prompt,pre,iFun,theRest)
1772 return handler(line,continue_prompt,pre,iFun,theRest)
1737 # Emacs ipython-mode tags certain input lines
1773 # Emacs ipython-mode tags certain input lines
1738 if line.endswith('# PYTHON-MODE'):
1774 if line.endswith('# PYTHON-MODE'):
1739 return self.handle_emacs(line,continue_prompt)
1775 return self.handle_emacs(line,continue_prompt)
1740
1776
1741 # Next, check if we can automatically execute this thing
1777 # Next, check if we can automatically execute this thing
1742
1778
1743 # Allow ! in multi-line statements if multi_line_specials is on:
1779 # Allow ! in multi-line statements if multi_line_specials is on:
1744 if continue_prompt and self.rc.multi_line_specials and \
1780 if continue_prompt and self.rc.multi_line_specials and \
1745 iFun.startswith(self.ESC_SHELL):
1781 iFun.startswith(self.ESC_SHELL):
1746 return self.handle_shell_escape(line,continue_prompt,
1782 return self.handle_shell_escape(line,continue_prompt,
1747 pre=pre,iFun=iFun,
1783 pre=pre,iFun=iFun,
1748 theRest=theRest)
1784 theRest=theRest)
1749
1785
1750 # Let's try to find if the input line is a magic fn
1786 # Let's try to find if the input line is a magic fn
1751 oinfo = None
1787 oinfo = None
1752 if hasattr(self,'magic_'+iFun):
1788 if hasattr(self,'magic_'+iFun):
1753 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1789 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1754 if oinfo['ismagic']:
1790 if oinfo['ismagic']:
1755 # Be careful not to call magics when a variable assignment is
1791 # Be careful not to call magics when a variable assignment is
1756 # being made (ls='hi', for example)
1792 # being made (ls='hi', for example)
1757 if self.rc.automagic and \
1793 if self.rc.automagic and \
1758 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1794 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1759 (self.rc.multi_line_specials or not continue_prompt):
1795 (self.rc.multi_line_specials or not continue_prompt):
1760 return self.handle_magic(line,continue_prompt,
1796 return self.handle_magic(line,continue_prompt,
1761 pre,iFun,theRest)
1797 pre,iFun,theRest)
1762 else:
1798 else:
1763 return self.handle_normal(line,continue_prompt)
1799 return self.handle_normal(line,continue_prompt)
1764
1800
1765 # If the rest of the line begins with an (in)equality, assginment or
1801 # If the rest of the line begins with an (in)equality, assginment or
1766 # function call, we should not call _ofind but simply execute it.
1802 # function call, we should not call _ofind but simply execute it.
1767 # This avoids spurious geattr() accesses on objects upon assignment.
1803 # This avoids spurious geattr() accesses on objects upon assignment.
1768 #
1804 #
1769 # It also allows users to assign to either alias or magic names true
1805 # It also allows users to assign to either alias or magic names true
1770 # python variables (the magic/alias systems always take second seat to
1806 # python variables (the magic/alias systems always take second seat to
1771 # true python code).
1807 # true python code).
1772 if theRest and theRest[0] in '!=()':
1808 if theRest and theRest[0] in '!=()':
1773 return self.handle_normal(line,continue_prompt)
1809 return self.handle_normal(line,continue_prompt)
1774
1810
1775 if oinfo is None:
1811 if oinfo is None:
1776 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1812 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1777
1813
1778 if not oinfo['found']:
1814 if not oinfo['found']:
1779 return self.handle_normal(line,continue_prompt)
1815 return self.handle_normal(line,continue_prompt)
1780 else:
1816 else:
1781 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1817 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1782 if oinfo['isalias']:
1818 if oinfo['isalias']:
1783 return self.handle_alias(line,continue_prompt,
1819 return self.handle_alias(line,continue_prompt,
1784 pre,iFun,theRest)
1820 pre,iFun,theRest)
1785
1821
1786 if self.rc.autocall and \
1822 if self.rc.autocall and \
1787 not self.re_exclude_auto.match(theRest) and \
1823 not self.re_exclude_auto.match(theRest) and \
1788 self.re_fun_name.match(iFun) and \
1824 self.re_fun_name.match(iFun) and \
1789 callable(oinfo['obj']) :
1825 callable(oinfo['obj']) :
1790 #print 'going auto' # dbg
1826 #print 'going auto' # dbg
1791 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1827 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1792 else:
1828 else:
1793 #print 'was callable?', callable(oinfo['obj']) # dbg
1829 #print 'was callable?', callable(oinfo['obj']) # dbg
1794 return self.handle_normal(line,continue_prompt)
1830 return self.handle_normal(line,continue_prompt)
1795
1831
1796 # If we get here, we have a normal Python line. Log and return.
1832 # If we get here, we have a normal Python line. Log and return.
1797 return self.handle_normal(line,continue_prompt)
1833 return self.handle_normal(line,continue_prompt)
1798
1834
1799 def _prefilter_dumb(self, line, continue_prompt):
1835 def _prefilter_dumb(self, line, continue_prompt):
1800 """simple prefilter function, for debugging"""
1836 """simple prefilter function, for debugging"""
1801 return self.handle_normal(line,continue_prompt)
1837 return self.handle_normal(line,continue_prompt)
1802
1838
1803 # Set the default prefilter() function (this can be user-overridden)
1839 # Set the default prefilter() function (this can be user-overridden)
1804 prefilter = _prefilter
1840 prefilter = _prefilter
1805
1841
1806 def handle_normal(self,line,continue_prompt=None,
1842 def handle_normal(self,line,continue_prompt=None,
1807 pre=None,iFun=None,theRest=None):
1843 pre=None,iFun=None,theRest=None):
1808 """Handle normal input lines. Use as a template for handlers."""
1844 """Handle normal input lines. Use as a template for handlers."""
1809
1845
1810 self.log(line,continue_prompt)
1846 self.log(line,continue_prompt)
1811 self.update_cache(line)
1847 self.update_cache(line)
1812 return line
1848 return line
1813
1849
1814 def handle_alias(self,line,continue_prompt=None,
1850 def handle_alias(self,line,continue_prompt=None,
1815 pre=None,iFun=None,theRest=None):
1851 pre=None,iFun=None,theRest=None):
1816 """Handle alias input lines. """
1852 """Handle alias input lines. """
1817
1853
1818 theRest = esc_quotes(theRest)
1854 theRest = esc_quotes(theRest)
1819 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1855 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1820 self.log(line_out,continue_prompt)
1856 self.log(line_out,continue_prompt)
1821 self.update_cache(line_out)
1857 self.update_cache(line_out)
1822 return line_out
1858 return line_out
1823
1859
1824 def handle_shell_escape(self, line, continue_prompt=None,
1860 def handle_shell_escape(self, line, continue_prompt=None,
1825 pre=None,iFun=None,theRest=None):
1861 pre=None,iFun=None,theRest=None):
1826 """Execute the line in a shell, empty return value"""
1862 """Execute the line in a shell, empty return value"""
1827
1863
1828 #print 'line in :', `line` # dbg
1864 #print 'line in :', `line` # dbg
1829 # Example of a special handler. Others follow a similar pattern.
1865 # Example of a special handler. Others follow a similar pattern.
1830 if continue_prompt: # multi-line statements
1866 if continue_prompt: # multi-line statements
1831 if iFun.startswith('!!'):
1867 if iFun.startswith('!!'):
1832 print 'SyntaxError: !! is not allowed in multiline statements'
1868 print 'SyntaxError: !! is not allowed in multiline statements'
1833 return pre
1869 return pre
1834 else:
1870 else:
1835 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1871 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1836 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1872 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1837 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1873 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1838 else: # single-line input
1874 else: # single-line input
1839 if line.startswith('!!'):
1875 if line.startswith('!!'):
1840 # rewrite iFun/theRest to properly hold the call to %sx and
1876 # rewrite iFun/theRest to properly hold the call to %sx and
1841 # the actual command to be executed, so handle_magic can work
1877 # the actual command to be executed, so handle_magic can work
1842 # correctly
1878 # correctly
1843 theRest = '%s %s' % (iFun[2:],theRest)
1879 theRest = '%s %s' % (iFun[2:],theRest)
1844 iFun = 'sx'
1880 iFun = 'sx'
1845 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1881 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1846 continue_prompt,pre,iFun,theRest)
1882 continue_prompt,pre,iFun,theRest)
1847 else:
1883 else:
1848 cmd = esc_quotes(line[1:])
1884 cmd = esc_quotes(line[1:])
1849 line_out = '%s.system("%s")' % (self.name,cmd)
1885 line_out = '%s.system("%s")' % (self.name,cmd)
1850 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1886 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1851 # update cache/log and return
1887 # update cache/log and return
1852 self.log(line_out,continue_prompt)
1888 self.log(line_out,continue_prompt)
1853 self.update_cache(line_out) # readline cache gets normal line
1889 self.update_cache(line_out) # readline cache gets normal line
1854 #print 'line out r:', `line_out` # dbg
1890 #print 'line out r:', `line_out` # dbg
1855 #print 'line out s:', line_out # dbg
1891 #print 'line out s:', line_out # dbg
1856 return line_out
1892 return line_out
1857
1893
1858 def handle_magic(self, line, continue_prompt=None,
1894 def handle_magic(self, line, continue_prompt=None,
1859 pre=None,iFun=None,theRest=None):
1895 pre=None,iFun=None,theRest=None):
1860 """Execute magic functions.
1896 """Execute magic functions.
1861
1897
1862 Also log them with a prepended # so the log is clean Python."""
1898 Also log them with a prepended # so the log is clean Python."""
1863
1899
1864 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1900 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1865 self.log(cmd,continue_prompt)
1901 self.log(cmd,continue_prompt)
1866 self.update_cache(line)
1902 self.update_cache(line)
1867 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1903 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1868 return cmd
1904 return cmd
1869
1905
1870 def handle_auto(self, line, continue_prompt=None,
1906 def handle_auto(self, line, continue_prompt=None,
1871 pre=None,iFun=None,theRest=None):
1907 pre=None,iFun=None,theRest=None):
1872 """Hande lines which can be auto-executed, quoting if requested."""
1908 """Hande lines which can be auto-executed, quoting if requested."""
1873
1909
1874 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1910 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1875
1911
1876 # This should only be active for single-line input!
1912 # This should only be active for single-line input!
1877 if continue_prompt:
1913 if continue_prompt:
1878 return line
1914 return line
1879
1915
1880 if pre == self.ESC_QUOTE:
1916 if pre == self.ESC_QUOTE:
1881 # Auto-quote splitting on whitespace
1917 # Auto-quote splitting on whitespace
1882 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1918 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1883 elif pre == self.ESC_QUOTE2:
1919 elif pre == self.ESC_QUOTE2:
1884 # Auto-quote whole string
1920 # Auto-quote whole string
1885 newcmd = '%s("%s")' % (iFun,theRest)
1921 newcmd = '%s("%s")' % (iFun,theRest)
1886 else:
1922 else:
1887 # Auto-paren
1923 # Auto-paren
1888 if theRest[0:1] in ('=','['):
1924 if theRest[0:1] in ('=','['):
1889 # Don't autocall in these cases. They can be either
1925 # Don't autocall in these cases. They can be either
1890 # rebindings of an existing callable's name, or item access
1926 # rebindings of an existing callable's name, or item access
1891 # for an object which is BOTH callable and implements
1927 # for an object which is BOTH callable and implements
1892 # __getitem__.
1928 # __getitem__.
1893 return '%s %s' % (iFun,theRest)
1929 return '%s %s' % (iFun,theRest)
1894 if theRest.endswith(';'):
1930 if theRest.endswith(';'):
1895 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1931 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1896 else:
1932 else:
1897 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1933 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1898
1934
1899 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1935 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1900 # log what is now valid Python, not the actual user input (without the
1936 # log what is now valid Python, not the actual user input (without the
1901 # final newline)
1937 # final newline)
1902 self.log(newcmd,continue_prompt)
1938 self.log(newcmd,continue_prompt)
1903 return newcmd
1939 return newcmd
1904
1940
1905 def handle_help(self, line, continue_prompt=None,
1941 def handle_help(self, line, continue_prompt=None,
1906 pre=None,iFun=None,theRest=None):
1942 pre=None,iFun=None,theRest=None):
1907 """Try to get some help for the object.
1943 """Try to get some help for the object.
1908
1944
1909 obj? or ?obj -> basic information.
1945 obj? or ?obj -> basic information.
1910 obj?? or ??obj -> more details.
1946 obj?? or ??obj -> more details.
1911 """
1947 """
1912
1948
1913 # We need to make sure that we don't process lines which would be
1949 # We need to make sure that we don't process lines which would be
1914 # otherwise valid python, such as "x=1 # what?"
1950 # otherwise valid python, such as "x=1 # what?"
1915 try:
1951 try:
1916 code.compile_command(line)
1952 code.compile_command(line)
1917 except SyntaxError:
1953 except SyntaxError:
1918 # We should only handle as help stuff which is NOT valid syntax
1954 # We should only handle as help stuff which is NOT valid syntax
1919 if line[0]==self.ESC_HELP:
1955 if line[0]==self.ESC_HELP:
1920 line = line[1:]
1956 line = line[1:]
1921 elif line[-1]==self.ESC_HELP:
1957 elif line[-1]==self.ESC_HELP:
1922 line = line[:-1]
1958 line = line[:-1]
1923 self.log('#?'+line)
1959 self.log('#?'+line)
1924 self.update_cache(line)
1960 self.update_cache(line)
1925 if line:
1961 if line:
1926 self.magic_pinfo(line)
1962 self.magic_pinfo(line)
1927 else:
1963 else:
1928 page(self.usage,screen_lines=self.rc.screen_length)
1964 page(self.usage,screen_lines=self.rc.screen_length)
1929 return '' # Empty string is needed here!
1965 return '' # Empty string is needed here!
1930 except:
1966 except:
1931 # Pass any other exceptions through to the normal handler
1967 # Pass any other exceptions through to the normal handler
1932 return self.handle_normal(line,continue_prompt)
1968 return self.handle_normal(line,continue_prompt)
1933 else:
1969 else:
1934 # If the code compiles ok, we should handle it normally
1970 # If the code compiles ok, we should handle it normally
1935 return self.handle_normal(line,continue_prompt)
1971 return self.handle_normal(line,continue_prompt)
1936
1972
1937 def handle_emacs(self,line,continue_prompt=None,
1973 def handle_emacs(self,line,continue_prompt=None,
1938 pre=None,iFun=None,theRest=None):
1974 pre=None,iFun=None,theRest=None):
1939 """Handle input lines marked by python-mode."""
1975 """Handle input lines marked by python-mode."""
1940
1976
1941 # Currently, nothing is done. Later more functionality can be added
1977 # Currently, nothing is done. Later more functionality can be added
1942 # here if needed.
1978 # here if needed.
1943
1979
1944 # The input cache shouldn't be updated
1980 # The input cache shouldn't be updated
1945
1981
1946 return line
1982 return line
1947
1983
1948 def write(self,data):
1984 def write(self,data):
1949 """Write a string to the default output"""
1985 """Write a string to the default output"""
1950 Term.cout.write(data)
1986 Term.cout.write(data)
1951
1987
1952 def write_err(self,data):
1988 def write_err(self,data):
1953 """Write a string to the default error output"""
1989 """Write a string to the default error output"""
1954 Term.cerr.write(data)
1990 Term.cerr.write(data)
1955
1991
1956 def safe_execfile(self,fname,*where,**kw):
1992 def safe_execfile(self,fname,*where,**kw):
1957 fname = os.path.expanduser(fname)
1993 fname = os.path.expanduser(fname)
1958
1994
1959 # find things also in current directory
1995 # find things also in current directory
1960 dname = os.path.dirname(fname)
1996 dname = os.path.dirname(fname)
1961 if not sys.path.count(dname):
1997 if not sys.path.count(dname):
1962 sys.path.append(dname)
1998 sys.path.append(dname)
1963
1999
1964 try:
2000 try:
1965 xfile = open(fname)
2001 xfile = open(fname)
1966 except:
2002 except:
1967 print >> Term.cerr, \
2003 print >> Term.cerr, \
1968 'Could not open file <%s> for safe execution.' % fname
2004 'Could not open file <%s> for safe execution.' % fname
1969 return None
2005 return None
1970
2006
1971 kw.setdefault('islog',0)
2007 kw.setdefault('islog',0)
1972 kw.setdefault('quiet',1)
2008 kw.setdefault('quiet',1)
1973 kw.setdefault('exit_ignore',0)
2009 kw.setdefault('exit_ignore',0)
1974 first = xfile.readline()
2010 first = xfile.readline()
1975 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
2011 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1976 xfile.close()
2012 xfile.close()
1977 # line by line execution
2013 # line by line execution
1978 if first.startswith(_LOGHEAD) or kw['islog']:
2014 if first.startswith(_LOGHEAD) or kw['islog']:
1979 print 'Loading log file <%s> one line at a time...' % fname
2015 print 'Loading log file <%s> one line at a time...' % fname
1980 if kw['quiet']:
2016 if kw['quiet']:
1981 stdout_save = sys.stdout
2017 stdout_save = sys.stdout
1982 sys.stdout = StringIO.StringIO()
2018 sys.stdout = StringIO.StringIO()
1983 try:
2019 try:
1984 globs,locs = where[0:2]
2020 globs,locs = where[0:2]
1985 except:
2021 except:
1986 try:
2022 try:
1987 globs = locs = where[0]
2023 globs = locs = where[0]
1988 except:
2024 except:
1989 globs = locs = globals()
2025 globs = locs = globals()
1990 badblocks = []
2026 badblocks = []
1991
2027
1992 # we also need to identify indented blocks of code when replaying
2028 # we also need to identify indented blocks of code when replaying
1993 # logs and put them together before passing them to an exec
2029 # logs and put them together before passing them to an exec
1994 # statement. This takes a bit of regexp and look-ahead work in the
2030 # statement. This takes a bit of regexp and look-ahead work in the
1995 # file. It's easiest if we swallow the whole thing in memory
2031 # file. It's easiest if we swallow the whole thing in memory
1996 # first, and manually walk through the lines list moving the
2032 # first, and manually walk through the lines list moving the
1997 # counter ourselves.
2033 # counter ourselves.
1998 indent_re = re.compile('\s+\S')
2034 indent_re = re.compile('\s+\S')
1999 xfile = open(fname)
2035 xfile = open(fname)
2000 filelines = xfile.readlines()
2036 filelines = xfile.readlines()
2001 xfile.close()
2037 xfile.close()
2002 nlines = len(filelines)
2038 nlines = len(filelines)
2003 lnum = 0
2039 lnum = 0
2004 while lnum < nlines:
2040 while lnum < nlines:
2005 line = filelines[lnum]
2041 line = filelines[lnum]
2006 lnum += 1
2042 lnum += 1
2007 # don't re-insert logger status info into cache
2043 # don't re-insert logger status info into cache
2008 if line.startswith('#log#'):
2044 if line.startswith('#log#'):
2009 continue
2045 continue
2010 elif line.startswith('#%s'% self.ESC_MAGIC):
2046 elif line.startswith('#%s'% self.ESC_MAGIC):
2011 self.update_cache(line[1:])
2047 self.update_cache(line[1:])
2012 line = magic2python(line)
2048 line = magic2python(line)
2013 elif line.startswith('#!'):
2049 elif line.startswith('#!'):
2014 self.update_cache(line[1:])
2050 self.update_cache(line[1:])
2015 else:
2051 else:
2016 # build a block of code (maybe a single line) for execution
2052 # build a block of code (maybe a single line) for execution
2017 block = line
2053 block = line
2018 try:
2054 try:
2019 next = filelines[lnum] # lnum has already incremented
2055 next = filelines[lnum] # lnum has already incremented
2020 except:
2056 except:
2021 next = None
2057 next = None
2022 while next and indent_re.match(next):
2058 while next and indent_re.match(next):
2023 block += next
2059 block += next
2024 lnum += 1
2060 lnum += 1
2025 try:
2061 try:
2026 next = filelines[lnum]
2062 next = filelines[lnum]
2027 except:
2063 except:
2028 next = None
2064 next = None
2029 # now execute the block of one or more lines
2065 # now execute the block of one or more lines
2030 try:
2066 try:
2031 exec block in globs,locs
2067 exec block in globs,locs
2032 self.update_cache(block.rstrip())
2068 self.update_cache(block.rstrip())
2033 except SystemExit:
2069 except SystemExit:
2034 pass
2070 pass
2035 except:
2071 except:
2036 badblocks.append(block.rstrip())
2072 badblocks.append(block.rstrip())
2037 if kw['quiet']: # restore stdout
2073 if kw['quiet']: # restore stdout
2038 sys.stdout.close()
2074 sys.stdout.close()
2039 sys.stdout = stdout_save
2075 sys.stdout = stdout_save
2040 print 'Finished replaying log file <%s>' % fname
2076 print 'Finished replaying log file <%s>' % fname
2041 if badblocks:
2077 if badblocks:
2042 print >> sys.stderr, \
2078 print >> sys.stderr, \
2043 '\nThe following lines/blocks in file <%s> reported errors:' \
2079 '\nThe following lines/blocks in file <%s> reported errors:' \
2044 % fname
2080 % fname
2045 for badline in badblocks:
2081 for badline in badblocks:
2046 print >> sys.stderr, badline
2082 print >> sys.stderr, badline
2047 else: # regular file execution
2083 else: # regular file execution
2048 try:
2084 try:
2049 execfile(fname,*where)
2085 execfile(fname,*where)
2050 except SyntaxError:
2086 except SyntaxError:
2051 etype, evalue = sys.exc_info()[0:2]
2087 etype, evalue = sys.exc_info()[0:2]
2052 self.SyntaxTB(etype,evalue,[])
2088 self.SyntaxTB(etype,evalue,[])
2053 warn('Failure executing file: <%s>' % fname)
2089 warn('Failure executing file: <%s>' % fname)
2054 except SystemExit,status:
2090 except SystemExit,status:
2055 if not kw['exit_ignore']:
2091 if not kw['exit_ignore']:
2056 self.InteractiveTB()
2092 self.InteractiveTB()
2057 warn('Failure executing file: <%s>' % fname)
2093 warn('Failure executing file: <%s>' % fname)
2058 except:
2094 except:
2059 self.InteractiveTB()
2095 self.InteractiveTB()
2060 warn('Failure executing file: <%s>' % fname)
2096 warn('Failure executing file: <%s>' % fname)
2061
2097
2062 #************************* end of file <iplib.py> *****************************
2098 #************************* end of file <iplib.py> *****************************
@@ -1,727 +1,734 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 911 2005-10-08 07:59:40Z fperez $"""
9 $Id: ipmaker.py 923 2005-11-15 08:51:15Z fperez $"""
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2004 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__, __builtin__
39 import __main__, __builtin__
40 import os,sys,types,re
40 import os,sys,types,re
41 from pprint import pprint,pformat
41 from pprint import pprint,pformat
42
42
43 # Our own
43 # Our own
44 from IPython import DPyGetOpt
44 from IPython import DPyGetOpt
45 from IPython.Struct import Struct
45 from IPython.Struct import Struct
46 from IPython.OutputTrap import OutputTrap
46 from IPython.OutputTrap import OutputTrap
47 from IPython.ConfigLoader import ConfigLoader
47 from IPython.ConfigLoader import ConfigLoader
48 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
48 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
49 from IPython.usage import cmd_line_usage,interactive_usage
49 from IPython.usage import cmd_line_usage,interactive_usage
50 from IPython.Prompts import CachedOutput
50 from IPython.Prompts import CachedOutput
51 from IPython.genutils import *
51 from IPython.genutils import *
52
52
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
54 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
55 shell_class=InteractiveShell,embedded=False,**kw):
55 shell_class=InteractiveShell,embedded=False,**kw):
56 """This is a dump of IPython into a single function.
56 """This is a dump of IPython into a single function.
57
57
58 Later it will have to be broken up in a sensible manner.
58 Later it will have to be broken up in a sensible manner.
59
59
60 Arguments:
60 Arguments:
61
61
62 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
62 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
63 script name, b/c DPyGetOpt strips the first argument only for the real
63 script name, b/c DPyGetOpt strips the first argument only for the real
64 sys.argv.
64 sys.argv.
65
65
66 - user_ns: a dict to be used as the user's namespace."""
66 - user_ns: a dict to be used as the user's namespace."""
67
67
68 #----------------------------------------------------------------------
68 #----------------------------------------------------------------------
69 # Defaults and initialization
69 # Defaults and initialization
70
70
71 # For developer debugging, deactivates crash handler and uses pdb.
71 # For developer debugging, deactivates crash handler and uses pdb.
72 DEVDEBUG = False
72 DEVDEBUG = False
73
73
74 if argv is None:
74 if argv is None:
75 argv = sys.argv
75 argv = sys.argv
76
76
77 # __IP is the main global that lives throughout and represents the whole
77 # __IP is the main global that lives throughout and represents the whole
78 # application. If the user redefines it, all bets are off as to what
78 # application. If the user redefines it, all bets are off as to what
79 # happens.
79 # happens.
80
80
81 # __IP is the name of he global which the caller will have accessible as
81 # __IP is the name of he global which the caller will have accessible as
82 # __IP.name. We set its name via the first parameter passed to
82 # __IP.name. We set its name via the first parameter passed to
83 # InteractiveShell:
83 # InteractiveShell:
84
84
85 IP = shell_class('__IP',user_ns=user_ns,**kw)
85 IP = shell_class('__IP',user_ns=user_ns,embedded=embedded,**kw)
86
86
87 # Put 'help' in the user namespace
87 # Put 'help' in the user namespace
88 from site import _Helper
88 from site import _Helper
89 IP.user_ns['help'] = _Helper()
89 IP.user_ns['help'] = _Helper()
90
90
91 if DEVDEBUG:
91 if DEVDEBUG:
92 # For developer debugging only (global flag)
92 # For developer debugging only (global flag)
93 from IPython import ultraTB
93 from IPython import ultraTB
94 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
94 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
95 else:
95 else:
96 # IPython itself shouldn't crash. This will produce a detailed
96 # IPython itself shouldn't crash. This will produce a detailed
97 # post-mortem if it does
97 # post-mortem if it does
98 from IPython import CrashHandler
98 from IPython import CrashHandler
99 sys.excepthook = CrashHandler.CrashHandler(IP)
99 sys.excepthook = CrashHandler.CrashHandler(IP)
100
100
101 IP.BANNER_PARTS = ['Python %s\n'
101 IP.BANNER_PARTS = ['Python %s\n'
102 'Type "copyright", "credits" or "license" '
102 'Type "copyright", "credits" or "license" '
103 'for more information.\n'
103 'for more information.\n'
104 % (sys.version.split('\n')[0],),
104 % (sys.version.split('\n')[0],),
105 "IPython %s -- An enhanced Interactive Python."
105 "IPython %s -- An enhanced Interactive Python."
106 % (__version__,),
106 % (__version__,),
107 """? -> Introduction to IPython's features.
107 """? -> Introduction to IPython's features.
108 %magic -> Information about IPython's 'magic' % functions.
108 %magic -> Information about IPython's 'magic' % functions.
109 help -> Python's own help system.
109 help -> Python's own help system.
110 object? -> Details about 'object'. ?object also works, ?? prints more.
110 object? -> Details about 'object'. ?object also works, ?? prints more.
111 """ ]
111 """ ]
112
112
113 IP.usage = interactive_usage
113 IP.usage = interactive_usage
114
114
115 # Platform-dependent suffix and directory names. We use _ipython instead
115 # Platform-dependent suffix and directory names. We use _ipython instead
116 # of .ipython under win32 b/c there's software that breaks with .named
116 # of .ipython under win32 b/c there's software that breaks with .named
117 # directories on that platform.
117 # directories on that platform.
118 if os.name == 'posix':
118 if os.name == 'posix':
119 rc_suffix = ''
119 rc_suffix = ''
120 ipdir_def = '.ipython'
120 ipdir_def = '.ipython'
121 else:
121 else:
122 rc_suffix = '.ini'
122 rc_suffix = '.ini'
123 ipdir_def = '_ipython'
123 ipdir_def = '_ipython'
124
124
125 # default directory for configuration
125 # default directory for configuration
126 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
126 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
127 os.path.join(IP.home_dir,ipdir_def)))
127 os.path.join(IP.home_dir,ipdir_def)))
128
128
129 # we need the directory where IPython itself is installed
129 # we need the directory where IPython itself is installed
130 import IPython
130 import IPython
131 IPython_dir = os.path.dirname(IPython.__file__)
131 IPython_dir = os.path.dirname(IPython.__file__)
132 del IPython
132 del IPython
133
133
134 #-------------------------------------------------------------------------
134 #-------------------------------------------------------------------------
135 # Command line handling
135 # Command line handling
136
136
137 # Valid command line options (uses DPyGetOpt syntax, like Perl's
137 # Valid command line options (uses DPyGetOpt syntax, like Perl's
138 # GetOpt::Long)
138 # GetOpt::Long)
139
139
140 # Any key not listed here gets deleted even if in the file (like session
140 # Any key not listed here gets deleted even if in the file (like session
141 # or profile). That's deliberate, to maintain the rc namespace clean.
141 # or profile). That's deliberate, to maintain the rc namespace clean.
142
142
143 # Each set of options appears twice: under _conv only the names are
143 # Each set of options appears twice: under _conv only the names are
144 # listed, indicating which type they must be converted to when reading the
144 # listed, indicating which type they must be converted to when reading the
145 # ipythonrc file. And under DPyGetOpt they are listed with the regular
145 # ipythonrc file. And under DPyGetOpt they are listed with the regular
146 # DPyGetOpt syntax (=s,=i,:f,etc).
146 # DPyGetOpt syntax (=s,=i,:f,etc).
147
147
148 # Make sure there's a space before each end of line (they get auto-joined!)
148 # Make sure there's a space before each end of line (they get auto-joined!)
149 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
149 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
150 'c=s classic|cl color_info! colors=s confirm_exit! '
150 'c=s classic|cl color_info! colors=s confirm_exit! '
151 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
151 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
152 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
152 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
153 'quick screen_length|sl=i prompts_pad_left=i '
153 'quick screen_length|sl=i prompts_pad_left=i '
154 'logfile|lf=s logplay|lp=s profile|p=s '
154 'logfile|lf=s logplay|lp=s profile|p=s '
155 'readline! readline_merge_completions! '
155 'readline! readline_merge_completions! '
156 'readline_omit__names! '
156 'readline_omit__names! '
157 'rcfile=s separate_in|si=s separate_out|so=s '
157 'rcfile=s separate_in|si=s separate_out|so=s '
158 'separate_out2|so2=s xmode=s '
158 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
159 'magic_docstrings system_verbose! '
159 'magic_docstrings system_verbose! '
160 'multi_line_specials!')
160 'multi_line_specials!')
161
161
162 # Options that can *only* appear at the cmd line (not in rcfiles).
162 # Options that can *only* appear at the cmd line (not in rcfiles).
163
163
164 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
164 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
165 # the 'C-c !' command in emacs automatically appends a -i option at the end.
165 # the 'C-c !' command in emacs automatically appends a -i option at the end.
166 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
166 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
167 'gthread! qthread! wthread! pylab! tk!')
167 'gthread! qthread! wthread! pylab! tk!')
168
168
169 # Build the actual name list to be used by DPyGetOpt
169 # Build the actual name list to be used by DPyGetOpt
170 opts_names = qw(cmdline_opts) + qw(cmdline_only)
170 opts_names = qw(cmdline_opts) + qw(cmdline_only)
171
171
172 # Set sensible command line defaults.
172 # Set sensible command line defaults.
173 # This should have everything from cmdline_opts and cmdline_only
173 # This should have everything from cmdline_opts and cmdline_only
174 opts_def = Struct(autocall = 1,
174 opts_def = Struct(autocall = 1,
175 autoindent=0,
175 autoindent=0,
176 automagic = 1,
176 automagic = 1,
177 banner = 1,
177 banner = 1,
178 cache_size = 1000,
178 cache_size = 1000,
179 c = '',
179 c = '',
180 classic = 0,
180 classic = 0,
181 colors = 'NoColor',
181 colors = 'NoColor',
182 color_info = 0,
182 color_info = 0,
183 confirm_exit = 1,
183 confirm_exit = 1,
184 debug = 0,
184 debug = 0,
185 deep_reload = 0,
185 deep_reload = 0,
186 editor = '0',
186 editor = '0',
187 help = 0,
187 help = 0,
188 ignore = 0,
188 ignore = 0,
189 ipythondir = ipythondir,
189 ipythondir = ipythondir,
190 log = 0,
190 log = 0,
191 logfile = '',
191 logfile = '',
192 logplay = '',
192 logplay = '',
193 multi_line_specials = 1,
193 multi_line_specials = 1,
194 messages = 1,
194 messages = 1,
195 nosep = 0,
195 nosep = 0,
196 pdb = 0,
196 pdb = 0,
197 pprint = 0,
197 pprint = 0,
198 profile = '',
198 profile = '',
199 prompt_in1 = 'In [\\#]: ',
199 prompt_in1 = 'In [\\#]: ',
200 prompt_in2 = ' .\\D.: ',
200 prompt_in2 = ' .\\D.: ',
201 prompt_out = 'Out[\\#]: ',
201 prompt_out = 'Out[\\#]: ',
202 prompts_pad_left = 1,
202 prompts_pad_left = 1,
203 quick = 0,
203 quick = 0,
204 readline = 1,
204 readline = 1,
205 readline_merge_completions = 1,
205 readline_merge_completions = 1,
206 readline_omit__names = 0,
206 readline_omit__names = 0,
207 rcfile = 'ipythonrc' + rc_suffix,
207 rcfile = 'ipythonrc' + rc_suffix,
208 screen_length = 0,
208 screen_length = 0,
209 separate_in = '\n',
209 separate_in = '\n',
210 separate_out = '\n',
210 separate_out = '\n',
211 separate_out2 = '',
211 separate_out2 = '',
212 system_verbose = 0,
212 system_verbose = 0,
213 gthread = 0,
213 gthread = 0,
214 qthread = 0,
214 qthread = 0,
215 wthread = 0,
215 wthread = 0,
216 pylab = 0,
216 pylab = 0,
217 tk = 0,
217 tk = 0,
218 upgrade = 0,
218 upgrade = 0,
219 Version = 0,
219 Version = 0,
220 xmode = 'Verbose',
220 xmode = 'Verbose',
221 wildcards_case_sensitive = 1,
221 magic_docstrings = 0, # undocumented, for doc generation
222 magic_docstrings = 0, # undocumented, for doc generation
222 )
223 )
223
224
224 # Things that will *only* appear in rcfiles (not at the command line).
225 # Things that will *only* appear in rcfiles (not at the command line).
225 # Make sure there's a space before each end of line (they get auto-joined!)
226 # Make sure there's a space before each end of line (they get auto-joined!)
226 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
227 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
227 qw_lol: 'import_some ',
228 qw_lol: 'import_some ',
228 # for things with embedded whitespace:
229 # for things with embedded whitespace:
229 list_strings:'execute alias readline_parse_and_bind ',
230 list_strings:'execute alias readline_parse_and_bind ',
230 # Regular strings need no conversion:
231 # Regular strings need no conversion:
231 None:'readline_remove_delims ',
232 None:'readline_remove_delims ',
232 }
233 }
233 # Default values for these
234 # Default values for these
234 rc_def = Struct(include = [],
235 rc_def = Struct(include = [],
235 import_mod = [],
236 import_mod = [],
236 import_all = [],
237 import_all = [],
237 import_some = [[]],
238 import_some = [[]],
238 execute = [],
239 execute = [],
239 execfile = [],
240 execfile = [],
240 alias = [],
241 alias = [],
241 readline_parse_and_bind = [],
242 readline_parse_and_bind = [],
242 readline_remove_delims = '',
243 readline_remove_delims = '',
243 )
244 )
244
245
245 # Build the type conversion dictionary from the above tables:
246 # Build the type conversion dictionary from the above tables:
246 typeconv = rcfile_opts.copy()
247 typeconv = rcfile_opts.copy()
247 typeconv.update(optstr2types(cmdline_opts))
248 typeconv.update(optstr2types(cmdline_opts))
248
249
249 # FIXME: the None key appears in both, put that back together by hand. Ugly!
250 # FIXME: the None key appears in both, put that back together by hand. Ugly!
250 typeconv[None] += ' ' + rcfile_opts[None]
251 typeconv[None] += ' ' + rcfile_opts[None]
251
252
252 # Remove quotes at ends of all strings (used to protect spaces)
253 # Remove quotes at ends of all strings (used to protect spaces)
253 typeconv[unquote_ends] = typeconv[None]
254 typeconv[unquote_ends] = typeconv[None]
254 del typeconv[None]
255 del typeconv[None]
255
256
256 # Build the list we'll use to make all config decisions with defaults:
257 # Build the list we'll use to make all config decisions with defaults:
257 opts_all = opts_def.copy()
258 opts_all = opts_def.copy()
258 opts_all.update(rc_def)
259 opts_all.update(rc_def)
259
260
260 # Build conflict resolver for recursive loading of config files:
261 # Build conflict resolver for recursive loading of config files:
261 # - preserve means the outermost file maintains the value, it is not
262 # - preserve means the outermost file maintains the value, it is not
262 # overwritten if an included file has the same key.
263 # overwritten if an included file has the same key.
263 # - add_flip applies + to the two values, so it better make sense to add
264 # - add_flip applies + to the two values, so it better make sense to add
264 # those types of keys. But it flips them first so that things loaded
265 # those types of keys. But it flips them first so that things loaded
265 # deeper in the inclusion chain have lower precedence.
266 # deeper in the inclusion chain have lower precedence.
266 conflict = {'preserve': ' '.join([ typeconv[int],
267 conflict = {'preserve': ' '.join([ typeconv[int],
267 typeconv[unquote_ends] ]),
268 typeconv[unquote_ends] ]),
268 'add_flip': ' '.join([ typeconv[qwflat],
269 'add_flip': ' '.join([ typeconv[qwflat],
269 typeconv[qw_lol],
270 typeconv[qw_lol],
270 typeconv[list_strings] ])
271 typeconv[list_strings] ])
271 }
272 }
272
273
273 # Now actually process the command line
274 # Now actually process the command line
274 getopt = DPyGetOpt.DPyGetOpt()
275 getopt = DPyGetOpt.DPyGetOpt()
275 getopt.setIgnoreCase(0)
276 getopt.setIgnoreCase(0)
276
277
277 getopt.parseConfiguration(opts_names)
278 getopt.parseConfiguration(opts_names)
278
279
279 try:
280 try:
280 getopt.processArguments(argv)
281 getopt.processArguments(argv)
281 except:
282 except:
282 print cmd_line_usage
283 print cmd_line_usage
283 warn('\nError in Arguments: ' + `sys.exc_value`)
284 warn('\nError in Arguments: ' + `sys.exc_value`)
284 sys.exit()
285 sys.exit(1)
285
286
286 # convert the options dict to a struct for much lighter syntax later
287 # convert the options dict to a struct for much lighter syntax later
287 opts = Struct(getopt.optionValues)
288 opts = Struct(getopt.optionValues)
288 args = getopt.freeValues
289 args = getopt.freeValues
289
290
290 # this is the struct (which has default values at this point) with which
291 # this is the struct (which has default values at this point) with which
291 # we make all decisions:
292 # we make all decisions:
292 opts_all.update(opts)
293 opts_all.update(opts)
293
294
294 # Options that force an immediate exit
295 # Options that force an immediate exit
295 if opts_all.help:
296 if opts_all.help:
296 page(cmd_line_usage)
297 page(cmd_line_usage)
297 sys.exit()
298 sys.exit()
298
299
299 if opts_all.Version:
300 if opts_all.Version:
300 print __version__
301 print __version__
301 sys.exit()
302 sys.exit()
302
303
303 if opts_all.magic_docstrings:
304 if opts_all.magic_docstrings:
304 IP.magic_magic('-latex')
305 IP.magic_magic('-latex')
305 sys.exit()
306 sys.exit()
306
307
307 # Create user config directory if it doesn't exist. This must be done
308 # Create user config directory if it doesn't exist. This must be done
308 # *after* getting the cmd line options.
309 # *after* getting the cmd line options.
309 if not os.path.isdir(opts_all.ipythondir):
310 if not os.path.isdir(opts_all.ipythondir):
310 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
311 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
311
312
312 # upgrade user config files while preserving a copy of the originals
313 # upgrade user config files while preserving a copy of the originals
313 if opts_all.upgrade:
314 if opts_all.upgrade:
314 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
315 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
315
316
316 # check mutually exclusive options in the *original* command line
317 # check mutually exclusive options in the *original* command line
317 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
318 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
318 qw('classic profile'),qw('classic rcfile')])
319 qw('classic profile'),qw('classic rcfile')])
319
320
320 # default logfilename used when -log is called.
321 # default logfilename used when -log is called.
321 IP.LOGDEF = 'ipython.log'
322 IP.LOGDEF = 'ipython.log'
322
323
323 #---------------------------------------------------------------------------
324 #---------------------------------------------------------------------------
324 # Log replay
325 # Log replay
325
326
326 # if -logplay, we need to 'become' the other session. That basically means
327 # if -logplay, we need to 'become' the other session. That basically means
327 # replacing the current command line environment with that of the old
328 # replacing the current command line environment with that of the old
328 # session and moving on.
329 # session and moving on.
329
330
330 # this is needed so that later we know we're in session reload mode, as
331 # this is needed so that later we know we're in session reload mode, as
331 # opts_all will get overwritten:
332 # opts_all will get overwritten:
332 load_logplay = 0
333 load_logplay = 0
333
334
334 if opts_all.logplay:
335 if opts_all.logplay:
335 load_logplay = opts_all.logplay
336 load_logplay = opts_all.logplay
336 opts_debug_save = opts_all.debug
337 opts_debug_save = opts_all.debug
337 try:
338 try:
338 logplay = open(opts_all.logplay)
339 logplay = open(opts_all.logplay)
339 except IOError:
340 except IOError:
340 if opts_all.debug: IP.InteractiveTB()
341 if opts_all.debug: IP.InteractiveTB()
341 warn('Could not open logplay file '+`opts_all.logplay`)
342 warn('Could not open logplay file '+`opts_all.logplay`)
342 # restore state as if nothing had happened and move on, but make
343 # restore state as if nothing had happened and move on, but make
343 # sure that later we don't try to actually load the session file
344 # sure that later we don't try to actually load the session file
344 logplay = None
345 logplay = None
345 load_logplay = 0
346 load_logplay = 0
346 del opts_all.logplay
347 del opts_all.logplay
347 else:
348 else:
348 try:
349 try:
349 logplay.readline()
350 logplay.readline()
350 logplay.readline();
351 logplay.readline();
351 # this reloads that session's command line
352 # this reloads that session's command line
352 cmd = logplay.readline()[6:]
353 cmd = logplay.readline()[6:]
353 exec cmd
354 exec cmd
354 # restore the true debug flag given so that the process of
355 # restore the true debug flag given so that the process of
355 # session loading itself can be monitored.
356 # session loading itself can be monitored.
356 opts.debug = opts_debug_save
357 opts.debug = opts_debug_save
357 # save the logplay flag so later we don't overwrite the log
358 # save the logplay flag so later we don't overwrite the log
358 opts.logplay = load_logplay
359 opts.logplay = load_logplay
359 # now we must update our own structure with defaults
360 # now we must update our own structure with defaults
360 opts_all.update(opts)
361 opts_all.update(opts)
361 # now load args
362 # now load args
362 cmd = logplay.readline()[6:]
363 cmd = logplay.readline()[6:]
363 exec cmd
364 exec cmd
364 logplay.close()
365 logplay.close()
365 except:
366 except:
366 logplay.close()
367 logplay.close()
367 if opts_all.debug: IP.InteractiveTB()
368 if opts_all.debug: IP.InteractiveTB()
368 warn("Logplay file lacking full configuration information.\n"
369 warn("Logplay file lacking full configuration information.\n"
369 "I'll try to read it, but some things may not work.")
370 "I'll try to read it, but some things may not work.")
370
371
371 #-------------------------------------------------------------------------
372 #-------------------------------------------------------------------------
372 # set up output traps: catch all output from files, being run, modules
373 # set up output traps: catch all output from files, being run, modules
373 # loaded, etc. Then give it to the user in a clean form at the end.
374 # loaded, etc. Then give it to the user in a clean form at the end.
374
375
375 msg_out = 'Output messages. '
376 msg_out = 'Output messages. '
376 msg_err = 'Error messages. '
377 msg_err = 'Error messages. '
377 msg_sep = '\n'
378 msg_sep = '\n'
378 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
379 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
379 msg_err,msg_sep,debug,
380 msg_err,msg_sep,debug,
380 quiet_out=1),
381 quiet_out=1),
381 user_exec = OutputTrap('User File Execution',msg_out,
382 user_exec = OutputTrap('User File Execution',msg_out,
382 msg_err,msg_sep,debug),
383 msg_err,msg_sep,debug),
383 logplay = OutputTrap('Log Loader',msg_out,
384 logplay = OutputTrap('Log Loader',msg_out,
384 msg_err,msg_sep,debug),
385 msg_err,msg_sep,debug),
385 summary = ''
386 summary = ''
386 )
387 )
387
388
388 #-------------------------------------------------------------------------
389 #-------------------------------------------------------------------------
389 # Process user ipythonrc-type configuration files
390 # Process user ipythonrc-type configuration files
390
391
391 # turn on output trapping and log to msg.config
392 # turn on output trapping and log to msg.config
392 # remember that with debug on, trapping is actually disabled
393 # remember that with debug on, trapping is actually disabled
393 msg.config.trap_all()
394 msg.config.trap_all()
394
395
395 # look for rcfile in current or default directory
396 # look for rcfile in current or default directory
396 try:
397 try:
397 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
398 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
398 except IOError:
399 except IOError:
399 if opts_all.debug: IP.InteractiveTB()
400 if opts_all.debug: IP.InteractiveTB()
400 warn('Configuration file %s not found. Ignoring request.'
401 warn('Configuration file %s not found. Ignoring request.'
401 % (opts_all.rcfile) )
402 % (opts_all.rcfile) )
402
403
403 # 'profiles' are a shorthand notation for config filenames
404 # 'profiles' are a shorthand notation for config filenames
404 if opts_all.profile:
405 if opts_all.profile:
405 try:
406 try:
406 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
407 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
407 + rc_suffix,
408 + rc_suffix,
408 opts_all.ipythondir)
409 opts_all.ipythondir)
409 except IOError:
410 except IOError:
410 if opts_all.debug: IP.InteractiveTB()
411 if opts_all.debug: IP.InteractiveTB()
411 opts.profile = '' # remove profile from options if invalid
412 opts.profile = '' # remove profile from options if invalid
412 warn('Profile configuration file %s not found. Ignoring request.'
413 warn('Profile configuration file %s not found. Ignoring request.'
413 % (opts_all.profile) )
414 % (opts_all.profile) )
414
415
415 # load the config file
416 # load the config file
416 rcfiledata = None
417 rcfiledata = None
417 if opts_all.quick:
418 if opts_all.quick:
418 print 'Launching IPython in quick mode. No config file read.'
419 print 'Launching IPython in quick mode. No config file read.'
419 elif opts_all.classic:
420 elif opts_all.classic:
420 print 'Launching IPython in classic mode. No config file read.'
421 print 'Launching IPython in classic mode. No config file read.'
421 elif opts_all.rcfile:
422 elif opts_all.rcfile:
422 try:
423 try:
423 cfg_loader = ConfigLoader(conflict)
424 cfg_loader = ConfigLoader(conflict)
424 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
425 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
425 'include',opts_all.ipythondir,
426 'include',opts_all.ipythondir,
426 purge = 1,
427 purge = 1,
427 unique = conflict['preserve'])
428 unique = conflict['preserve'])
428 except:
429 except:
429 IP.InteractiveTB()
430 IP.InteractiveTB()
430 warn('Problems loading configuration file '+
431 warn('Problems loading configuration file '+
431 `opts_all.rcfile`+
432 `opts_all.rcfile`+
432 '\nStarting with default -bare bones- configuration.')
433 '\nStarting with default -bare bones- configuration.')
433 else:
434 else:
434 warn('No valid configuration file found in either currrent directory\n'+
435 warn('No valid configuration file found in either currrent directory\n'+
435 'or in the IPython config. directory: '+`opts_all.ipythondir`+
436 'or in the IPython config. directory: '+`opts_all.ipythondir`+
436 '\nProceeding with internal defaults.')
437 '\nProceeding with internal defaults.')
437
438
438 #------------------------------------------------------------------------
439 #------------------------------------------------------------------------
439 # Set exception handlers in mode requested by user.
440 # Set exception handlers in mode requested by user.
440 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
441 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
441 IP.magic_xmode(opts_all.xmode)
442 IP.magic_xmode(opts_all.xmode)
442 otrap.release_out()
443 otrap.release_out()
443
444
444 #------------------------------------------------------------------------
445 #------------------------------------------------------------------------
445 # Execute user config
446 # Execute user config
446
447
447 # first, create a valid config structure with the right precedence order:
448 # first, create a valid config structure with the right precedence order:
448 # defaults < rcfile < command line
449 # defaults < rcfile < command line. We make it as a local (IP_rc) to
449 IP.rc = rc_def.copy()
450 # avoid a zillion attribute accesses. Right before returning, this will
450 IP.rc.update(opts_def)
451 # be set as IP.rc.
452 IP_rc = rc_def.copy()
453 IP_rc.update(opts_def)
451 if rcfiledata:
454 if rcfiledata:
452 # now we can update
455 # now we can update
453 IP.rc.update(rcfiledata)
456 IP_rc.update(rcfiledata)
454 IP.rc.update(opts)
457 IP_rc.update(opts)
455 IP.rc.update(rc_override)
458 IP_rc.update(rc_override)
456
459
457 # Store the original cmd line for reference:
460 # Store the original cmd line for reference:
458 IP.rc.opts = opts
461 IP_rc.opts = opts
459 IP.rc.args = args
462 IP_rc.args = args
460
463
461 # create a *runtime* Struct like rc for holding parameters which may be
464 # create a *runtime* Struct like rc for holding parameters which may be
462 # created and/or modified by runtime user extensions.
465 # created and/or modified by runtime user extensions.
463 IP.runtime_rc = Struct()
466 IP.runtime_rc = Struct()
464
467
465 # from this point on, all config should be handled through IP.rc,
468 # from this point on, all config should be handled through IP_rc,
466 # opts* shouldn't be used anymore.
469 # opts* shouldn't be used anymore.
467
470
468 # add personal .ipython dir to sys.path so that users can put things in
471 # add personal .ipython dir to sys.path so that users can put things in
469 # there for customization
472 # there for customization
470 sys.path.append(IP.rc.ipythondir)
473 sys.path.append(IP_rc.ipythondir)
471 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
474 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
472
475
473 # update IP.rc with some special things that need manual
476 # update IP_rc with some special things that need manual
474 # tweaks. Basically options which affect other options. I guess this
477 # tweaks. Basically options which affect other options. I guess this
475 # should just be written so that options are fully orthogonal and we
478 # should just be written so that options are fully orthogonal and we
476 # wouldn't worry about this stuff!
479 # wouldn't worry about this stuff!
477
480
478 if IP.rc.classic:
481 if IP_rc.classic:
479 IP.rc.quick = 1
482 IP_rc.quick = 1
480 IP.rc.cache_size = 0
483 IP_rc.cache_size = 0
481 IP.rc.pprint = 0
484 IP_rc.pprint = 0
482 IP.rc.prompt_in1 = '>>> '
485 IP_rc.prompt_in1 = '>>> '
483 IP.rc.prompt_in2 = '... '
486 IP_rc.prompt_in2 = '... '
484 IP.rc.prompt_out = ''
487 IP_rc.prompt_out = ''
485 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
488 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
486 IP.rc.colors = 'NoColor'
489 IP_rc.colors = 'NoColor'
487 IP.rc.xmode = 'Plain'
490 IP_rc.xmode = 'Plain'
488
491
489 # configure readline
492 # configure readline
490 # Define the history file for saving commands in between sessions
493 # Define the history file for saving commands in between sessions
491 if IP.rc.profile:
494 if IP_rc.profile:
492 histfname = 'history-%s' % IP.rc.profile
495 histfname = 'history-%s' % IP_rc.profile
493 else:
496 else:
494 histfname = 'history'
497 histfname = 'history'
495 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
498 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
496 # Load readline proper
497 if IP.rc.readline:
498 IP.init_readline()
499
499
500 # update exception handlers with rc file status
500 # update exception handlers with rc file status
501 otrap.trap_out() # I don't want these messages ever.
501 otrap.trap_out() # I don't want these messages ever.
502 IP.magic_xmode(IP.rc.xmode)
502 IP.magic_xmode(IP_rc.xmode)
503 otrap.release_out()
503 otrap.release_out()
504
504
505 # activate logging if requested and not reloading a log
505 # activate logging if requested and not reloading a log
506 if IP.rc.logplay:
506 if IP_rc.logplay:
507 IP.magic_logstart(IP.rc.logplay + ' append')
507 IP.magic_logstart(IP_rc.logplay + ' append')
508 elif IP.rc.logfile:
508 elif IP_rc.logfile:
509 IP.magic_logstart(IP.rc.logfile)
509 IP.magic_logstart(IP_rc.logfile)
510 elif IP.rc.log:
510 elif IP_rc.log:
511 IP.magic_logstart()
511 IP.magic_logstart()
512
512
513 # find user editor so that it we don't have to look it up constantly
513 # find user editor so that it we don't have to look it up constantly
514 if IP.rc.editor.strip()=='0':
514 if IP_rc.editor.strip()=='0':
515 try:
515 try:
516 ed = os.environ['EDITOR']
516 ed = os.environ['EDITOR']
517 except KeyError:
517 except KeyError:
518 if os.name == 'posix':
518 if os.name == 'posix':
519 ed = 'vi' # the only one guaranteed to be there!
519 ed = 'vi' # the only one guaranteed to be there!
520 else:
520 else:
521 ed = 'notepad' # same in Windows!
521 ed = 'notepad' # same in Windows!
522 IP.rc.editor = ed
522 IP_rc.editor = ed
523
524 # Keep track of whether this is an embedded instance or not (useful for
525 # post-mortems).
526 IP_rc.embedded = IP.embedded
523
527
524 # Recursive reload
528 # Recursive reload
525 try:
529 try:
526 from IPython import deep_reload
530 from IPython import deep_reload
527 if IP.rc.deep_reload:
531 if IP_rc.deep_reload:
528 __builtin__.reload = deep_reload.reload
532 __builtin__.reload = deep_reload.reload
529 else:
533 else:
530 __builtin__.dreload = deep_reload.reload
534 __builtin__.dreload = deep_reload.reload
531 del deep_reload
535 del deep_reload
532 except ImportError:
536 except ImportError:
533 pass
537 pass
534
538
535 # Save the current state of our namespace so that the interactive shell
539 # Save the current state of our namespace so that the interactive shell
536 # can later know which variables have been created by us from config files
540 # can later know which variables have been created by us from config files
537 # and loading. This way, loading a file (in any way) is treated just like
541 # and loading. This way, loading a file (in any way) is treated just like
538 # defining things on the command line, and %who works as expected.
542 # defining things on the command line, and %who works as expected.
539
543
540 # DON'T do anything that affects the namespace beyond this point!
544 # DON'T do anything that affects the namespace beyond this point!
541 IP.internal_ns = __main__.__dict__.copy()
545 IP.internal_ns.update(__main__.__dict__)
542
546
543 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
547 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
544
548
545 # Now run through the different sections of the users's config
549 # Now run through the different sections of the users's config
546 if IP.rc.debug:
550 if IP_rc.debug:
547 print 'Trying to execute the following configuration structure:'
551 print 'Trying to execute the following configuration structure:'
548 print '(Things listed first are deeper in the inclusion tree and get'
552 print '(Things listed first are deeper in the inclusion tree and get'
549 print 'loaded first).\n'
553 print 'loaded first).\n'
550 pprint(IP.rc.__dict__)
554 pprint(IP_rc.__dict__)
551
555
552 for mod in IP.rc.import_mod:
556 for mod in IP_rc.import_mod:
553 try:
557 try:
554 exec 'import '+mod in IP.user_ns
558 exec 'import '+mod in IP.user_ns
555 except :
559 except :
556 IP.InteractiveTB()
560 IP.InteractiveTB()
557 import_fail_info(mod)
561 import_fail_info(mod)
558
562
559 for mod_fn in IP.rc.import_some:
563 for mod_fn in IP_rc.import_some:
560 if mod_fn == []: break
564 if mod_fn == []: break
561 mod,fn = mod_fn[0],','.join(mod_fn[1:])
565 mod,fn = mod_fn[0],','.join(mod_fn[1:])
562 try:
566 try:
563 exec 'from '+mod+' import '+fn in IP.user_ns
567 exec 'from '+mod+' import '+fn in IP.user_ns
564 except :
568 except :
565 IP.InteractiveTB()
569 IP.InteractiveTB()
566 import_fail_info(mod,fn)
570 import_fail_info(mod,fn)
567
571
568 for mod in IP.rc.import_all:
572 for mod in IP_rc.import_all:
569 try:
573 try:
570 exec 'from '+mod+' import *' in IP.user_ns
574 exec 'from '+mod+' import *' in IP.user_ns
571 except :
575 except :
572 IP.InteractiveTB()
576 IP.InteractiveTB()
573 import_fail_info(mod)
577 import_fail_info(mod)
574
578
575 for code in IP.rc.execute:
579 for code in IP_rc.execute:
576 try:
580 try:
577 exec code in IP.user_ns
581 exec code in IP.user_ns
578 except:
582 except:
579 IP.InteractiveTB()
583 IP.InteractiveTB()
580 warn('Failure executing code: ' + `code`)
584 warn('Failure executing code: ' + `code`)
581
585
582 # Execute the files the user wants in ipythonrc
586 # Execute the files the user wants in ipythonrc
583 for file in IP.rc.execfile:
587 for file in IP_rc.execfile:
584 try:
588 try:
585 file = filefind(file,sys.path+[IPython_dir])
589 file = filefind(file,sys.path+[IPython_dir])
586 except IOError:
590 except IOError:
587 warn(itpl('File $file not found. Skipping it.'))
591 warn(itpl('File $file not found. Skipping it.'))
588 else:
592 else:
589 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
593 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
590
594
591 # Load user aliases
595 # Load user aliases
592 for alias in IP.rc.alias:
596 for alias in IP_rc.alias:
593 IP.magic_alias(alias)
597 IP.magic_alias(alias)
594
598
595 # release stdout and stderr and save config log into a global summary
599 # release stdout and stderr and save config log into a global summary
596 msg.config.release_all()
600 msg.config.release_all()
597 if IP.rc.messages:
601 if IP_rc.messages:
598 msg.summary += msg.config.summary_all()
602 msg.summary += msg.config.summary_all()
599
603
600 #------------------------------------------------------------------------
604 #------------------------------------------------------------------------
601 # Setup interactive session
605 # Setup interactive session
602
606
603 # Now we should be fully configured. We can then execute files or load
607 # Now we should be fully configured. We can then execute files or load
604 # things only needed for interactive use. Then we'll open the shell.
608 # things only needed for interactive use. Then we'll open the shell.
605
609
606 # Take a snapshot of the user namespace before opening the shell. That way
610 # Take a snapshot of the user namespace before opening the shell. That way
607 # we'll be able to identify which things were interactively defined and
611 # we'll be able to identify which things were interactively defined and
608 # which were defined through config files.
612 # which were defined through config files.
609 IP.user_config_ns = IP.user_ns.copy()
613 IP.user_config_ns = IP.user_ns.copy()
610
614
611 # Force reading a file as if it were a session log. Slower but safer.
615 # Force reading a file as if it were a session log. Slower but safer.
612 if load_logplay:
616 if load_logplay:
613 print 'Replaying log...'
617 print 'Replaying log...'
614 try:
618 try:
615 if IP.rc.debug:
619 if IP_rc.debug:
616 logplay_quiet = 0
620 logplay_quiet = 0
617 else:
621 else:
618 logplay_quiet = 1
622 logplay_quiet = 1
619
623
620 msg.logplay.trap_all()
624 msg.logplay.trap_all()
621 IP.safe_execfile(load_logplay,IP.user_ns,
625 IP.safe_execfile(load_logplay,IP.user_ns,
622 islog = 1, quiet = logplay_quiet)
626 islog = 1, quiet = logplay_quiet)
623 msg.logplay.release_all()
627 msg.logplay.release_all()
624 if IP.rc.messages:
628 if IP_rc.messages:
625 msg.summary += msg.logplay.summary_all()
629 msg.summary += msg.logplay.summary_all()
626 except:
630 except:
627 warn('Problems replaying logfile %s.' % load_logplay)
631 warn('Problems replaying logfile %s.' % load_logplay)
628 IP.InteractiveTB()
632 IP.InteractiveTB()
629
633
630 # Load remaining files in command line
634 # Load remaining files in command line
631 msg.user_exec.trap_all()
635 msg.user_exec.trap_all()
632
636
633 # Do NOT execute files named in the command line as scripts to be loaded
637 # Do NOT execute files named in the command line as scripts to be loaded
634 # by embedded instances. Doing so has the potential for an infinite
638 # by embedded instances. Doing so has the potential for an infinite
635 # recursion if there are exceptions thrown in the process.
639 # recursion if there are exceptions thrown in the process.
636
640
637 # XXX FIXME: the execution of user files should be moved out to after
641 # XXX FIXME: the execution of user files should be moved out to after
638 # ipython is fully initialized, just as if they were run via %run at the
642 # ipython is fully initialized, just as if they were run via %run at the
639 # ipython prompt. This would also give them the benefit of ipython's
643 # ipython prompt. This would also give them the benefit of ipython's
640 # nice tracebacks.
644 # nice tracebacks.
641
645
642 if not embedded and IP.rc.args:
646 if not embedded and IP_rc.args:
643 name_save = IP.user_ns['__name__']
647 name_save = IP.user_ns['__name__']
644 IP.user_ns['__name__'] = '__main__'
648 IP.user_ns['__name__'] = '__main__'
645 try:
649 try:
646 # Set our own excepthook in case the user code tries to call it
650 # Set our own excepthook in case the user code tries to call it
647 # directly. This prevents triggering the IPython crash handler.
651 # directly. This prevents triggering the IPython crash handler.
648 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
652 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
649 for run in args:
653 for run in args:
650 IP.safe_execfile(run,IP.user_ns)
654 IP.safe_execfile(run,IP.user_ns)
651 finally:
655 finally:
652 # Reset our crash handler in place
656 # Reset our crash handler in place
653 sys.excepthook = old_excepthook
657 sys.excepthook = old_excepthook
654
658
655 IP.user_ns['__name__'] = name_save
659 IP.user_ns['__name__'] = name_save
656
660
657 msg.user_exec.release_all()
661 msg.user_exec.release_all()
658 if IP.rc.messages:
662 if IP_rc.messages:
659 msg.summary += msg.user_exec.summary_all()
663 msg.summary += msg.user_exec.summary_all()
660
664
661 # since we can't specify a null string on the cmd line, 0 is the equivalent:
665 # since we can't specify a null string on the cmd line, 0 is the equivalent:
662 if IP.rc.nosep:
666 if IP_rc.nosep:
663 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
667 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
664 if IP.rc.separate_in == '0': IP.rc.separate_in = ''
668 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
665 if IP.rc.separate_out == '0': IP.rc.separate_out = ''
669 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
666 if IP.rc.separate_out2 == '0': IP.rc.separate_out2 = ''
670 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
667 IP.rc.separate_in = IP.rc.separate_in.replace('\\n','\n')
671 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
668 IP.rc.separate_out = IP.rc.separate_out.replace('\\n','\n')
672 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
669 IP.rc.separate_out2 = IP.rc.separate_out2.replace('\\n','\n')
673 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
670
674
671 # Determine how many lines at the bottom of the screen are needed for
675 # Determine how many lines at the bottom of the screen are needed for
672 # showing prompts, so we can know wheter long strings are to be printed or
676 # showing prompts, so we can know wheter long strings are to be printed or
673 # paged:
677 # paged:
674 num_lines_bot = IP.rc.separate_in.count('\n')+1
678 num_lines_bot = IP_rc.separate_in.count('\n')+1
675 IP.rc.screen_length = IP.rc.screen_length - num_lines_bot
679 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
676 # Initialize cache, set in/out prompts and printing system
680 # Initialize cache, set in/out prompts and printing system
677 IP.outputcache = CachedOutput(IP.rc.cache_size,
681 IP.outputcache = CachedOutput(IP_rc.cache_size,
678 IP.rc.pprint,
682 IP_rc.pprint,
679 input_sep = IP.rc.separate_in,
683 input_sep = IP_rc.separate_in,
680 output_sep = IP.rc.separate_out,
684 output_sep = IP_rc.separate_out,
681 output_sep2 = IP.rc.separate_out2,
685 output_sep2 = IP_rc.separate_out2,
682 ps1 = IP.rc.prompt_in1,
686 ps1 = IP_rc.prompt_in1,
683 ps2 = IP.rc.prompt_in2,
687 ps2 = IP_rc.prompt_in2,
684 ps_out = IP.rc.prompt_out,
688 ps_out = IP_rc.prompt_out,
685 user_ns = IP.user_ns,
689 user_ns = IP.user_ns,
686 input_hist = IP.input_hist,
690 input_hist = IP.input_hist,
687 pad_left = IP.rc.prompts_pad_left)
691 pad_left = IP_rc.prompts_pad_left)
688
689 # Set user colors (don't do it in the constructor above so that it doesn't
690 # crash if colors option is invalid)
691 IP.magic_colors(IP.rc.colors)
692
692
693 # user may have over-ridden the default print hook:
693 # user may have over-ridden the default print hook:
694 try:
694 try:
695 IP.outputcache.__class__.display = IP.hooks.display
695 IP.outputcache.__class__.display = IP.hooks.display
696 except AttributeError:
696 except AttributeError:
697 pass
697 pass
698
698
699 # Set calling of pdb on exceptions
699 # Set calling of pdb on exceptions
700 IP.InteractiveTB.call_pdb = IP.rc.pdb
700 IP.InteractiveTB.call_pdb = IP_rc.pdb
701
701
702 # I don't like assigning globally to sys, because it means when embedding
702 # I don't like assigning globally to sys, because it means when embedding
703 # instances, each embedded instance overrides the previous choice. But
703 # instances, each embedded instance overrides the previous choice. But
704 # sys.displayhook seems to be called internally by exec, so I don't see a
704 # sys.displayhook seems to be called internally by exec, so I don't see a
705 # way around it.
705 # way around it.
706 sys.displayhook = IP.outputcache
706 sys.displayhook = IP.outputcache
707
707
708 # we need to know globally if we're caching i/o or not
708 # we need to know globally if we're caching i/o or not
709 IP.do_full_cache = IP.outputcache.do_full_cache
709 IP.do_full_cache = IP.outputcache.do_full_cache
710
710
711 # configure startup banner
711 # configure startup banner
712 if IP.rc.c: # regular python doesn't print the banner with -c
712 if IP_rc.c: # regular python doesn't print the banner with -c
713 IP.rc.banner = 0
713 IP_rc.banner = 0
714 if IP.rc.banner:
714 if IP_rc.banner:
715 IP.BANNER = '\n'.join(IP.BANNER_PARTS)
715 BANN_P = IP.BANNER_PARTS
716 else:
716 else:
717 IP.BANNER = ''
717 BANN_P = []
718
718
719 if IP.rc.profile: IP.BANNER += '\nIPython profile: '+IP.rc.profile+'\n'
719 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
720
720
721 # add message log (possibly empty)
721 # add message log (possibly empty)
722 IP.BANNER += msg.summary
722 if msg.summary: BANN_P.append(msg.summary)
723 # Final banner is a string
724 IP.BANNER = '\n'.join(BANN_P)
725
726 # Assign the IP_rc object as an attribute of IP
727 IP.rc = IP_rc
723
728
729 # Finalize the IPython instance. This assumes the rc structure is fully
730 # in place.
724 IP.post_config_initialization()
731 IP.post_config_initialization()
725
732
726 return IP
733 return IP
727 #************************ end of file <ipmaker.py> **************************
734 #************************ end of file <ipmaker.py> **************************
@@ -1,156 +1,138 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Support for wildcard pattern matching in object inspection.
2 """Support for wildcard pattern matching in object inspection.
3
3
4 $Id: OInspect.py 608 2005-07-06 17:52:32Z fperez $
4 $Id: OInspect.py 608 2005-07-06 17:52:32Z fperez $
5 """
5 """
6
6
7 #*****************************************************************************
7 #*****************************************************************************
8 # Copyright (C) 2005 Jörgen Stenarson <jorgen.stenarson@bostream.nu>
8 # Copyright (C) 2005 Jörgen Stenarson <jorgen.stenarson@bostream.nu>
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 from IPython import Release
14 from IPython import Release
15 __author__ = "Jörgen Stenarson <jorgen.stenarson@bostream.nu>"
15 __author__ = "Jörgen Stenarson <jorgen.stenarson@bostream.nu>"
16 __license__ = Release.license
16 __license__ = Release.license
17
17
18 import __builtin__
18 import __builtin__
19 import types
19 import types
20 import re
20 import re
21 import pprint
21 import pprint
22 import exceptions
22 import exceptions
23 import pdb
23 import pdb
24 import IPython.genutils as genutils
25
24
26 def create_typestr2type_dicts(dont_include_in_type2type2str=["lambda"]):
25 def create_typestr2type_dicts(dont_include_in_type2type2str=["lambda"]):
27 """Return dictionaries mapping lower case typename to type objects, from
26 """Return dictionaries mapping lower case typename to type objects, from
28 the types package, and vice versa."""
27 the types package, and vice versa."""
29 typenamelist=[]
28 typenamelist=[]
30 for tname in dir(types):
29 for tname in dir(types):
31 if tname[-4:]=="Type":
30 if tname[-4:]=="Type":
32 typenamelist.append(tname)
31 typenamelist.append(tname)
33 typestr2type={}
32 typestr2type={}
34 type2typestr={}
33 type2typestr={}
35 for tname in typenamelist:
34 for tname in typenamelist:
36 name=tname[:-4].lower()
35 name=tname[:-4].lower()
37 obj=getattr(types,tname)
36 obj=getattr(types,tname)
38 typestr2type[name]=getattr(types,tname)
37 typestr2type[name]=getattr(types,tname)
39 if name in dont_include_in_type2type2str:
38 if name in dont_include_in_type2type2str:
40 type2typestr[obj]=name
39 type2typestr[obj]=name
41 return typestr2type,type2typestr
40 return typestr2type,type2typestr
42
41
43 typestr2type,type2typestr=create_typestr2type_dicts()
42 typestr2type,type2typestr=create_typestr2type_dicts()
44
43
45 def is_type(obj,typestr_or_type):
44 def is_type(obj,typestr_or_type):
46 """is_type(obj,typestr_or_type) verifies if obj is of a certain type or
45 """is_type(obj,typestr_or_type) verifies if obj is of a certain type or
47 group of types takes strings as parameters of the for 'tuple'<->TupleType
46 group of types takes strings as parameters of the for 'tuple'<->TupleType
48 'all' matches all types. TODO: Should be extended for choosing more than
47 'all' matches all types. TODO: Should be extended for choosing more than
49 one type
48 one type
50 """
49 """
51 if typestr_or_type=="all":
50 if typestr_or_type=="all":
52 return True
51 return True
53 if type(typestr_or_type)==types.TypeType:
52 if type(typestr_or_type)==types.TypeType:
54 test_type=typestr_or_type
53 test_type=typestr_or_type
55 else:
54 else:
56 test_type=typestr2type.get(typestr_or_type,False)
55 test_type=typestr2type.get(typestr_or_type,False)
57 if test_type:
56 if test_type:
58 return isinstance(obj,test_type)
57 return isinstance(obj,test_type)
59 else:
58 else:
60 return False
59 return False
61
60
62 def show_hidden(str,showhidden=False):
61 def show_hidden(str,show_all=False):
63 """Return true for strings starting with single _ if showhidden is true."""
62 """Return true for strings starting with single _ if show_all is true."""
64 return showhidden or str.startswith("__") or not str.startswith("_")
63 return show_all or str.startswith("__") or not str.startswith("_")
65
64
66
65
67 class NameSpace(object):
66 class NameSpace(object):
68 """NameSpace holds the dictionary for a namespace and implements filtering
67 """NameSpace holds the dictionary for a namespace and implements filtering
69 on name and types"""
68 on name and types"""
70 def __init__(self,obj,namepattern="*",typepattern="all",ignorecase=True,
69 def __init__(self,obj,name_pattern="*",type_pattern="all",ignore_case=True,
71 showhidden=True):
70 show_all=True):
72 self.showhidden = showhidden #Hide names beginning with single _
71 self.show_all = show_all #Hide names beginning with single _
73 self.object = obj
72 self.object = obj
74 self.namepattern = namepattern
73 self.name_pattern = name_pattern
75 self.typepattern = typepattern
74 self.type_pattern = type_pattern
76 self.ignorecase = ignorecase
75 self.ignore_case = ignore_case
77
76
78 # We should only match EXACT dicts here, so DON'T use isinstance()
77 # We should only match EXACT dicts here, so DON'T use isinstance()
79 if type(obj) == types.DictType:
78 if type(obj) == types.DictType:
80 self._ns = obj
79 self._ns = obj
81 else:
80 else:
82 self._ns = dict([(key,getattr(obj,key)) for key in dir(obj)
81 self._ns = dict([(key,getattr(obj,key)) for key in dir(obj)
83 if isinstance(key, basestring)])
82 if isinstance(key, basestring)])
84
83
85 def get_ns(self):
84 def get_ns(self):
86 """Return name space dictionary with objects matching type and name patterns."""
85 """Return name space dictionary with objects matching type and name patterns."""
87 return self.filter(self.namepattern,self.typepattern)
86 return self.filter(self.name_pattern,self.type_pattern)
88 ns=property(get_ns)
87 ns=property(get_ns)
89
88
90 def get_ns_names(self):
89 def get_ns_names(self):
91 """Return list of object names in namespace that match the patterns."""
90 """Return list of object names in namespace that match the patterns."""
92 return self.ns.keys()
91 return self.ns.keys()
93 ns_names=property(get_ns_names,doc="List of objects in name space that "
92 ns_names=property(get_ns_names,doc="List of objects in name space that "
94 "match the type and name patterns.")
93 "match the type and name patterns.")
95
94
96 def filter(self,namepattern,typepattern):
95 def filter(self,name_pattern,type_pattern):
97 """Return dictionary of filtered namespace."""
96 """Return dictionary of filtered namespace."""
98 def glob_filter(lista,namepattern,hidehidden,ignorecase):
97 def glob_filter(lista,name_pattern,hidehidden,ignore_case):
99 """Return list of elements in lista that match pattern."""
98 """Return list of elements in lista that match pattern."""
100 pattern=namepattern.replace("*",".*")
99 pattern=name_pattern.replace("*",".*")
101 if ignorecase:
100 if ignore_case:
102 reg=re.compile(pattern+"$",re.I)
101 reg=re.compile(pattern+"$",re.I)
103 else:
102 else:
104 reg=re.compile(pattern+"$")
103 reg=re.compile(pattern+"$")
105 result=[x for x in lista if reg.match(x) and show_hidden(x,hidehidden)]
104 result=[x for x in lista if reg.match(x) and show_hidden(x,hidehidden)]
106 return result
105 return result
107 ns=self._ns
106 ns=self._ns
108 #Filter namespace by the namepattern
107 #Filter namespace by the name_pattern
109 all=[(x,ns[x]) for x in glob_filter(ns.keys(),namepattern,
108 all=[(x,ns[x]) for x in glob_filter(ns.keys(),name_pattern,
110 self.showhidden,self.ignorecase)]
109 self.show_all,self.ignore_case)]
111 #Filter namespace by typepattern
110 #Filter namespace by type_pattern
112 all=[(key,obj) for key,obj in all if is_type(obj,typepattern)]
111 all=[(key,obj) for key,obj in all if is_type(obj,type_pattern)]
113 all=dict(all)
112 all=dict(all)
114 return all
113 return all
115
114
116 #TODO: Implement dictionary like access to filtered name space?
115 #TODO: Implement dictionary like access to filtered name space?
117
116
118 def list_namespace(namespace,typepattern,filter,ignorecase=False,showhidden=False):
117 def list_namespace(namespace,type_pattern,filter,ignore_case=False,show_all=False):
119 """Return dictionary of all objects in namespace that matches typepattern
118 """Return dictionary of all objects in namespace that matches type_pattern
120 and filter."""
119 and filter."""
121 patternlist=filter.split(".")
120 pattern_list=filter.split(".")
122 if len(patternlist)==1:
121 if len(pattern_list)==1:
123 ns=NameSpace(namespace,namepattern=patternlist[0],typepattern=typepattern,
122 ns=NameSpace(namespace,name_pattern=pattern_list[0],type_pattern=type_pattern,
124 ignorecase=ignorecase,showhidden=showhidden)
123 ignore_case=ignore_case,show_all=show_all)
125 return ns.ns
124 return ns.ns
126 if len(patternlist)>1:
125 else:
127 #This is where we can change if all objects should be searched or only moduleas
126 # This is where we can change if all objects should be searched or
128 #Just change the typepattern to module to search only modules
127 # only modules. Just change the type_pattern to module to search only
129 ns=NameSpace(namespace,
128 # modules
130 namepattern=patternlist[0],
129 ns=NameSpace(namespace,name_pattern=pattern_list[0],type_pattern="all",
131 typepattern="all",ignorecase=ignorecase,showhidden=showhidden)
130 ignore_case=ignore_case,show_all=show_all)
132 res={}
131 res={}
133 nsdict=ns.ns
132 nsdict=ns.ns
134 for name,obj in nsdict.iteritems():
133 for name,obj in nsdict.iteritems():
135 ns=list_namespace(obj,typepattern,".".join(patternlist[1:]),
134 ns=list_namespace(obj,type_pattern,".".join(pattern_list[1:]),
136 ignorecase=ignorecase,showhidden=showhidden)
135 ignore_case=ignore_case,show_all=show_all)
137 for inner_name,inner_obj in ns.iteritems():
136 for inner_name,inner_obj in ns.iteritems():
138 res["%s.%s"%(name,inner_name)]=inner_obj
137 res["%s.%s"%(name,inner_name)]=inner_obj
139 return res
138 return res
140
141 def choose_namespaces(shell,cmds):
142 """Returns a list of namespaces modified by arguments."""
143 nslist=genutils.mkdict(user=shell.user_ns,internal=shell.internal_ns,
144 builtin=__builtin__.__dict__,alias=shell.alias_table)
145 default_list=["user","builtin"] # Should this list be a user option??
146 for cmd in cmds:
147 if cmd[0]=="-": #remove from defaultlist
148 if cmd[1:] in default_list:
149 default_list.remove(cmd[1:])
150 elif cmd[0]=="+":
151 if cmd[1:] not in default_list and cmd[1:]in nslist:
152 default_list.append(cmd[1:])
153 else:
154 if cmd in nslist:
155 default_list.append(cmd[1:])
156 return [nslist[x] for x in default_list]
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now