##// END OF EJS Templates
first part of rocky bernstein's pydb patch - Magic.py and ipython.el"
vivainio -
Show More

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

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