##// END OF EJS Templates
new generic inspect_object
vivainio -
Show More

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

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