##// END OF EJS Templates
GetoptErrors when invoking magics etc. with wrong args ...
vivainio -
Show More

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

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