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