##// END OF EJS Templates
- Close %timeit bug reported by Stefan.
fptest -
Show More

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

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