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