##// END OF EJS Templates
result_display can return value. ipapi.is_ipython_session(). %paste -> %cpaste.
vivainio -
Show More

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

@@ -1,2809 +1,2809 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 1071 2006-01-23 21:30:41Z vivainio $"""
4 $Id: Magic.py 1076 2006-01-24 17:27:05Z vivainio $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt
36 from getopt import getopt
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38
38
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 # Homebrewed
45 # Homebrewed
46 from IPython import Debugger, OInspect, wildcard
46 from IPython import Debugger, OInspect, wildcard
47 from IPython.FakeModule import FakeModule
47 from IPython.FakeModule import FakeModule
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.PyColorize import Parser
49 from IPython.PyColorize import Parser
50 from IPython.ipstruct import Struct
50 from IPython.ipstruct import Struct
51 from IPython.macro import Macro
51 from IPython.macro import Macro
52 from IPython.genutils import *
52 from IPython.genutils import *
53 from IPython import platutils
53 from IPython import platutils
54
54
55 #***************************************************************************
55 #***************************************************************************
56 # Utility functions
56 # Utility functions
57 def on_off(tag):
57 def on_off(tag):
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 return ['OFF','ON'][tag]
59 return ['OFF','ON'][tag]
60
60
61 class Bunch: pass
61 class Bunch: pass
62
62
63 #***************************************************************************
63 #***************************************************************************
64 # Main class implementing Magic functionality
64 # Main class implementing Magic functionality
65 class Magic:
65 class Magic:
66 """Magic functions for InteractiveShell.
66 """Magic functions for InteractiveShell.
67
67
68 Shell functions which can be reached as %function_name. All magic
68 Shell functions which can be reached as %function_name. All magic
69 functions should accept a string, which they can parse for their own
69 functions should accept a string, which they can parse for their own
70 needs. This can make some functions easier to type, eg `%cd ../`
70 needs. This can make some functions easier to type, eg `%cd ../`
71 vs. `%cd("../")`
71 vs. `%cd("../")`
72
72
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
74 at the command line, but it is is needed in the definition. """
74 at the command line, but it is is needed in the definition. """
75
75
76 # class globals
76 # class globals
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
78 'Automagic is ON, % prefix NOT needed for magic functions.']
78 'Automagic is ON, % prefix NOT needed for magic functions.']
79
79
80 #......................................................................
80 #......................................................................
81 # some utility functions
81 # some utility functions
82
82
83 def __init__(self,shell):
83 def __init__(self,shell):
84
84
85 self.options_table = {}
85 self.options_table = {}
86 if profile is None:
86 if profile is None:
87 self.magic_prun = self.profile_missing_notice
87 self.magic_prun = self.profile_missing_notice
88 self.shell = shell
88 self.shell = shell
89
89
90 # namespace for holding state we may need
90 # namespace for holding state we may need
91 self._magic_state = Bunch()
91 self._magic_state = Bunch()
92
92
93 def profile_missing_notice(self, *args, **kwargs):
93 def profile_missing_notice(self, *args, **kwargs):
94 error("""\
94 error("""\
95 The profile module could not be found. If you are a Debian user,
95 The profile module could not be found. If you are a Debian user,
96 it has been removed from the standard Debian package because of its non-free
96 it has been removed from the standard Debian package because of its non-free
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
98
98
99 def default_option(self,fn,optstr):
99 def default_option(self,fn,optstr):
100 """Make an entry in the options_table for fn, with value optstr"""
100 """Make an entry in the options_table for fn, with value optstr"""
101
101
102 if fn not in self.lsmagic():
102 if fn not in self.lsmagic():
103 error("%s is not a magic function" % fn)
103 error("%s is not a magic function" % fn)
104 self.options_table[fn] = optstr
104 self.options_table[fn] = optstr
105
105
106 def lsmagic(self):
106 def lsmagic(self):
107 """Return a list of currently available magic functions.
107 """Return a list of currently available magic functions.
108
108
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
110 ['magic_ls','magic_cd',...]"""
110 ['magic_ls','magic_cd',...]"""
111
111
112 # FIXME. This needs a cleanup, in the way the magics list is built.
112 # FIXME. This needs a cleanup, in the way the magics list is built.
113
113
114 # magics in class definition
114 # magics in class definition
115 class_magic = lambda fn: fn.startswith('magic_') and \
115 class_magic = lambda fn: fn.startswith('magic_') and \
116 callable(Magic.__dict__[fn])
116 callable(Magic.__dict__[fn])
117 # in instance namespace (run-time user additions)
117 # in instance namespace (run-time user additions)
118 inst_magic = lambda fn: fn.startswith('magic_') and \
118 inst_magic = lambda fn: fn.startswith('magic_') and \
119 callable(self.__dict__[fn])
119 callable(self.__dict__[fn])
120 # and bound magics by user (so they can access self):
120 # and bound magics by user (so they can access self):
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
122 callable(self.__class__.__dict__[fn])
122 callable(self.__class__.__dict__[fn])
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
126 out = []
126 out = []
127 for fn in magics:
127 for fn in magics:
128 out.append(fn.replace('magic_','',1))
128 out.append(fn.replace('magic_','',1))
129 out.sort()
129 out.sort()
130 return out
130 return out
131
131
132 def extract_input_slices(self,slices):
132 def extract_input_slices(self,slices):
133 """Return as a string a set of input history slices.
133 """Return as a string a set of input history slices.
134
134
135 The set of slices is given as a list of strings (like ['1','4:8','9'],
135 The set of slices is given as a list of strings (like ['1','4:8','9'],
136 since this function is for use by magic functions which get their
136 since this function is for use by magic functions which get their
137 arguments as strings.
137 arguments as strings.
138
138
139 Note that slices can be called with two notations:
139 Note that slices can be called with two notations:
140
140
141 N:M -> standard python form, means including items N...(M-1).
141 N:M -> standard python form, means including items N...(M-1).
142
142
143 N-M -> include items N..M (closed endpoint)."""
143 N-M -> include items N..M (closed endpoint)."""
144
144
145 cmds = []
145 cmds = []
146 for chunk in slices:
146 for chunk in slices:
147 if ':' in chunk:
147 if ':' in chunk:
148 ini,fin = map(int,chunk.split(':'))
148 ini,fin = map(int,chunk.split(':'))
149 elif '-' in chunk:
149 elif '-' in chunk:
150 ini,fin = map(int,chunk.split('-'))
150 ini,fin = map(int,chunk.split('-'))
151 fin += 1
151 fin += 1
152 else:
152 else:
153 ini = int(chunk)
153 ini = int(chunk)
154 fin = ini+1
154 fin = ini+1
155 cmds.append(self.shell.input_hist[ini:fin])
155 cmds.append(self.shell.input_hist[ini:fin])
156 return cmds
156 return cmds
157
157
158 def _ofind(self,oname):
158 def _ofind(self,oname):
159 """Find an object in the available namespaces.
159 """Find an object in the available namespaces.
160
160
161 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
161 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
162
162
163 Has special code to detect magic functions.
163 Has special code to detect magic functions.
164 """
164 """
165
165
166 oname = oname.strip()
166 oname = oname.strip()
167
167
168 # Namespaces to search in:
168 # Namespaces to search in:
169 user_ns = self.shell.user_ns
169 user_ns = self.shell.user_ns
170 internal_ns = self.shell.internal_ns
170 internal_ns = self.shell.internal_ns
171 builtin_ns = __builtin__.__dict__
171 builtin_ns = __builtin__.__dict__
172 alias_ns = self.shell.alias_table
172 alias_ns = self.shell.alias_table
173
173
174 # Put them in a list. The order is important so that we find things in
174 # Put them in a list. The order is important so that we find things in
175 # the same order that Python finds them.
175 # the same order that Python finds them.
176 namespaces = [ ('Interactive',user_ns),
176 namespaces = [ ('Interactive',user_ns),
177 ('IPython internal',internal_ns),
177 ('IPython internal',internal_ns),
178 ('Python builtin',builtin_ns),
178 ('Python builtin',builtin_ns),
179 ('Alias',alias_ns),
179 ('Alias',alias_ns),
180 ]
180 ]
181
181
182 # initialize results to 'null'
182 # initialize results to 'null'
183 found = 0; obj = None; ospace = None; ds = None;
183 found = 0; obj = None; ospace = None; ds = None;
184 ismagic = 0; isalias = 0
184 ismagic = 0; isalias = 0
185
185
186 # Look for the given name by splitting it in parts. If the head is
186 # Look for the given name by splitting it in parts. If the head is
187 # found, then we look for all the remaining parts as members, and only
187 # found, then we look for all the remaining parts as members, and only
188 # declare success if we can find them all.
188 # declare success if we can find them all.
189 oname_parts = oname.split('.')
189 oname_parts = oname.split('.')
190 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
190 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
191 for nsname,ns in namespaces:
191 for nsname,ns in namespaces:
192 try:
192 try:
193 obj = ns[oname_head]
193 obj = ns[oname_head]
194 except KeyError:
194 except KeyError:
195 continue
195 continue
196 else:
196 else:
197 for part in oname_rest:
197 for part in oname_rest:
198 try:
198 try:
199 obj = getattr(obj,part)
199 obj = getattr(obj,part)
200 except:
200 except:
201 # Blanket except b/c some badly implemented objects
201 # Blanket except b/c some badly implemented objects
202 # allow __getattr__ to raise exceptions other than
202 # allow __getattr__ to raise exceptions other than
203 # AttributeError, which then crashes IPython.
203 # AttributeError, which then crashes IPython.
204 break
204 break
205 else:
205 else:
206 # If we finish the for loop (no break), we got all members
206 # If we finish the for loop (no break), we got all members
207 found = 1
207 found = 1
208 ospace = nsname
208 ospace = nsname
209 if ns == alias_ns:
209 if ns == alias_ns:
210 isalias = 1
210 isalias = 1
211 break # namespace loop
211 break # namespace loop
212
212
213 # Try to see if it's magic
213 # Try to see if it's magic
214 if not found:
214 if not found:
215 if oname.startswith(self.shell.ESC_MAGIC):
215 if oname.startswith(self.shell.ESC_MAGIC):
216 oname = oname[1:]
216 oname = oname[1:]
217 obj = getattr(self,'magic_'+oname,None)
217 obj = getattr(self,'magic_'+oname,None)
218 if obj is not None:
218 if obj is not None:
219 found = 1
219 found = 1
220 ospace = 'IPython internal'
220 ospace = 'IPython internal'
221 ismagic = 1
221 ismagic = 1
222
222
223 # Last try: special-case some literals like '', [], {}, etc:
223 # Last try: special-case some literals like '', [], {}, etc:
224 if not found and oname_head in ["''",'""','[]','{}','()']:
224 if not found and oname_head in ["''",'""','[]','{}','()']:
225 obj = eval(oname_head)
225 obj = eval(oname_head)
226 found = 1
226 found = 1
227 ospace = 'Interactive'
227 ospace = 'Interactive'
228
228
229 return {'found':found, 'obj':obj, 'namespace':ospace,
229 return {'found':found, 'obj':obj, 'namespace':ospace,
230 'ismagic':ismagic, 'isalias':isalias}
230 'ismagic':ismagic, 'isalias':isalias}
231
231
232 def arg_err(self,func):
232 def arg_err(self,func):
233 """Print docstring if incorrect arguments were passed"""
233 """Print docstring if incorrect arguments were passed"""
234 print 'Error in arguments:'
234 print 'Error in arguments:'
235 print OInspect.getdoc(func)
235 print OInspect.getdoc(func)
236
236
237 def format_latex(self,strng):
237 def format_latex(self,strng):
238 """Format a string for latex inclusion."""
238 """Format a string for latex inclusion."""
239
239
240 # Characters that need to be escaped for latex:
240 # Characters that need to be escaped for latex:
241 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
241 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
242 # Magic command names as headers:
242 # Magic command names as headers:
243 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
243 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
244 re.MULTILINE)
244 re.MULTILINE)
245 # Magic commands
245 # Magic commands
246 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
246 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
247 re.MULTILINE)
247 re.MULTILINE)
248 # Paragraph continue
248 # Paragraph continue
249 par_re = re.compile(r'\\$',re.MULTILINE)
249 par_re = re.compile(r'\\$',re.MULTILINE)
250
250
251 # The "\n" symbol
251 # The "\n" symbol
252 newline_re = re.compile(r'\\n')
252 newline_re = re.compile(r'\\n')
253
253
254 # Now build the string for output:
254 # Now build the string for output:
255 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
255 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
256 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
256 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
257 strng)
257 strng)
258 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
258 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
259 strng = par_re.sub(r'\\\\',strng)
259 strng = par_re.sub(r'\\\\',strng)
260 strng = escape_re.sub(r'\\\1',strng)
260 strng = escape_re.sub(r'\\\1',strng)
261 strng = newline_re.sub(r'\\textbackslash{}n',strng)
261 strng = newline_re.sub(r'\\textbackslash{}n',strng)
262 return strng
262 return strng
263
263
264 def format_screen(self,strng):
264 def format_screen(self,strng):
265 """Format a string for screen printing.
265 """Format a string for screen printing.
266
266
267 This removes some latex-type format codes."""
267 This removes some latex-type format codes."""
268 # Paragraph continue
268 # Paragraph continue
269 par_re = re.compile(r'\\$',re.MULTILINE)
269 par_re = re.compile(r'\\$',re.MULTILINE)
270 strng = par_re.sub('',strng)
270 strng = par_re.sub('',strng)
271 return strng
271 return strng
272
272
273 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
273 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
274 """Parse options passed to an argument string.
274 """Parse options passed to an argument string.
275
275
276 The interface is similar to that of getopt(), but it returns back a
276 The interface is similar to that of getopt(), but it returns back a
277 Struct with the options as keys and the stripped argument string still
277 Struct with the options as keys and the stripped argument string still
278 as a string.
278 as a string.
279
279
280 arg_str is quoted as a true sys.argv vector by using shlex.split.
280 arg_str is quoted as a true sys.argv vector by using shlex.split.
281 This allows us to easily expand variables, glob files, quote
281 This allows us to easily expand variables, glob files, quote
282 arguments, etc.
282 arguments, etc.
283
283
284 Options:
284 Options:
285 -mode: default 'string'. If given as 'list', the argument string is
285 -mode: default 'string'. If given as 'list', the argument string is
286 returned as a list (split on whitespace) instead of a string.
286 returned as a list (split on whitespace) instead of a string.
287
287
288 -list_all: put all option values in lists. Normally only options
288 -list_all: put all option values in lists. Normally only options
289 appearing more than once are put in a list."""
289 appearing more than once are put in a list."""
290
290
291 # inject default options at the beginning of the input line
291 # inject default options at the beginning of the input line
292 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
292 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
293 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
293 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
294
294
295 mode = kw.get('mode','string')
295 mode = kw.get('mode','string')
296 if mode not in ['string','list']:
296 if mode not in ['string','list']:
297 raise ValueError,'incorrect mode given: %s' % mode
297 raise ValueError,'incorrect mode given: %s' % mode
298 # Get options
298 # Get options
299 list_all = kw.get('list_all',0)
299 list_all = kw.get('list_all',0)
300
300
301 # Check if we have more than one argument to warrant extra processing:
301 # Check if we have more than one argument to warrant extra processing:
302 odict = {} # Dictionary with options
302 odict = {} # Dictionary with options
303 args = arg_str.split()
303 args = arg_str.split()
304 if len(args) >= 1:
304 if len(args) >= 1:
305 # If the list of inputs only has 0 or 1 thing in it, there's no
305 # If the list of inputs only has 0 or 1 thing in it, there's no
306 # need to look for options
306 # need to look for options
307 argv = shlex_split(arg_str)
307 argv = shlex_split(arg_str)
308 # Do regular option processing
308 # Do regular option processing
309 opts,args = getopt(argv,opt_str,*long_opts)
309 opts,args = getopt(argv,opt_str,*long_opts)
310 for o,a in opts:
310 for o,a in opts:
311 if o.startswith('--'):
311 if o.startswith('--'):
312 o = o[2:]
312 o = o[2:]
313 else:
313 else:
314 o = o[1:]
314 o = o[1:]
315 try:
315 try:
316 odict[o].append(a)
316 odict[o].append(a)
317 except AttributeError:
317 except AttributeError:
318 odict[o] = [odict[o],a]
318 odict[o] = [odict[o],a]
319 except KeyError:
319 except KeyError:
320 if list_all:
320 if list_all:
321 odict[o] = [a]
321 odict[o] = [a]
322 else:
322 else:
323 odict[o] = a
323 odict[o] = a
324
324
325 # Prepare opts,args for return
325 # Prepare opts,args for return
326 opts = Struct(odict)
326 opts = Struct(odict)
327 if mode == 'string':
327 if mode == 'string':
328 args = ' '.join(args)
328 args = ' '.join(args)
329
329
330 return opts,args
330 return opts,args
331
331
332 #......................................................................
332 #......................................................................
333 # And now the actual magic functions
333 # And now the actual magic functions
334
334
335 # Functions for IPython shell work (vars,funcs, config, etc)
335 # Functions for IPython shell work (vars,funcs, config, etc)
336 def magic_lsmagic(self, parameter_s = ''):
336 def magic_lsmagic(self, parameter_s = ''):
337 """List currently available magic functions."""
337 """List currently available magic functions."""
338 mesc = self.shell.ESC_MAGIC
338 mesc = self.shell.ESC_MAGIC
339 print 'Available magic functions:\n'+mesc+\
339 print 'Available magic functions:\n'+mesc+\
340 (' '+mesc).join(self.lsmagic())
340 (' '+mesc).join(self.lsmagic())
341 print '\n' + Magic.auto_status[self.shell.rc.automagic]
341 print '\n' + Magic.auto_status[self.shell.rc.automagic]
342 return None
342 return None
343
343
344 def magic_magic(self, parameter_s = ''):
344 def magic_magic(self, parameter_s = ''):
345 """Print information about the magic function system."""
345 """Print information about the magic function system."""
346
346
347 mode = ''
347 mode = ''
348 try:
348 try:
349 if parameter_s.split()[0] == '-latex':
349 if parameter_s.split()[0] == '-latex':
350 mode = 'latex'
350 mode = 'latex'
351 except:
351 except:
352 pass
352 pass
353
353
354 magic_docs = []
354 magic_docs = []
355 for fname in self.lsmagic():
355 for fname in self.lsmagic():
356 mname = 'magic_' + fname
356 mname = 'magic_' + fname
357 for space in (Magic,self,self.__class__):
357 for space in (Magic,self,self.__class__):
358 try:
358 try:
359 fn = space.__dict__[mname]
359 fn = space.__dict__[mname]
360 except KeyError:
360 except KeyError:
361 pass
361 pass
362 else:
362 else:
363 break
363 break
364 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
364 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
365 fname,fn.__doc__))
365 fname,fn.__doc__))
366 magic_docs = ''.join(magic_docs)
366 magic_docs = ''.join(magic_docs)
367
367
368 if mode == 'latex':
368 if mode == 'latex':
369 print self.format_latex(magic_docs)
369 print self.format_latex(magic_docs)
370 return
370 return
371 else:
371 else:
372 magic_docs = self.format_screen(magic_docs)
372 magic_docs = self.format_screen(magic_docs)
373
373
374 outmsg = """
374 outmsg = """
375 IPython's 'magic' functions
375 IPython's 'magic' functions
376 ===========================
376 ===========================
377
377
378 The magic function system provides a series of functions which allow you to
378 The magic function system provides a series of functions which allow you to
379 control the behavior of IPython itself, plus a lot of system-type
379 control the behavior of IPython itself, plus a lot of system-type
380 features. All these functions are prefixed with a % character, but parameters
380 features. All these functions are prefixed with a % character, but parameters
381 are given without parentheses or quotes.
381 are given without parentheses or quotes.
382
382
383 NOTE: If you have 'automagic' enabled (via the command line option or with the
383 NOTE: If you have 'automagic' enabled (via the command line option or with the
384 %automagic function), you don't need to type in the % explicitly. By default,
384 %automagic function), you don't need to type in the % explicitly. By default,
385 IPython ships with automagic on, so you should only rarely need the % escape.
385 IPython ships with automagic on, so you should only rarely need the % escape.
386
386
387 Example: typing '%cd mydir' (without the quotes) changes you working directory
387 Example: typing '%cd mydir' (without the quotes) changes you working directory
388 to 'mydir', if it exists.
388 to 'mydir', if it exists.
389
389
390 You can define your own magic functions to extend the system. See the supplied
390 You can define your own magic functions to extend the system. See the supplied
391 ipythonrc and example-magic.py files for details (in your ipython
391 ipythonrc and example-magic.py files for details (in your ipython
392 configuration directory, typically $HOME/.ipython/).
392 configuration directory, typically $HOME/.ipython/).
393
393
394 You can also define your own aliased names for magic functions. In your
394 You can also define your own aliased names for magic functions. In your
395 ipythonrc file, placing a line like:
395 ipythonrc file, placing a line like:
396
396
397 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
397 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
398
398
399 will define %pf as a new name for %profile.
399 will define %pf as a new name for %profile.
400
400
401 You can also call magics in code using the ipmagic() function, which IPython
401 You can also call magics in code using the ipmagic() function, which IPython
402 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
402 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
403
403
404 For a list of the available magic functions, use %lsmagic. For a description
404 For a list of the available magic functions, use %lsmagic. For a description
405 of any of them, type %magic_name?, e.g. '%cd?'.
405 of any of them, type %magic_name?, e.g. '%cd?'.
406
406
407 Currently the magic system has the following functions:\n"""
407 Currently the magic system has the following functions:\n"""
408
408
409 mesc = self.shell.ESC_MAGIC
409 mesc = self.shell.ESC_MAGIC
410 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
410 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
411 "\n\n%s%s\n\n%s" % (outmsg,
411 "\n\n%s%s\n\n%s" % (outmsg,
412 magic_docs,mesc,mesc,
412 magic_docs,mesc,mesc,
413 (' '+mesc).join(self.lsmagic()),
413 (' '+mesc).join(self.lsmagic()),
414 Magic.auto_status[self.shell.rc.automagic] ) )
414 Magic.auto_status[self.shell.rc.automagic] ) )
415
415
416 page(outmsg,screen_lines=self.shell.rc.screen_length)
416 page(outmsg,screen_lines=self.shell.rc.screen_length)
417
417
418 def magic_automagic(self, parameter_s = ''):
418 def magic_automagic(self, parameter_s = ''):
419 """Make magic functions callable without having to type the initial %.
419 """Make magic functions callable without having to type the initial %.
420
420
421 Toggles on/off (when off, you must call it as %automagic, of
421 Toggles on/off (when off, you must call it as %automagic, of
422 course). Note that magic functions have lowest priority, so if there's
422 course). Note that magic functions have lowest priority, so if there's
423 a variable whose name collides with that of a magic fn, automagic
423 a variable whose name collides with that of a magic fn, automagic
424 won't work for that function (you get the variable instead). However,
424 won't work for that function (you get the variable instead). However,
425 if you delete the variable (del var), the previously shadowed magic
425 if you delete the variable (del var), the previously shadowed magic
426 function becomes visible to automagic again."""
426 function becomes visible to automagic again."""
427
427
428 rc = self.shell.rc
428 rc = self.shell.rc
429 rc.automagic = not rc.automagic
429 rc.automagic = not rc.automagic
430 print '\n' + Magic.auto_status[rc.automagic]
430 print '\n' + Magic.auto_status[rc.automagic]
431
431
432 def magic_autocall(self, parameter_s = ''):
432 def magic_autocall(self, parameter_s = ''):
433 """Make functions callable without having to type parentheses.
433 """Make functions callable without having to type parentheses.
434
434
435 Usage:
435 Usage:
436
436
437 %autocall [mode]
437 %autocall [mode]
438
438
439 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
439 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
440 value is toggled on and off (remembering the previous state)."""
440 value is toggled on and off (remembering the previous state)."""
441
441
442 rc = self.shell.rc
442 rc = self.shell.rc
443
443
444 if parameter_s:
444 if parameter_s:
445 arg = int(parameter_s)
445 arg = int(parameter_s)
446 else:
446 else:
447 arg = 'toggle'
447 arg = 'toggle'
448
448
449 if not arg in (0,1,2,'toggle'):
449 if not arg in (0,1,2,'toggle'):
450 error('Valid modes: (0->Off, 1->Smart, 2->Full')
450 error('Valid modes: (0->Off, 1->Smart, 2->Full')
451 return
451 return
452
452
453 if arg in (0,1,2):
453 if arg in (0,1,2):
454 rc.autocall = arg
454 rc.autocall = arg
455 else: # toggle
455 else: # toggle
456 if rc.autocall:
456 if rc.autocall:
457 self._magic_state.autocall_save = rc.autocall
457 self._magic_state.autocall_save = rc.autocall
458 rc.autocall = 0
458 rc.autocall = 0
459 else:
459 else:
460 try:
460 try:
461 rc.autocall = self._magic_state.autocall_save
461 rc.autocall = self._magic_state.autocall_save
462 except AttributeError:
462 except AttributeError:
463 rc.autocall = self._magic_state.autocall_save = 1
463 rc.autocall = self._magic_state.autocall_save = 1
464
464
465 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
465 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
466
466
467 def magic_autoindent(self, parameter_s = ''):
467 def magic_autoindent(self, parameter_s = ''):
468 """Toggle autoindent on/off (if available)."""
468 """Toggle autoindent on/off (if available)."""
469
469
470 self.shell.set_autoindent()
470 self.shell.set_autoindent()
471 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
471 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
472
472
473 def magic_system_verbose(self, parameter_s = ''):
473 def magic_system_verbose(self, parameter_s = ''):
474 """Toggle verbose printing of system calls on/off."""
474 """Toggle verbose printing of system calls on/off."""
475
475
476 self.shell.rc_set_toggle('system_verbose')
476 self.shell.rc_set_toggle('system_verbose')
477 print "System verbose printing is:",\
477 print "System verbose printing is:",\
478 ['OFF','ON'][self.shell.rc.system_verbose]
478 ['OFF','ON'][self.shell.rc.system_verbose]
479
479
480 def magic_history(self, parameter_s = ''):
480 def magic_history(self, parameter_s = ''):
481 """Print input history (_i<n> variables), with most recent last.
481 """Print input history (_i<n> variables), with most recent last.
482
482
483 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
483 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
484 %history [-n] n -> print at most n inputs\\
484 %history [-n] n -> print at most n inputs\\
485 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
485 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
486
486
487 Each input's number <n> is shown, and is accessible as the
487 Each input's number <n> is shown, and is accessible as the
488 automatically generated variable _i<n>. Multi-line statements are
488 automatically generated variable _i<n>. Multi-line statements are
489 printed starting at a new line for easy copy/paste.
489 printed starting at a new line for easy copy/paste.
490
490
491 If option -n is used, input numbers are not printed. This is useful if
491 If option -n is used, input numbers are not printed. This is useful if
492 you want to get a printout of many lines which can be directly pasted
492 you want to get a printout of many lines which can be directly pasted
493 into a text editor.
493 into a text editor.
494
494
495 This feature is only available if numbered prompts are in use."""
495 This feature is only available if numbered prompts are in use."""
496
496
497 shell = self.shell
497 shell = self.shell
498 if not shell.outputcache.do_full_cache:
498 if not shell.outputcache.do_full_cache:
499 print 'This feature is only available if numbered prompts are in use.'
499 print 'This feature is only available if numbered prompts are in use.'
500 return
500 return
501 opts,args = self.parse_options(parameter_s,'n',mode='list')
501 opts,args = self.parse_options(parameter_s,'n',mode='list')
502
502
503 input_hist = shell.input_hist
503 input_hist = shell.input_hist
504 default_length = 40
504 default_length = 40
505 if len(args) == 0:
505 if len(args) == 0:
506 final = len(input_hist)
506 final = len(input_hist)
507 init = max(1,final-default_length)
507 init = max(1,final-default_length)
508 elif len(args) == 1:
508 elif len(args) == 1:
509 final = len(input_hist)
509 final = len(input_hist)
510 init = max(1,final-int(args[0]))
510 init = max(1,final-int(args[0]))
511 elif len(args) == 2:
511 elif len(args) == 2:
512 init,final = map(int,args)
512 init,final = map(int,args)
513 else:
513 else:
514 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
514 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
515 print self.magic_hist.__doc__
515 print self.magic_hist.__doc__
516 return
516 return
517 width = len(str(final))
517 width = len(str(final))
518 line_sep = ['','\n']
518 line_sep = ['','\n']
519 print_nums = not opts.has_key('n')
519 print_nums = not opts.has_key('n')
520 for in_num in range(init,final):
520 for in_num in range(init,final):
521 inline = input_hist[in_num]
521 inline = input_hist[in_num]
522 multiline = int(inline.count('\n') > 1)
522 multiline = int(inline.count('\n') > 1)
523 if print_nums:
523 if print_nums:
524 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
524 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
525 print inline,
525 print inline,
526
526
527 def magic_hist(self, parameter_s=''):
527 def magic_hist(self, parameter_s=''):
528 """Alternate name for %history."""
528 """Alternate name for %history."""
529 return self.magic_history(parameter_s)
529 return self.magic_history(parameter_s)
530
530
531 def magic_p(self, parameter_s=''):
531 def magic_p(self, parameter_s=''):
532 """Just a short alias for Python's 'print'."""
532 """Just a short alias for Python's 'print'."""
533 exec 'print ' + parameter_s in self.shell.user_ns
533 exec 'print ' + parameter_s in self.shell.user_ns
534
534
535 def magic_r(self, parameter_s=''):
535 def magic_r(self, parameter_s=''):
536 """Repeat previous input.
536 """Repeat previous input.
537
537
538 If given an argument, repeats the previous command which starts with
538 If given an argument, repeats the previous command which starts with
539 the same string, otherwise it just repeats the previous input.
539 the same string, otherwise it just repeats the previous input.
540
540
541 Shell escaped commands (with ! as first character) are not recognized
541 Shell escaped commands (with ! as first character) are not recognized
542 by this system, only pure python code and magic commands.
542 by this system, only pure python code and magic commands.
543 """
543 """
544
544
545 start = parameter_s.strip()
545 start = parameter_s.strip()
546 esc_magic = self.shell.ESC_MAGIC
546 esc_magic = self.shell.ESC_MAGIC
547 # Identify magic commands even if automagic is on (which means
547 # Identify magic commands even if automagic is on (which means
548 # the in-memory version is different from that typed by the user).
548 # the in-memory version is different from that typed by the user).
549 if self.shell.rc.automagic:
549 if self.shell.rc.automagic:
550 start_magic = esc_magic+start
550 start_magic = esc_magic+start
551 else:
551 else:
552 start_magic = start
552 start_magic = start
553 # Look through the input history in reverse
553 # Look through the input history in reverse
554 for n in range(len(self.shell.input_hist)-2,0,-1):
554 for n in range(len(self.shell.input_hist)-2,0,-1):
555 input = self.shell.input_hist[n]
555 input = self.shell.input_hist[n]
556 # skip plain 'r' lines so we don't recurse to infinity
556 # skip plain 'r' lines so we don't recurse to infinity
557 if input != 'ipmagic("r")\n' and \
557 if input != 'ipmagic("r")\n' and \
558 (input.startswith(start) or input.startswith(start_magic)):
558 (input.startswith(start) or input.startswith(start_magic)):
559 #print 'match',`input` # dbg
559 #print 'match',`input` # dbg
560 print 'Executing:',input,
560 print 'Executing:',input,
561 self.shell.runlines(input)
561 self.shell.runlines(input)
562 return
562 return
563 print 'No previous input matching `%s` found.' % start
563 print 'No previous input matching `%s` found.' % start
564
564
565 def magic_page(self, parameter_s=''):
565 def magic_page(self, parameter_s=''):
566 """Pretty print the object and display it through a pager.
566 """Pretty print the object and display it through a pager.
567
567
568 If no parameter is given, use _ (last output)."""
568 If no parameter is given, use _ (last output)."""
569 # After a function contributed by Olivier Aubert, slightly modified.
569 # After a function contributed by Olivier Aubert, slightly modified.
570
570
571 oname = parameter_s and parameter_s or '_'
571 oname = parameter_s and parameter_s or '_'
572 info = self._ofind(oname)
572 info = self._ofind(oname)
573 if info['found']:
573 if info['found']:
574 page(pformat(info['obj']))
574 page(pformat(info['obj']))
575 else:
575 else:
576 print 'Object `%s` not found' % oname
576 print 'Object `%s` not found' % oname
577
577
578 def magic_profile(self, parameter_s=''):
578 def magic_profile(self, parameter_s=''):
579 """Print your currently active IPyhton profile."""
579 """Print your currently active IPyhton profile."""
580 if self.shell.rc.profile:
580 if self.shell.rc.profile:
581 printpl('Current IPython profile: $self.shell.rc.profile.')
581 printpl('Current IPython profile: $self.shell.rc.profile.')
582 else:
582 else:
583 print 'No profile active.'
583 print 'No profile active.'
584
584
585 def _inspect(self,meth,oname,**kw):
585 def _inspect(self,meth,oname,**kw):
586 """Generic interface to the inspector system.
586 """Generic interface to the inspector system.
587
587
588 This function is meant to be called by pdef, pdoc & friends."""
588 This function is meant to be called by pdef, pdoc & friends."""
589
589
590 oname = oname.strip()
590 oname = oname.strip()
591 info = Struct(self._ofind(oname))
591 info = Struct(self._ofind(oname))
592 if info.found:
592 if info.found:
593 pmethod = getattr(self.shell.inspector,meth)
593 pmethod = getattr(self.shell.inspector,meth)
594 formatter = info.ismagic and self.format_screen or None
594 formatter = info.ismagic and self.format_screen or None
595 if meth == 'pdoc':
595 if meth == 'pdoc':
596 pmethod(info.obj,oname,formatter)
596 pmethod(info.obj,oname,formatter)
597 elif meth == 'pinfo':
597 elif meth == 'pinfo':
598 pmethod(info.obj,oname,formatter,info,**kw)
598 pmethod(info.obj,oname,formatter,info,**kw)
599 else:
599 else:
600 pmethod(info.obj,oname)
600 pmethod(info.obj,oname)
601 else:
601 else:
602 print 'Object `%s` not found.' % oname
602 print 'Object `%s` not found.' % oname
603 return 'not found' # so callers can take other action
603 return 'not found' # so callers can take other action
604
604
605 def magic_pdef(self, parameter_s=''):
605 def magic_pdef(self, parameter_s=''):
606 """Print the definition header for any callable object.
606 """Print the definition header for any callable object.
607
607
608 If the object is a class, print the constructor information."""
608 If the object is a class, print the constructor information."""
609 self._inspect('pdef',parameter_s)
609 self._inspect('pdef',parameter_s)
610
610
611 def magic_pdoc(self, parameter_s=''):
611 def magic_pdoc(self, parameter_s=''):
612 """Print the docstring for an object.
612 """Print the docstring for an object.
613
613
614 If the given object is a class, it will print both the class and the
614 If the given object is a class, it will print both the class and the
615 constructor docstrings."""
615 constructor docstrings."""
616 self._inspect('pdoc',parameter_s)
616 self._inspect('pdoc',parameter_s)
617
617
618 def magic_psource(self, parameter_s=''):
618 def magic_psource(self, parameter_s=''):
619 """Print (or run through pager) the source code for an object."""
619 """Print (or run through pager) the source code for an object."""
620 self._inspect('psource',parameter_s)
620 self._inspect('psource',parameter_s)
621
621
622 def magic_pfile(self, parameter_s=''):
622 def magic_pfile(self, parameter_s=''):
623 """Print (or run through pager) the file where an object is defined.
623 """Print (or run through pager) the file where an object is defined.
624
624
625 The file opens at the line where the object definition begins. IPython
625 The file opens at the line where the object definition begins. IPython
626 will honor the environment variable PAGER if set, and otherwise will
626 will honor the environment variable PAGER if set, and otherwise will
627 do its best to print the file in a convenient form.
627 do its best to print the file in a convenient form.
628
628
629 If the given argument is not an object currently defined, IPython will
629 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
630 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
631 if needed). You can thus use %pfile as a syntax highlighting code
632 viewer."""
632 viewer."""
633
633
634 # first interpret argument as an object name
634 # first interpret argument as an object name
635 out = self._inspect('pfile',parameter_s)
635 out = self._inspect('pfile',parameter_s)
636 # if not, try the input as a filename
636 # if not, try the input as a filename
637 if out == 'not found':
637 if out == 'not found':
638 try:
638 try:
639 filename = get_py_filename(parameter_s)
639 filename = get_py_filename(parameter_s)
640 except IOError,msg:
640 except IOError,msg:
641 print msg
641 print msg
642 return
642 return
643 page(self.shell.inspector.format(file(filename).read()))
643 page(self.shell.inspector.format(file(filename).read()))
644
644
645 def magic_pinfo(self, parameter_s=''):
645 def magic_pinfo(self, parameter_s=''):
646 """Provide detailed information about an object.
646 """Provide detailed information about an object.
647
647
648 '%pinfo object' is just a synonym for object? or ?object."""
648 '%pinfo object' is just a synonym for object? or ?object."""
649
649
650 #print 'pinfo par: <%s>' % parameter_s # dbg
650 #print 'pinfo par: <%s>' % parameter_s # dbg
651
651
652 # detail_level: 0 -> obj? , 1 -> obj??
652 # detail_level: 0 -> obj? , 1 -> obj??
653 detail_level = 0
653 detail_level = 0
654 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 # 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.
655 # happen if the user types 'pinfo foo?' at the cmd line.
656 pinfo,qmark1,oname,qmark2 = \
656 pinfo,qmark1,oname,qmark2 = \
657 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
658 if pinfo or qmark1 or qmark2:
658 if pinfo or qmark1 or qmark2:
659 detail_level = 1
659 detail_level = 1
660 if "*" in oname:
660 if "*" in oname:
661 self.magic_psearch(oname)
661 self.magic_psearch(oname)
662 else:
662 else:
663 self._inspect('pinfo',oname,detail_level=detail_level)
663 self._inspect('pinfo',oname,detail_level=detail_level)
664
664
665 def magic_psearch(self, parameter_s=''):
665 def magic_psearch(self, parameter_s=''):
666 """Search for object in namespaces by wildcard.
666 """Search for object in namespaces by wildcard.
667
667
668 %psearch [options] PATTERN [OBJECT TYPE]
668 %psearch [options] PATTERN [OBJECT TYPE]
669
669
670 Note: ? can be used as a synonym for %psearch, at the beginning or at
670 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*'. Still, the
671 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
672 rest of the command line must be unchanged (options come first), so
672 rest of the command line must be unchanged (options come first), so
673 for example the following forms are equivalent
673 for example the following forms are equivalent
674
674
675 %psearch -i a* function
675 %psearch -i a* function
676 -i a* function?
676 -i a* function?
677 ?-i a* function
677 ?-i a* function
678
678
679 Arguments:
679 Arguments:
680
680
681 PATTERN
681 PATTERN
682
682
683 where PATTERN is a string containing * as a wildcard similar to its
683 where PATTERN is a string containing * as a wildcard similar to its
684 use in a shell. The pattern is matched in all namespaces on the
684 use in a shell. The pattern is matched in all namespaces on the
685 search path. By default objects starting with a single _ are not
685 search path. By default objects starting with a single _ are not
686 matched, many IPython generated objects have a single
686 matched, many IPython generated objects have a single
687 underscore. The default is case insensitive matching. Matching is
687 underscore. The default is case insensitive matching. Matching is
688 also done on the attributes of objects and not only on the objects
688 also done on the attributes of objects and not only on the objects
689 in a module.
689 in a module.
690
690
691 [OBJECT TYPE]
691 [OBJECT TYPE]
692
692
693 Is the name of a python type from the types module. The name is
693 Is the name of a python type from the types module. The name is
694 given in lowercase without the ending type, ex. StringType is
694 given in lowercase without the ending type, ex. StringType is
695 written string. By adding a type here only objects matching the
695 written string. By adding a type here only objects matching the
696 given type are matched. Using all here makes the pattern match all
696 given type are matched. Using all here makes the pattern match all
697 types (this is the default).
697 types (this is the default).
698
698
699 Options:
699 Options:
700
700
701 -a: makes the pattern match even objects whose names start with a
701 -a: makes the pattern match even objects whose names start with a
702 single underscore. These names are normally ommitted from the
702 single underscore. These names are normally ommitted from the
703 search.
703 search.
704
704
705 -i/-c: make the pattern case insensitive/sensitive. If neither of
705 -i/-c: make the pattern case insensitive/sensitive. If neither of
706 these options is given, the default is read from your ipythonrc
706 these options is given, the default is read from your ipythonrc
707 file. The option name which sets this value is
707 file. The option name which sets this value is
708 'wildcards_case_sensitive'. If this option is not specified in your
708 'wildcards_case_sensitive'. If this option is not specified in your
709 ipythonrc file, IPython's internal default is to do a case sensitive
709 ipythonrc file, IPython's internal default is to do a case sensitive
710 search.
710 search.
711
711
712 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
712 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
713 specifiy can be searched in any of the following namespaces:
713 specifiy can be searched in any of the following namespaces:
714 'builtin', 'user', 'user_global','internal', 'alias', where
714 'builtin', 'user', 'user_global','internal', 'alias', where
715 'builtin' and 'user' are the search defaults. Note that you should
715 'builtin' and 'user' are the search defaults. Note that you should
716 not use quotes when specifying namespaces.
716 not use quotes when specifying namespaces.
717
717
718 'Builtin' contains the python module builtin, 'user' contains all
718 'Builtin' contains the python module builtin, 'user' contains all
719 user data, 'alias' only contain the shell aliases and no python
719 user data, 'alias' only contain the shell aliases and no python
720 objects, 'internal' contains objects used by IPython. The
720 objects, 'internal' contains objects used by IPython. The
721 'user_global' namespace is only used by embedded IPython instances,
721 'user_global' namespace is only used by embedded IPython instances,
722 and it contains module-level globals. You can add namespaces to the
722 and it contains module-level globals. You can add namespaces to the
723 search with -s or exclude them with -e (these options can be given
723 search with -s or exclude them with -e (these options can be given
724 more than once).
724 more than once).
725
725
726 Examples:
726 Examples:
727
727
728 %psearch a* -> objects beginning with an a
728 %psearch a* -> objects beginning with an a
729 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
729 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
730 %psearch a* function -> all functions beginning with an a
730 %psearch a* function -> all functions beginning with an a
731 %psearch re.e* -> objects beginning with an e in module re
731 %psearch re.e* -> objects beginning with an e in module re
732 %psearch r*.e* -> objects that start with e in modules starting in r
732 %psearch r*.e* -> objects that start with e in modules starting in r
733 %psearch r*.* string -> all strings in modules beginning with r
733 %psearch r*.* string -> all strings in modules beginning with r
734
734
735 Case sensitve search:
735 Case sensitve search:
736
736
737 %psearch -c a* list all object beginning with lower case a
737 %psearch -c a* list all object beginning with lower case a
738
738
739 Show objects beginning with a single _:
739 Show objects beginning with a single _:
740
740
741 %psearch -a _* list objects beginning with a single underscore"""
741 %psearch -a _* list objects beginning with a single underscore"""
742
742
743 # default namespaces to be searched
743 # default namespaces to be searched
744 def_search = ['user','builtin']
744 def_search = ['user','builtin']
745
745
746 # Process options/args
746 # Process options/args
747 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
747 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
748 opt = opts.get
748 opt = opts.get
749 shell = self.shell
749 shell = self.shell
750 psearch = shell.inspector.psearch
750 psearch = shell.inspector.psearch
751
751
752 # select case options
752 # select case options
753 if opts.has_key('i'):
753 if opts.has_key('i'):
754 ignore_case = True
754 ignore_case = True
755 elif opts.has_key('c'):
755 elif opts.has_key('c'):
756 ignore_case = False
756 ignore_case = False
757 else:
757 else:
758 ignore_case = not shell.rc.wildcards_case_sensitive
758 ignore_case = not shell.rc.wildcards_case_sensitive
759
759
760 # Build list of namespaces to search from user options
760 # Build list of namespaces to search from user options
761 def_search.extend(opt('s',[]))
761 def_search.extend(opt('s',[]))
762 ns_exclude = ns_exclude=opt('e',[])
762 ns_exclude = ns_exclude=opt('e',[])
763 ns_search = [nm for nm in def_search if nm not in ns_exclude]
763 ns_search = [nm for nm in def_search if nm not in ns_exclude]
764
764
765 # Call the actual search
765 # Call the actual search
766 try:
766 try:
767 psearch(args,shell.ns_table,ns_search,
767 psearch(args,shell.ns_table,ns_search,
768 show_all=opt('a'),ignore_case=ignore_case)
768 show_all=opt('a'),ignore_case=ignore_case)
769 except:
769 except:
770 shell.showtraceback()
770 shell.showtraceback()
771
771
772 def magic_who_ls(self, parameter_s=''):
772 def magic_who_ls(self, parameter_s=''):
773 """Return a sorted list of all interactive variables.
773 """Return a sorted list of all interactive variables.
774
774
775 If arguments are given, only variables of types matching these
775 If arguments are given, only variables of types matching these
776 arguments are returned."""
776 arguments are returned."""
777
777
778 user_ns = self.shell.user_ns
778 user_ns = self.shell.user_ns
779 internal_ns = self.shell.internal_ns
779 internal_ns = self.shell.internal_ns
780 user_config_ns = self.shell.user_config_ns
780 user_config_ns = self.shell.user_config_ns
781 out = []
781 out = []
782 typelist = parameter_s.split()
782 typelist = parameter_s.split()
783
783
784 for i in user_ns:
784 for i in user_ns:
785 if not (i.startswith('_') or i.startswith('_i')) \
785 if not (i.startswith('_') or i.startswith('_i')) \
786 and not (i in internal_ns or i in user_config_ns):
786 and not (i in internal_ns or i in user_config_ns):
787 if typelist:
787 if typelist:
788 if type(user_ns[i]).__name__ in typelist:
788 if type(user_ns[i]).__name__ in typelist:
789 out.append(i)
789 out.append(i)
790 else:
790 else:
791 out.append(i)
791 out.append(i)
792 out.sort()
792 out.sort()
793 return out
793 return out
794
794
795 def magic_who(self, parameter_s=''):
795 def magic_who(self, parameter_s=''):
796 """Print all interactive variables, with some minimal formatting.
796 """Print all interactive variables, with some minimal formatting.
797
797
798 If any arguments are given, only variables whose type matches one of
798 If any arguments are given, only variables whose type matches one of
799 these are printed. For example:
799 these are printed. For example:
800
800
801 %who function str
801 %who function str
802
802
803 will only list functions and strings, excluding all other types of
803 will only list functions and strings, excluding all other types of
804 variables. To find the proper type names, simply use type(var) at a
804 variables. To find the proper type names, simply use type(var) at a
805 command line to see how python prints type names. For example:
805 command line to see how python prints type names. For example:
806
806
807 In [1]: type('hello')\\
807 In [1]: type('hello')\\
808 Out[1]: <type 'str'>
808 Out[1]: <type 'str'>
809
809
810 indicates that the type name for strings is 'str'.
810 indicates that the type name for strings is 'str'.
811
811
812 %who always excludes executed names loaded through your configuration
812 %who always excludes executed names loaded through your configuration
813 file and things which are internal to IPython.
813 file and things which are internal to IPython.
814
814
815 This is deliberate, as typically you may load many modules and the
815 This is deliberate, as typically you may load many modules and the
816 purpose of %who is to show you only what you've manually defined."""
816 purpose of %who is to show you only what you've manually defined."""
817
817
818 varlist = self.magic_who_ls(parameter_s)
818 varlist = self.magic_who_ls(parameter_s)
819 if not varlist:
819 if not varlist:
820 print 'Interactive namespace is empty.'
820 print 'Interactive namespace is empty.'
821 return
821 return
822
822
823 # if we have variables, move on...
823 # if we have variables, move on...
824
824
825 # stupid flushing problem: when prompts have no separators, stdout is
825 # stupid flushing problem: when prompts have no separators, stdout is
826 # getting lost. I'm starting to think this is a python bug. I'm having
826 # getting lost. I'm starting to think this is a python bug. I'm having
827 # to force a flush with a print because even a sys.stdout.flush
827 # to force a flush with a print because even a sys.stdout.flush
828 # doesn't seem to do anything!
828 # doesn't seem to do anything!
829
829
830 count = 0
830 count = 0
831 for i in varlist:
831 for i in varlist:
832 print i+'\t',
832 print i+'\t',
833 count += 1
833 count += 1
834 if count > 8:
834 if count > 8:
835 count = 0
835 count = 0
836 print
836 print
837 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
837 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
838
838
839 print # well, this does force a flush at the expense of an extra \n
839 print # well, this does force a flush at the expense of an extra \n
840
840
841 def magic_whos(self, parameter_s=''):
841 def magic_whos(self, parameter_s=''):
842 """Like %who, but gives some extra information about each variable.
842 """Like %who, but gives some extra information about each variable.
843
843
844 The same type filtering of %who can be applied here.
844 The same type filtering of %who can be applied here.
845
845
846 For all variables, the type is printed. Additionally it prints:
846 For all variables, the type is printed. Additionally it prints:
847
847
848 - For {},[],(): their length.
848 - For {},[],(): their length.
849
849
850 - For Numeric arrays, a summary with shape, number of elements,
850 - For Numeric arrays, a summary with shape, number of elements,
851 typecode and size in memory.
851 typecode and size in memory.
852
852
853 - Everything else: a string representation, snipping their middle if
853 - Everything else: a string representation, snipping their middle if
854 too long."""
854 too long."""
855
855
856 varnames = self.magic_who_ls(parameter_s)
856 varnames = self.magic_who_ls(parameter_s)
857 if not varnames:
857 if not varnames:
858 print 'Interactive namespace is empty.'
858 print 'Interactive namespace is empty.'
859 return
859 return
860
860
861 # if we have variables, move on...
861 # if we have variables, move on...
862
862
863 # for these types, show len() instead of data:
863 # for these types, show len() instead of data:
864 seq_types = [types.DictType,types.ListType,types.TupleType]
864 seq_types = [types.DictType,types.ListType,types.TupleType]
865
865
866 # for Numeric arrays, display summary info
866 # for Numeric arrays, display summary info
867 try:
867 try:
868 import Numeric
868 import Numeric
869 except ImportError:
869 except ImportError:
870 array_type = None
870 array_type = None
871 else:
871 else:
872 array_type = Numeric.ArrayType.__name__
872 array_type = Numeric.ArrayType.__name__
873
873
874 # Find all variable names and types so we can figure out column sizes
874 # Find all variable names and types so we can figure out column sizes
875 get_vars = lambda i: self.shell.user_ns[i]
875 get_vars = lambda i: self.shell.user_ns[i]
876 type_name = lambda v: type(v).__name__
876 type_name = lambda v: type(v).__name__
877 varlist = map(get_vars,varnames)
877 varlist = map(get_vars,varnames)
878
878
879 typelist = []
879 typelist = []
880 for vv in varlist:
880 for vv in varlist:
881 tt = type_name(vv)
881 tt = type_name(vv)
882 if tt=='instance':
882 if tt=='instance':
883 typelist.append(str(vv.__class__))
883 typelist.append(str(vv.__class__))
884 else:
884 else:
885 typelist.append(tt)
885 typelist.append(tt)
886
886
887 # column labels and # of spaces as separator
887 # column labels and # of spaces as separator
888 varlabel = 'Variable'
888 varlabel = 'Variable'
889 typelabel = 'Type'
889 typelabel = 'Type'
890 datalabel = 'Data/Info'
890 datalabel = 'Data/Info'
891 colsep = 3
891 colsep = 3
892 # variable format strings
892 # variable format strings
893 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
893 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
894 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
894 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
895 aformat = "%s: %s elems, type `%s`, %s bytes"
895 aformat = "%s: %s elems, type `%s`, %s bytes"
896 # find the size of the columns to format the output nicely
896 # find the size of the columns to format the output nicely
897 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
897 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
898 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
898 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
899 # table header
899 # table header
900 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
900 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
901 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
901 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
902 # and the table itself
902 # and the table itself
903 kb = 1024
903 kb = 1024
904 Mb = 1048576 # kb**2
904 Mb = 1048576 # kb**2
905 for vname,var,vtype in zip(varnames,varlist,typelist):
905 for vname,var,vtype in zip(varnames,varlist,typelist):
906 print itpl(vformat),
906 print itpl(vformat),
907 if vtype in seq_types:
907 if vtype in seq_types:
908 print len(var)
908 print len(var)
909 elif vtype==array_type:
909 elif vtype==array_type:
910 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
910 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
911 vsize = Numeric.size(var)
911 vsize = Numeric.size(var)
912 vbytes = vsize*var.itemsize()
912 vbytes = vsize*var.itemsize()
913 if vbytes < 100000:
913 if vbytes < 100000:
914 print aformat % (vshape,vsize,var.typecode(),vbytes)
914 print aformat % (vshape,vsize,var.typecode(),vbytes)
915 else:
915 else:
916 print aformat % (vshape,vsize,var.typecode(),vbytes),
916 print aformat % (vshape,vsize,var.typecode(),vbytes),
917 if vbytes < Mb:
917 if vbytes < Mb:
918 print '(%s kb)' % (vbytes/kb,)
918 print '(%s kb)' % (vbytes/kb,)
919 else:
919 else:
920 print '(%s Mb)' % (vbytes/Mb,)
920 print '(%s Mb)' % (vbytes/Mb,)
921 else:
921 else:
922 vstr = str(var).replace('\n','\\n')
922 vstr = str(var).replace('\n','\\n')
923 if len(vstr) < 50:
923 if len(vstr) < 50:
924 print vstr
924 print vstr
925 else:
925 else:
926 printpl(vfmt_short)
926 printpl(vfmt_short)
927
927
928 def magic_reset(self, parameter_s=''):
928 def magic_reset(self, parameter_s=''):
929 """Resets the namespace by removing all names defined by the user.
929 """Resets the namespace by removing all names defined by the user.
930
930
931 Input/Output history are left around in case you need them."""
931 Input/Output history are left around in case you need them."""
932
932
933 ans = raw_input(
933 ans = raw_input(
934 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
934 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
935 if not ans.lower() == 'y':
935 if not ans.lower() == 'y':
936 print 'Nothing done.'
936 print 'Nothing done.'
937 return
937 return
938 user_ns = self.shell.user_ns
938 user_ns = self.shell.user_ns
939 for i in self.magic_who_ls():
939 for i in self.magic_who_ls():
940 del(user_ns[i])
940 del(user_ns[i])
941
941
942 def magic_config(self,parameter_s=''):
942 def magic_config(self,parameter_s=''):
943 """Show IPython's internal configuration."""
943 """Show IPython's internal configuration."""
944
944
945 page('Current configuration structure:\n'+
945 page('Current configuration structure:\n'+
946 pformat(self.shell.rc.dict()))
946 pformat(self.shell.rc.dict()))
947
947
948 def magic_logstart(self,parameter_s=''):
948 def magic_logstart(self,parameter_s=''):
949 """Start logging anywhere in a session.
949 """Start logging anywhere in a session.
950
950
951 %logstart [-o|-t] [log_name [log_mode]]
951 %logstart [-o|-t] [log_name [log_mode]]
952
952
953 If no name is given, it defaults to a file named 'ipython_log.py' in your
953 If no name is given, it defaults to a file named 'ipython_log.py' in your
954 current directory, in 'rotate' mode (see below).
954 current directory, in 'rotate' mode (see below).
955
955
956 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
956 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
957 history up to that point and then continues logging.
957 history up to that point and then continues logging.
958
958
959 %logstart takes a second optional parameter: logging mode. This can be one
959 %logstart takes a second optional parameter: logging mode. This can be one
960 of (note that the modes are given unquoted):\\
960 of (note that the modes are given unquoted):\\
961 append: well, that says it.\\
961 append: well, that says it.\\
962 backup: rename (if exists) to name~ and start name.\\
962 backup: rename (if exists) to name~ and start name.\\
963 global: single logfile in your home dir, appended to.\\
963 global: single logfile in your home dir, appended to.\\
964 over : overwrite existing log.\\
964 over : overwrite existing log.\\
965 rotate: create rotating logs name.1~, name.2~, etc.
965 rotate: create rotating logs name.1~, name.2~, etc.
966
966
967 Options:
967 Options:
968
968
969 -o: log also IPython's output. In this mode, all commands which
969 -o: log also IPython's output. In this mode, all commands which
970 generate an Out[NN] prompt are recorded to the logfile, right after
970 generate an Out[NN] prompt are recorded to the logfile, right after
971 their corresponding input line. The output lines are always
971 their corresponding input line. The output lines are always
972 prepended with a '#[Out]# ' marker, so that the log remains valid
972 prepended with a '#[Out]# ' marker, so that the log remains valid
973 Python code.
973 Python code.
974
974
975 Since this marker is always the same, filtering only the output from
975 Since this marker is always the same, filtering only the output from
976 a log is very easy, using for example a simple awk call:
976 a log is very easy, using for example a simple awk call:
977
977
978 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
978 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
979
979
980 -t: put timestamps before each input line logged (these are put in
980 -t: put timestamps before each input line logged (these are put in
981 comments)."""
981 comments)."""
982
982
983 opts,par = self.parse_options(parameter_s,'ot')
983 opts,par = self.parse_options(parameter_s,'ot')
984 log_output = 'o' in opts
984 log_output = 'o' in opts
985 timestamp = 't' in opts
985 timestamp = 't' in opts
986
986
987 rc = self.shell.rc
987 rc = self.shell.rc
988 logger = self.shell.logger
988 logger = self.shell.logger
989
989
990 # if no args are given, the defaults set in the logger constructor by
990 # if no args are given, the defaults set in the logger constructor by
991 # ipytohn remain valid
991 # ipytohn remain valid
992 if par:
992 if par:
993 try:
993 try:
994 logfname,logmode = par.split()
994 logfname,logmode = par.split()
995 except:
995 except:
996 logfname = par
996 logfname = par
997 logmode = 'backup'
997 logmode = 'backup'
998 else:
998 else:
999 logfname = logger.logfname
999 logfname = logger.logfname
1000 logmode = logger.logmode
1000 logmode = logger.logmode
1001 # put logfname into rc struct as if it had been called on the command
1001 # put logfname into rc struct as if it had been called on the command
1002 # line, so it ends up saved in the log header Save it in case we need
1002 # line, so it ends up saved in the log header Save it in case we need
1003 # to restore it...
1003 # to restore it...
1004 old_logfile = rc.opts.get('logfile','')
1004 old_logfile = rc.opts.get('logfile','')
1005 if logfname:
1005 if logfname:
1006 logfname = os.path.expanduser(logfname)
1006 logfname = os.path.expanduser(logfname)
1007 rc.opts.logfile = logfname
1007 rc.opts.logfile = logfname
1008 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1008 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1009 try:
1009 try:
1010 started = logger.logstart(logfname,loghead,logmode,
1010 started = logger.logstart(logfname,loghead,logmode,
1011 log_output,timestamp)
1011 log_output,timestamp)
1012 except:
1012 except:
1013 rc.opts.logfile = old_logfile
1013 rc.opts.logfile = old_logfile
1014 warn("Couldn't start log: %s" % sys.exc_info()[1])
1014 warn("Couldn't start log: %s" % sys.exc_info()[1])
1015 else:
1015 else:
1016 # log input history up to this point, optionally interleaving
1016 # log input history up to this point, optionally interleaving
1017 # output if requested
1017 # output if requested
1018
1018
1019 if timestamp:
1019 if timestamp:
1020 # disable timestamping for the previous history, since we've
1020 # disable timestamping for the previous history, since we've
1021 # lost those already (no time machine here).
1021 # lost those already (no time machine here).
1022 logger.timestamp = False
1022 logger.timestamp = False
1023 if log_output:
1023 if log_output:
1024 log_write = logger.log_write
1024 log_write = logger.log_write
1025 input_hist = self.shell.input_hist
1025 input_hist = self.shell.input_hist
1026 output_hist = self.shell.output_hist
1026 output_hist = self.shell.output_hist
1027 for n in range(1,len(input_hist)-1):
1027 for n in range(1,len(input_hist)-1):
1028 log_write(input_hist[n].rstrip())
1028 log_write(input_hist[n].rstrip())
1029 if n in output_hist:
1029 if n in output_hist:
1030 log_write(repr(output_hist[n]),'output')
1030 log_write(repr(output_hist[n]),'output')
1031 else:
1031 else:
1032 logger.log_write(self.shell.input_hist[1:])
1032 logger.log_write(self.shell.input_hist[1:])
1033 if timestamp:
1033 if timestamp:
1034 # re-enable timestamping
1034 # re-enable timestamping
1035 logger.timestamp = True
1035 logger.timestamp = True
1036
1036
1037 print ('Activating auto-logging. '
1037 print ('Activating auto-logging. '
1038 'Current session state plus future input saved.')
1038 'Current session state plus future input saved.')
1039 logger.logstate()
1039 logger.logstate()
1040
1040
1041 def magic_logoff(self,parameter_s=''):
1041 def magic_logoff(self,parameter_s=''):
1042 """Temporarily stop logging.
1042 """Temporarily stop logging.
1043
1043
1044 You must have previously started logging."""
1044 You must have previously started logging."""
1045 self.shell.logger.switch_log(0)
1045 self.shell.logger.switch_log(0)
1046
1046
1047 def magic_logon(self,parameter_s=''):
1047 def magic_logon(self,parameter_s=''):
1048 """Restart logging.
1048 """Restart logging.
1049
1049
1050 This function is for restarting logging which you've temporarily
1050 This function is for restarting logging which you've temporarily
1051 stopped with %logoff. For starting logging for the first time, you
1051 stopped with %logoff. For starting logging for the first time, you
1052 must use the %logstart function, which allows you to specify an
1052 must use the %logstart function, which allows you to specify an
1053 optional log filename."""
1053 optional log filename."""
1054
1054
1055 self.shell.logger.switch_log(1)
1055 self.shell.logger.switch_log(1)
1056
1056
1057 def magic_logstate(self,parameter_s=''):
1057 def magic_logstate(self,parameter_s=''):
1058 """Print the status of the logging system."""
1058 """Print the status of the logging system."""
1059
1059
1060 self.shell.logger.logstate()
1060 self.shell.logger.logstate()
1061
1061
1062 def magic_pdb(self, parameter_s=''):
1062 def magic_pdb(self, parameter_s=''):
1063 """Control the calling of the pdb interactive debugger.
1063 """Control the calling of the pdb interactive debugger.
1064
1064
1065 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1065 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1066 argument it works as a toggle.
1066 argument it works as a toggle.
1067
1067
1068 When an exception is triggered, IPython can optionally call the
1068 When an exception is triggered, IPython can optionally call the
1069 interactive pdb debugger after the traceback printout. %pdb toggles
1069 interactive pdb debugger after the traceback printout. %pdb toggles
1070 this feature on and off."""
1070 this feature on and off."""
1071
1071
1072 par = parameter_s.strip().lower()
1072 par = parameter_s.strip().lower()
1073
1073
1074 if par:
1074 if par:
1075 try:
1075 try:
1076 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1076 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1077 except KeyError:
1077 except KeyError:
1078 print ('Incorrect argument. Use on/1, off/0, '
1078 print ('Incorrect argument. Use on/1, off/0, '
1079 'or nothing for a toggle.')
1079 'or nothing for a toggle.')
1080 return
1080 return
1081 else:
1081 else:
1082 # toggle
1082 # toggle
1083 new_pdb = not self.shell.InteractiveTB.call_pdb
1083 new_pdb = not self.shell.InteractiveTB.call_pdb
1084
1084
1085 # set on the shell
1085 # set on the shell
1086 self.shell.call_pdb = new_pdb
1086 self.shell.call_pdb = new_pdb
1087 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1087 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1088
1088
1089 def magic_prun(self, parameter_s ='',user_mode=1,
1089 def magic_prun(self, parameter_s ='',user_mode=1,
1090 opts=None,arg_lst=None,prog_ns=None):
1090 opts=None,arg_lst=None,prog_ns=None):
1091
1091
1092 """Run a statement through the python code profiler.
1092 """Run a statement through the python code profiler.
1093
1093
1094 Usage:\\
1094 Usage:\\
1095 %prun [options] statement
1095 %prun [options] statement
1096
1096
1097 The given statement (which doesn't require quote marks) is run via the
1097 The given statement (which doesn't require quote marks) is run via the
1098 python profiler in a manner similar to the profile.run() function.
1098 python profiler in a manner similar to the profile.run() function.
1099 Namespaces are internally managed to work correctly; profile.run
1099 Namespaces are internally managed to work correctly; profile.run
1100 cannot be used in IPython because it makes certain assumptions about
1100 cannot be used in IPython because it makes certain assumptions about
1101 namespaces which do not hold under IPython.
1101 namespaces which do not hold under IPython.
1102
1102
1103 Options:
1103 Options:
1104
1104
1105 -l <limit>: you can place restrictions on what or how much of the
1105 -l <limit>: you can place restrictions on what or how much of the
1106 profile gets printed. The limit value can be:
1106 profile gets printed. The limit value can be:
1107
1107
1108 * A string: only information for function names containing this string
1108 * A string: only information for function names containing this string
1109 is printed.
1109 is printed.
1110
1110
1111 * An integer: only these many lines are printed.
1111 * An integer: only these many lines are printed.
1112
1112
1113 * A float (between 0 and 1): this fraction of the report is printed
1113 * A float (between 0 and 1): this fraction of the report is printed
1114 (for example, use a limit of 0.4 to see the topmost 40% only).
1114 (for example, use a limit of 0.4 to see the topmost 40% only).
1115
1115
1116 You can combine several limits with repeated use of the option. For
1116 You can combine several limits with repeated use of the option. For
1117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1118 information about class constructors.
1118 information about class constructors.
1119
1119
1120 -r: return the pstats.Stats object generated by the profiling. This
1120 -r: return the pstats.Stats object generated by the profiling. This
1121 object has all the information about the profile in it, and you can
1121 object has all the information about the profile in it, and you can
1122 later use it for further analysis or in other functions.
1122 later use it for further analysis or in other functions.
1123
1123
1124 Since magic functions have a particular form of calling which prevents
1124 Since magic functions have a particular form of calling which prevents
1125 you from writing something like:\\
1125 you from writing something like:\\
1126 In [1]: p = %prun -r print 4 # invalid!\\
1126 In [1]: p = %prun -r print 4 # invalid!\\
1127 you must instead use IPython's automatic variables to assign this:\\
1127 you must instead use IPython's automatic variables to assign this:\\
1128 In [1]: %prun -r print 4 \\
1128 In [1]: %prun -r print 4 \\
1129 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1129 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1130 In [2]: stats = _
1130 In [2]: stats = _
1131
1131
1132 If you really need to assign this value via an explicit function call,
1132 If you really need to assign this value via an explicit function call,
1133 you can always tap directly into the true name of the magic function
1133 you can always tap directly into the true name of the magic function
1134 by using the ipmagic function (which IPython automatically adds to the
1134 by using the ipmagic function (which IPython automatically adds to the
1135 builtins):\\
1135 builtins):\\
1136 In [3]: stats = ipmagic('prun','-r print 4')
1136 In [3]: stats = ipmagic('prun','-r print 4')
1137
1137
1138 You can type ipmagic? for more details on ipmagic.
1138 You can type ipmagic? for more details on ipmagic.
1139
1139
1140 -s <key>: sort profile by given key. You can provide more than one key
1140 -s <key>: sort profile by given key. You can provide more than one key
1141 by using the option several times: '-s key1 -s key2 -s key3...'. The
1141 by using the option several times: '-s key1 -s key2 -s key3...'. The
1142 default sorting key is 'time'.
1142 default sorting key is 'time'.
1143
1143
1144 The following is copied verbatim from the profile documentation
1144 The following is copied verbatim from the profile documentation
1145 referenced below:
1145 referenced below:
1146
1146
1147 When more than one key is provided, additional keys are used as
1147 When more than one key is provided, additional keys are used as
1148 secondary criteria when the there is equality in all keys selected
1148 secondary criteria when the there is equality in all keys selected
1149 before them.
1149 before them.
1150
1150
1151 Abbreviations can be used for any key names, as long as the
1151 Abbreviations can be used for any key names, as long as the
1152 abbreviation is unambiguous. The following are the keys currently
1152 abbreviation is unambiguous. The following are the keys currently
1153 defined:
1153 defined:
1154
1154
1155 Valid Arg Meaning\\
1155 Valid Arg Meaning\\
1156 "calls" call count\\
1156 "calls" call count\\
1157 "cumulative" cumulative time\\
1157 "cumulative" cumulative time\\
1158 "file" file name\\
1158 "file" file name\\
1159 "module" file name\\
1159 "module" file name\\
1160 "pcalls" primitive call count\\
1160 "pcalls" primitive call count\\
1161 "line" line number\\
1161 "line" line number\\
1162 "name" function name\\
1162 "name" function name\\
1163 "nfl" name/file/line\\
1163 "nfl" name/file/line\\
1164 "stdname" standard name\\
1164 "stdname" standard name\\
1165 "time" internal time
1165 "time" internal time
1166
1166
1167 Note that all sorts on statistics are in descending order (placing
1167 Note that all sorts on statistics are in descending order (placing
1168 most time consuming items first), where as name, file, and line number
1168 most time consuming items first), where as name, file, and line number
1169 searches are in ascending order (i.e., alphabetical). The subtle
1169 searches are in ascending order (i.e., alphabetical). The subtle
1170 distinction between "nfl" and "stdname" is that the standard name is a
1170 distinction between "nfl" and "stdname" is that the standard name is a
1171 sort of the name as printed, which means that the embedded line
1171 sort of the name as printed, which means that the embedded line
1172 numbers get compared in an odd way. For example, lines 3, 20, and 40
1172 numbers get compared in an odd way. For example, lines 3, 20, and 40
1173 would (if the file names were the same) appear in the string order
1173 would (if the file names were the same) appear in the string order
1174 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1174 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1175 line numbers. In fact, sort_stats("nfl") is the same as
1175 line numbers. In fact, sort_stats("nfl") is the same as
1176 sort_stats("name", "file", "line").
1176 sort_stats("name", "file", "line").
1177
1177
1178 -T <filename>: save profile results as shown on screen to a text
1178 -T <filename>: save profile results as shown on screen to a text
1179 file. The profile is still shown on screen.
1179 file. The profile is still shown on screen.
1180
1180
1181 -D <filename>: save (via dump_stats) profile statistics to given
1181 -D <filename>: save (via dump_stats) profile statistics to given
1182 filename. This data is in a format understod by the pstats module, and
1182 filename. This data is in a format understod by the pstats module, and
1183 is generated by a call to the dump_stats() method of profile
1183 is generated by a call to the dump_stats() method of profile
1184 objects. The profile is still shown on screen.
1184 objects. The profile is still shown on screen.
1185
1185
1186 If you want to run complete programs under the profiler's control, use
1186 If you want to run complete programs under the profiler's control, use
1187 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1187 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1188 contains profiler specific options as described here.
1188 contains profiler specific options as described here.
1189
1189
1190 You can read the complete documentation for the profile module with:\\
1190 You can read the complete documentation for the profile module with:\\
1191 In [1]: import profile; profile.help() """
1191 In [1]: import profile; profile.help() """
1192
1192
1193 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1193 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1194 # protect user quote marks
1194 # protect user quote marks
1195 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1195 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1196
1196
1197 if user_mode: # regular user call
1197 if user_mode: # regular user call
1198 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1198 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1199 list_all=1)
1199 list_all=1)
1200 namespace = self.shell.user_ns
1200 namespace = self.shell.user_ns
1201 else: # called to run a program by %run -p
1201 else: # called to run a program by %run -p
1202 try:
1202 try:
1203 filename = get_py_filename(arg_lst[0])
1203 filename = get_py_filename(arg_lst[0])
1204 except IOError,msg:
1204 except IOError,msg:
1205 error(msg)
1205 error(msg)
1206 return
1206 return
1207
1207
1208 arg_str = 'execfile(filename,prog_ns)'
1208 arg_str = 'execfile(filename,prog_ns)'
1209 namespace = locals()
1209 namespace = locals()
1210
1210
1211 opts.merge(opts_def)
1211 opts.merge(opts_def)
1212
1212
1213 prof = profile.Profile()
1213 prof = profile.Profile()
1214 try:
1214 try:
1215 prof = prof.runctx(arg_str,namespace,namespace)
1215 prof = prof.runctx(arg_str,namespace,namespace)
1216 sys_exit = ''
1216 sys_exit = ''
1217 except SystemExit:
1217 except SystemExit:
1218 sys_exit = """*** SystemExit exception caught in code being profiled."""
1218 sys_exit = """*** SystemExit exception caught in code being profiled."""
1219
1219
1220 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1220 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1221
1221
1222 lims = opts.l
1222 lims = opts.l
1223 if lims:
1223 if lims:
1224 lims = [] # rebuild lims with ints/floats/strings
1224 lims = [] # rebuild lims with ints/floats/strings
1225 for lim in opts.l:
1225 for lim in opts.l:
1226 try:
1226 try:
1227 lims.append(int(lim))
1227 lims.append(int(lim))
1228 except ValueError:
1228 except ValueError:
1229 try:
1229 try:
1230 lims.append(float(lim))
1230 lims.append(float(lim))
1231 except ValueError:
1231 except ValueError:
1232 lims.append(lim)
1232 lims.append(lim)
1233
1233
1234 # trap output
1234 # trap output
1235 sys_stdout = sys.stdout
1235 sys_stdout = sys.stdout
1236 stdout_trap = StringIO()
1236 stdout_trap = StringIO()
1237 try:
1237 try:
1238 sys.stdout = stdout_trap
1238 sys.stdout = stdout_trap
1239 stats.print_stats(*lims)
1239 stats.print_stats(*lims)
1240 finally:
1240 finally:
1241 sys.stdout = sys_stdout
1241 sys.stdout = sys_stdout
1242 output = stdout_trap.getvalue()
1242 output = stdout_trap.getvalue()
1243 output = output.rstrip()
1243 output = output.rstrip()
1244
1244
1245 page(output,screen_lines=self.shell.rc.screen_length)
1245 page(output,screen_lines=self.shell.rc.screen_length)
1246 print sys_exit,
1246 print sys_exit,
1247
1247
1248 dump_file = opts.D[0]
1248 dump_file = opts.D[0]
1249 text_file = opts.T[0]
1249 text_file = opts.T[0]
1250 if dump_file:
1250 if dump_file:
1251 prof.dump_stats(dump_file)
1251 prof.dump_stats(dump_file)
1252 print '\n*** Profile stats marshalled to file',\
1252 print '\n*** Profile stats marshalled to file',\
1253 `dump_file`+'.',sys_exit
1253 `dump_file`+'.',sys_exit
1254 if text_file:
1254 if text_file:
1255 file(text_file,'w').write(output)
1255 file(text_file,'w').write(output)
1256 print '\n*** Profile printout saved to text file',\
1256 print '\n*** Profile printout saved to text file',\
1257 `text_file`+'.',sys_exit
1257 `text_file`+'.',sys_exit
1258
1258
1259 if opts.has_key('r'):
1259 if opts.has_key('r'):
1260 return stats
1260 return stats
1261 else:
1261 else:
1262 return None
1262 return None
1263
1263
1264 def magic_run(self, parameter_s ='',runner=None):
1264 def magic_run(self, parameter_s ='',runner=None):
1265 """Run the named file inside IPython as a program.
1265 """Run the named file inside IPython as a program.
1266
1266
1267 Usage:\\
1267 Usage:\\
1268 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1268 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1269
1269
1270 Parameters after the filename are passed as command-line arguments to
1270 Parameters after the filename are passed as command-line arguments to
1271 the program (put in sys.argv). Then, control returns to IPython's
1271 the program (put in sys.argv). Then, control returns to IPython's
1272 prompt.
1272 prompt.
1273
1273
1274 This is similar to running at a system prompt:\\
1274 This is similar to running at a system prompt:\\
1275 $ python file args\\
1275 $ python file args\\
1276 but with the advantage of giving you IPython's tracebacks, and of
1276 but with the advantage of giving you IPython's tracebacks, and of
1277 loading all variables into your interactive namespace for further use
1277 loading all variables into your interactive namespace for further use
1278 (unless -p is used, see below).
1278 (unless -p is used, see below).
1279
1279
1280 The file is executed in a namespace initially consisting only of
1280 The file is executed in a namespace initially consisting only of
1281 __name__=='__main__' and sys.argv constructed as indicated. It thus
1281 __name__=='__main__' and sys.argv constructed as indicated. It thus
1282 sees its environment as if it were being run as a stand-alone
1282 sees its environment as if it were being run as a stand-alone
1283 program. But after execution, the IPython interactive namespace gets
1283 program. But after execution, the IPython interactive namespace gets
1284 updated with all variables defined in the program (except for __name__
1284 updated with all variables defined in the program (except for __name__
1285 and sys.argv). This allows for very convenient loading of code for
1285 and sys.argv). This allows for very convenient loading of code for
1286 interactive work, while giving each program a 'clean sheet' to run in.
1286 interactive work, while giving each program a 'clean sheet' to run in.
1287
1287
1288 Options:
1288 Options:
1289
1289
1290 -n: __name__ is NOT set to '__main__', but to the running file's name
1290 -n: __name__ is NOT set to '__main__', but to the running file's name
1291 without extension (as python does under import). This allows running
1291 without extension (as python does under import). This allows running
1292 scripts and reloading the definitions in them without calling code
1292 scripts and reloading the definitions in them without calling code
1293 protected by an ' if __name__ == "__main__" ' clause.
1293 protected by an ' if __name__ == "__main__" ' clause.
1294
1294
1295 -i: run the file in IPython's namespace instead of an empty one. This
1295 -i: run the file in IPython's namespace instead of an empty one. This
1296 is useful if you are experimenting with code written in a text editor
1296 is useful if you are experimenting with code written in a text editor
1297 which depends on variables defined interactively.
1297 which depends on variables defined interactively.
1298
1298
1299 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1299 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1300 being run. This is particularly useful if IPython is being used to
1300 being run. This is particularly useful if IPython is being used to
1301 run unittests, which always exit with a sys.exit() call. In such
1301 run unittests, which always exit with a sys.exit() call. In such
1302 cases you are interested in the output of the test results, not in
1302 cases you are interested in the output of the test results, not in
1303 seeing a traceback of the unittest module.
1303 seeing a traceback of the unittest module.
1304
1304
1305 -t: print timing information at the end of the run. IPython will give
1305 -t: print timing information at the end of the run. IPython will give
1306 you an estimated CPU time consumption for your script, which under
1306 you an estimated CPU time consumption for your script, which under
1307 Unix uses the resource module to avoid the wraparound problems of
1307 Unix uses the resource module to avoid the wraparound problems of
1308 time.clock(). Under Unix, an estimate of time spent on system tasks
1308 time.clock(). Under Unix, an estimate of time spent on system tasks
1309 is also given (for Windows platforms this is reported as 0.0).
1309 is also given (for Windows platforms this is reported as 0.0).
1310
1310
1311 If -t is given, an additional -N<N> option can be given, where <N>
1311 If -t is given, an additional -N<N> option can be given, where <N>
1312 must be an integer indicating how many times you want the script to
1312 must be an integer indicating how many times you want the script to
1313 run. The final timing report will include total and per run results.
1313 run. The final timing report will include total and per run results.
1314
1314
1315 For example (testing the script uniq_stable.py):
1315 For example (testing the script uniq_stable.py):
1316
1316
1317 In [1]: run -t uniq_stable
1317 In [1]: run -t uniq_stable
1318
1318
1319 IPython CPU timings (estimated):\\
1319 IPython CPU timings (estimated):\\
1320 User : 0.19597 s.\\
1320 User : 0.19597 s.\\
1321 System: 0.0 s.\\
1321 System: 0.0 s.\\
1322
1322
1323 In [2]: run -t -N5 uniq_stable
1323 In [2]: run -t -N5 uniq_stable
1324
1324
1325 IPython CPU timings (estimated):\\
1325 IPython CPU timings (estimated):\\
1326 Total runs performed: 5\\
1326 Total runs performed: 5\\
1327 Times : Total Per run\\
1327 Times : Total Per run\\
1328 User : 0.910862 s, 0.1821724 s.\\
1328 User : 0.910862 s, 0.1821724 s.\\
1329 System: 0.0 s, 0.0 s.
1329 System: 0.0 s, 0.0 s.
1330
1330
1331 -d: run your program under the control of pdb, the Python debugger.
1331 -d: run your program under the control of pdb, the Python debugger.
1332 This allows you to execute your program step by step, watch variables,
1332 This allows you to execute your program step by step, watch variables,
1333 etc. Internally, what IPython does is similar to calling:
1333 etc. Internally, what IPython does is similar to calling:
1334
1334
1335 pdb.run('execfile("YOURFILENAME")')
1335 pdb.run('execfile("YOURFILENAME")')
1336
1336
1337 with a breakpoint set on line 1 of your file. You can change the line
1337 with a breakpoint set on line 1 of your file. You can change the line
1338 number for this automatic breakpoint to be <N> by using the -bN option
1338 number for this automatic breakpoint to be <N> by using the -bN option
1339 (where N must be an integer). For example:
1339 (where N must be an integer). For example:
1340
1340
1341 %run -d -b40 myscript
1341 %run -d -b40 myscript
1342
1342
1343 will set the first breakpoint at line 40 in myscript.py. Note that
1343 will set the first breakpoint at line 40 in myscript.py. Note that
1344 the first breakpoint must be set on a line which actually does
1344 the first breakpoint must be set on a line which actually does
1345 something (not a comment or docstring) for it to stop execution.
1345 something (not a comment or docstring) for it to stop execution.
1346
1346
1347 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1347 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1348 first enter 'c' (without qoutes) to start execution up to the first
1348 first enter 'c' (without qoutes) to start execution up to the first
1349 breakpoint.
1349 breakpoint.
1350
1350
1351 Entering 'help' gives information about the use of the debugger. You
1351 Entering 'help' gives information about the use of the debugger. You
1352 can easily see pdb's full documentation with "import pdb;pdb.help()"
1352 can easily see pdb's full documentation with "import pdb;pdb.help()"
1353 at a prompt.
1353 at a prompt.
1354
1354
1355 -p: run program under the control of the Python profiler module (which
1355 -p: run program under the control of the Python profiler module (which
1356 prints a detailed report of execution times, function calls, etc).
1356 prints a detailed report of execution times, function calls, etc).
1357
1357
1358 You can pass other options after -p which affect the behavior of the
1358 You can pass other options after -p which affect the behavior of the
1359 profiler itself. See the docs for %prun for details.
1359 profiler itself. See the docs for %prun for details.
1360
1360
1361 In this mode, the program's variables do NOT propagate back to the
1361 In this mode, the program's variables do NOT propagate back to the
1362 IPython interactive namespace (because they remain in the namespace
1362 IPython interactive namespace (because they remain in the namespace
1363 where the profiler executes them).
1363 where the profiler executes them).
1364
1364
1365 Internally this triggers a call to %prun, see its documentation for
1365 Internally this triggers a call to %prun, see its documentation for
1366 details on the options available specifically for profiling."""
1366 details on the options available specifically for profiling."""
1367
1367
1368 # get arguments and set sys.argv for program to be run.
1368 # get arguments and set sys.argv for program to be run.
1369 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1369 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1370 mode='list',list_all=1)
1370 mode='list',list_all=1)
1371
1371
1372 try:
1372 try:
1373 filename = get_py_filename(arg_lst[0])
1373 filename = get_py_filename(arg_lst[0])
1374 except IndexError:
1374 except IndexError:
1375 warn('you must provide at least a filename.')
1375 warn('you must provide at least a filename.')
1376 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1376 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1377 return
1377 return
1378 except IOError,msg:
1378 except IOError,msg:
1379 error(msg)
1379 error(msg)
1380 return
1380 return
1381
1381
1382 # Control the response to exit() calls made by the script being run
1382 # Control the response to exit() calls made by the script being run
1383 exit_ignore = opts.has_key('e')
1383 exit_ignore = opts.has_key('e')
1384
1384
1385 # Make sure that the running script gets a proper sys.argv as if it
1385 # Make sure that the running script gets a proper sys.argv as if it
1386 # were run from a system shell.
1386 # were run from a system shell.
1387 save_argv = sys.argv # save it for later restoring
1387 save_argv = sys.argv # save it for later restoring
1388 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1388 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1389
1389
1390 if opts.has_key('i'):
1390 if opts.has_key('i'):
1391 prog_ns = self.shell.user_ns
1391 prog_ns = self.shell.user_ns
1392 __name__save = self.shell.user_ns['__name__']
1392 __name__save = self.shell.user_ns['__name__']
1393 prog_ns['__name__'] = '__main__'
1393 prog_ns['__name__'] = '__main__'
1394 else:
1394 else:
1395 if opts.has_key('n'):
1395 if opts.has_key('n'):
1396 name = os.path.splitext(os.path.basename(filename))[0]
1396 name = os.path.splitext(os.path.basename(filename))[0]
1397 else:
1397 else:
1398 name = '__main__'
1398 name = '__main__'
1399 prog_ns = {'__name__':name}
1399 prog_ns = {'__name__':name}
1400
1400
1401 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1401 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1402 # set the __file__ global in the script's namespace
1402 # set the __file__ global in the script's namespace
1403 prog_ns['__file__'] = filename
1403 prog_ns['__file__'] = filename
1404
1404
1405 # pickle fix. See iplib for an explanation. But we need to make sure
1405 # pickle fix. See iplib for an explanation. But we need to make sure
1406 # that, if we overwrite __main__, we replace it at the end
1406 # that, if we overwrite __main__, we replace it at the end
1407 if prog_ns['__name__'] == '__main__':
1407 if prog_ns['__name__'] == '__main__':
1408 restore_main = sys.modules['__main__']
1408 restore_main = sys.modules['__main__']
1409 else:
1409 else:
1410 restore_main = False
1410 restore_main = False
1411
1411
1412 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1412 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1413
1413
1414 stats = None
1414 stats = None
1415 try:
1415 try:
1416 if opts.has_key('p'):
1416 if opts.has_key('p'):
1417 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1417 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1418 else:
1418 else:
1419 if opts.has_key('d'):
1419 if opts.has_key('d'):
1420 deb = Debugger.Pdb(self.shell.rc.colors)
1420 deb = Debugger.Pdb(self.shell.rc.colors)
1421 # reset Breakpoint state, which is moronically kept
1421 # reset Breakpoint state, which is moronically kept
1422 # in a class
1422 # in a class
1423 bdb.Breakpoint.next = 1
1423 bdb.Breakpoint.next = 1
1424 bdb.Breakpoint.bplist = {}
1424 bdb.Breakpoint.bplist = {}
1425 bdb.Breakpoint.bpbynumber = [None]
1425 bdb.Breakpoint.bpbynumber = [None]
1426 # Set an initial breakpoint to stop execution
1426 # Set an initial breakpoint to stop execution
1427 maxtries = 10
1427 maxtries = 10
1428 bp = int(opts.get('b',[1])[0])
1428 bp = int(opts.get('b',[1])[0])
1429 checkline = deb.checkline(filename,bp)
1429 checkline = deb.checkline(filename,bp)
1430 if not checkline:
1430 if not checkline:
1431 for bp in range(bp+1,bp+maxtries+1):
1431 for bp in range(bp+1,bp+maxtries+1):
1432 if deb.checkline(filename,bp):
1432 if deb.checkline(filename,bp):
1433 break
1433 break
1434 else:
1434 else:
1435 msg = ("\nI failed to find a valid line to set "
1435 msg = ("\nI failed to find a valid line to set "
1436 "a breakpoint\n"
1436 "a breakpoint\n"
1437 "after trying up to line: %s.\n"
1437 "after trying up to line: %s.\n"
1438 "Please set a valid breakpoint manually "
1438 "Please set a valid breakpoint manually "
1439 "with the -b option." % bp)
1439 "with the -b option." % bp)
1440 error(msg)
1440 error(msg)
1441 return
1441 return
1442 # if we find a good linenumber, set the breakpoint
1442 # if we find a good linenumber, set the breakpoint
1443 deb.do_break('%s:%s' % (filename,bp))
1443 deb.do_break('%s:%s' % (filename,bp))
1444 # Start file run
1444 # Start file run
1445 print "NOTE: Enter 'c' at the",
1445 print "NOTE: Enter 'c' at the",
1446 print "ipdb> prompt to start your script."
1446 print "ipdb> prompt to start your script."
1447 try:
1447 try:
1448 deb.run('execfile("%s")' % filename,prog_ns)
1448 deb.run('execfile("%s")' % filename,prog_ns)
1449 except:
1449 except:
1450 etype, value, tb = sys.exc_info()
1450 etype, value, tb = sys.exc_info()
1451 # Skip three frames in the traceback: the %run one,
1451 # Skip three frames in the traceback: the %run one,
1452 # one inside bdb.py, and the command-line typed by the
1452 # one inside bdb.py, and the command-line typed by the
1453 # user (run by exec in pdb itself).
1453 # user (run by exec in pdb itself).
1454 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1454 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1455 else:
1455 else:
1456 if runner is None:
1456 if runner is None:
1457 runner = self.shell.safe_execfile
1457 runner = self.shell.safe_execfile
1458 if opts.has_key('t'):
1458 if opts.has_key('t'):
1459 try:
1459 try:
1460 nruns = int(opts['N'][0])
1460 nruns = int(opts['N'][0])
1461 if nruns < 1:
1461 if nruns < 1:
1462 error('Number of runs must be >=1')
1462 error('Number of runs must be >=1')
1463 return
1463 return
1464 except (KeyError):
1464 except (KeyError):
1465 nruns = 1
1465 nruns = 1
1466 if nruns == 1:
1466 if nruns == 1:
1467 t0 = clock2()
1467 t0 = clock2()
1468 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1468 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1469 t1 = clock2()
1469 t1 = clock2()
1470 t_usr = t1[0]-t0[0]
1470 t_usr = t1[0]-t0[0]
1471 t_sys = t1[1]-t1[1]
1471 t_sys = t1[1]-t1[1]
1472 print "\nIPython CPU timings (estimated):"
1472 print "\nIPython CPU timings (estimated):"
1473 print " User : %10s s." % t_usr
1473 print " User : %10s s." % t_usr
1474 print " System: %10s s." % t_sys
1474 print " System: %10s s." % t_sys
1475 else:
1475 else:
1476 runs = range(nruns)
1476 runs = range(nruns)
1477 t0 = clock2()
1477 t0 = clock2()
1478 for nr in runs:
1478 for nr in runs:
1479 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1479 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1480 t1 = clock2()
1480 t1 = clock2()
1481 t_usr = t1[0]-t0[0]
1481 t_usr = t1[0]-t0[0]
1482 t_sys = t1[1]-t1[1]
1482 t_sys = t1[1]-t1[1]
1483 print "\nIPython CPU timings (estimated):"
1483 print "\nIPython CPU timings (estimated):"
1484 print "Total runs performed:",nruns
1484 print "Total runs performed:",nruns
1485 print " Times : %10s %10s" % ('Total','Per run')
1485 print " Times : %10s %10s" % ('Total','Per run')
1486 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1486 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1487 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1487 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1488
1488
1489 else:
1489 else:
1490 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1490 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1491 if opts.has_key('i'):
1491 if opts.has_key('i'):
1492 self.shell.user_ns['__name__'] = __name__save
1492 self.shell.user_ns['__name__'] = __name__save
1493 else:
1493 else:
1494 # update IPython interactive namespace
1494 # update IPython interactive namespace
1495 del prog_ns['__name__']
1495 del prog_ns['__name__']
1496 self.shell.user_ns.update(prog_ns)
1496 self.shell.user_ns.update(prog_ns)
1497 finally:
1497 finally:
1498 sys.argv = save_argv
1498 sys.argv = save_argv
1499 if restore_main:
1499 if restore_main:
1500 sys.modules['__main__'] = restore_main
1500 sys.modules['__main__'] = restore_main
1501 return stats
1501 return stats
1502
1502
1503 def magic_runlog(self, parameter_s =''):
1503 def magic_runlog(self, parameter_s =''):
1504 """Run files as logs.
1504 """Run files as logs.
1505
1505
1506 Usage:\\
1506 Usage:\\
1507 %runlog file1 file2 ...
1507 %runlog file1 file2 ...
1508
1508
1509 Run the named files (treating them as log files) in sequence inside
1509 Run the named files (treating them as log files) in sequence inside
1510 the interpreter, and return to the prompt. This is much slower than
1510 the interpreter, and return to the prompt. This is much slower than
1511 %run because each line is executed in a try/except block, but it
1511 %run because each line is executed in a try/except block, but it
1512 allows running files with syntax errors in them.
1512 allows running files with syntax errors in them.
1513
1513
1514 Normally IPython will guess when a file is one of its own logfiles, so
1514 Normally IPython will guess when a file is one of its own logfiles, so
1515 you can typically use %run even for logs. This shorthand allows you to
1515 you can typically use %run even for logs. This shorthand allows you to
1516 force any file to be treated as a log file."""
1516 force any file to be treated as a log file."""
1517
1517
1518 for f in parameter_s.split():
1518 for f in parameter_s.split():
1519 self.shell.safe_execfile(f,self.shell.user_ns,
1519 self.shell.safe_execfile(f,self.shell.user_ns,
1520 self.shell.user_ns,islog=1)
1520 self.shell.user_ns,islog=1)
1521
1521
1522 def magic_time(self,parameter_s = ''):
1522 def magic_time(self,parameter_s = ''):
1523 """Time execution of a Python statement or expression.
1523 """Time execution of a Python statement or expression.
1524
1524
1525 The CPU and wall clock times are printed, and the value of the
1525 The CPU and wall clock times are printed, and the value of the
1526 expression (if any) is returned. Note that under Win32, system time
1526 expression (if any) is returned. Note that under Win32, system time
1527 is always reported as 0, since it can not be measured.
1527 is always reported as 0, since it can not be measured.
1528
1528
1529 This function provides very basic timing functionality. In Python
1529 This function provides very basic timing functionality. In Python
1530 2.3, the timeit module offers more control and sophistication, but for
1530 2.3, the timeit module offers more control and sophistication, but for
1531 now IPython supports Python 2.2, so we can not rely on timeit being
1531 now IPython supports Python 2.2, so we can not rely on timeit being
1532 present.
1532 present.
1533
1533
1534 Some examples:
1534 Some examples:
1535
1535
1536 In [1]: time 2**128
1536 In [1]: time 2**128
1537 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1537 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1538 Wall time: 0.00
1538 Wall time: 0.00
1539 Out[1]: 340282366920938463463374607431768211456L
1539 Out[1]: 340282366920938463463374607431768211456L
1540
1540
1541 In [2]: n = 1000000
1541 In [2]: n = 1000000
1542
1542
1543 In [3]: time sum(range(n))
1543 In [3]: time sum(range(n))
1544 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1544 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1545 Wall time: 1.37
1545 Wall time: 1.37
1546 Out[3]: 499999500000L
1546 Out[3]: 499999500000L
1547
1547
1548 In [4]: time print 'hello world'
1548 In [4]: time print 'hello world'
1549 hello world
1549 hello world
1550 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1550 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1551 Wall time: 0.00
1551 Wall time: 0.00
1552 """
1552 """
1553
1553
1554 # fail immediately if the given expression can't be compiled
1554 # fail immediately if the given expression can't be compiled
1555 try:
1555 try:
1556 mode = 'eval'
1556 mode = 'eval'
1557 code = compile(parameter_s,'<timed eval>',mode)
1557 code = compile(parameter_s,'<timed eval>',mode)
1558 except SyntaxError:
1558 except SyntaxError:
1559 mode = 'exec'
1559 mode = 'exec'
1560 code = compile(parameter_s,'<timed exec>',mode)
1560 code = compile(parameter_s,'<timed exec>',mode)
1561 # skew measurement as little as possible
1561 # skew measurement as little as possible
1562 glob = self.shell.user_ns
1562 glob = self.shell.user_ns
1563 clk = clock2
1563 clk = clock2
1564 wtime = time.time
1564 wtime = time.time
1565 # time execution
1565 # time execution
1566 wall_st = wtime()
1566 wall_st = wtime()
1567 if mode=='eval':
1567 if mode=='eval':
1568 st = clk()
1568 st = clk()
1569 out = eval(code,glob)
1569 out = eval(code,glob)
1570 end = clk()
1570 end = clk()
1571 else:
1571 else:
1572 st = clk()
1572 st = clk()
1573 exec code in glob
1573 exec code in glob
1574 end = clk()
1574 end = clk()
1575 out = None
1575 out = None
1576 wall_end = wtime()
1576 wall_end = wtime()
1577 # Compute actual times and report
1577 # Compute actual times and report
1578 wall_time = wall_end-wall_st
1578 wall_time = wall_end-wall_st
1579 cpu_user = end[0]-st[0]
1579 cpu_user = end[0]-st[0]
1580 cpu_sys = end[1]-st[1]
1580 cpu_sys = end[1]-st[1]
1581 cpu_tot = cpu_user+cpu_sys
1581 cpu_tot = cpu_user+cpu_sys
1582 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1582 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1583 (cpu_user,cpu_sys,cpu_tot)
1583 (cpu_user,cpu_sys,cpu_tot)
1584 print "Wall time: %.2f" % wall_time
1584 print "Wall time: %.2f" % wall_time
1585 return out
1585 return out
1586
1586
1587 def magic_macro(self,parameter_s = ''):
1587 def magic_macro(self,parameter_s = ''):
1588 """Define a set of input lines as a macro for future re-execution.
1588 """Define a set of input lines as a macro for future re-execution.
1589
1589
1590 Usage:\\
1590 Usage:\\
1591 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1591 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1592
1592
1593 This will define a global variable called `name` which is a string
1593 This will define a global variable called `name` which is a string
1594 made of joining the slices and lines you specify (n1,n2,... numbers
1594 made of joining the slices and lines you specify (n1,n2,... numbers
1595 above) from your input history into a single string. This variable
1595 above) from your input history into a single string. This variable
1596 acts like an automatic function which re-executes those lines as if
1596 acts like an automatic function which re-executes those lines as if
1597 you had typed them. You just type 'name' at the prompt and the code
1597 you had typed them. You just type 'name' at the prompt and the code
1598 executes.
1598 executes.
1599
1599
1600 The notation for indicating number ranges is: n1-n2 means 'use line
1600 The notation for indicating number ranges is: n1-n2 means 'use line
1601 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1601 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1602 using the lines numbered 5,6 and 7.
1602 using the lines numbered 5,6 and 7.
1603
1603
1604 Note: as a 'hidden' feature, you can also use traditional python slice
1604 Note: as a 'hidden' feature, you can also use traditional python slice
1605 notation, where N:M means numbers N through M-1.
1605 notation, where N:M means numbers N through M-1.
1606
1606
1607 For example, if your history contains (%hist prints it):
1607 For example, if your history contains (%hist prints it):
1608
1608
1609 44: x=1\\
1609 44: x=1\\
1610 45: y=3\\
1610 45: y=3\\
1611 46: z=x+y\\
1611 46: z=x+y\\
1612 47: print x\\
1612 47: print x\\
1613 48: a=5\\
1613 48: a=5\\
1614 49: print 'x',x,'y',y\\
1614 49: print 'x',x,'y',y\\
1615
1615
1616 you can create a macro with lines 44 through 47 (included) and line 49
1616 you can create a macro with lines 44 through 47 (included) and line 49
1617 called my_macro with:
1617 called my_macro with:
1618
1618
1619 In [51]: %macro my_macro 44-47 49
1619 In [51]: %macro my_macro 44-47 49
1620
1620
1621 Now, typing `my_macro` (without quotes) will re-execute all this code
1621 Now, typing `my_macro` (without quotes) will re-execute all this code
1622 in one pass.
1622 in one pass.
1623
1623
1624 You don't need to give the line-numbers in order, and any given line
1624 You don't need to give the line-numbers in order, and any given line
1625 number can appear multiple times. You can assemble macros with any
1625 number can appear multiple times. You can assemble macros with any
1626 lines from your input history in any order.
1626 lines from your input history in any order.
1627
1627
1628 The macro is a simple object which holds its value in an attribute,
1628 The macro is a simple object which holds its value in an attribute,
1629 but IPython's display system checks for macros and executes them as
1629 but IPython's display system checks for macros and executes them as
1630 code instead of printing them when you type their name.
1630 code instead of printing them when you type their name.
1631
1631
1632 You can view a macro's contents by explicitly printing it with:
1632 You can view a macro's contents by explicitly printing it with:
1633
1633
1634 'print macro_name'.
1634 'print macro_name'.
1635
1635
1636 For one-off cases which DON'T contain magic function calls in them you
1636 For one-off cases which DON'T contain magic function calls in them you
1637 can obtain similar results by explicitly executing slices from your
1637 can obtain similar results by explicitly executing slices from your
1638 input history with:
1638 input history with:
1639
1639
1640 In [60]: exec In[44:48]+In[49]"""
1640 In [60]: exec In[44:48]+In[49]"""
1641
1641
1642 args = parameter_s.split()
1642 args = parameter_s.split()
1643 name,ranges = args[0], args[1:]
1643 name,ranges = args[0], args[1:]
1644 #print 'rng',ranges # dbg
1644 #print 'rng',ranges # dbg
1645 lines = self.extract_input_slices(ranges)
1645 lines = self.extract_input_slices(ranges)
1646 macro = Macro(lines)
1646 macro = Macro(lines)
1647 self.shell.user_ns.update({name:macro})
1647 self.shell.user_ns.update({name:macro})
1648 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1648 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1649 print 'Macro contents:'
1649 print 'Macro contents:'
1650 print macro,
1650 print macro,
1651
1651
1652 def magic_save(self,parameter_s = ''):
1652 def magic_save(self,parameter_s = ''):
1653 """Save a set of lines to a given filename.
1653 """Save a set of lines to a given filename.
1654
1654
1655 Usage:\\
1655 Usage:\\
1656 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1656 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1657
1657
1658 This function uses the same syntax as %macro for line extraction, but
1658 This function uses the same syntax as %macro for line extraction, but
1659 instead of creating a macro it saves the resulting string to the
1659 instead of creating a macro it saves the resulting string to the
1660 filename you specify.
1660 filename you specify.
1661
1661
1662 It adds a '.py' extension to the file if you don't do so yourself, and
1662 It adds a '.py' extension to the file if you don't do so yourself, and
1663 it asks for confirmation before overwriting existing files."""
1663 it asks for confirmation before overwriting existing files."""
1664
1664
1665 args = parameter_s.split()
1665 args = parameter_s.split()
1666 fname,ranges = args[0], args[1:]
1666 fname,ranges = args[0], args[1:]
1667 if not fname.endswith('.py'):
1667 if not fname.endswith('.py'):
1668 fname += '.py'
1668 fname += '.py'
1669 if os.path.isfile(fname):
1669 if os.path.isfile(fname):
1670 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1670 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1671 if ans.lower() not in ['y','yes']:
1671 if ans.lower() not in ['y','yes']:
1672 print 'Operation cancelled.'
1672 print 'Operation cancelled.'
1673 return
1673 return
1674 cmds = ''.join(self.extract_input_slices(ranges))
1674 cmds = ''.join(self.extract_input_slices(ranges))
1675 f = file(fname,'w')
1675 f = file(fname,'w')
1676 f.write(cmds)
1676 f.write(cmds)
1677 f.close()
1677 f.close()
1678 print 'The following commands were written to file `%s`:' % fname
1678 print 'The following commands were written to file `%s`:' % fname
1679 print cmds
1679 print cmds
1680
1680
1681 def _edit_macro(self,mname,macro):
1681 def _edit_macro(self,mname,macro):
1682 """open an editor with the macro data in a file"""
1682 """open an editor with the macro data in a file"""
1683 filename = self.shell.mktempfile(macro.value)
1683 filename = self.shell.mktempfile(macro.value)
1684 self.shell.hooks.editor(filename)
1684 self.shell.hooks.editor(filename)
1685
1685
1686 # and make a new macro object, to replace the old one
1686 # and make a new macro object, to replace the old one
1687 mfile = open(filename)
1687 mfile = open(filename)
1688 mvalue = mfile.read()
1688 mvalue = mfile.read()
1689 mfile.close()
1689 mfile.close()
1690 self.shell.user_ns[mname] = Macro(mvalue)
1690 self.shell.user_ns[mname] = Macro(mvalue)
1691
1691
1692 def magic_ed(self,parameter_s=''):
1692 def magic_ed(self,parameter_s=''):
1693 """Alias to %edit."""
1693 """Alias to %edit."""
1694 return self.magic_edit(parameter_s)
1694 return self.magic_edit(parameter_s)
1695
1695
1696 def magic_edit(self,parameter_s='',last_call=['','']):
1696 def magic_edit(self,parameter_s='',last_call=['','']):
1697 """Bring up an editor and execute the resulting code.
1697 """Bring up an editor and execute the resulting code.
1698
1698
1699 Usage:
1699 Usage:
1700 %edit [options] [args]
1700 %edit [options] [args]
1701
1701
1702 %edit runs IPython's editor hook. The default version of this hook is
1702 %edit runs IPython's editor hook. The default version of this hook is
1703 set to call the __IPYTHON__.rc.editor command. This is read from your
1703 set to call the __IPYTHON__.rc.editor command. This is read from your
1704 environment variable $EDITOR. If this isn't found, it will default to
1704 environment variable $EDITOR. If this isn't found, it will default to
1705 vi under Linux/Unix and to notepad under Windows. See the end of this
1705 vi under Linux/Unix and to notepad under Windows. See the end of this
1706 docstring for how to change the editor hook.
1706 docstring for how to change the editor hook.
1707
1707
1708 You can also set the value of this editor via the command line option
1708 You can also set the value of this editor via the command line option
1709 '-editor' or in your ipythonrc file. This is useful if you wish to use
1709 '-editor' or in your ipythonrc file. This is useful if you wish to use
1710 specifically for IPython an editor different from your typical default
1710 specifically for IPython an editor different from your typical default
1711 (and for Windows users who typically don't set environment variables).
1711 (and for Windows users who typically don't set environment variables).
1712
1712
1713 This command allows you to conveniently edit multi-line code right in
1713 This command allows you to conveniently edit multi-line code right in
1714 your IPython session.
1714 your IPython session.
1715
1715
1716 If called without arguments, %edit opens up an empty editor with a
1716 If called without arguments, %edit opens up an empty editor with a
1717 temporary file and will execute the contents of this file when you
1717 temporary file and will execute the contents of this file when you
1718 close it (don't forget to save it!).
1718 close it (don't forget to save it!).
1719
1719
1720
1720
1721 Options:
1721 Options:
1722
1722
1723 -p: this will call the editor with the same data as the previous time
1723 -p: this will call the editor with the same data as the previous time
1724 it was used, regardless of how long ago (in your current session) it
1724 it was used, regardless of how long ago (in your current session) it
1725 was.
1725 was.
1726
1726
1727 -x: do not execute the edited code immediately upon exit. This is
1727 -x: do not execute the edited code immediately upon exit. This is
1728 mainly useful if you are editing programs which need to be called with
1728 mainly useful if you are editing programs which need to be called with
1729 command line arguments, which you can then do using %run.
1729 command line arguments, which you can then do using %run.
1730
1730
1731
1731
1732 Arguments:
1732 Arguments:
1733
1733
1734 If arguments are given, the following possibilites exist:
1734 If arguments are given, the following possibilites exist:
1735
1735
1736 - The arguments are numbers or pairs of colon-separated numbers (like
1736 - The arguments are numbers or pairs of colon-separated numbers (like
1737 1 4:8 9). These are interpreted as lines of previous input to be
1737 1 4:8 9). These are interpreted as lines of previous input to be
1738 loaded into the editor. The syntax is the same of the %macro command.
1738 loaded into the editor. The syntax is the same of the %macro command.
1739
1739
1740 - If the argument doesn't start with a number, it is evaluated as a
1740 - If the argument doesn't start with a number, it is evaluated as a
1741 variable and its contents loaded into the editor. You can thus edit
1741 variable and its contents loaded into the editor. You can thus edit
1742 any string which contains python code (including the result of
1742 any string which contains python code (including the result of
1743 previous edits).
1743 previous edits).
1744
1744
1745 - If the argument is the name of an object (other than a string),
1745 - If the argument is the name of an object (other than a string),
1746 IPython will try to locate the file where it was defined and open the
1746 IPython will try to locate the file where it was defined and open the
1747 editor at the point where it is defined. You can use `%edit function`
1747 editor at the point where it is defined. You can use `%edit function`
1748 to load an editor exactly at the point where 'function' is defined,
1748 to load an editor exactly at the point where 'function' is defined,
1749 edit it and have the file be executed automatically.
1749 edit it and have the file be executed automatically.
1750
1750
1751 If the object is a macro (see %macro for details), this opens up your
1751 If the object is a macro (see %macro for details), this opens up your
1752 specified editor with a temporary file containing the macro's data.
1752 specified editor with a temporary file containing the macro's data.
1753 Upon exit, the macro is reloaded with the contents of the file.
1753 Upon exit, the macro is reloaded with the contents of the file.
1754
1754
1755 Note: opening at an exact line is only supported under Unix, and some
1755 Note: opening at an exact line is only supported under Unix, and some
1756 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1756 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1757 '+NUMBER' parameter necessary for this feature. Good editors like
1757 '+NUMBER' parameter necessary for this feature. Good editors like
1758 (X)Emacs, vi, jed, pico and joe all do.
1758 (X)Emacs, vi, jed, pico and joe all do.
1759
1759
1760 - If the argument is not found as a variable, IPython will look for a
1760 - If the argument is not found as a variable, IPython will look for a
1761 file with that name (adding .py if necessary) and load it into the
1761 file with that name (adding .py if necessary) and load it into the
1762 editor. It will execute its contents with execfile() when you exit,
1762 editor. It will execute its contents with execfile() when you exit,
1763 loading any code in the file into your interactive namespace.
1763 loading any code in the file into your interactive namespace.
1764
1764
1765 After executing your code, %edit will return as output the code you
1765 After executing your code, %edit will return as output the code you
1766 typed in the editor (except when it was an existing file). This way
1766 typed in the editor (except when it was an existing file). This way
1767 you can reload the code in further invocations of %edit as a variable,
1767 you can reload the code in further invocations of %edit as a variable,
1768 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1768 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1769 the output.
1769 the output.
1770
1770
1771 Note that %edit is also available through the alias %ed.
1771 Note that %edit is also available through the alias %ed.
1772
1772
1773 This is an example of creating a simple function inside the editor and
1773 This is an example of creating a simple function inside the editor and
1774 then modifying it. First, start up the editor:
1774 then modifying it. First, start up the editor:
1775
1775
1776 In [1]: ed\\
1776 In [1]: ed\\
1777 Editing... done. Executing edited code...\\
1777 Editing... done. Executing edited code...\\
1778 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1778 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1779
1779
1780 We can then call the function foo():
1780 We can then call the function foo():
1781
1781
1782 In [2]: foo()\\
1782 In [2]: foo()\\
1783 foo() was defined in an editing session
1783 foo() was defined in an editing session
1784
1784
1785 Now we edit foo. IPython automatically loads the editor with the
1785 Now we edit foo. IPython automatically loads the editor with the
1786 (temporary) file where foo() was previously defined:
1786 (temporary) file where foo() was previously defined:
1787
1787
1788 In [3]: ed foo\\
1788 In [3]: ed foo\\
1789 Editing... done. Executing edited code...
1789 Editing... done. Executing edited code...
1790
1790
1791 And if we call foo() again we get the modified version:
1791 And if we call foo() again we get the modified version:
1792
1792
1793 In [4]: foo()\\
1793 In [4]: foo()\\
1794 foo() has now been changed!
1794 foo() has now been changed!
1795
1795
1796 Here is an example of how to edit a code snippet successive
1796 Here is an example of how to edit a code snippet successive
1797 times. First we call the editor:
1797 times. First we call the editor:
1798
1798
1799 In [8]: ed\\
1799 In [8]: ed\\
1800 Editing... done. Executing edited code...\\
1800 Editing... done. Executing edited code...\\
1801 hello\\
1801 hello\\
1802 Out[8]: "print 'hello'\\n"
1802 Out[8]: "print 'hello'\\n"
1803
1803
1804 Now we call it again with the previous output (stored in _):
1804 Now we call it again with the previous output (stored in _):
1805
1805
1806 In [9]: ed _\\
1806 In [9]: ed _\\
1807 Editing... done. Executing edited code...\\
1807 Editing... done. Executing edited code...\\
1808 hello world\\
1808 hello world\\
1809 Out[9]: "print 'hello world'\\n"
1809 Out[9]: "print 'hello world'\\n"
1810
1810
1811 Now we call it with the output #8 (stored in _8, also as Out[8]):
1811 Now we call it with the output #8 (stored in _8, also as Out[8]):
1812
1812
1813 In [10]: ed _8\\
1813 In [10]: ed _8\\
1814 Editing... done. Executing edited code...\\
1814 Editing... done. Executing edited code...\\
1815 hello again\\
1815 hello again\\
1816 Out[10]: "print 'hello again'\\n"
1816 Out[10]: "print 'hello again'\\n"
1817
1817
1818
1818
1819 Changing the default editor hook:
1819 Changing the default editor hook:
1820
1820
1821 If you wish to write your own editor hook, you can put it in a
1821 If you wish to write your own editor hook, you can put it in a
1822 configuration file which you load at startup time. The default hook
1822 configuration file which you load at startup time. The default hook
1823 is defined in the IPython.hooks module, and you can use that as a
1823 is defined in the IPython.hooks module, and you can use that as a
1824 starting example for further modifications. That file also has
1824 starting example for further modifications. That file also has
1825 general instructions on how to set a new hook for use once you've
1825 general instructions on how to set a new hook for use once you've
1826 defined it."""
1826 defined it."""
1827
1827
1828 # FIXME: This function has become a convoluted mess. It needs a
1828 # FIXME: This function has become a convoluted mess. It needs a
1829 # ground-up rewrite with clean, simple logic.
1829 # ground-up rewrite with clean, simple logic.
1830
1830
1831 def make_filename(arg):
1831 def make_filename(arg):
1832 "Make a filename from the given args"
1832 "Make a filename from the given args"
1833 try:
1833 try:
1834 filename = get_py_filename(arg)
1834 filename = get_py_filename(arg)
1835 except IOError:
1835 except IOError:
1836 if args.endswith('.py'):
1836 if args.endswith('.py'):
1837 filename = arg
1837 filename = arg
1838 else:
1838 else:
1839 filename = None
1839 filename = None
1840 return filename
1840 return filename
1841
1841
1842 # custom exceptions
1842 # custom exceptions
1843 class DataIsObject(Exception): pass
1843 class DataIsObject(Exception): pass
1844
1844
1845 opts,args = self.parse_options(parameter_s,'px')
1845 opts,args = self.parse_options(parameter_s,'px')
1846
1846
1847 # Default line number value
1847 # Default line number value
1848 lineno = None
1848 lineno = None
1849 if opts.has_key('p'):
1849 if opts.has_key('p'):
1850 args = '_%s' % last_call[0]
1850 args = '_%s' % last_call[0]
1851 if not self.shell.user_ns.has_key(args):
1851 if not self.shell.user_ns.has_key(args):
1852 args = last_call[1]
1852 args = last_call[1]
1853
1853
1854 # use last_call to remember the state of the previous call, but don't
1854 # use last_call to remember the state of the previous call, but don't
1855 # let it be clobbered by successive '-p' calls.
1855 # let it be clobbered by successive '-p' calls.
1856 try:
1856 try:
1857 last_call[0] = self.shell.outputcache.prompt_count
1857 last_call[0] = self.shell.outputcache.prompt_count
1858 if not opts.has_key('p'):
1858 if not opts.has_key('p'):
1859 last_call[1] = parameter_s
1859 last_call[1] = parameter_s
1860 except:
1860 except:
1861 pass
1861 pass
1862
1862
1863 # by default this is done with temp files, except when the given
1863 # by default this is done with temp files, except when the given
1864 # arg is a filename
1864 # arg is a filename
1865 use_temp = 1
1865 use_temp = 1
1866
1866
1867 if re.match(r'\d',args):
1867 if re.match(r'\d',args):
1868 # Mode where user specifies ranges of lines, like in %macro.
1868 # Mode where user specifies ranges of lines, like in %macro.
1869 # This means that you can't edit files whose names begin with
1869 # This means that you can't edit files whose names begin with
1870 # numbers this way. Tough.
1870 # numbers this way. Tough.
1871 ranges = args.split()
1871 ranges = args.split()
1872 data = ''.join(self.extract_input_slices(ranges))
1872 data = ''.join(self.extract_input_slices(ranges))
1873 elif args.endswith('.py'):
1873 elif args.endswith('.py'):
1874 filename = make_filename(args)
1874 filename = make_filename(args)
1875 data = ''
1875 data = ''
1876 use_temp = 0
1876 use_temp = 0
1877 elif args:
1877 elif args:
1878 try:
1878 try:
1879 # Load the parameter given as a variable. If not a string,
1879 # Load the parameter given as a variable. If not a string,
1880 # process it as an object instead (below)
1880 # process it as an object instead (below)
1881
1881
1882 #print '*** args',args,'type',type(args) # dbg
1882 #print '*** args',args,'type',type(args) # dbg
1883 data = eval(args,self.shell.user_ns)
1883 data = eval(args,self.shell.user_ns)
1884 if not type(data) in StringTypes:
1884 if not type(data) in StringTypes:
1885 raise DataIsObject
1885 raise DataIsObject
1886
1886
1887 except (NameError,SyntaxError):
1887 except (NameError,SyntaxError):
1888 # given argument is not a variable, try as a filename
1888 # given argument is not a variable, try as a filename
1889 filename = make_filename(args)
1889 filename = make_filename(args)
1890 if filename is None:
1890 if filename is None:
1891 warn("Argument given (%s) can't be found as a variable "
1891 warn("Argument given (%s) can't be found as a variable "
1892 "or as a filename." % args)
1892 "or as a filename." % args)
1893 return
1893 return
1894
1894
1895 data = ''
1895 data = ''
1896 use_temp = 0
1896 use_temp = 0
1897 except DataIsObject:
1897 except DataIsObject:
1898
1898
1899 # macros have a special edit function
1899 # macros have a special edit function
1900 if isinstance(data,Macro):
1900 if isinstance(data,Macro):
1901 self._edit_macro(args,data)
1901 self._edit_macro(args,data)
1902 return
1902 return
1903
1903
1904 # For objects, try to edit the file where they are defined
1904 # For objects, try to edit the file where they are defined
1905 try:
1905 try:
1906 filename = inspect.getabsfile(data)
1906 filename = inspect.getabsfile(data)
1907 datafile = 1
1907 datafile = 1
1908 except TypeError:
1908 except TypeError:
1909 filename = make_filename(args)
1909 filename = make_filename(args)
1910 datafile = 1
1910 datafile = 1
1911 warn('Could not find file where `%s` is defined.\n'
1911 warn('Could not find file where `%s` is defined.\n'
1912 'Opening a file named `%s`' % (args,filename))
1912 'Opening a file named `%s`' % (args,filename))
1913 # Now, make sure we can actually read the source (if it was in
1913 # Now, make sure we can actually read the source (if it was in
1914 # a temp file it's gone by now).
1914 # a temp file it's gone by now).
1915 if datafile:
1915 if datafile:
1916 try:
1916 try:
1917 lineno = inspect.getsourcelines(data)[1]
1917 lineno = inspect.getsourcelines(data)[1]
1918 except IOError:
1918 except IOError:
1919 filename = make_filename(args)
1919 filename = make_filename(args)
1920 if filename is None:
1920 if filename is None:
1921 warn('The file `%s` where `%s` was defined cannot '
1921 warn('The file `%s` where `%s` was defined cannot '
1922 'be read.' % (filename,data))
1922 'be read.' % (filename,data))
1923 return
1923 return
1924 use_temp = 0
1924 use_temp = 0
1925 else:
1925 else:
1926 data = ''
1926 data = ''
1927
1927
1928 if use_temp:
1928 if use_temp:
1929 filename = self.shell.mktempfile(data)
1929 filename = self.shell.mktempfile(data)
1930 print 'IPython will make a temporary file named:',filename
1930 print 'IPython will make a temporary file named:',filename
1931
1931
1932 # do actual editing here
1932 # do actual editing here
1933 print 'Editing...',
1933 print 'Editing...',
1934 sys.stdout.flush()
1934 sys.stdout.flush()
1935 self.shell.hooks.editor(filename,lineno)
1935 self.shell.hooks.editor(filename,lineno)
1936 if opts.has_key('x'): # -x prevents actual execution
1936 if opts.has_key('x'): # -x prevents actual execution
1937 print
1937 print
1938 else:
1938 else:
1939 print 'done. Executing edited code...'
1939 print 'done. Executing edited code...'
1940 self.shell.safe_execfile(filename,self.shell.user_ns)
1940 self.shell.safe_execfile(filename,self.shell.user_ns)
1941 if use_temp:
1941 if use_temp:
1942 try:
1942 try:
1943 return open(filename).read()
1943 return open(filename).read()
1944 except IOError,msg:
1944 except IOError,msg:
1945 if msg.filename == filename:
1945 if msg.filename == filename:
1946 warn('File not found. Did you forget to save?')
1946 warn('File not found. Did you forget to save?')
1947 return
1947 return
1948 else:
1948 else:
1949 self.shell.showtraceback()
1949 self.shell.showtraceback()
1950
1950
1951 def magic_xmode(self,parameter_s = ''):
1951 def magic_xmode(self,parameter_s = ''):
1952 """Switch modes for the exception handlers.
1952 """Switch modes for the exception handlers.
1953
1953
1954 Valid modes: Plain, Context and Verbose.
1954 Valid modes: Plain, Context and Verbose.
1955
1955
1956 If called without arguments, acts as a toggle."""
1956 If called without arguments, acts as a toggle."""
1957
1957
1958 def xmode_switch_err(name):
1958 def xmode_switch_err(name):
1959 warn('Error changing %s exception modes.\n%s' %
1959 warn('Error changing %s exception modes.\n%s' %
1960 (name,sys.exc_info()[1]))
1960 (name,sys.exc_info()[1]))
1961
1961
1962 shell = self.shell
1962 shell = self.shell
1963 new_mode = parameter_s.strip().capitalize()
1963 new_mode = parameter_s.strip().capitalize()
1964 try:
1964 try:
1965 shell.InteractiveTB.set_mode(mode=new_mode)
1965 shell.InteractiveTB.set_mode(mode=new_mode)
1966 print 'Exception reporting mode:',shell.InteractiveTB.mode
1966 print 'Exception reporting mode:',shell.InteractiveTB.mode
1967 except:
1967 except:
1968 xmode_switch_err('user')
1968 xmode_switch_err('user')
1969
1969
1970 # threaded shells use a special handler in sys.excepthook
1970 # threaded shells use a special handler in sys.excepthook
1971 if shell.isthreaded:
1971 if shell.isthreaded:
1972 try:
1972 try:
1973 shell.sys_excepthook.set_mode(mode=new_mode)
1973 shell.sys_excepthook.set_mode(mode=new_mode)
1974 except:
1974 except:
1975 xmode_switch_err('threaded')
1975 xmode_switch_err('threaded')
1976
1976
1977 def magic_colors(self,parameter_s = ''):
1977 def magic_colors(self,parameter_s = ''):
1978 """Switch color scheme for prompts, info system and exception handlers.
1978 """Switch color scheme for prompts, info system and exception handlers.
1979
1979
1980 Currently implemented schemes: NoColor, Linux, LightBG.
1980 Currently implemented schemes: NoColor, Linux, LightBG.
1981
1981
1982 Color scheme names are not case-sensitive."""
1982 Color scheme names are not case-sensitive."""
1983
1983
1984 def color_switch_err(name):
1984 def color_switch_err(name):
1985 warn('Error changing %s color schemes.\n%s' %
1985 warn('Error changing %s color schemes.\n%s' %
1986 (name,sys.exc_info()[1]))
1986 (name,sys.exc_info()[1]))
1987
1987
1988
1988
1989 new_scheme = parameter_s.strip()
1989 new_scheme = parameter_s.strip()
1990 if not new_scheme:
1990 if not new_scheme:
1991 print 'You must specify a color scheme.'
1991 print 'You must specify a color scheme.'
1992 return
1992 return
1993 # Under Windows, check for Gary Bishop's readline, which is necessary
1993 # Under Windows, check for Gary Bishop's readline, which is necessary
1994 # for ANSI coloring
1994 # for ANSI coloring
1995 if os.name in ['nt','dos']:
1995 if os.name in ['nt','dos']:
1996 try:
1996 try:
1997 import readline
1997 import readline
1998 except ImportError:
1998 except ImportError:
1999 has_readline = 0
1999 has_readline = 0
2000 else:
2000 else:
2001 try:
2001 try:
2002 readline.GetOutputFile()
2002 readline.GetOutputFile()
2003 except AttributeError:
2003 except AttributeError:
2004 has_readline = 0
2004 has_readline = 0
2005 else:
2005 else:
2006 has_readline = 1
2006 has_readline = 1
2007 if not has_readline:
2007 if not has_readline:
2008 msg = """\
2008 msg = """\
2009 Proper color support under MS Windows requires Gary Bishop's readline library.
2009 Proper color support under MS Windows requires Gary Bishop's readline library.
2010 You can find it at:
2010 You can find it at:
2011 http://sourceforge.net/projects/uncpythontools
2011 http://sourceforge.net/projects/uncpythontools
2012 Gary's readline needs the ctypes module, from:
2012 Gary's readline needs the ctypes module, from:
2013 http://starship.python.net/crew/theller/ctypes
2013 http://starship.python.net/crew/theller/ctypes
2014
2014
2015 Defaulting color scheme to 'NoColor'"""
2015 Defaulting color scheme to 'NoColor'"""
2016 new_scheme = 'NoColor'
2016 new_scheme = 'NoColor'
2017 warn(msg)
2017 warn(msg)
2018 # local shortcut
2018 # local shortcut
2019 shell = self.shell
2019 shell = self.shell
2020
2020
2021 # Set prompt colors
2021 # Set prompt colors
2022 try:
2022 try:
2023 shell.outputcache.set_colors(new_scheme)
2023 shell.outputcache.set_colors(new_scheme)
2024 except:
2024 except:
2025 color_switch_err('prompt')
2025 color_switch_err('prompt')
2026 else:
2026 else:
2027 shell.rc.colors = \
2027 shell.rc.colors = \
2028 shell.outputcache.color_table.active_scheme_name
2028 shell.outputcache.color_table.active_scheme_name
2029 # Set exception colors
2029 # Set exception colors
2030 try:
2030 try:
2031 shell.InteractiveTB.set_colors(scheme = new_scheme)
2031 shell.InteractiveTB.set_colors(scheme = new_scheme)
2032 shell.SyntaxTB.set_colors(scheme = new_scheme)
2032 shell.SyntaxTB.set_colors(scheme = new_scheme)
2033 except:
2033 except:
2034 color_switch_err('exception')
2034 color_switch_err('exception')
2035
2035
2036 # threaded shells use a verbose traceback in sys.excepthook
2036 # threaded shells use a verbose traceback in sys.excepthook
2037 if shell.isthreaded:
2037 if shell.isthreaded:
2038 try:
2038 try:
2039 shell.sys_excepthook.set_colors(scheme=new_scheme)
2039 shell.sys_excepthook.set_colors(scheme=new_scheme)
2040 except:
2040 except:
2041 color_switch_err('system exception handler')
2041 color_switch_err('system exception handler')
2042
2042
2043 # Set info (for 'object?') colors
2043 # Set info (for 'object?') colors
2044 if shell.rc.color_info:
2044 if shell.rc.color_info:
2045 try:
2045 try:
2046 shell.inspector.set_active_scheme(new_scheme)
2046 shell.inspector.set_active_scheme(new_scheme)
2047 except:
2047 except:
2048 color_switch_err('object inspector')
2048 color_switch_err('object inspector')
2049 else:
2049 else:
2050 shell.inspector.set_active_scheme('NoColor')
2050 shell.inspector.set_active_scheme('NoColor')
2051
2051
2052 def magic_color_info(self,parameter_s = ''):
2052 def magic_color_info(self,parameter_s = ''):
2053 """Toggle color_info.
2053 """Toggle color_info.
2054
2054
2055 The color_info configuration parameter controls whether colors are
2055 The color_info configuration parameter controls whether colors are
2056 used for displaying object details (by things like %psource, %pfile or
2056 used for displaying object details (by things like %psource, %pfile or
2057 the '?' system). This function toggles this value with each call.
2057 the '?' system). This function toggles this value with each call.
2058
2058
2059 Note that unless you have a fairly recent pager (less works better
2059 Note that unless you have a fairly recent pager (less works better
2060 than more) in your system, using colored object information displays
2060 than more) in your system, using colored object information displays
2061 will not work properly. Test it and see."""
2061 will not work properly. Test it and see."""
2062
2062
2063 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2063 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2064 self.magic_colors(self.shell.rc.colors)
2064 self.magic_colors(self.shell.rc.colors)
2065 print 'Object introspection functions have now coloring:',
2065 print 'Object introspection functions have now coloring:',
2066 print ['OFF','ON'][self.shell.rc.color_info]
2066 print ['OFF','ON'][self.shell.rc.color_info]
2067
2067
2068 def magic_Pprint(self, parameter_s=''):
2068 def magic_Pprint(self, parameter_s=''):
2069 """Toggle pretty printing on/off."""
2069 """Toggle pretty printing on/off."""
2070
2070
2071 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2071 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2072 print 'Pretty printing has been turned', \
2072 print 'Pretty printing has been turned', \
2073 ['OFF','ON'][self.shell.outputcache.Pprint]
2073 ['OFF','ON'][self.shell.outputcache.Pprint]
2074
2074
2075 def magic_exit(self, parameter_s=''):
2075 def magic_exit(self, parameter_s=''):
2076 """Exit IPython, confirming if configured to do so.
2076 """Exit IPython, confirming if configured to do so.
2077
2077
2078 You can configure whether IPython asks for confirmation upon exit by
2078 You can configure whether IPython asks for confirmation upon exit by
2079 setting the confirm_exit flag in the ipythonrc file."""
2079 setting the confirm_exit flag in the ipythonrc file."""
2080
2080
2081 self.shell.exit()
2081 self.shell.exit()
2082
2082
2083 def magic_quit(self, parameter_s=''):
2083 def magic_quit(self, parameter_s=''):
2084 """Exit IPython, confirming if configured to do so (like %exit)"""
2084 """Exit IPython, confirming if configured to do so (like %exit)"""
2085
2085
2086 self.shell.exit()
2086 self.shell.exit()
2087
2087
2088 def magic_Exit(self, parameter_s=''):
2088 def magic_Exit(self, parameter_s=''):
2089 """Exit IPython without confirmation."""
2089 """Exit IPython without confirmation."""
2090
2090
2091 self.shell.exit_now = True
2091 self.shell.exit_now = True
2092
2092
2093 def magic_Quit(self, parameter_s=''):
2093 def magic_Quit(self, parameter_s=''):
2094 """Exit IPython without confirmation (like %Exit)."""
2094 """Exit IPython without confirmation (like %Exit)."""
2095
2095
2096 self.shell.exit_now = True
2096 self.shell.exit_now = True
2097
2097
2098 #......................................................................
2098 #......................................................................
2099 # Functions to implement unix shell-type things
2099 # Functions to implement unix shell-type things
2100
2100
2101 def magic_alias(self, parameter_s = ''):
2101 def magic_alias(self, parameter_s = ''):
2102 """Define an alias for a system command.
2102 """Define an alias for a system command.
2103
2103
2104 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2104 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2105
2105
2106 Then, typing 'alias_name params' will execute the system command 'cmd
2106 Then, typing 'alias_name params' will execute the system command 'cmd
2107 params' (from your underlying operating system).
2107 params' (from your underlying operating system).
2108
2108
2109 Aliases have lower precedence than magic functions and Python normal
2109 Aliases have lower precedence than magic functions and Python normal
2110 variables, so if 'foo' is both a Python variable and an alias, the
2110 variables, so if 'foo' is both a Python variable and an alias, the
2111 alias can not be executed until 'del foo' removes the Python variable.
2111 alias can not be executed until 'del foo' removes the Python variable.
2112
2112
2113 You can use the %l specifier in an alias definition to represent the
2113 You can use the %l specifier in an alias definition to represent the
2114 whole line when the alias is called. For example:
2114 whole line when the alias is called. For example:
2115
2115
2116 In [2]: alias all echo "Input in brackets: <%l>"\\
2116 In [2]: alias all echo "Input in brackets: <%l>"\\
2117 In [3]: all hello world\\
2117 In [3]: all hello world\\
2118 Input in brackets: <hello world>
2118 Input in brackets: <hello world>
2119
2119
2120 You can also define aliases with parameters using %s specifiers (one
2120 You can also define aliases with parameters using %s specifiers (one
2121 per parameter):
2121 per parameter):
2122
2122
2123 In [1]: alias parts echo first %s second %s\\
2123 In [1]: alias parts echo first %s second %s\\
2124 In [2]: %parts A B\\
2124 In [2]: %parts A B\\
2125 first A second B\\
2125 first A second B\\
2126 In [3]: %parts A\\
2126 In [3]: %parts A\\
2127 Incorrect number of arguments: 2 expected.\\
2127 Incorrect number of arguments: 2 expected.\\
2128 parts is an alias to: 'echo first %s second %s'
2128 parts is an alias to: 'echo first %s second %s'
2129
2129
2130 Note that %l and %s are mutually exclusive. You can only use one or
2130 Note that %l and %s are mutually exclusive. You can only use one or
2131 the other in your aliases.
2131 the other in your aliases.
2132
2132
2133 Aliases expand Python variables just like system calls using ! or !!
2133 Aliases expand Python variables just like system calls using ! or !!
2134 do: all expressions prefixed with '$' get expanded. For details of
2134 do: all expressions prefixed with '$' get expanded. For details of
2135 the semantic rules, see PEP-215:
2135 the semantic rules, see PEP-215:
2136 http://www.python.org/peps/pep-0215.html. This is the library used by
2136 http://www.python.org/peps/pep-0215.html. This is the library used by
2137 IPython for variable expansion. If you want to access a true shell
2137 IPython for variable expansion. If you want to access a true shell
2138 variable, an extra $ is necessary to prevent its expansion by IPython:
2138 variable, an extra $ is necessary to prevent its expansion by IPython:
2139
2139
2140 In [6]: alias show echo\\
2140 In [6]: alias show echo\\
2141 In [7]: PATH='A Python string'\\
2141 In [7]: PATH='A Python string'\\
2142 In [8]: show $PATH\\
2142 In [8]: show $PATH\\
2143 A Python string\\
2143 A Python string\\
2144 In [9]: show $$PATH\\
2144 In [9]: show $$PATH\\
2145 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2145 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2146
2146
2147 You can use the alias facility to acess all of $PATH. See the %rehash
2147 You can use the alias facility to acess all of $PATH. See the %rehash
2148 and %rehashx functions, which automatically create aliases for the
2148 and %rehashx functions, which automatically create aliases for the
2149 contents of your $PATH.
2149 contents of your $PATH.
2150
2150
2151 If called with no parameters, %alias prints the current alias table."""
2151 If called with no parameters, %alias prints the current alias table."""
2152
2152
2153 par = parameter_s.strip()
2153 par = parameter_s.strip()
2154 if not par:
2154 if not par:
2155 if self.shell.rc.automagic:
2155 if self.shell.rc.automagic:
2156 prechar = ''
2156 prechar = ''
2157 else:
2157 else:
2158 prechar = self.shell.ESC_MAGIC
2158 prechar = self.shell.ESC_MAGIC
2159 print 'Alias\t\tSystem Command\n'+'-'*30
2159 print 'Alias\t\tSystem Command\n'+'-'*30
2160 atab = self.shell.alias_table
2160 atab = self.shell.alias_table
2161 aliases = atab.keys()
2161 aliases = atab.keys()
2162 aliases.sort()
2162 aliases.sort()
2163 for alias in aliases:
2163 for alias in aliases:
2164 print prechar+alias+'\t\t'+atab[alias][1]
2164 print prechar+alias+'\t\t'+atab[alias][1]
2165 print '-'*30+'\nTotal number of aliases:',len(aliases)
2165 print '-'*30+'\nTotal number of aliases:',len(aliases)
2166 return
2166 return
2167 try:
2167 try:
2168 alias,cmd = par.split(None,1)
2168 alias,cmd = par.split(None,1)
2169 except:
2169 except:
2170 print OInspect.getdoc(self.magic_alias)
2170 print OInspect.getdoc(self.magic_alias)
2171 else:
2171 else:
2172 nargs = cmd.count('%s')
2172 nargs = cmd.count('%s')
2173 if nargs>0 and cmd.find('%l')>=0:
2173 if nargs>0 and cmd.find('%l')>=0:
2174 error('The %s and %l specifiers are mutually exclusive '
2174 error('The %s and %l specifiers are mutually exclusive '
2175 'in alias definitions.')
2175 'in alias definitions.')
2176 else: # all looks OK
2176 else: # all looks OK
2177 self.shell.alias_table[alias] = (nargs,cmd)
2177 self.shell.alias_table[alias] = (nargs,cmd)
2178 self.shell.alias_table_validate(verbose=1)
2178 self.shell.alias_table_validate(verbose=1)
2179 # end magic_alias
2179 # end magic_alias
2180
2180
2181 def magic_unalias(self, parameter_s = ''):
2181 def magic_unalias(self, parameter_s = ''):
2182 """Remove an alias"""
2182 """Remove an alias"""
2183
2183
2184 aname = parameter_s.strip()
2184 aname = parameter_s.strip()
2185 if aname in self.shell.alias_table:
2185 if aname in self.shell.alias_table:
2186 del self.shell.alias_table[aname]
2186 del self.shell.alias_table[aname]
2187
2187
2188 def magic_rehash(self, parameter_s = ''):
2188 def magic_rehash(self, parameter_s = ''):
2189 """Update the alias table with all entries in $PATH.
2189 """Update the alias table with all entries in $PATH.
2190
2190
2191 This version does no checks on execute permissions or whether the
2191 This version does no checks on execute permissions or whether the
2192 contents of $PATH are truly files (instead of directories or something
2192 contents of $PATH are truly files (instead of directories or something
2193 else). For such a safer (but slower) version, use %rehashx."""
2193 else). For such a safer (but slower) version, use %rehashx."""
2194
2194
2195 # This function (and rehashx) manipulate the alias_table directly
2195 # This function (and rehashx) manipulate the alias_table directly
2196 # rather than calling magic_alias, for speed reasons. A rehash on a
2196 # rather than calling magic_alias, for speed reasons. A rehash on a
2197 # typical Linux box involves several thousand entries, so efficiency
2197 # typical Linux box involves several thousand entries, so efficiency
2198 # here is a top concern.
2198 # here is a top concern.
2199
2199
2200 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2200 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2201 alias_table = self.shell.alias_table
2201 alias_table = self.shell.alias_table
2202 for pdir in path:
2202 for pdir in path:
2203 for ff in os.listdir(pdir):
2203 for ff in os.listdir(pdir):
2204 # each entry in the alias table must be (N,name), where
2204 # each entry in the alias table must be (N,name), where
2205 # N is the number of positional arguments of the alias.
2205 # N is the number of positional arguments of the alias.
2206 alias_table[ff] = (0,ff)
2206 alias_table[ff] = (0,ff)
2207 # Make sure the alias table doesn't contain keywords or builtins
2207 # Make sure the alias table doesn't contain keywords or builtins
2208 self.shell.alias_table_validate()
2208 self.shell.alias_table_validate()
2209 # Call again init_auto_alias() so we get 'rm -i' and other modified
2209 # Call again init_auto_alias() so we get 'rm -i' and other modified
2210 # aliases since %rehash will probably clobber them
2210 # aliases since %rehash will probably clobber them
2211 self.shell.init_auto_alias()
2211 self.shell.init_auto_alias()
2212
2212
2213 def magic_rehashx(self, parameter_s = ''):
2213 def magic_rehashx(self, parameter_s = ''):
2214 """Update the alias table with all executable files in $PATH.
2214 """Update the alias table with all executable files in $PATH.
2215
2215
2216 This version explicitly checks that every entry in $PATH is a file
2216 This version explicitly checks that every entry in $PATH is a file
2217 with execute access (os.X_OK), so it is much slower than %rehash.
2217 with execute access (os.X_OK), so it is much slower than %rehash.
2218
2218
2219 Under Windows, it checks executability as a match agains a
2219 Under Windows, it checks executability as a match agains a
2220 '|'-separated string of extensions, stored in the IPython config
2220 '|'-separated string of extensions, stored in the IPython config
2221 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2221 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2222
2222
2223 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2223 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2224 alias_table = self.shell.alias_table
2224 alias_table = self.shell.alias_table
2225
2225
2226 if os.name == 'posix':
2226 if os.name == 'posix':
2227 isexec = lambda fname:os.path.isfile(fname) and \
2227 isexec = lambda fname:os.path.isfile(fname) and \
2228 os.access(fname,os.X_OK)
2228 os.access(fname,os.X_OK)
2229 else:
2229 else:
2230
2230
2231 try:
2231 try:
2232 winext = os.environ['pathext'].replace(';','|').replace('.','')
2232 winext = os.environ['pathext'].replace(';','|').replace('.','')
2233 except KeyError:
2233 except KeyError:
2234 winext = 'exe|com|bat'
2234 winext = 'exe|com|bat'
2235
2235
2236 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2236 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2237 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2237 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2238 savedir = os.getcwd()
2238 savedir = os.getcwd()
2239 try:
2239 try:
2240 # write the whole loop for posix/Windows so we don't have an if in
2240 # write the whole loop for posix/Windows so we don't have an if in
2241 # the innermost part
2241 # the innermost part
2242 if os.name == 'posix':
2242 if os.name == 'posix':
2243 for pdir in path:
2243 for pdir in path:
2244 os.chdir(pdir)
2244 os.chdir(pdir)
2245 for ff in os.listdir(pdir):
2245 for ff in os.listdir(pdir):
2246 if isexec(ff):
2246 if isexec(ff):
2247 # each entry in the alias table must be (N,name),
2247 # each entry in the alias table must be (N,name),
2248 # where N is the number of positional arguments of the
2248 # where N is the number of positional arguments of the
2249 # alias.
2249 # alias.
2250 alias_table[ff] = (0,ff)
2250 alias_table[ff] = (0,ff)
2251 else:
2251 else:
2252 for pdir in path:
2252 for pdir in path:
2253 os.chdir(pdir)
2253 os.chdir(pdir)
2254 for ff in os.listdir(pdir):
2254 for ff in os.listdir(pdir):
2255 if isexec(ff):
2255 if isexec(ff):
2256 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2256 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2257 # Make sure the alias table doesn't contain keywords or builtins
2257 # Make sure the alias table doesn't contain keywords or builtins
2258 self.shell.alias_table_validate()
2258 self.shell.alias_table_validate()
2259 # Call again init_auto_alias() so we get 'rm -i' and other
2259 # Call again init_auto_alias() so we get 'rm -i' and other
2260 # modified aliases since %rehashx will probably clobber them
2260 # modified aliases since %rehashx will probably clobber them
2261 self.shell.init_auto_alias()
2261 self.shell.init_auto_alias()
2262 finally:
2262 finally:
2263 os.chdir(savedir)
2263 os.chdir(savedir)
2264
2264
2265 def magic_pwd(self, parameter_s = ''):
2265 def magic_pwd(self, parameter_s = ''):
2266 """Return the current working directory path."""
2266 """Return the current working directory path."""
2267 return os.getcwd()
2267 return os.getcwd()
2268
2268
2269 def magic_cd(self, parameter_s=''):
2269 def magic_cd(self, parameter_s=''):
2270 """Change the current working directory.
2270 """Change the current working directory.
2271
2271
2272 This command automatically maintains an internal list of directories
2272 This command automatically maintains an internal list of directories
2273 you visit during your IPython session, in the variable _dh. The
2273 you visit during your IPython session, in the variable _dh. The
2274 command %dhist shows this history nicely formatted.
2274 command %dhist shows this history nicely formatted.
2275
2275
2276 Usage:
2276 Usage:
2277
2277
2278 cd 'dir': changes to directory 'dir'.
2278 cd 'dir': changes to directory 'dir'.
2279
2279
2280 cd -: changes to the last visited directory.
2280 cd -: changes to the last visited directory.
2281
2281
2282 cd -<n>: changes to the n-th directory in the directory history.
2282 cd -<n>: changes to the n-th directory in the directory history.
2283
2283
2284 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2284 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2285 (note: cd <bookmark_name> is enough if there is no
2285 (note: cd <bookmark_name> is enough if there is no
2286 directory <bookmark_name>, but a bookmark with the name exists.)
2286 directory <bookmark_name>, but a bookmark with the name exists.)
2287
2287
2288 Options:
2288 Options:
2289
2289
2290 -q: quiet. Do not print the working directory after the cd command is
2290 -q: quiet. Do not print the working directory after the cd command is
2291 executed. By default IPython's cd command does print this directory,
2291 executed. By default IPython's cd command does print this directory,
2292 since the default prompts do not display path information.
2292 since the default prompts do not display path information.
2293
2293
2294 Note that !cd doesn't work for this purpose because the shell where
2294 Note that !cd doesn't work for this purpose because the shell where
2295 !command runs is immediately discarded after executing 'command'."""
2295 !command runs is immediately discarded after executing 'command'."""
2296
2296
2297 parameter_s = parameter_s.strip()
2297 parameter_s = parameter_s.strip()
2298 bkms = self.shell.persist.get("bookmarks",{})
2298 bkms = self.shell.persist.get("bookmarks",{})
2299
2299
2300 numcd = re.match(r'(-)(\d+)$',parameter_s)
2300 numcd = re.match(r'(-)(\d+)$',parameter_s)
2301 # jump in directory history by number
2301 # jump in directory history by number
2302 if numcd:
2302 if numcd:
2303 nn = int(numcd.group(2))
2303 nn = int(numcd.group(2))
2304 try:
2304 try:
2305 ps = self.shell.user_ns['_dh'][nn]
2305 ps = self.shell.user_ns['_dh'][nn]
2306 except IndexError:
2306 except IndexError:
2307 print 'The requested directory does not exist in history.'
2307 print 'The requested directory does not exist in history.'
2308 return
2308 return
2309 else:
2309 else:
2310 opts = {}
2310 opts = {}
2311 else:
2311 else:
2312 #turn all non-space-escaping backslashes to slashes,
2312 #turn all non-space-escaping backslashes to slashes,
2313 # for c:\windows\directory\names\
2313 # for c:\windows\directory\names\
2314 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2314 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2315 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2315 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2316 # jump to previous
2316 # jump to previous
2317 if ps == '-':
2317 if ps == '-':
2318 try:
2318 try:
2319 ps = self.shell.user_ns['_dh'][-2]
2319 ps = self.shell.user_ns['_dh'][-2]
2320 except IndexError:
2320 except IndexError:
2321 print 'No previous directory to change to.'
2321 print 'No previous directory to change to.'
2322 return
2322 return
2323 # jump to bookmark
2323 # jump to bookmark
2324 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2324 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2325 if bkms.has_key(ps):
2325 if bkms.has_key(ps):
2326 target = bkms[ps]
2326 target = bkms[ps]
2327 print '(bookmark:%s) -> %s' % (ps,target)
2327 print '(bookmark:%s) -> %s' % (ps,target)
2328 ps = target
2328 ps = target
2329 else:
2329 else:
2330 if bkms:
2330 if bkms:
2331 error("Bookmark '%s' not found. "
2331 error("Bookmark '%s' not found. "
2332 "Use '%%bookmark -l' to see your bookmarks." % ps)
2332 "Use '%%bookmark -l' to see your bookmarks." % ps)
2333 else:
2333 else:
2334 print "Bookmarks not set - use %bookmark <bookmarkname>"
2334 print "Bookmarks not set - use %bookmark <bookmarkname>"
2335 return
2335 return
2336
2336
2337 # at this point ps should point to the target dir
2337 # at this point ps should point to the target dir
2338 if ps:
2338 if ps:
2339 try:
2339 try:
2340 os.chdir(os.path.expanduser(ps))
2340 os.chdir(os.path.expanduser(ps))
2341 ttitle = ("IPy:" + (
2341 ttitle = ("IPy:" + (
2342 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2342 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2343 platutils.set_term_title(ttitle)
2343 platutils.set_term_title(ttitle)
2344 except OSError:
2344 except OSError:
2345 print sys.exc_info()[1]
2345 print sys.exc_info()[1]
2346 else:
2346 else:
2347 self.shell.user_ns['_dh'].append(os.getcwd())
2347 self.shell.user_ns['_dh'].append(os.getcwd())
2348 else:
2348 else:
2349 os.chdir(self.shell.home_dir)
2349 os.chdir(self.shell.home_dir)
2350 platutils.set_term_title("IPy:~")
2350 platutils.set_term_title("IPy:~")
2351 self.shell.user_ns['_dh'].append(os.getcwd())
2351 self.shell.user_ns['_dh'].append(os.getcwd())
2352 if not 'q' in opts:
2352 if not 'q' in opts:
2353 print self.shell.user_ns['_dh'][-1]
2353 print self.shell.user_ns['_dh'][-1]
2354
2354
2355 def magic_dhist(self, parameter_s=''):
2355 def magic_dhist(self, parameter_s=''):
2356 """Print your history of visited directories.
2356 """Print your history of visited directories.
2357
2357
2358 %dhist -> print full history\\
2358 %dhist -> print full history\\
2359 %dhist n -> print last n entries only\\
2359 %dhist n -> print last n entries only\\
2360 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2360 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2361
2361
2362 This history is automatically maintained by the %cd command, and
2362 This history is automatically maintained by the %cd command, and
2363 always available as the global list variable _dh. You can use %cd -<n>
2363 always available as the global list variable _dh. You can use %cd -<n>
2364 to go to directory number <n>."""
2364 to go to directory number <n>."""
2365
2365
2366 dh = self.shell.user_ns['_dh']
2366 dh = self.shell.user_ns['_dh']
2367 if parameter_s:
2367 if parameter_s:
2368 try:
2368 try:
2369 args = map(int,parameter_s.split())
2369 args = map(int,parameter_s.split())
2370 except:
2370 except:
2371 self.arg_err(Magic.magic_dhist)
2371 self.arg_err(Magic.magic_dhist)
2372 return
2372 return
2373 if len(args) == 1:
2373 if len(args) == 1:
2374 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2374 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2375 elif len(args) == 2:
2375 elif len(args) == 2:
2376 ini,fin = args
2376 ini,fin = args
2377 else:
2377 else:
2378 self.arg_err(Magic.magic_dhist)
2378 self.arg_err(Magic.magic_dhist)
2379 return
2379 return
2380 else:
2380 else:
2381 ini,fin = 0,len(dh)
2381 ini,fin = 0,len(dh)
2382 nlprint(dh,
2382 nlprint(dh,
2383 header = 'Directory history (kept in _dh)',
2383 header = 'Directory history (kept in _dh)',
2384 start=ini,stop=fin)
2384 start=ini,stop=fin)
2385
2385
2386 def magic_env(self, parameter_s=''):
2386 def magic_env(self, parameter_s=''):
2387 """List environment variables."""
2387 """List environment variables."""
2388
2388
2389 return os.environ.data
2389 return os.environ.data
2390
2390
2391 def magic_pushd(self, parameter_s=''):
2391 def magic_pushd(self, parameter_s=''):
2392 """Place the current dir on stack and change directory.
2392 """Place the current dir on stack and change directory.
2393
2393
2394 Usage:\\
2394 Usage:\\
2395 %pushd ['dirname']
2395 %pushd ['dirname']
2396
2396
2397 %pushd with no arguments does a %pushd to your home directory.
2397 %pushd with no arguments does a %pushd to your home directory.
2398 """
2398 """
2399 if parameter_s == '': parameter_s = '~'
2399 if parameter_s == '': parameter_s = '~'
2400 dir_s = self.shell.dir_stack
2400 dir_s = self.shell.dir_stack
2401 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2401 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2402 os.path.expanduser(self.shell.dir_stack[0]):
2402 os.path.expanduser(self.shell.dir_stack[0]):
2403 try:
2403 try:
2404 self.magic_cd(parameter_s)
2404 self.magic_cd(parameter_s)
2405 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2405 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2406 self.magic_dirs()
2406 self.magic_dirs()
2407 except:
2407 except:
2408 print 'Invalid directory'
2408 print 'Invalid directory'
2409 else:
2409 else:
2410 print 'You are already there!'
2410 print 'You are already there!'
2411
2411
2412 def magic_popd(self, parameter_s=''):
2412 def magic_popd(self, parameter_s=''):
2413 """Change to directory popped off the top of the stack.
2413 """Change to directory popped off the top of the stack.
2414 """
2414 """
2415 if len (self.shell.dir_stack) > 1:
2415 if len (self.shell.dir_stack) > 1:
2416 self.shell.dir_stack.pop(0)
2416 self.shell.dir_stack.pop(0)
2417 self.magic_cd(self.shell.dir_stack[0])
2417 self.magic_cd(self.shell.dir_stack[0])
2418 print self.shell.dir_stack[0]
2418 print self.shell.dir_stack[0]
2419 else:
2419 else:
2420 print "You can't remove the starting directory from the stack:",\
2420 print "You can't remove the starting directory from the stack:",\
2421 self.shell.dir_stack
2421 self.shell.dir_stack
2422
2422
2423 def magic_dirs(self, parameter_s=''):
2423 def magic_dirs(self, parameter_s=''):
2424 """Return the current directory stack."""
2424 """Return the current directory stack."""
2425
2425
2426 return self.shell.dir_stack[:]
2426 return self.shell.dir_stack[:]
2427
2427
2428 def magic_sc(self, parameter_s=''):
2428 def magic_sc(self, parameter_s=''):
2429 """Shell capture - execute a shell command and capture its output.
2429 """Shell capture - execute a shell command and capture its output.
2430
2430
2431 %sc [options] varname=command
2431 %sc [options] varname=command
2432
2432
2433 IPython will run the given command using commands.getoutput(), and
2433 IPython will run the given command using commands.getoutput(), and
2434 will then update the user's interactive namespace with a variable
2434 will then update the user's interactive namespace with a variable
2435 called varname, containing the value of the call. Your command can
2435 called varname, containing the value of the call. Your command can
2436 contain shell wildcards, pipes, etc.
2436 contain shell wildcards, pipes, etc.
2437
2437
2438 The '=' sign in the syntax is mandatory, and the variable name you
2438 The '=' sign in the syntax is mandatory, and the variable name you
2439 supply must follow Python's standard conventions for valid names.
2439 supply must follow Python's standard conventions for valid names.
2440
2440
2441 Options:
2441 Options:
2442
2442
2443 -l: list output. Split the output on newlines into a list before
2443 -l: list output. Split the output on newlines into a list before
2444 assigning it to the given variable. By default the output is stored
2444 assigning it to the given variable. By default the output is stored
2445 as a single string.
2445 as a single string.
2446
2446
2447 -v: verbose. Print the contents of the variable.
2447 -v: verbose. Print the contents of the variable.
2448
2448
2449 In most cases you should not need to split as a list, because the
2449 In most cases you should not need to split as a list, because the
2450 returned value is a special type of string which can automatically
2450 returned value is a special type of string which can automatically
2451 provide its contents either as a list (split on newlines) or as a
2451 provide its contents either as a list (split on newlines) or as a
2452 space-separated string. These are convenient, respectively, either
2452 space-separated string. These are convenient, respectively, either
2453 for sequential processing or to be passed to a shell command.
2453 for sequential processing or to be passed to a shell command.
2454
2454
2455 For example:
2455 For example:
2456
2456
2457 # Capture into variable a
2457 # Capture into variable a
2458 In [9]: sc a=ls *py
2458 In [9]: sc a=ls *py
2459
2459
2460 # a is a string with embedded newlines
2460 # a is a string with embedded newlines
2461 In [10]: a
2461 In [10]: a
2462 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2462 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2463
2463
2464 # which can be seen as a list:
2464 # which can be seen as a list:
2465 In [11]: a.l
2465 In [11]: a.l
2466 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2466 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2467
2467
2468 # or as a whitespace-separated string:
2468 # or as a whitespace-separated string:
2469 In [12]: a.s
2469 In [12]: a.s
2470 Out[12]: 'setup.py win32_manual_post_install.py'
2470 Out[12]: 'setup.py win32_manual_post_install.py'
2471
2471
2472 # a.s is useful to pass as a single command line:
2472 # a.s is useful to pass as a single command line:
2473 In [13]: !wc -l $a.s
2473 In [13]: !wc -l $a.s
2474 146 setup.py
2474 146 setup.py
2475 130 win32_manual_post_install.py
2475 130 win32_manual_post_install.py
2476 276 total
2476 276 total
2477
2477
2478 # while the list form is useful to loop over:
2478 # while the list form is useful to loop over:
2479 In [14]: for f in a.l:
2479 In [14]: for f in a.l:
2480 ....: !wc -l $f
2480 ....: !wc -l $f
2481 ....:
2481 ....:
2482 146 setup.py
2482 146 setup.py
2483 130 win32_manual_post_install.py
2483 130 win32_manual_post_install.py
2484
2484
2485 Similiarly, the lists returned by the -l option are also special, in
2485 Similiarly, the lists returned by the -l option are also special, in
2486 the sense that you can equally invoke the .s attribute on them to
2486 the sense that you can equally invoke the .s attribute on them to
2487 automatically get a whitespace-separated string from their contents:
2487 automatically get a whitespace-separated string from their contents:
2488
2488
2489 In [1]: sc -l b=ls *py
2489 In [1]: sc -l b=ls *py
2490
2490
2491 In [2]: b
2491 In [2]: b
2492 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2492 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2493
2493
2494 In [3]: b.s
2494 In [3]: b.s
2495 Out[3]: 'setup.py win32_manual_post_install.py'
2495 Out[3]: 'setup.py win32_manual_post_install.py'
2496
2496
2497 In summary, both the lists and strings used for ouptut capture have
2497 In summary, both the lists and strings used for ouptut capture have
2498 the following special attributes:
2498 the following special attributes:
2499
2499
2500 .l (or .list) : value as list.
2500 .l (or .list) : value as list.
2501 .n (or .nlstr): value as newline-separated string.
2501 .n (or .nlstr): value as newline-separated string.
2502 .s (or .spstr): value as space-separated string.
2502 .s (or .spstr): value as space-separated string.
2503 """
2503 """
2504
2504
2505 opts,args = self.parse_options(parameter_s,'lv')
2505 opts,args = self.parse_options(parameter_s,'lv')
2506 # Try to get a variable name and command to run
2506 # Try to get a variable name and command to run
2507 try:
2507 try:
2508 # the variable name must be obtained from the parse_options
2508 # the variable name must be obtained from the parse_options
2509 # output, which uses shlex.split to strip options out.
2509 # output, which uses shlex.split to strip options out.
2510 var,_ = args.split('=',1)
2510 var,_ = args.split('=',1)
2511 var = var.strip()
2511 var = var.strip()
2512 # But the the command has to be extracted from the original input
2512 # But the the command has to be extracted from the original input
2513 # parameter_s, not on what parse_options returns, to avoid the
2513 # parameter_s, not on what parse_options returns, to avoid the
2514 # quote stripping which shlex.split performs on it.
2514 # quote stripping which shlex.split performs on it.
2515 _,cmd = parameter_s.split('=',1)
2515 _,cmd = parameter_s.split('=',1)
2516 except ValueError:
2516 except ValueError:
2517 var,cmd = '',''
2517 var,cmd = '',''
2518 if not var:
2518 if not var:
2519 error('you must specify a variable to assign the command to.')
2519 error('you must specify a variable to assign the command to.')
2520 return
2520 return
2521 # If all looks ok, proceed
2521 # If all looks ok, proceed
2522 out,err = self.shell.getoutputerror(cmd)
2522 out,err = self.shell.getoutputerror(cmd)
2523 if err:
2523 if err:
2524 print >> Term.cerr,err
2524 print >> Term.cerr,err
2525 if opts.has_key('l'):
2525 if opts.has_key('l'):
2526 out = SList(out.split('\n'))
2526 out = SList(out.split('\n'))
2527 else:
2527 else:
2528 out = LSString(out)
2528 out = LSString(out)
2529 if opts.has_key('v'):
2529 if opts.has_key('v'):
2530 print '%s ==\n%s' % (var,pformat(out))
2530 print '%s ==\n%s' % (var,pformat(out))
2531 self.shell.user_ns.update({var:out})
2531 self.shell.user_ns.update({var:out})
2532
2532
2533 def magic_sx(self, parameter_s=''):
2533 def magic_sx(self, parameter_s=''):
2534 """Shell execute - run a shell command and capture its output.
2534 """Shell execute - run a shell command and capture its output.
2535
2535
2536 %sx command
2536 %sx command
2537
2537
2538 IPython will run the given command using commands.getoutput(), and
2538 IPython will run the given command using commands.getoutput(), and
2539 return the result formatted as a list (split on '\\n'). Since the
2539 return the result formatted as a list (split on '\\n'). Since the
2540 output is _returned_, it will be stored in ipython's regular output
2540 output is _returned_, it will be stored in ipython's regular output
2541 cache Out[N] and in the '_N' automatic variables.
2541 cache Out[N] and in the '_N' automatic variables.
2542
2542
2543 Notes:
2543 Notes:
2544
2544
2545 1) If an input line begins with '!!', then %sx is automatically
2545 1) If an input line begins with '!!', then %sx is automatically
2546 invoked. That is, while:
2546 invoked. That is, while:
2547 !ls
2547 !ls
2548 causes ipython to simply issue system('ls'), typing
2548 causes ipython to simply issue system('ls'), typing
2549 !!ls
2549 !!ls
2550 is a shorthand equivalent to:
2550 is a shorthand equivalent to:
2551 %sx ls
2551 %sx ls
2552
2552
2553 2) %sx differs from %sc in that %sx automatically splits into a list,
2553 2) %sx differs from %sc in that %sx automatically splits into a list,
2554 like '%sc -l'. The reason for this is to make it as easy as possible
2554 like '%sc -l'. The reason for this is to make it as easy as possible
2555 to process line-oriented shell output via further python commands.
2555 to process line-oriented shell output via further python commands.
2556 %sc is meant to provide much finer control, but requires more
2556 %sc is meant to provide much finer control, but requires more
2557 typing.
2557 typing.
2558
2558
2559 3) Just like %sc -l, this is a list with special attributes:
2559 3) Just like %sc -l, this is a list with special attributes:
2560
2560
2561 .l (or .list) : value as list.
2561 .l (or .list) : value as list.
2562 .n (or .nlstr): value as newline-separated string.
2562 .n (or .nlstr): value as newline-separated string.
2563 .s (or .spstr): value as whitespace-separated string.
2563 .s (or .spstr): value as whitespace-separated string.
2564
2564
2565 This is very useful when trying to use such lists as arguments to
2565 This is very useful when trying to use such lists as arguments to
2566 system commands."""
2566 system commands."""
2567
2567
2568 if parameter_s:
2568 if parameter_s:
2569 out,err = self.shell.getoutputerror(parameter_s)
2569 out,err = self.shell.getoutputerror(parameter_s)
2570 if err:
2570 if err:
2571 print >> Term.cerr,err
2571 print >> Term.cerr,err
2572 return SList(out.split('\n'))
2572 return SList(out.split('\n'))
2573
2573
2574 def magic_bg(self, parameter_s=''):
2574 def magic_bg(self, parameter_s=''):
2575 """Run a job in the background, in a separate thread.
2575 """Run a job in the background, in a separate thread.
2576
2576
2577 For example,
2577 For example,
2578
2578
2579 %bg myfunc(x,y,z=1)
2579 %bg myfunc(x,y,z=1)
2580
2580
2581 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2581 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2582 execution starts, a message will be printed indicating the job
2582 execution starts, a message will be printed indicating the job
2583 number. If your job number is 5, you can use
2583 number. If your job number is 5, you can use
2584
2584
2585 myvar = jobs.result(5) or myvar = jobs[5].result
2585 myvar = jobs.result(5) or myvar = jobs[5].result
2586
2586
2587 to assign this result to variable 'myvar'.
2587 to assign this result to variable 'myvar'.
2588
2588
2589 IPython has a job manager, accessible via the 'jobs' object. You can
2589 IPython has a job manager, accessible via the 'jobs' object. You can
2590 type jobs? to get more information about it, and use jobs.<TAB> to see
2590 type jobs? to get more information about it, and use jobs.<TAB> to see
2591 its attributes. All attributes not starting with an underscore are
2591 its attributes. All attributes not starting with an underscore are
2592 meant for public use.
2592 meant for public use.
2593
2593
2594 In particular, look at the jobs.new() method, which is used to create
2594 In particular, look at the jobs.new() method, which is used to create
2595 new jobs. This magic %bg function is just a convenience wrapper
2595 new jobs. This magic %bg function is just a convenience wrapper
2596 around jobs.new(), for expression-based jobs. If you want to create a
2596 around jobs.new(), for expression-based jobs. If you want to create a
2597 new job with an explicit function object and arguments, you must call
2597 new job with an explicit function object and arguments, you must call
2598 jobs.new() directly.
2598 jobs.new() directly.
2599
2599
2600 The jobs.new docstring also describes in detail several important
2600 The jobs.new docstring also describes in detail several important
2601 caveats associated with a thread-based model for background job
2601 caveats associated with a thread-based model for background job
2602 execution. Type jobs.new? for details.
2602 execution. Type jobs.new? for details.
2603
2603
2604 You can check the status of all jobs with jobs.status().
2604 You can check the status of all jobs with jobs.status().
2605
2605
2606 The jobs variable is set by IPython into the Python builtin namespace.
2606 The jobs variable is set by IPython into the Python builtin namespace.
2607 If you ever declare a variable named 'jobs', you will shadow this
2607 If you ever declare a variable named 'jobs', you will shadow this
2608 name. You can either delete your global jobs variable to regain
2608 name. You can either delete your global jobs variable to regain
2609 access to the job manager, or make a new name and assign it manually
2609 access to the job manager, or make a new name and assign it manually
2610 to the manager (stored in IPython's namespace). For example, to
2610 to the manager (stored in IPython's namespace). For example, to
2611 assign the job manager to the Jobs name, use:
2611 assign the job manager to the Jobs name, use:
2612
2612
2613 Jobs = __builtins__.jobs"""
2613 Jobs = __builtins__.jobs"""
2614
2614
2615 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2615 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2616
2616
2617 def magic_store(self, parameter_s=''):
2617 def magic_store(self, parameter_s=''):
2618 """Lightweight persistence for python variables.
2618 """Lightweight persistence for python variables.
2619
2619
2620 Example:
2620 Example:
2621
2621
2622 ville@badger[~]|1> A = ['hello',10,'world']\\
2622 ville@badger[~]|1> A = ['hello',10,'world']\\
2623 ville@badger[~]|2> %store A\\
2623 ville@badger[~]|2> %store A\\
2624 ville@badger[~]|3> Exit
2624 ville@badger[~]|3> Exit
2625
2625
2626 (IPython session is closed and started again...)
2626 (IPython session is closed and started again...)
2627
2627
2628 ville@badger:~$ ipython -p pysh\\
2628 ville@badger:~$ ipython -p pysh\\
2629 ville@badger[~]|1> print A
2629 ville@badger[~]|1> print A
2630
2630
2631 ['hello', 10, 'world']
2631 ['hello', 10, 'world']
2632
2632
2633 Usage:
2633 Usage:
2634
2634
2635 %store - Show list of all variables and their current values\\
2635 %store - Show list of all variables and their current values\\
2636 %store <var> - Store the *current* value of the variable to disk\\
2636 %store <var> - Store the *current* value of the variable to disk\\
2637 %store -d <var> - Remove the variable and its value from storage\\
2637 %store -d <var> - Remove the variable and its value from storage\\
2638 %store -r - Remove all variables from storage
2638 %store -r - Remove all variables from storage
2639
2639
2640 It should be noted that if you change the value of a variable, you
2640 It should be noted that if you change the value of a variable, you
2641 need to %store it again if you want to persist the new value.
2641 need to %store it again if you want to persist the new value.
2642
2642
2643 Note also that the variables will need to be pickleable; most basic
2643 Note also that the variables will need to be pickleable; most basic
2644 python types can be safely %stored.
2644 python types can be safely %stored.
2645 """
2645 """
2646
2646
2647 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2647 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2648 # delete
2648 # delete
2649 if opts.has_key('d'):
2649 if opts.has_key('d'):
2650 try:
2650 try:
2651 todel = args[0]
2651 todel = args[0]
2652 except IndexError:
2652 except IndexError:
2653 error('You must provide the variable to forget')
2653 error('You must provide the variable to forget')
2654 else:
2654 else:
2655 try:
2655 try:
2656 del self.shell.persist['S:' + todel]
2656 del self.shell.persist['S:' + todel]
2657 except:
2657 except:
2658 error("Can't delete variable '%s'" % todel)
2658 error("Can't delete variable '%s'" % todel)
2659 # reset
2659 # reset
2660 elif opts.has_key('r'):
2660 elif opts.has_key('r'):
2661 for k in self.shell.persist.keys():
2661 for k in self.shell.persist.keys():
2662 if k.startswith('S:'):
2662 if k.startswith('S:'):
2663 del self.shell.persist[k]
2663 del self.shell.persist[k]
2664
2664
2665 # run without arguments -> list variables & values
2665 # run without arguments -> list variables & values
2666 elif not args:
2666 elif not args:
2667 vars = [v[2:] for v in self.shell.persist.keys()
2667 vars = [v[2:] for v in self.shell.persist.keys()
2668 if v.startswith('S:')]
2668 if v.startswith('S:')]
2669 vars.sort()
2669 vars.sort()
2670 if vars:
2670 if vars:
2671 size = max(map(len,vars))
2671 size = max(map(len,vars))
2672 else:
2672 else:
2673 size = 0
2673 size = 0
2674
2674
2675 print 'Stored variables and their in-memory values:'
2675 print 'Stored variables and their in-memory values:'
2676 fmt = '%-'+str(size)+'s -> %s'
2676 fmt = '%-'+str(size)+'s -> %s'
2677 get = self.shell.user_ns.get
2677 get = self.shell.user_ns.get
2678 for var in vars:
2678 for var in vars:
2679 # print 30 first characters from every var
2679 # print 30 first characters from every var
2680 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2680 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2681
2681
2682 # default action - store the variable
2682 # default action - store the variable
2683 else:
2683 else:
2684 obj = self.shell.user_ns[args[0] ]
2684 obj = self.shell.user_ns[args[0] ]
2685 if isinstance(inspect.getmodule(obj), FakeModule):
2685 if isinstance(inspect.getmodule(obj), FakeModule):
2686 print textwrap.dedent("""\
2686 print textwrap.dedent("""\
2687 Warning:%s is %s
2687 Warning:%s is %s
2688 Proper storage of interactively declared classes (or instances
2688 Proper storage of interactively declared classes (or instances
2689 of those classes) is not possible! Only instances
2689 of those classes) is not possible! Only instances
2690 of classes in real modules on file system can be %%store'd.
2690 of classes in real modules on file system can be %%store'd.
2691 """ % (args[0], obj) )
2691 """ % (args[0], obj) )
2692 return
2692 return
2693 pickled = pickle.dumps(obj)
2693 pickled = pickle.dumps(obj)
2694 self.shell.persist[ 'S:' + args[0] ] = pickled
2694 self.shell.persist[ 'S:' + args[0] ] = pickled
2695 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2695 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2696
2696
2697 def magic_bookmark(self, parameter_s=''):
2697 def magic_bookmark(self, parameter_s=''):
2698 """Manage IPython's bookmark system.
2698 """Manage IPython's bookmark system.
2699
2699
2700 %bookmark <name> - set bookmark to current dir
2700 %bookmark <name> - set bookmark to current dir
2701 %bookmark <name> <dir> - set bookmark to <dir>
2701 %bookmark <name> <dir> - set bookmark to <dir>
2702 %bookmark -l - list all bookmarks
2702 %bookmark -l - list all bookmarks
2703 %bookmark -d <name> - remove bookmark
2703 %bookmark -d <name> - remove bookmark
2704 %bookmark -r - remove all bookmarks
2704 %bookmark -r - remove all bookmarks
2705
2705
2706 You can later on access a bookmarked folder with:
2706 You can later on access a bookmarked folder with:
2707 %cd -b <name>
2707 %cd -b <name>
2708 or simply '%cd <name>' if there is no directory called <name> AND
2708 or simply '%cd <name>' if there is no directory called <name> AND
2709 there is such a bookmark defined.
2709 there is such a bookmark defined.
2710
2710
2711 Your bookmarks persist through IPython sessions, but they are
2711 Your bookmarks persist through IPython sessions, but they are
2712 associated with each profile."""
2712 associated with each profile."""
2713
2713
2714 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2714 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2715 if len(args) > 2:
2715 if len(args) > 2:
2716 error('You can only give at most two arguments')
2716 error('You can only give at most two arguments')
2717 return
2717 return
2718
2718
2719 bkms = self.shell.persist.get('bookmarks',{})
2719 bkms = self.shell.persist.get('bookmarks',{})
2720
2720
2721 if opts.has_key('d'):
2721 if opts.has_key('d'):
2722 try:
2722 try:
2723 todel = args[0]
2723 todel = args[0]
2724 except IndexError:
2724 except IndexError:
2725 error('You must provide a bookmark to delete')
2725 error('You must provide a bookmark to delete')
2726 else:
2726 else:
2727 try:
2727 try:
2728 del bkms[todel]
2728 del bkms[todel]
2729 except:
2729 except:
2730 error("Can't delete bookmark '%s'" % todel)
2730 error("Can't delete bookmark '%s'" % todel)
2731 elif opts.has_key('r'):
2731 elif opts.has_key('r'):
2732 bkms = {}
2732 bkms = {}
2733 elif opts.has_key('l'):
2733 elif opts.has_key('l'):
2734 bks = bkms.keys()
2734 bks = bkms.keys()
2735 bks.sort()
2735 bks.sort()
2736 if bks:
2736 if bks:
2737 size = max(map(len,bks))
2737 size = max(map(len,bks))
2738 else:
2738 else:
2739 size = 0
2739 size = 0
2740 fmt = '%-'+str(size)+'s -> %s'
2740 fmt = '%-'+str(size)+'s -> %s'
2741 print 'Current bookmarks:'
2741 print 'Current bookmarks:'
2742 for bk in bks:
2742 for bk in bks:
2743 print fmt % (bk,bkms[bk])
2743 print fmt % (bk,bkms[bk])
2744 else:
2744 else:
2745 if not args:
2745 if not args:
2746 error("You must specify the bookmark name")
2746 error("You must specify the bookmark name")
2747 elif len(args)==1:
2747 elif len(args)==1:
2748 bkms[args[0]] = os.getcwd()
2748 bkms[args[0]] = os.getcwd()
2749 elif len(args)==2:
2749 elif len(args)==2:
2750 bkms[args[0]] = args[1]
2750 bkms[args[0]] = args[1]
2751 self.shell.persist['bookmarks'] = bkms
2751 self.shell.persist['bookmarks'] = bkms
2752
2752
2753 def magic_pycat(self, parameter_s=''):
2753 def magic_pycat(self, parameter_s=''):
2754 """Show a syntax-highlighted file through a pager.
2754 """Show a syntax-highlighted file through a pager.
2755
2755
2756 This magic is similar to the cat utility, but it will assume the file
2756 This magic is similar to the cat utility, but it will assume the file
2757 to be Python source and will show it with syntax highlighting. """
2757 to be Python source and will show it with syntax highlighting. """
2758
2758
2759 filename = get_py_filename(parameter_s)
2759 filename = get_py_filename(parameter_s)
2760 page(self.shell.pycolorize(file_read(filename)),
2760 page(self.shell.pycolorize(file_read(filename)),
2761 screen_lines=self.shell.rc.screen_length)
2761 screen_lines=self.shell.rc.screen_length)
2762
2762
2763 def magic_paste(self, parameter_s=''):
2763 def magic_cpaste(self, parameter_s=''):
2764 """Allows you to paste & execute a pre-formatted code block from
2764 """Allows you to paste & execute a pre-formatted code block from
2765 clipboard.
2765 clipboard.
2766
2766
2767 You must terminate the block with '--' (two minus-signs) alone on the
2767 You must terminate the block with '--' (two minus-signs) alone on the
2768 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2768 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2769 is the new sentinel for this operation)
2769 is the new sentinel for this operation)
2770
2770
2771 The block is dedented prior to execution to enable execution of
2771 The block is dedented prior to execution to enable execution of
2772 method definitions. The executed block is also assigned to variable
2772 method definitions. The executed block is also assigned to variable
2773 named 'pasted_block' for later editing with '%edit pasted_block'.
2773 named 'pasted_block' for later editing with '%edit pasted_block'.
2774
2774
2775 You can also pass a variable name as an argument, e.g. '%paste foo'.
2775 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2776 This assigns the pasted block to variable 'foo' as string, without
2776 This assigns the pasted block to variable 'foo' as string, without
2777 dedenting or executing it.
2777 dedenting or executing it.
2778
2778
2779 Do not be alarmed by garbled output on Windows (it's a readline bug).
2779 Do not be alarmed by garbled output on Windows (it's a readline bug).
2780 Just press enter and type -- (and press enter again) and the block
2780 Just press enter and type -- (and press enter again) and the block
2781 will be what was just pasted.
2781 will be what was just pasted.
2782
2782
2783 IPython statements (magics, shell escapes) are not supported (yet).
2783 IPython statements (magics, shell escapes) are not supported (yet).
2784 """
2784 """
2785 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2785 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2786 par = args.strip()
2786 par = args.strip()
2787 sentinel = opts.get('s','--')
2787 sentinel = opts.get('s','--')
2788
2788
2789 from IPython import iplib
2789 from IPython import iplib
2790 lines = []
2790 lines = []
2791 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2791 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2792 while 1:
2792 while 1:
2793 l = iplib.raw_input_original(':')
2793 l = iplib.raw_input_original(':')
2794 if l ==sentinel:
2794 if l ==sentinel:
2795 break
2795 break
2796 lines.append(l)
2796 lines.append(l)
2797 block = "\n".join(lines)
2797 block = "\n".join(lines)
2798 #print "block:\n",block
2798 #print "block:\n",block
2799 if not par:
2799 if not par:
2800 b = textwrap.dedent(block)
2800 b = textwrap.dedent(block)
2801 exec b in self.user_ns
2801 exec b in self.user_ns
2802 self.user_ns['pasted_block'] = b
2802 self.user_ns['pasted_block'] = b
2803 else:
2803 else:
2804 self.user_ns[par] = block
2804 self.user_ns[par] = block
2805 print "Block assigned to '%s'" % par
2805 print "Block assigned to '%s'" % par
2806
2806
2807
2807
2808
2808
2809 # end Magic
2809 # end Magic
@@ -1,575 +1,584 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Classes for handling input/output prompts.
3 Classes for handling input/output prompts.
4
4
5 $Id: Prompts.py 1020 2006-01-14 13:22:58Z vivainio $"""
5 $Id: Prompts.py 1076 2006-01-24 17:27:05Z vivainio $"""
6
6
7 #*****************************************************************************
7 #*****************************************************************************
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 from IPython import Release
14 from IPython import Release
15 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 __license__ = Release.license
16 __license__ = Release.license
17 __version__ = Release.version
17 __version__ = Release.version
18
18
19 #****************************************************************************
19 #****************************************************************************
20 # Required modules
20 # Required modules
21 import __builtin__
21 import __builtin__
22 import os
22 import os
23 import socket
23 import socket
24 import sys
24 import sys
25 import time
25 import time
26 from pprint import pprint,pformat
26 from pprint import pprint,pformat
27
27
28 # IPython's own
28 # IPython's own
29 from IPython import ColorANSI
29 from IPython import ColorANSI
30 from IPython.Itpl import ItplNS
30 from IPython.Itpl import ItplNS
31 from IPython.ipstruct import Struct
31 from IPython.ipstruct import Struct
32 from IPython.macro import Macro
32 from IPython.macro import Macro
33 from IPython.genutils import *
33 from IPython.genutils import *
34
34
35 #****************************************************************************
35 #****************************************************************************
36 #Color schemes for Prompts.
36 #Color schemes for Prompts.
37
37
38 PromptColors = ColorANSI.ColorSchemeTable()
38 PromptColors = ColorANSI.ColorSchemeTable()
39 InputColors = ColorANSI.InputTermColors # just a shorthand
39 InputColors = ColorANSI.InputTermColors # just a shorthand
40 Colors = ColorANSI.TermColors # just a shorthand
40 Colors = ColorANSI.TermColors # just a shorthand
41
41
42 PromptColors.add_scheme(ColorANSI.ColorScheme(
42 PromptColors.add_scheme(ColorANSI.ColorScheme(
43 'NoColor',
43 'NoColor',
44 in_prompt = InputColors.NoColor, # Input prompt
44 in_prompt = InputColors.NoColor, # Input prompt
45 in_number = InputColors.NoColor, # Input prompt number
45 in_number = InputColors.NoColor, # Input prompt number
46 in_prompt2 = InputColors.NoColor, # Continuation prompt
46 in_prompt2 = InputColors.NoColor, # Continuation prompt
47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
48
48
49 out_prompt = Colors.NoColor, # Output prompt
49 out_prompt = Colors.NoColor, # Output prompt
50 out_number = Colors.NoColor, # Output prompt number
50 out_number = Colors.NoColor, # Output prompt number
51
51
52 normal = Colors.NoColor # color off (usu. Colors.Normal)
52 normal = Colors.NoColor # color off (usu. Colors.Normal)
53 ))
53 ))
54
54
55 # make some schemes as instances so we can copy them for modification easily:
55 # make some schemes as instances so we can copy them for modification easily:
56 __PColLinux = ColorANSI.ColorScheme(
56 __PColLinux = ColorANSI.ColorScheme(
57 'Linux',
57 'Linux',
58 in_prompt = InputColors.Green,
58 in_prompt = InputColors.Green,
59 in_number = InputColors.LightGreen,
59 in_number = InputColors.LightGreen,
60 in_prompt2 = InputColors.Green,
60 in_prompt2 = InputColors.Green,
61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
62
62
63 out_prompt = Colors.Red,
63 out_prompt = Colors.Red,
64 out_number = Colors.LightRed,
64 out_number = Colors.LightRed,
65
65
66 normal = Colors.Normal
66 normal = Colors.Normal
67 )
67 )
68 # Don't forget to enter it into the table!
68 # Don't forget to enter it into the table!
69 PromptColors.add_scheme(__PColLinux)
69 PromptColors.add_scheme(__PColLinux)
70
70
71 # Slightly modified Linux for light backgrounds
71 # Slightly modified Linux for light backgrounds
72 __PColLightBG = __PColLinux.copy('LightBG')
72 __PColLightBG = __PColLinux.copy('LightBG')
73
73
74 __PColLightBG.colors.update(
74 __PColLightBG.colors.update(
75 in_prompt = InputColors.Blue,
75 in_prompt = InputColors.Blue,
76 in_number = InputColors.LightBlue,
76 in_number = InputColors.LightBlue,
77 in_prompt2 = InputColors.Blue
77 in_prompt2 = InputColors.Blue
78 )
78 )
79 PromptColors.add_scheme(__PColLightBG)
79 PromptColors.add_scheme(__PColLightBG)
80
80
81 del Colors,InputColors
81 del Colors,InputColors
82
82
83 #-----------------------------------------------------------------------------
83 #-----------------------------------------------------------------------------
84 def multiple_replace(dict, text):
84 def multiple_replace(dict, text):
85 """ Replace in 'text' all occurences of any key in the given
85 """ Replace in 'text' all occurences of any key in the given
86 dictionary by its corresponding value. Returns the new string."""
86 dictionary by its corresponding value. Returns the new string."""
87
87
88 # Function by Xavier Defrang, originally found at:
88 # Function by Xavier Defrang, originally found at:
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
90
90
91 # Create a regular expression from the dictionary keys
91 # Create a regular expression from the dictionary keys
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
93 # For each match, look-up corresponding value in dictionary
93 # For each match, look-up corresponding value in dictionary
94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
95
95
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97 # Special characters that can be used in prompt templates, mainly bash-like
97 # Special characters that can be used in prompt templates, mainly bash-like
98
98
99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
100 # never be expanded out into '~'. Basically anything which can never be a
100 # never be expanded out into '~'. Basically anything which can never be a
101 # reasonable directory name will do, we just want the $HOME -> '~' operation
101 # reasonable directory name will do, we just want the $HOME -> '~' operation
102 # to become a no-op. We pre-compute $HOME here so it's not done on every
102 # to become a no-op. We pre-compute $HOME here so it's not done on every
103 # prompt call.
103 # prompt call.
104
104
105 # FIXME:
105 # FIXME:
106
106
107 # - This should be turned into a class which does proper namespace management,
107 # - This should be turned into a class which does proper namespace management,
108 # since the prompt specials need to be evaluated in a certain namespace.
108 # since the prompt specials need to be evaluated in a certain namespace.
109 # Currently it's just globals, which need to be managed manually by code
109 # Currently it's just globals, which need to be managed manually by code
110 # below.
110 # below.
111
111
112 # - I also need to split up the color schemes from the prompt specials
112 # - I also need to split up the color schemes from the prompt specials
113 # somehow. I don't have a clean design for that quite yet.
113 # somehow. I don't have a clean design for that quite yet.
114
114
115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
116
116
117 # We precompute a few more strings here for the prompt_specials, which are
117 # We precompute a few more strings here for the prompt_specials, which are
118 # fixed once ipython starts. This reduces the runtime overhead of computing
118 # fixed once ipython starts. This reduces the runtime overhead of computing
119 # prompt strings.
119 # prompt strings.
120 USER = os.environ.get("USER")
120 USER = os.environ.get("USER")
121 HOSTNAME = socket.gethostname()
121 HOSTNAME = socket.gethostname()
122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
124
124
125 prompt_specials_color = {
125 prompt_specials_color = {
126 # Prompt/history count
126 # Prompt/history count
127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 # Prompt/history count, with the actual digits replaced by dots. Used
129 # Prompt/history count, with the actual digits replaced by dots. Used
130 # mainly in continuation prompts (prompt_in2)
130 # mainly in continuation prompts (prompt_in2)
131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
132 # Current working directory
132 # Current working directory
133 '\\w': '${os.getcwd()}',
133 '\\w': '${os.getcwd()}',
134 # Current time
134 # Current time
135 '\\t' : '${time.strftime("%H:%M:%S")}',
135 '\\t' : '${time.strftime("%H:%M:%S")}',
136 # Basename of current working directory.
136 # Basename of current working directory.
137 # (use os.sep to make this portable across OSes)
137 # (use os.sep to make this portable across OSes)
138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
139 # These X<N> are an extension to the normal bash prompts. They return
139 # These X<N> are an extension to the normal bash prompts. They return
140 # N terms of the path, after replacing $HOME with '~'
140 # N terms of the path, after replacing $HOME with '~'
141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
142 '\\X1': '${self.cwd_filt(1)}',
142 '\\X1': '${self.cwd_filt(1)}',
143 '\\X2': '${self.cwd_filt(2)}',
143 '\\X2': '${self.cwd_filt(2)}',
144 '\\X3': '${self.cwd_filt(3)}',
144 '\\X3': '${self.cwd_filt(3)}',
145 '\\X4': '${self.cwd_filt(4)}',
145 '\\X4': '${self.cwd_filt(4)}',
146 '\\X5': '${self.cwd_filt(5)}',
146 '\\X5': '${self.cwd_filt(5)}',
147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
148 # N+1 in the list. Somewhat like %cN in tcsh.
148 # N+1 in the list. Somewhat like %cN in tcsh.
149 '\\Y0': '${self.cwd_filt2(0)}',
149 '\\Y0': '${self.cwd_filt2(0)}',
150 '\\Y1': '${self.cwd_filt2(1)}',
150 '\\Y1': '${self.cwd_filt2(1)}',
151 '\\Y2': '${self.cwd_filt2(2)}',
151 '\\Y2': '${self.cwd_filt2(2)}',
152 '\\Y3': '${self.cwd_filt2(3)}',
152 '\\Y3': '${self.cwd_filt2(3)}',
153 '\\Y4': '${self.cwd_filt2(4)}',
153 '\\Y4': '${self.cwd_filt2(4)}',
154 '\\Y5': '${self.cwd_filt2(5)}',
154 '\\Y5': '${self.cwd_filt2(5)}',
155 # Hostname up to first .
155 # Hostname up to first .
156 '\\h': HOSTNAME_SHORT,
156 '\\h': HOSTNAME_SHORT,
157 # Full hostname
157 # Full hostname
158 '\\H': HOSTNAME,
158 '\\H': HOSTNAME,
159 # Username of current user
159 # Username of current user
160 '\\u': USER,
160 '\\u': USER,
161 # Escaped '\'
161 # Escaped '\'
162 '\\\\': '\\',
162 '\\\\': '\\',
163 # Newline
163 # Newline
164 '\\n': '\n',
164 '\\n': '\n',
165 # Carriage return
165 # Carriage return
166 '\\r': '\r',
166 '\\r': '\r',
167 # Release version
167 # Release version
168 '\\v': __version__,
168 '\\v': __version__,
169 # Root symbol ($ or #)
169 # Root symbol ($ or #)
170 '\\$': ROOT_SYMBOL,
170 '\\$': ROOT_SYMBOL,
171 }
171 }
172
172
173 # A copy of the prompt_specials dictionary but with all color escapes removed,
173 # A copy of the prompt_specials dictionary but with all color escapes removed,
174 # so we can correctly compute the prompt length for the auto_rewrite method.
174 # so we can correctly compute the prompt length for the auto_rewrite method.
175 prompt_specials_nocolor = prompt_specials_color.copy()
175 prompt_specials_nocolor = prompt_specials_color.copy()
176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
178
178
179 # Add in all the InputTermColors color escapes as valid prompt characters.
179 # Add in all the InputTermColors color escapes as valid prompt characters.
180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
181 # with a color name which may begin with a letter used by any other of the
181 # with a color name which may begin with a letter used by any other of the
182 # allowed specials. This of course means that \\C will never be allowed for
182 # allowed specials. This of course means that \\C will never be allowed for
183 # anything else.
183 # anything else.
184 input_colors = ColorANSI.InputTermColors
184 input_colors = ColorANSI.InputTermColors
185 for _color in dir(input_colors):
185 for _color in dir(input_colors):
186 if _color[0] != '_':
186 if _color[0] != '_':
187 c_name = '\\C_'+_color
187 c_name = '\\C_'+_color
188 prompt_specials_color[c_name] = getattr(input_colors,_color)
188 prompt_specials_color[c_name] = getattr(input_colors,_color)
189 prompt_specials_nocolor[c_name] = ''
189 prompt_specials_nocolor[c_name] = ''
190
190
191 # we default to no color for safety. Note that prompt_specials is a global
191 # we default to no color for safety. Note that prompt_specials is a global
192 # variable used by all prompt objects.
192 # variable used by all prompt objects.
193 prompt_specials = prompt_specials_nocolor
193 prompt_specials = prompt_specials_nocolor
194
194
195 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
196 def str_safe(arg):
196 def str_safe(arg):
197 """Convert to a string, without ever raising an exception.
197 """Convert to a string, without ever raising an exception.
198
198
199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
200 error message."""
200 error message."""
201
201
202 try:
202 try:
203 out = str(arg)
203 out = str(arg)
204 except UnicodeError:
204 except UnicodeError:
205 try:
205 try:
206 out = arg.encode('utf_8','replace')
206 out = arg.encode('utf_8','replace')
207 except Exception,msg:
207 except Exception,msg:
208 # let's keep this little duplication here, so that the most common
208 # let's keep this little duplication here, so that the most common
209 # case doesn't suffer from a double try wrapping.
209 # case doesn't suffer from a double try wrapping.
210 out = '<ERROR: %s>' % msg
210 out = '<ERROR: %s>' % msg
211 except Exception,msg:
211 except Exception,msg:
212 out = '<ERROR: %s>' % msg
212 out = '<ERROR: %s>' % msg
213 return out
213 return out
214
214
215 class BasePrompt:
215 class BasePrompt:
216 """Interactive prompt similar to Mathematica's."""
216 """Interactive prompt similar to Mathematica's."""
217 def __init__(self,cache,sep,prompt,pad_left=False):
217 def __init__(self,cache,sep,prompt,pad_left=False):
218
218
219 # Hack: we access information about the primary prompt through the
219 # Hack: we access information about the primary prompt through the
220 # cache argument. We need this, because we want the secondary prompt
220 # cache argument. We need this, because we want the secondary prompt
221 # to be aligned with the primary one. Color table info is also shared
221 # to be aligned with the primary one. Color table info is also shared
222 # by all prompt classes through the cache. Nice OO spaghetti code!
222 # by all prompt classes through the cache. Nice OO spaghetti code!
223 self.cache = cache
223 self.cache = cache
224 self.sep = sep
224 self.sep = sep
225
225
226 # regexp to count the number of spaces at the end of a prompt
226 # regexp to count the number of spaces at the end of a prompt
227 # expression, useful for prompt auto-rewriting
227 # expression, useful for prompt auto-rewriting
228 self.rspace = re.compile(r'(\s*)$')
228 self.rspace = re.compile(r'(\s*)$')
229 # Flag to left-pad prompt strings to match the length of the primary
229 # Flag to left-pad prompt strings to match the length of the primary
230 # prompt
230 # prompt
231 self.pad_left = pad_left
231 self.pad_left = pad_left
232 # Set template to create each actual prompt (where numbers change)
232 # Set template to create each actual prompt (where numbers change)
233 self.p_template = prompt
233 self.p_template = prompt
234 self.set_p_str()
234 self.set_p_str()
235
235
236 def set_p_str(self):
236 def set_p_str(self):
237 """ Set the interpolating prompt strings.
237 """ Set the interpolating prompt strings.
238
238
239 This must be called every time the color settings change, because the
239 This must be called every time the color settings change, because the
240 prompt_specials global may have changed."""
240 prompt_specials global may have changed."""
241
241
242 import os,time # needed in locals for prompt string handling
242 import os,time # needed in locals for prompt string handling
243 loc = locals()
243 loc = locals()
244 self.p_str = ItplNS('%s%s%s' %
244 self.p_str = ItplNS('%s%s%s' %
245 ('${self.sep}${self.col_p}',
245 ('${self.sep}${self.col_p}',
246 multiple_replace(prompt_specials, self.p_template),
246 multiple_replace(prompt_specials, self.p_template),
247 '${self.col_norm}'),self.cache.user_ns,loc)
247 '${self.col_norm}'),self.cache.user_ns,loc)
248
248
249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
250 self.p_template),
250 self.p_template),
251 self.cache.user_ns,loc)
251 self.cache.user_ns,loc)
252
252
253 def write(self,msg): # dbg
253 def write(self,msg): # dbg
254 sys.stdout.write(msg)
254 sys.stdout.write(msg)
255 return ''
255 return ''
256
256
257 def __str__(self):
257 def __str__(self):
258 """Return a string form of the prompt.
258 """Return a string form of the prompt.
259
259
260 This for is useful for continuation and output prompts, since it is
260 This for is useful for continuation and output prompts, since it is
261 left-padded to match lengths with the primary one (if the
261 left-padded to match lengths with the primary one (if the
262 self.pad_left attribute is set)."""
262 self.pad_left attribute is set)."""
263
263
264 out_str = str_safe(self.p_str)
264 out_str = str_safe(self.p_str)
265 if self.pad_left:
265 if self.pad_left:
266 # We must find the amount of padding required to match lengths,
266 # We must find the amount of padding required to match lengths,
267 # taking the color escapes (which are invisible on-screen) into
267 # taking the color escapes (which are invisible on-screen) into
268 # account.
268 # account.
269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
271 return format % out_str
271 return format % out_str
272 else:
272 else:
273 return out_str
273 return out_str
274
274
275 # these path filters are put in as methods so that we can control the
275 # these path filters are put in as methods so that we can control the
276 # namespace where the prompt strings get evaluated
276 # namespace where the prompt strings get evaluated
277 def cwd_filt(self,depth):
277 def cwd_filt(self,depth):
278 """Return the last depth elements of the current working directory.
278 """Return the last depth elements of the current working directory.
279
279
280 $HOME is always replaced with '~'.
280 $HOME is always replaced with '~'.
281 If depth==0, the full path is returned."""
281 If depth==0, the full path is returned."""
282
282
283 cwd = os.getcwd().replace(HOME,"~")
283 cwd = os.getcwd().replace(HOME,"~")
284 out = os.sep.join(cwd.split(os.sep)[-depth:])
284 out = os.sep.join(cwd.split(os.sep)[-depth:])
285 if out:
285 if out:
286 return out
286 return out
287 else:
287 else:
288 return os.sep
288 return os.sep
289
289
290 def cwd_filt2(self,depth):
290 def cwd_filt2(self,depth):
291 """Return the last depth elements of the current working directory.
291 """Return the last depth elements of the current working directory.
292
292
293 $HOME is always replaced with '~'.
293 $HOME is always replaced with '~'.
294 If depth==0, the full path is returned."""
294 If depth==0, the full path is returned."""
295
295
296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
297 if '~' in cwd and len(cwd) == depth+1:
297 if '~' in cwd and len(cwd) == depth+1:
298 depth += 1
298 depth += 1
299 out = os.sep.join(cwd[-depth:])
299 out = os.sep.join(cwd[-depth:])
300 if out:
300 if out:
301 return out
301 return out
302 else:
302 else:
303 return os.sep
303 return os.sep
304
304
305 class Prompt1(BasePrompt):
305 class Prompt1(BasePrompt):
306 """Input interactive prompt similar to Mathematica's."""
306 """Input interactive prompt similar to Mathematica's."""
307
307
308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
310
310
311 def set_colors(self):
311 def set_colors(self):
312 self.set_p_str()
312 self.set_p_str()
313 Colors = self.cache.color_table.active_colors # shorthand
313 Colors = self.cache.color_table.active_colors # shorthand
314 self.col_p = Colors.in_prompt
314 self.col_p = Colors.in_prompt
315 self.col_num = Colors.in_number
315 self.col_num = Colors.in_number
316 self.col_norm = Colors.in_normal
316 self.col_norm = Colors.in_normal
317 # We need a non-input version of these escapes for the '--->'
317 # We need a non-input version of these escapes for the '--->'
318 # auto-call prompts used in the auto_rewrite() method.
318 # auto-call prompts used in the auto_rewrite() method.
319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
320 self.col_norm_ni = Colors.normal
320 self.col_norm_ni = Colors.normal
321
321
322 def __str__(self):
322 def __str__(self):
323 self.cache.prompt_count += 1
323 self.cache.prompt_count += 1
324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
325 return str_safe(self.p_str)
325 return str_safe(self.p_str)
326
326
327 def auto_rewrite(self):
327 def auto_rewrite(self):
328 """Print a string of the form '--->' which lines up with the previous
328 """Print a string of the form '--->' which lines up with the previous
329 input string. Useful for systems which re-write the user input when
329 input string. Useful for systems which re-write the user input when
330 handling automatically special syntaxes."""
330 handling automatically special syntaxes."""
331
331
332 curr = str(self.cache.last_prompt)
332 curr = str(self.cache.last_prompt)
333 nrspaces = len(self.rspace.search(curr).group())
333 nrspaces = len(self.rspace.search(curr).group())
334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
335 ' '*nrspaces,self.col_norm_ni)
335 ' '*nrspaces,self.col_norm_ni)
336
336
337 class PromptOut(BasePrompt):
337 class PromptOut(BasePrompt):
338 """Output interactive prompt similar to Mathematica's."""
338 """Output interactive prompt similar to Mathematica's."""
339
339
340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
342 if not self.p_template:
342 if not self.p_template:
343 self.__str__ = lambda: ''
343 self.__str__ = lambda: ''
344
344
345 def set_colors(self):
345 def set_colors(self):
346 self.set_p_str()
346 self.set_p_str()
347 Colors = self.cache.color_table.active_colors # shorthand
347 Colors = self.cache.color_table.active_colors # shorthand
348 self.col_p = Colors.out_prompt
348 self.col_p = Colors.out_prompt
349 self.col_num = Colors.out_number
349 self.col_num = Colors.out_number
350 self.col_norm = Colors.normal
350 self.col_norm = Colors.normal
351
351
352 class Prompt2(BasePrompt):
352 class Prompt2(BasePrompt):
353 """Interactive continuation prompt."""
353 """Interactive continuation prompt."""
354
354
355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
356 self.cache = cache
356 self.cache = cache
357 self.p_template = prompt
357 self.p_template = prompt
358 self.pad_left = pad_left
358 self.pad_left = pad_left
359 self.set_p_str()
359 self.set_p_str()
360
360
361 def set_p_str(self):
361 def set_p_str(self):
362 import os,time # needed in locals for prompt string handling
362 import os,time # needed in locals for prompt string handling
363 loc = locals()
363 loc = locals()
364 self.p_str = ItplNS('%s%s%s' %
364 self.p_str = ItplNS('%s%s%s' %
365 ('${self.col_p2}',
365 ('${self.col_p2}',
366 multiple_replace(prompt_specials, self.p_template),
366 multiple_replace(prompt_specials, self.p_template),
367 '$self.col_norm'),
367 '$self.col_norm'),
368 self.cache.user_ns,loc)
368 self.cache.user_ns,loc)
369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
370 self.p_template),
370 self.p_template),
371 self.cache.user_ns,loc)
371 self.cache.user_ns,loc)
372
372
373 def set_colors(self):
373 def set_colors(self):
374 self.set_p_str()
374 self.set_p_str()
375 Colors = self.cache.color_table.active_colors
375 Colors = self.cache.color_table.active_colors
376 self.col_p2 = Colors.in_prompt2
376 self.col_p2 = Colors.in_prompt2
377 self.col_norm = Colors.in_normal
377 self.col_norm = Colors.in_normal
378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
379 # updated their prompt_in2 definitions. Remove eventually.
379 # updated their prompt_in2 definitions. Remove eventually.
380 self.col_p = Colors.out_prompt
380 self.col_p = Colors.out_prompt
381 self.col_num = Colors.out_number
381 self.col_num = Colors.out_number
382
382
383 #-----------------------------------------------------------------------------
383 #-----------------------------------------------------------------------------
384 class CachedOutput:
384 class CachedOutput:
385 """Class for printing output from calculations while keeping a cache of
385 """Class for printing output from calculations while keeping a cache of
386 reults. It dynamically creates global variables prefixed with _ which
386 reults. It dynamically creates global variables prefixed with _ which
387 contain these results.
387 contain these results.
388
388
389 Meant to be used as a sys.displayhook replacement, providing numbered
389 Meant to be used as a sys.displayhook replacement, providing numbered
390 prompts and cache services.
390 prompts and cache services.
391
391
392 Initialize with initial and final values for cache counter (this defines
392 Initialize with initial and final values for cache counter (this defines
393 the maximum size of the cache."""
393 the maximum size of the cache."""
394
394
395 def __init__(self,shell,cache_size,Pprint,
395 def __init__(self,shell,cache_size,Pprint,
396 colors='NoColor',input_sep='\n',
396 colors='NoColor',input_sep='\n',
397 output_sep='\n',output_sep2='',
397 output_sep='\n',output_sep2='',
398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
399
399
400 cache_size_min = 20
400 cache_size_min = 20
401 if cache_size <= 0:
401 if cache_size <= 0:
402 self.do_full_cache = 0
402 self.do_full_cache = 0
403 cache_size = 0
403 cache_size = 0
404 elif cache_size < cache_size_min:
404 elif cache_size < cache_size_min:
405 self.do_full_cache = 0
405 self.do_full_cache = 0
406 cache_size = 0
406 cache_size = 0
407 warn('caching was disabled (min value for cache size is %s).' %
407 warn('caching was disabled (min value for cache size is %s).' %
408 cache_size_min,level=3)
408 cache_size_min,level=3)
409 else:
409 else:
410 self.do_full_cache = 1
410 self.do_full_cache = 1
411
411
412 self.cache_size = cache_size
412 self.cache_size = cache_size
413 self.input_sep = input_sep
413 self.input_sep = input_sep
414
414
415 # we need a reference to the user-level namespace
415 # we need a reference to the user-level namespace
416 self.shell = shell
416 self.shell = shell
417 self.user_ns = shell.user_ns
417 self.user_ns = shell.user_ns
418 # and to the user's input
418 # and to the user's input
419 self.input_hist = shell.input_hist
419 self.input_hist = shell.input_hist
420 # and to the user's logger, for logging output
420 # and to the user's logger, for logging output
421 self.logger = shell.logger
421 self.logger = shell.logger
422
422
423 # Set input prompt strings and colors
423 # Set input prompt strings and colors
424 if cache_size == 0:
424 if cache_size == 0:
425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
430
430
431 self.color_table = PromptColors
431 self.color_table = PromptColors
432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
433 pad_left=pad_left)
433 pad_left=pad_left)
434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
436 pad_left=pad_left)
436 pad_left=pad_left)
437 self.set_colors(colors)
437 self.set_colors(colors)
438
438
439 # other more normal stuff
439 # other more normal stuff
440 # b/c each call to the In[] prompt raises it by 1, even the first.
440 # b/c each call to the In[] prompt raises it by 1, even the first.
441 self.prompt_count = 0
441 self.prompt_count = 0
442 self.cache_count = 1
442 self.cache_count = 1
443 # Store the last prompt string each time, we need it for aligning
443 # Store the last prompt string each time, we need it for aligning
444 # continuation and auto-rewrite prompts
444 # continuation and auto-rewrite prompts
445 self.last_prompt = ''
445 self.last_prompt = ''
446 self.entries = [None] # output counter starts at 1 for the user
446 self.entries = [None] # output counter starts at 1 for the user
447 self.Pprint = Pprint
447 self.Pprint = Pprint
448 self.output_sep = output_sep
448 self.output_sep = output_sep
449 self.output_sep2 = output_sep2
449 self.output_sep2 = output_sep2
450 self._,self.__,self.___ = '','',''
450 self._,self.__,self.___ = '','',''
451 self.pprint_types = map(type,[(),[],{}])
451 self.pprint_types = map(type,[(),[],{}])
452
452
453 # these are deliberately global:
453 # these are deliberately global:
454 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
454 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
455 self.user_ns.update(to_user_ns)
455 self.user_ns.update(to_user_ns)
456
456
457 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
457 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
458 if p_str is None:
458 if p_str is None:
459 if self.do_full_cache:
459 if self.do_full_cache:
460 return cache_def
460 return cache_def
461 else:
461 else:
462 return no_cache_def
462 return no_cache_def
463 else:
463 else:
464 return p_str
464 return p_str
465
465
466 def set_colors(self,colors):
466 def set_colors(self,colors):
467 """Set the active color scheme and configure colors for the three
467 """Set the active color scheme and configure colors for the three
468 prompt subsystems."""
468 prompt subsystems."""
469
469
470 # FIXME: the prompt_specials global should be gobbled inside this
470 # FIXME: the prompt_specials global should be gobbled inside this
471 # class instead. Do it when cleaning up the whole 3-prompt system.
471 # class instead. Do it when cleaning up the whole 3-prompt system.
472 global prompt_specials
472 global prompt_specials
473 if colors.lower()=='nocolor':
473 if colors.lower()=='nocolor':
474 prompt_specials = prompt_specials_nocolor
474 prompt_specials = prompt_specials_nocolor
475 else:
475 else:
476 prompt_specials = prompt_specials_color
476 prompt_specials = prompt_specials_color
477
477
478 self.color_table.set_active_scheme(colors)
478 self.color_table.set_active_scheme(colors)
479 self.prompt1.set_colors()
479 self.prompt1.set_colors()
480 self.prompt2.set_colors()
480 self.prompt2.set_colors()
481 self.prompt_out.set_colors()
481 self.prompt_out.set_colors()
482
482
483 def __call__(self,arg=None):
483 def __call__(self,arg=None):
484 """Printing with history cache management.
484 """Printing with history cache management.
485
485
486 This is invoked everytime the interpreter needs to print, and is
486 This is invoked everytime the interpreter needs to print, and is
487 activated by setting the variable sys.displayhook to it."""
487 activated by setting the variable sys.displayhook to it."""
488
488
489 # If something injected a '_' variable in __builtin__, delete
489 # If something injected a '_' variable in __builtin__, delete
490 # ipython's automatic one so we don't clobber that. gettext() in
490 # ipython's automatic one so we don't clobber that. gettext() in
491 # particular uses _, so we need to stay away from it.
491 # particular uses _, so we need to stay away from it.
492 if '_' in __builtin__.__dict__:
492 if '_' in __builtin__.__dict__:
493 try:
493 try:
494 del self.user_ns['_']
494 del self.user_ns['_']
495 except KeyError:
495 except KeyError:
496 pass
496 pass
497 if arg is not None:
497 if arg is not None:
498 cout_write = Term.cout.write # fast lookup
498 cout_write = Term.cout.write # fast lookup
499 # first handle the cache and counters
499 # first handle the cache and counters
500 # but avoid recursive reference when displaying _oh/Out
500
501 if arg is not self.user_ns['_oh']:
502 self.update(arg)
503 # do not print output if input ends in ';'
501 # do not print output if input ends in ';'
504 if self.input_hist[self.prompt_count].endswith(';\n'):
502 if self.input_hist[self.prompt_count].endswith(';\n'):
505 return
503 return
506 # don't use print, puts an extra space
504 # don't use print, puts an extra space
507 cout_write(self.output_sep)
505 cout_write(self.output_sep)
508 if self.do_full_cache:
506 if self.do_full_cache:
509 cout_write(str(self.prompt_out))
507 cout_write(str(self.prompt_out))
510
508
511 if isinstance(arg,Macro):
509 if isinstance(arg,Macro):
512 print 'Executing Macro...'
510 print 'Executing Macro...'
513 # in case the macro takes a long time to execute
511 # in case the macro takes a long time to execute
514 Term.cout.flush()
512 Term.cout.flush()
515 self.shell.runlines(arg.value)
513 self.shell.runlines(arg.value)
516 return None
514 return None
517
515
518 # and now call a possibly user-defined print mechanism
516 # and now call a possibly user-defined print mechanism
519 self.display(arg)
517 manipulated_val = self.display(arg)
518
519 # user display hooks can change the variable to be stored in
520 # output history
521
522 if manipulated_val is not None:
523 arg = manipulated_val
524
525 # avoid recursive reference when displaying _oh/Out
526 if arg is not self.user_ns['_oh']:
527 self.update(arg)
528
520 if self.logger.log_output:
529 if self.logger.log_output:
521 self.logger.log_write(repr(arg),'output')
530 self.logger.log_write(repr(arg),'output')
522 cout_write(self.output_sep2)
531 cout_write(self.output_sep2)
523 Term.cout.flush()
532 Term.cout.flush()
524
533
525 def _display(self,arg):
534 def _display(self,arg):
526 """Default printer method, uses pprint.
535 """Default printer method, uses pprint.
527
536
528 Do ip.set_hook("result_display", my_displayhook) for custom result
537 Do ip.set_hook("result_display", my_displayhook) for custom result
529 display, e.g. when your own objects need special formatting.
538 display, e.g. when your own objects need special formatting.
530 """
539 """
531
540
532 self.shell.hooks.result_display(arg)
541 return self.shell.hooks.result_display(arg)
533
542
534 # Assign the default display method:
543 # Assign the default display method:
535 display = _display
544 display = _display
536
545
537 def update(self,arg):
546 def update(self,arg):
538 #print '***cache_count', self.cache_count # dbg
547 #print '***cache_count', self.cache_count # dbg
539 if self.cache_count >= self.cache_size and self.do_full_cache:
548 if self.cache_count >= self.cache_size and self.do_full_cache:
540 self.flush()
549 self.flush()
541 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
550 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
542 # we cause buggy behavior for things like gettext).
551 # we cause buggy behavior for things like gettext).
543 if '_' not in __builtin__.__dict__:
552 if '_' not in __builtin__.__dict__:
544 self.___ = self.__
553 self.___ = self.__
545 self.__ = self._
554 self.__ = self._
546 self._ = arg
555 self._ = arg
547 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
556 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
548
557
549 # hackish access to top-level namespace to create _1,_2... dynamically
558 # hackish access to top-level namespace to create _1,_2... dynamically
550 to_main = {}
559 to_main = {}
551 if self.do_full_cache:
560 if self.do_full_cache:
552 self.cache_count += 1
561 self.cache_count += 1
553 self.entries.append(arg)
562 self.entries.append(arg)
554 new_result = '_'+`self.prompt_count`
563 new_result = '_'+`self.prompt_count`
555 to_main[new_result] = self.entries[-1]
564 to_main[new_result] = self.entries[-1]
556 self.user_ns.update(to_main)
565 self.user_ns.update(to_main)
557 self.user_ns['_oh'][self.prompt_count] = arg
566 self.user_ns['_oh'][self.prompt_count] = arg
558
567
559 def flush(self):
568 def flush(self):
560 if not self.do_full_cache:
569 if not self.do_full_cache:
561 raise ValueError,"You shouldn't have reached the cache flush "\
570 raise ValueError,"You shouldn't have reached the cache flush "\
562 "if full caching is not enabled!"
571 "if full caching is not enabled!"
563 warn('Output cache limit (currently '+\
572 warn('Output cache limit (currently '+\
564 `self.cache_count`+' entries) hit.\n'
573 `self.cache_count`+' entries) hit.\n'
565 'Flushing cache and resetting history counter...\n'
574 'Flushing cache and resetting history counter...\n'
566 'The only history variables available will be _,__,___ and _1\n'
575 'The only history variables available will be _,__,___ and _1\n'
567 'with the current result.')
576 'with the current result.')
568 # delete auto-generated vars from global namespace
577 # delete auto-generated vars from global namespace
569 for n in range(1,self.prompt_count + 1):
578 for n in range(1,self.prompt_count + 1):
570 key = '_'+`n`
579 key = '_'+`n`
571 try:
580 try:
572 del self.user_ns[key]
581 del self.user_ns[key]
573 except: pass
582 except: pass
574 self.prompt_count = 1
583 self.prompt_count = 1
575 self.cache_count = 1
584 self.cache_count = 1
@@ -1,149 +1,150 b''
1 """hooks for IPython.
1 """hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 hooks are simple functions, but they should be declared with 'self' as their
9 hooks are simple functions, but they should be declared with 'self' as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you need to put the
14 If you wish to define a new hook and activate it, you need to put the
15 necessary code into a python file which can be either imported or execfile()'d
15 necessary code into a python file which can be either imported or execfile()'d
16 from within your ipythonrc configuration.
16 from within your ipythonrc configuration.
17
17
18 For example, suppose that you have a module called 'myiphooks' in your
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 def calljed(self,filename, linenum):
22 def calljed(self,filename, linenum):
23 "My editor hook calls the jed editor directly."
23 "My editor hook calls the jed editor directly."
24 print "Calling my own editor, jed ..."
24 print "Calling my own editor, jed ..."
25 os.system('jed +%d %s' % (linenum,filename))
25 os.system('jed +%d %s' % (linenum,filename))
26
26
27 You can then execute the following line of code to make it the new IPython
27 You can then execute the following line of code to make it the new IPython
28 editor hook, after having imported 'myiphooks':
28 editor hook, after having imported 'myiphooks':
29
29
30 ip_set_hook('editor',myiphooks.calljed)
30 ip_set_hook('editor',myiphooks.calljed)
31
31
32 The ip_set_hook function is put by IPython into the builtin namespace, so it
32 The ip_set_hook function is put by IPython into the builtin namespace, so it
33 is always available from all running code.
33 is always available from all running code.
34
34
35 $Id: hooks.py 1020 2006-01-14 13:22:58Z vivainio $"""
35 $Id: hooks.py 1076 2006-01-24 17:27:05Z vivainio $"""
36
36
37 #*****************************************************************************
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
39 #
40 # Distributed under the terms of the BSD License. The full license is in
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 from IPython import Release
44 from IPython import Release
45 from IPython import ipapi
45 __author__ = '%s <%s>' % Release.authors['Fernando']
46 __author__ = '%s <%s>' % Release.authors['Fernando']
46 __license__ = Release.license
47 __license__ = Release.license
47 __version__ = Release.version
48 __version__ = Release.version
48
49
49 import os,bisect
50 import os,bisect
50 from genutils import Term
51 from genutils import Term
51 from pprint import pformat
52 from pprint import pformat
52
53
53 # List here all the default hooks. For now it's just the editor functions
54 # List here all the default hooks. For now it's just the editor functions
54 # but over time we'll move here all the public API for user-accessible things.
55 # but over time we'll move here all the public API for user-accessible things.
55 __all__ = ['editor', 'fix_error_editor', 'result_display']
56 __all__ = ['editor', 'fix_error_editor', 'result_display']
56
57
57 def editor(self,filename, linenum=None):
58 def editor(self,filename, linenum=None):
58 """Open the default editor at the given filename and linenumber.
59 """Open the default editor at the given filename and linenumber.
59
60
60 This is IPython's default editor hook, you can use it as an example to
61 This is IPython's default editor hook, you can use it as an example to
61 write your own modified one. To set your own editor function as the
62 write your own modified one. To set your own editor function as the
62 new editor hook, call ip_set_hook('editor',yourfunc)."""
63 new editor hook, call ip_set_hook('editor',yourfunc)."""
63
64
64 # IPython configures a default editor at startup by reading $EDITOR from
65 # IPython configures a default editor at startup by reading $EDITOR from
65 # the environment, and falling back on vi (unix) or notepad (win32).
66 # the environment, and falling back on vi (unix) or notepad (win32).
66 editor = self.rc.editor
67 editor = self.rc.editor
67
68
68 # marker for at which line to open the file (for existing objects)
69 # marker for at which line to open the file (for existing objects)
69 if linenum is None or editor=='notepad':
70 if linenum is None or editor=='notepad':
70 linemark = ''
71 linemark = ''
71 else:
72 else:
72 linemark = '+%d' % linenum
73 linemark = '+%d' % linenum
73 # Call the actual editor
74 # Call the actual editor
74 os.system('%s %s %s' % (editor,linemark,filename))
75 os.system('%s %s %s' % (editor,linemark,filename))
75
76
76 import tempfile
77 import tempfile
77 def fix_error_editor(self,filename,linenum,column,msg):
78 def fix_error_editor(self,filename,linenum,column,msg):
78 """Open the editor at the given filename, linenumber, column and
79 """Open the editor at the given filename, linenumber, column and
79 show an error message. This is used for correcting syntax errors.
80 show an error message. This is used for correcting syntax errors.
80 The current implementation only has special support for the VIM editor,
81 The current implementation only has special support for the VIM editor,
81 and falls back on the 'editor' hook if VIM is not used.
82 and falls back on the 'editor' hook if VIM is not used.
82
83
83 Call ip_set_hook('fix_error_editor',youfunc) to use your own function,
84 Call ip_set_hook('fix_error_editor',youfunc) to use your own function,
84 """
85 """
85 def vim_quickfix_file():
86 def vim_quickfix_file():
86 t = tempfile.NamedTemporaryFile()
87 t = tempfile.NamedTemporaryFile()
87 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
88 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
88 t.flush()
89 t.flush()
89 return t
90 return t
90 if os.path.basename(self.rc.editor) != 'vim':
91 if os.path.basename(self.rc.editor) != 'vim':
91 self.hooks.editor(filename,linenum)
92 self.hooks.editor(filename,linenum)
92 return
93 return
93 t = vim_quickfix_file()
94 t = vim_quickfix_file()
94 try:
95 try:
95 os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name)
96 os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name)
96 finally:
97 finally:
97 t.close()
98 t.close()
98
99
99 class TryNext(Exception):
100 pass
101
100
102 class CommandChainDispatcher:
101 class CommandChainDispatcher:
103 """ Dispatch calls to a chain of commands until some func can handle it
102 """ Dispatch calls to a chain of commands until some func can handle it
104
103
105 Usage: instantiate, execute "add" to add commands (with optional
104 Usage: instantiate, execute "add" to add commands (with optional
106 priority), execute normally via f() calling mechanism.
105 priority), execute normally via f() calling mechanism.
107
106
108 """
107 """
109 def __init__(self,commands=None):
108 def __init__(self,commands=None):
110 if commands is None:
109 if commands is None:
111 self.chain = []
110 self.chain = []
112 else:
111 else:
113 self.chain = commands
112 self.chain = commands
114
113
115
114
116 def __call__(self,*args, **kw):
115 def __call__(self,*args, **kw):
117 """ Command chain is called just like normal func.
116 """ Command chain is called just like normal func.
118
117
119 This will call all funcs in chain with the same args as were given to this
118 This will call all funcs in chain with the same args as were given to this
120 function, and return the result of first func that didn't raise
119 function, and return the result of first func that didn't raise
121 TryNext """
120 TryNext """
122
121
123 for prio,cmd in self.chain:
122 for prio,cmd in self.chain:
124 #print "prio",prio,"cmd",cmd #dbg
123 #print "prio",prio,"cmd",cmd #dbg
125 try:
124 try:
126 ret = cmd(*args, **kw)
125 ret = cmd(*args, **kw)
127 return ret
126 return ret
128 except TryNext:
127 except ipapi.TryNext:
129 pass
128 pass
130
129
131 def __str__(self):
130 def __str__(self):
132 return str(self.chain)
131 return str(self.chain)
133
132
134 def add(self, func, priority=0):
133 def add(self, func, priority=0):
135 """ Add a func to the cmd chain with given priority """
134 """ Add a func to the cmd chain with given priority """
136 bisect.insort(self.chain,(priority,func))
135 bisect.insort(self.chain,(priority,func))
137
136
138 def result_display(self,arg):
137 def result_display(self,arg):
139 if self.rc.pprint:
138 if self.rc.pprint:
140 out = pformat(arg)
139 out = pformat(arg)
141 if '\n' in out:
140 if '\n' in out:
142 # So that multi-line strings line up with the left column of
141 # So that multi-line strings line up with the left column of
143 # the screen, instead of having the output prompt mess up
142 # the screen, instead of having the output prompt mess up
144 # their first line.
143 # their first line.
145 Term.cout.write('\n')
144 Term.cout.write('\n')
146 print >>Term.cout, out
145 print >>Term.cout, out
147 else:
146 else:
148 print >>Term.cout, arg
147 print >>Term.cout, arg
148 # the default display hook doesn't manipulate the value to put in history
149 return None
149 No newline at end of file
150
@@ -1,157 +1,174 b''
1 ''' IPython customization API
1 ''' IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
27 -----------------------------------------------
28 import IPython.ipapi as ip
28 import IPython.ipapi as ip
29
29
30 def ankka_f(self, arg):
30 def ankka_f(self, arg):
31 print "Ankka",self,"says uppercase:",arg.upper()
31 print "Ankka",self,"says uppercase:",arg.upper()
32
32
33 ip.expose_magic("ankka",ankka_f)
33 ip.expose_magic("ankka",ankka_f)
34
34
35 ip.magic('alias sayhi echo "Testing, hi ok"')
35 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias helloworld echo "Hello world"')
36 ip.magic('alias helloworld echo "Hello world"')
37 ip.system('pwd')
37 ip.system('pwd')
38
38
39 ip.ex('import re')
39 ip.ex('import re')
40 ip.ex("""
40 ip.ex("""
41 def funcci(a,b):
41 def funcci(a,b):
42 print a+b
42 print a+b
43 print funcci(3,4)
43 print funcci(3,4)
44 """)
44 """)
45 ip.ex("funcci(348,9)")
45 ip.ex("funcci(348,9)")
46
46
47 def jed_editor(self,filename, linenum=None):
47 def jed_editor(self,filename, linenum=None):
48 print "Calling my own editor, jed ... via hook!"
48 print "Calling my own editor, jed ... via hook!"
49 import os
49 import os
50 if linenum is None: linenum = 0
50 if linenum is None: linenum = 0
51 os.system('jed +%d %s' % (linenum, filename))
51 os.system('jed +%d %s' % (linenum, filename))
52 print "exiting jed"
52 print "exiting jed"
53
53
54 ip.set_hook('editor',jed_editor)
54 ip.set_hook('editor',jed_editor)
55
55
56 o = ip.options()
56 o = ip.options()
57 o.autocall = 2 # FULL autocall mode
57 o.autocall = 2 # FULL autocall mode
58
58
59 print "done!"
59 print "done!"
60
60
61 '''
61 '''
62
62
63
64 class TryNext(Exception):
65 """ Try next hook exception.
66
67 Raise this in your hook function to indicate that the next
68 hook handler should be used to handle the operation.
69 """
70
71
72
73 __IP = None
74
63 def _init_with_shell(ip):
75 def _init_with_shell(ip):
64 global magic
76 global magic
65 magic = ip.ipmagic
77 magic = ip.ipmagic
66 global system
78 global system
67 system = ip.ipsystem
79 system = ip.ipsystem
68 global set_hook
80 global set_hook
69 set_hook = ip.set_hook
81 set_hook = ip.set_hook
70
82
71 global __IP
83 global __IP
72 __IP = ip
84 __IP = ip
73
85
74 def options():
86 def options():
75 """ All configurable variables """
87 """ All configurable variables """
76 return __IP.rc
88 return __IP.rc
77
89
78 def user_ns():
90 def user_ns():
79 return __IP.user_ns
91 return __IP.user_ns
80
92
81 def expose_magic(magicname, func):
93 def expose_magic(magicname, func):
82 ''' Expose own function as magic function for ipython
94 ''' Expose own function as magic function for ipython
83
95
84 def foo_impl(self,parameter_s=''):
96 def foo_impl(self,parameter_s=''):
85 """My very own magic!. (Use docstrings, IPython reads them)."""
97 """My very own magic!. (Use docstrings, IPython reads them)."""
86 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
98 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
87 print 'The self object is:',self
99 print 'The self object is:',self
88
100
89 ipapi.expose_magic("foo",foo_impl)
101 ipapi.expose_magic("foo",foo_impl)
90 '''
102 '''
91
103
92 from IPython import Magic
104 from IPython import Magic
93 import new
105 import new
94 im = new.instancemethod(func,__IP, __IP.__class__)
106 im = new.instancemethod(func,__IP, __IP.__class__)
95 setattr(__IP, "magic_" + magicname, im)
107 setattr(__IP, "magic_" + magicname, im)
96
108
97 class asmagic:
109 class asmagic:
98 """ Decorator for exposing magics in a friendly 2.4 decorator form
110 """ Decorator for exposing magics in a friendly 2.4 decorator form
99
111
100 @ip.asmagic("foo")
112 @ip.asmagic("foo")
101 def f(self,arg):
113 def f(self,arg):
102 pring "arg given:",arg
114 pring "arg given:",arg
103
115
104 After this, %foo is a magic function.
116 After this, %foo is a magic function.
105 """
117 """
106
118
107 def __init__(self,magicname):
119 def __init__(self,magicname):
108 self.name = magicname
120 self.name = magicname
109
121
110 def __call__(self,f):
122 def __call__(self,f):
111 expose_magic(self.name, f)
123 expose_magic(self.name, f)
112 return f
124 return f
113
125
114 class ashook:
126 class ashook:
115 """ Decorator for exposing magics in a friendly 2.4 decorator form
127 """ Decorator for exposing magics in a friendly 2.4 decorator form
116
128
117 @ip.ashook("editor")
129 @ip.ashook("editor")
118 def jed_editor(self,filename, linenum=None):
130 def jed_editor(self,filename, linenum=None):
119 import os
131 import os
120 if linenum is None: linenum = 0
132 if linenum is None: linenum = 0
121 os.system('jed +%d %s' % (linenum, filename))
133 os.system('jed +%d %s' % (linenum, filename))
122
134
123 """
135 """
124
136
125 def __init__(self,name,priority=50):
137 def __init__(self,name,priority=50):
126 self.name = name
138 self.name = name
127 self.prio = priority
139 self.prio = priority
128
140
129 def __call__(self,f):
141 def __call__(self,f):
130 set_hook(self.name, f, self.prio)
142 set_hook(self.name, f, self.prio)
131 return f
143 return f
132
144
133
145
134 def ex(cmd):
146 def ex(cmd):
135 """ Execute a normal python statement in user namespace """
147 """ Execute a normal python statement in user namespace """
136 exec cmd in user_ns()
148 exec cmd in user_ns()
137
149
138 def ev(expr):
150 def ev(expr):
139 """ Evaluate python expression expr in user namespace
151 """ Evaluate python expression expr in user namespace
140
152
141 Returns the result """
153 Returns the result """
142 return eval(expr,user_ns())
154 return eval(expr,user_ns())
143
155
144 def launch_new_instance():
156 def launch_new_instance():
145 """ Creata and start a new ipython instance.
157 """ Creata and start a new ipython instance.
146
158
147 This can be called even without having an already initialized
159 This can be called even without having an already initialized
148 ipython session running.
160 ipython session running.
149
161
150 """
162 """
151 import IPython
163 import IPython
152
164
153 IPython.Shell.start().mainloop()
165 IPython.Shell.start().mainloop()
154
166
167 def is_ipython_session():
168 """ Return a true value if running inside IPython.
155
169
170 """
156
171
157 No newline at end of file
172 # Yes, this is the shell object or None - however, it's an implementation
173 # detail and should not be relied on, only truth value matters.
174 return __IP
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