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