##// END OF EJS Templates
Implement %doctest_mode magic in zmqshell with payload....
Fernando Perez -
Show More
@@ -1,3482 +1,3486 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
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 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__
18 import __builtin__
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import os
22 import os
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import time
26 import time
27 import textwrap
27 import textwrap
28 import types
28 import types
29 from cStringIO import StringIO
29 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pformat
31 from pprint import pformat
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # print_function was added to __future__ in Python2.6, remove this when we drop
44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 # 2.5 compatibility
45 # 2.5 compatibility
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48
48
49 import IPython
49 import IPython
50 from IPython.core import debugger, oinspect
50 from IPython.core import debugger, oinspect
51 from IPython.core.error import TryNext
51 from IPython.core.error import TryNext
52 from IPython.core.error import UsageError
52 from IPython.core.error import UsageError
53 from IPython.core.fakemodule import FakeModule
53 from IPython.core.fakemodule import FakeModule
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core import page
55 from IPython.core import page
56 from IPython.core.prefilter import ESC_MAGIC
56 from IPython.core.prefilter import ESC_MAGIC
57 from IPython.lib.pylabtools import mpl_runner
57 from IPython.lib.pylabtools import mpl_runner
58 from IPython.external.Itpl import itpl, printpl
58 from IPython.external.Itpl import itpl, printpl
59 from IPython.testing import decorators as testdec
59 from IPython.testing import decorators as testdec
60 from IPython.utils.io import file_read, nlprint
60 from IPython.utils.io import file_read, nlprint
61 import IPython.utils.io
61 import IPython.utils.io
62 from IPython.utils.path import get_py_filename
62 from IPython.utils.path import get_py_filename
63 from IPython.utils.process import arg_split, abbrev_cwd
63 from IPython.utils.process import arg_split, abbrev_cwd
64 from IPython.utils.terminal import set_term_title
64 from IPython.utils.terminal import set_term_title
65 from IPython.utils.text import LSString, SList, StringTypes, format_screen
65 from IPython.utils.text import LSString, SList, StringTypes, format_screen
66 from IPython.utils.timing import clock, clock2
66 from IPython.utils.timing import clock, clock2
67 from IPython.utils.warn import warn, error
67 from IPython.utils.warn import warn, error
68 from IPython.utils.ipstruct import Struct
68 from IPython.utils.ipstruct import Struct
69 import IPython.utils.generics
69 import IPython.utils.generics
70
70
71 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
72 # Utility functions
72 # Utility functions
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74
74
75 def on_off(tag):
75 def on_off(tag):
76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 return ['OFF','ON'][tag]
77 return ['OFF','ON'][tag]
78
78
79 class Bunch: pass
79 class Bunch: pass
80
80
81 def compress_dhist(dh):
81 def compress_dhist(dh):
82 head, tail = dh[:-10], dh[-10:]
82 head, tail = dh[:-10], dh[-10:]
83
83
84 newhead = []
84 newhead = []
85 done = set()
85 done = set()
86 for h in head:
86 for h in head:
87 if h in done:
87 if h in done:
88 continue
88 continue
89 newhead.append(h)
89 newhead.append(h)
90 done.add(h)
90 done.add(h)
91
91
92 return newhead + tail
92 return newhead + tail
93
93
94
94
95 #***************************************************************************
95 #***************************************************************************
96 # Main class implementing Magic functionality
96 # Main class implementing Magic functionality
97
97
98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # on construction of the main InteractiveShell object. Something odd is going
99 # on construction of the main InteractiveShell object. Something odd is going
100 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
100 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 # eventually this needs to be clarified.
101 # eventually this needs to be clarified.
102 # BG: This is because InteractiveShell inherits from this, but is itself a
102 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # Configurable. This messes up the MRO in some way. The fix is that we need to
103 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 # make Magic a configurable that InteractiveShell does not subclass.
104 # make Magic a configurable that InteractiveShell does not subclass.
105
105
106 class Magic:
106 class Magic:
107 """Magic functions for InteractiveShell.
107 """Magic functions for InteractiveShell.
108
108
109 Shell functions which can be reached as %function_name. All magic
109 Shell functions which can be reached as %function_name. All magic
110 functions should accept a string, which they can parse for their own
110 functions should accept a string, which they can parse for their own
111 needs. This can make some functions easier to type, eg `%cd ../`
111 needs. This can make some functions easier to type, eg `%cd ../`
112 vs. `%cd("../")`
112 vs. `%cd("../")`
113
113
114 ALL definitions MUST begin with the prefix magic_. The user won't need it
114 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 at the command line, but it is is needed in the definition. """
115 at the command line, but it is is needed in the definition. """
116
116
117 # class globals
117 # class globals
118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 'Automagic is ON, % prefix NOT needed for magic functions.']
119 'Automagic is ON, % prefix NOT needed for magic functions.']
120
120
121 #......................................................................
121 #......................................................................
122 # some utility functions
122 # some utility functions
123
123
124 def __init__(self,shell):
124 def __init__(self,shell):
125
125
126 self.options_table = {}
126 self.options_table = {}
127 if profile is None:
127 if profile is None:
128 self.magic_prun = self.profile_missing_notice
128 self.magic_prun = self.profile_missing_notice
129 self.shell = shell
129 self.shell = shell
130
130
131 # namespace for holding state we may need
131 # namespace for holding state we may need
132 self._magic_state = Bunch()
132 self._magic_state = Bunch()
133
133
134 def profile_missing_notice(self, *args, **kwargs):
134 def profile_missing_notice(self, *args, **kwargs):
135 error("""\
135 error("""\
136 The profile module could not be found. It has been removed from the standard
136 The profile module could not be found. It has been removed from the standard
137 python packages because of its non-free license. To use profiling, install the
137 python packages because of its non-free license. To use profiling, install the
138 python-profiler package from non-free.""")
138 python-profiler package from non-free.""")
139
139
140 def default_option(self,fn,optstr):
140 def default_option(self,fn,optstr):
141 """Make an entry in the options_table for fn, with value optstr"""
141 """Make an entry in the options_table for fn, with value optstr"""
142
142
143 if fn not in self.lsmagic():
143 if fn not in self.lsmagic():
144 error("%s is not a magic function" % fn)
144 error("%s is not a magic function" % fn)
145 self.options_table[fn] = optstr
145 self.options_table[fn] = optstr
146
146
147 def lsmagic(self):
147 def lsmagic(self):
148 """Return a list of currently available magic functions.
148 """Return a list of currently available magic functions.
149
149
150 Gives a list of the bare names after mangling (['ls','cd', ...], not
150 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 ['magic_ls','magic_cd',...]"""
151 ['magic_ls','magic_cd',...]"""
152
152
153 # FIXME. This needs a cleanup, in the way the magics list is built.
153 # FIXME. This needs a cleanup, in the way the magics list is built.
154
154
155 # magics in class definition
155 # magics in class definition
156 class_magic = lambda fn: fn.startswith('magic_') and \
156 class_magic = lambda fn: fn.startswith('magic_') and \
157 callable(Magic.__dict__[fn])
157 callable(Magic.__dict__[fn])
158 # in instance namespace (run-time user additions)
158 # in instance namespace (run-time user additions)
159 inst_magic = lambda fn: fn.startswith('magic_') and \
159 inst_magic = lambda fn: fn.startswith('magic_') and \
160 callable(self.__dict__[fn])
160 callable(self.__dict__[fn])
161 # and bound magics by user (so they can access self):
161 # and bound magics by user (so they can access self):
162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 callable(self.__class__.__dict__[fn])
163 callable(self.__class__.__dict__[fn])
164 magics = filter(class_magic,Magic.__dict__.keys()) + \
164 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 filter(inst_magic,self.__dict__.keys()) + \
165 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_bound_magic,self.__class__.__dict__.keys())
166 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 out = []
167 out = []
168 for fn in set(magics):
168 for fn in set(magics):
169 out.append(fn.replace('magic_','',1))
169 out.append(fn.replace('magic_','',1))
170 out.sort()
170 out.sort()
171 return out
171 return out
172
172
173 def extract_input_slices(self,slices,raw=False):
173 def extract_input_slices(self,slices,raw=False):
174 """Return as a string a set of input history slices.
174 """Return as a string a set of input history slices.
175
175
176 Inputs:
176 Inputs:
177
177
178 - slices: the set of slices is given as a list of strings (like
178 - slices: the set of slices is given as a list of strings (like
179 ['1','4:8','9'], since this function is for use by magic functions
179 ['1','4:8','9'], since this function is for use by magic functions
180 which get their arguments as strings.
180 which get their arguments as strings.
181
181
182 Optional inputs:
182 Optional inputs:
183
183
184 - raw(False): by default, the processed input is used. If this is
184 - raw(False): by default, the processed input is used. If this is
185 true, the raw input history is used instead.
185 true, the raw input history is used instead.
186
186
187 Note that slices can be called with two notations:
187 Note that slices can be called with two notations:
188
188
189 N:M -> standard python form, means including items N...(M-1).
189 N:M -> standard python form, means including items N...(M-1).
190
190
191 N-M -> include items N..M (closed endpoint)."""
191 N-M -> include items N..M (closed endpoint)."""
192
192
193 if raw:
193 if raw:
194 hist = self.shell.input_hist_raw
194 hist = self.shell.input_hist_raw
195 else:
195 else:
196 hist = self.shell.input_hist
196 hist = self.shell.input_hist
197
197
198 cmds = []
198 cmds = []
199 for chunk in slices:
199 for chunk in slices:
200 if ':' in chunk:
200 if ':' in chunk:
201 ini,fin = map(int,chunk.split(':'))
201 ini,fin = map(int,chunk.split(':'))
202 elif '-' in chunk:
202 elif '-' in chunk:
203 ini,fin = map(int,chunk.split('-'))
203 ini,fin = map(int,chunk.split('-'))
204 fin += 1
204 fin += 1
205 else:
205 else:
206 ini = int(chunk)
206 ini = int(chunk)
207 fin = ini+1
207 fin = ini+1
208 cmds.append(hist[ini:fin])
208 cmds.append(hist[ini:fin])
209 return cmds
209 return cmds
210
210
211 def arg_err(self,func):
211 def arg_err(self,func):
212 """Print docstring if incorrect arguments were passed"""
212 """Print docstring if incorrect arguments were passed"""
213 print 'Error in arguments:'
213 print 'Error in arguments:'
214 print oinspect.getdoc(func)
214 print oinspect.getdoc(func)
215
215
216 def format_latex(self,strng):
216 def format_latex(self,strng):
217 """Format a string for latex inclusion."""
217 """Format a string for latex inclusion."""
218
218
219 # Characters that need to be escaped for latex:
219 # Characters that need to be escaped for latex:
220 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
220 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
221 # Magic command names as headers:
221 # Magic command names as headers:
222 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
222 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
223 re.MULTILINE)
223 re.MULTILINE)
224 # Magic commands
224 # Magic commands
225 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
225 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
226 re.MULTILINE)
226 re.MULTILINE)
227 # Paragraph continue
227 # Paragraph continue
228 par_re = re.compile(r'\\$',re.MULTILINE)
228 par_re = re.compile(r'\\$',re.MULTILINE)
229
229
230 # The "\n" symbol
230 # The "\n" symbol
231 newline_re = re.compile(r'\\n')
231 newline_re = re.compile(r'\\n')
232
232
233 # Now build the string for output:
233 # Now build the string for output:
234 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
234 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
235 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
235 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
236 strng)
236 strng)
237 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
237 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
238 strng = par_re.sub(r'\\\\',strng)
238 strng = par_re.sub(r'\\\\',strng)
239 strng = escape_re.sub(r'\\\1',strng)
239 strng = escape_re.sub(r'\\\1',strng)
240 strng = newline_re.sub(r'\\textbackslash{}n',strng)
240 strng = newline_re.sub(r'\\textbackslash{}n',strng)
241 return strng
241 return strng
242
242
243 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
243 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
244 """Parse options passed to an argument string.
244 """Parse options passed to an argument string.
245
245
246 The interface is similar to that of getopt(), but it returns back a
246 The interface is similar to that of getopt(), but it returns back a
247 Struct with the options as keys and the stripped argument string still
247 Struct with the options as keys and the stripped argument string still
248 as a string.
248 as a string.
249
249
250 arg_str is quoted as a true sys.argv vector by using shlex.split.
250 arg_str is quoted as a true sys.argv vector by using shlex.split.
251 This allows us to easily expand variables, glob files, quote
251 This allows us to easily expand variables, glob files, quote
252 arguments, etc.
252 arguments, etc.
253
253
254 Options:
254 Options:
255 -mode: default 'string'. If given as 'list', the argument string is
255 -mode: default 'string'. If given as 'list', the argument string is
256 returned as a list (split on whitespace) instead of a string.
256 returned as a list (split on whitespace) instead of a string.
257
257
258 -list_all: put all option values in lists. Normally only options
258 -list_all: put all option values in lists. Normally only options
259 appearing more than once are put in a list.
259 appearing more than once are put in a list.
260
260
261 -posix (True): whether to split the input line in POSIX mode or not,
261 -posix (True): whether to split the input line in POSIX mode or not,
262 as per the conventions outlined in the shlex module from the
262 as per the conventions outlined in the shlex module from the
263 standard library."""
263 standard library."""
264
264
265 # inject default options at the beginning of the input line
265 # inject default options at the beginning of the input line
266 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
266 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
267 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
267 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
268
268
269 mode = kw.get('mode','string')
269 mode = kw.get('mode','string')
270 if mode not in ['string','list']:
270 if mode not in ['string','list']:
271 raise ValueError,'incorrect mode given: %s' % mode
271 raise ValueError,'incorrect mode given: %s' % mode
272 # Get options
272 # Get options
273 list_all = kw.get('list_all',0)
273 list_all = kw.get('list_all',0)
274 posix = kw.get('posix', os.name == 'posix')
274 posix = kw.get('posix', os.name == 'posix')
275
275
276 # Check if we have more than one argument to warrant extra processing:
276 # Check if we have more than one argument to warrant extra processing:
277 odict = {} # Dictionary with options
277 odict = {} # Dictionary with options
278 args = arg_str.split()
278 args = arg_str.split()
279 if len(args) >= 1:
279 if len(args) >= 1:
280 # If the list of inputs only has 0 or 1 thing in it, there's no
280 # If the list of inputs only has 0 or 1 thing in it, there's no
281 # need to look for options
281 # need to look for options
282 argv = arg_split(arg_str,posix)
282 argv = arg_split(arg_str,posix)
283 # Do regular option processing
283 # Do regular option processing
284 try:
284 try:
285 opts,args = getopt(argv,opt_str,*long_opts)
285 opts,args = getopt(argv,opt_str,*long_opts)
286 except GetoptError,e:
286 except GetoptError,e:
287 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
287 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
288 " ".join(long_opts)))
288 " ".join(long_opts)))
289 for o,a in opts:
289 for o,a in opts:
290 if o.startswith('--'):
290 if o.startswith('--'):
291 o = o[2:]
291 o = o[2:]
292 else:
292 else:
293 o = o[1:]
293 o = o[1:]
294 try:
294 try:
295 odict[o].append(a)
295 odict[o].append(a)
296 except AttributeError:
296 except AttributeError:
297 odict[o] = [odict[o],a]
297 odict[o] = [odict[o],a]
298 except KeyError:
298 except KeyError:
299 if list_all:
299 if list_all:
300 odict[o] = [a]
300 odict[o] = [a]
301 else:
301 else:
302 odict[o] = a
302 odict[o] = a
303
303
304 # Prepare opts,args for return
304 # Prepare opts,args for return
305 opts = Struct(odict)
305 opts = Struct(odict)
306 if mode == 'string':
306 if mode == 'string':
307 args = ' '.join(args)
307 args = ' '.join(args)
308
308
309 return opts,args
309 return opts,args
310
310
311 #......................................................................
311 #......................................................................
312 # And now the actual magic functions
312 # And now the actual magic functions
313
313
314 # Functions for IPython shell work (vars,funcs, config, etc)
314 # Functions for IPython shell work (vars,funcs, config, etc)
315 def magic_lsmagic(self, parameter_s = ''):
315 def magic_lsmagic(self, parameter_s = ''):
316 """List currently available magic functions."""
316 """List currently available magic functions."""
317 mesc = ESC_MAGIC
317 mesc = ESC_MAGIC
318 print 'Available magic functions:\n'+mesc+\
318 print 'Available magic functions:\n'+mesc+\
319 (' '+mesc).join(self.lsmagic())
319 (' '+mesc).join(self.lsmagic())
320 print '\n' + Magic.auto_status[self.shell.automagic]
320 print '\n' + Magic.auto_status[self.shell.automagic]
321 return None
321 return None
322
322
323 def magic_magic(self, parameter_s = ''):
323 def magic_magic(self, parameter_s = ''):
324 """Print information about the magic function system.
324 """Print information about the magic function system.
325
325
326 Supported formats: -latex, -brief, -rest
326 Supported formats: -latex, -brief, -rest
327 """
327 """
328
328
329 mode = ''
329 mode = ''
330 try:
330 try:
331 if parameter_s.split()[0] == '-latex':
331 if parameter_s.split()[0] == '-latex':
332 mode = 'latex'
332 mode = 'latex'
333 if parameter_s.split()[0] == '-brief':
333 if parameter_s.split()[0] == '-brief':
334 mode = 'brief'
334 mode = 'brief'
335 if parameter_s.split()[0] == '-rest':
335 if parameter_s.split()[0] == '-rest':
336 mode = 'rest'
336 mode = 'rest'
337 rest_docs = []
337 rest_docs = []
338 except:
338 except:
339 pass
339 pass
340
340
341 magic_docs = []
341 magic_docs = []
342 for fname in self.lsmagic():
342 for fname in self.lsmagic():
343 mname = 'magic_' + fname
343 mname = 'magic_' + fname
344 for space in (Magic,self,self.__class__):
344 for space in (Magic,self,self.__class__):
345 try:
345 try:
346 fn = space.__dict__[mname]
346 fn = space.__dict__[mname]
347 except KeyError:
347 except KeyError:
348 pass
348 pass
349 else:
349 else:
350 break
350 break
351 if mode == 'brief':
351 if mode == 'brief':
352 # only first line
352 # only first line
353 if fn.__doc__:
353 if fn.__doc__:
354 fndoc = fn.__doc__.split('\n',1)[0]
354 fndoc = fn.__doc__.split('\n',1)[0]
355 else:
355 else:
356 fndoc = 'No documentation'
356 fndoc = 'No documentation'
357 else:
357 else:
358 if fn.__doc__:
358 if fn.__doc__:
359 fndoc = fn.__doc__.rstrip()
359 fndoc = fn.__doc__.rstrip()
360 else:
360 else:
361 fndoc = 'No documentation'
361 fndoc = 'No documentation'
362
362
363
363
364 if mode == 'rest':
364 if mode == 'rest':
365 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
365 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
366 fname,fndoc))
366 fname,fndoc))
367
367
368 else:
368 else:
369 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
369 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
370 fname,fndoc))
370 fname,fndoc))
371
371
372 magic_docs = ''.join(magic_docs)
372 magic_docs = ''.join(magic_docs)
373
373
374 if mode == 'rest':
374 if mode == 'rest':
375 return "".join(rest_docs)
375 return "".join(rest_docs)
376
376
377 if mode == 'latex':
377 if mode == 'latex':
378 print self.format_latex(magic_docs)
378 print self.format_latex(magic_docs)
379 return
379 return
380 else:
380 else:
381 magic_docs = format_screen(magic_docs)
381 magic_docs = format_screen(magic_docs)
382 if mode == 'brief':
382 if mode == 'brief':
383 return magic_docs
383 return magic_docs
384
384
385 outmsg = """
385 outmsg = """
386 IPython's 'magic' functions
386 IPython's 'magic' functions
387 ===========================
387 ===========================
388
388
389 The magic function system provides a series of functions which allow you to
389 The magic function system provides a series of functions which allow you to
390 control the behavior of IPython itself, plus a lot of system-type
390 control the behavior of IPython itself, plus a lot of system-type
391 features. All these functions are prefixed with a % character, but parameters
391 features. All these functions are prefixed with a % character, but parameters
392 are given without parentheses or quotes.
392 are given without parentheses or quotes.
393
393
394 NOTE: If you have 'automagic' enabled (via the command line option or with the
394 NOTE: If you have 'automagic' enabled (via the command line option or with the
395 %automagic function), you don't need to type in the % explicitly. By default,
395 %automagic function), you don't need to type in the % explicitly. By default,
396 IPython ships with automagic on, so you should only rarely need the % escape.
396 IPython ships with automagic on, so you should only rarely need the % escape.
397
397
398 Example: typing '%cd mydir' (without the quotes) changes you working directory
398 Example: typing '%cd mydir' (without the quotes) changes you working directory
399 to 'mydir', if it exists.
399 to 'mydir', if it exists.
400
400
401 You can define your own magic functions to extend the system. See the supplied
401 You can define your own magic functions to extend the system. See the supplied
402 ipythonrc and example-magic.py files for details (in your ipython
402 ipythonrc and example-magic.py files for details (in your ipython
403 configuration directory, typically $HOME/.ipython/).
403 configuration directory, typically $HOME/.ipython/).
404
404
405 You can also define your own aliased names for magic functions. In your
405 You can also define your own aliased names for magic functions. In your
406 ipythonrc file, placing a line like:
406 ipythonrc file, placing a line like:
407
407
408 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
408 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
409
409
410 will define %pf as a new name for %profile.
410 will define %pf as a new name for %profile.
411
411
412 You can also call magics in code using the magic() function, which IPython
412 You can also call magics in code using the magic() function, which IPython
413 automatically adds to the builtin namespace. Type 'magic?' for details.
413 automatically adds to the builtin namespace. Type 'magic?' for details.
414
414
415 For a list of the available magic functions, use %lsmagic. For a description
415 For a list of the available magic functions, use %lsmagic. For a description
416 of any of them, type %magic_name?, e.g. '%cd?'.
416 of any of them, type %magic_name?, e.g. '%cd?'.
417
417
418 Currently the magic system has the following functions:\n"""
418 Currently the magic system has the following functions:\n"""
419
419
420 mesc = ESC_MAGIC
420 mesc = ESC_MAGIC
421 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
421 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
422 "\n\n%s%s\n\n%s" % (outmsg,
422 "\n\n%s%s\n\n%s" % (outmsg,
423 magic_docs,mesc,mesc,
423 magic_docs,mesc,mesc,
424 (' '+mesc).join(self.lsmagic()),
424 (' '+mesc).join(self.lsmagic()),
425 Magic.auto_status[self.shell.automagic] ) )
425 Magic.auto_status[self.shell.automagic] ) )
426 page.page(outmsg)
426 page.page(outmsg)
427
427
428 def magic_autoindent(self, parameter_s = ''):
428 def magic_autoindent(self, parameter_s = ''):
429 """Toggle autoindent on/off (if available)."""
429 """Toggle autoindent on/off (if available)."""
430
430
431 self.shell.set_autoindent()
431 self.shell.set_autoindent()
432 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
432 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
433
433
434 def magic_automagic(self, parameter_s = ''):
434 def magic_automagic(self, parameter_s = ''):
435 """Make magic functions callable without having to type the initial %.
435 """Make magic functions callable without having to type the initial %.
436
436
437 Without argumentsl toggles on/off (when off, you must call it as
437 Without argumentsl toggles on/off (when off, you must call it as
438 %automagic, of course). With arguments it sets the value, and you can
438 %automagic, of course). With arguments it sets the value, and you can
439 use any of (case insensitive):
439 use any of (case insensitive):
440
440
441 - on,1,True: to activate
441 - on,1,True: to activate
442
442
443 - off,0,False: to deactivate.
443 - off,0,False: to deactivate.
444
444
445 Note that magic functions have lowest priority, so if there's a
445 Note that magic functions have lowest priority, so if there's a
446 variable whose name collides with that of a magic fn, automagic won't
446 variable whose name collides with that of a magic fn, automagic won't
447 work for that function (you get the variable instead). However, if you
447 work for that function (you get the variable instead). However, if you
448 delete the variable (del var), the previously shadowed magic function
448 delete the variable (del var), the previously shadowed magic function
449 becomes visible to automagic again."""
449 becomes visible to automagic again."""
450
450
451 arg = parameter_s.lower()
451 arg = parameter_s.lower()
452 if parameter_s in ('on','1','true'):
452 if parameter_s in ('on','1','true'):
453 self.shell.automagic = True
453 self.shell.automagic = True
454 elif parameter_s in ('off','0','false'):
454 elif parameter_s in ('off','0','false'):
455 self.shell.automagic = False
455 self.shell.automagic = False
456 else:
456 else:
457 self.shell.automagic = not self.shell.automagic
457 self.shell.automagic = not self.shell.automagic
458 print '\n' + Magic.auto_status[self.shell.automagic]
458 print '\n' + Magic.auto_status[self.shell.automagic]
459
459
460 @testdec.skip_doctest
460 @testdec.skip_doctest
461 def magic_autocall(self, parameter_s = ''):
461 def magic_autocall(self, parameter_s = ''):
462 """Make functions callable without having to type parentheses.
462 """Make functions callable without having to type parentheses.
463
463
464 Usage:
464 Usage:
465
465
466 %autocall [mode]
466 %autocall [mode]
467
467
468 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
468 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
469 value is toggled on and off (remembering the previous state).
469 value is toggled on and off (remembering the previous state).
470
470
471 In more detail, these values mean:
471 In more detail, these values mean:
472
472
473 0 -> fully disabled
473 0 -> fully disabled
474
474
475 1 -> active, but do not apply if there are no arguments on the line.
475 1 -> active, but do not apply if there are no arguments on the line.
476
476
477 In this mode, you get:
477 In this mode, you get:
478
478
479 In [1]: callable
479 In [1]: callable
480 Out[1]: <built-in function callable>
480 Out[1]: <built-in function callable>
481
481
482 In [2]: callable 'hello'
482 In [2]: callable 'hello'
483 ------> callable('hello')
483 ------> callable('hello')
484 Out[2]: False
484 Out[2]: False
485
485
486 2 -> Active always. Even if no arguments are present, the callable
486 2 -> Active always. Even if no arguments are present, the callable
487 object is called:
487 object is called:
488
488
489 In [2]: float
489 In [2]: float
490 ------> float()
490 ------> float()
491 Out[2]: 0.0
491 Out[2]: 0.0
492
492
493 Note that even with autocall off, you can still use '/' at the start of
493 Note that even with autocall off, you can still use '/' at the start of
494 a line to treat the first argument on the command line as a function
494 a line to treat the first argument on the command line as a function
495 and add parentheses to it:
495 and add parentheses to it:
496
496
497 In [8]: /str 43
497 In [8]: /str 43
498 ------> str(43)
498 ------> str(43)
499 Out[8]: '43'
499 Out[8]: '43'
500
500
501 # all-random (note for auto-testing)
501 # all-random (note for auto-testing)
502 """
502 """
503
503
504 if parameter_s:
504 if parameter_s:
505 arg = int(parameter_s)
505 arg = int(parameter_s)
506 else:
506 else:
507 arg = 'toggle'
507 arg = 'toggle'
508
508
509 if not arg in (0,1,2,'toggle'):
509 if not arg in (0,1,2,'toggle'):
510 error('Valid modes: (0->Off, 1->Smart, 2->Full')
510 error('Valid modes: (0->Off, 1->Smart, 2->Full')
511 return
511 return
512
512
513 if arg in (0,1,2):
513 if arg in (0,1,2):
514 self.shell.autocall = arg
514 self.shell.autocall = arg
515 else: # toggle
515 else: # toggle
516 if self.shell.autocall:
516 if self.shell.autocall:
517 self._magic_state.autocall_save = self.shell.autocall
517 self._magic_state.autocall_save = self.shell.autocall
518 self.shell.autocall = 0
518 self.shell.autocall = 0
519 else:
519 else:
520 try:
520 try:
521 self.shell.autocall = self._magic_state.autocall_save
521 self.shell.autocall = self._magic_state.autocall_save
522 except AttributeError:
522 except AttributeError:
523 self.shell.autocall = self._magic_state.autocall_save = 1
523 self.shell.autocall = self._magic_state.autocall_save = 1
524
524
525 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
525 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
526
526
527
527
528 def magic_page(self, parameter_s=''):
528 def magic_page(self, parameter_s=''):
529 """Pretty print the object and display it through a pager.
529 """Pretty print the object and display it through a pager.
530
530
531 %page [options] OBJECT
531 %page [options] OBJECT
532
532
533 If no object is given, use _ (last output).
533 If no object is given, use _ (last output).
534
534
535 Options:
535 Options:
536
536
537 -r: page str(object), don't pretty-print it."""
537 -r: page str(object), don't pretty-print it."""
538
538
539 # After a function contributed by Olivier Aubert, slightly modified.
539 # After a function contributed by Olivier Aubert, slightly modified.
540
540
541 # Process options/args
541 # Process options/args
542 opts,args = self.parse_options(parameter_s,'r')
542 opts,args = self.parse_options(parameter_s,'r')
543 raw = 'r' in opts
543 raw = 'r' in opts
544
544
545 oname = args and args or '_'
545 oname = args and args or '_'
546 info = self._ofind(oname)
546 info = self._ofind(oname)
547 if info['found']:
547 if info['found']:
548 txt = (raw and str or pformat)( info['obj'] )
548 txt = (raw and str or pformat)( info['obj'] )
549 page.page(txt)
549 page.page(txt)
550 else:
550 else:
551 print 'Object `%s` not found' % oname
551 print 'Object `%s` not found' % oname
552
552
553 def magic_profile(self, parameter_s=''):
553 def magic_profile(self, parameter_s=''):
554 """Print your currently active IPython profile."""
554 """Print your currently active IPython profile."""
555 if self.shell.profile:
555 if self.shell.profile:
556 printpl('Current IPython profile: $self.shell.profile.')
556 printpl('Current IPython profile: $self.shell.profile.')
557 else:
557 else:
558 print 'No profile active.'
558 print 'No profile active.'
559
559
560 def magic_pinfo(self, parameter_s='', namespaces=None):
560 def magic_pinfo(self, parameter_s='', namespaces=None):
561 """Provide detailed information about an object.
561 """Provide detailed information about an object.
562
562
563 '%pinfo object' is just a synonym for object? or ?object."""
563 '%pinfo object' is just a synonym for object? or ?object."""
564
564
565 #print 'pinfo par: <%s>' % parameter_s # dbg
565 #print 'pinfo par: <%s>' % parameter_s # dbg
566
566
567
567
568 # detail_level: 0 -> obj? , 1 -> obj??
568 # detail_level: 0 -> obj? , 1 -> obj??
569 detail_level = 0
569 detail_level = 0
570 # We need to detect if we got called as 'pinfo pinfo foo', which can
570 # We need to detect if we got called as 'pinfo pinfo foo', which can
571 # happen if the user types 'pinfo foo?' at the cmd line.
571 # happen if the user types 'pinfo foo?' at the cmd line.
572 pinfo,qmark1,oname,qmark2 = \
572 pinfo,qmark1,oname,qmark2 = \
573 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
573 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
574 if pinfo or qmark1 or qmark2:
574 if pinfo or qmark1 or qmark2:
575 detail_level = 1
575 detail_level = 1
576 if "*" in oname:
576 if "*" in oname:
577 self.magic_psearch(oname)
577 self.magic_psearch(oname)
578 else:
578 else:
579 self.shell._inspect('pinfo', oname, detail_level=detail_level,
579 self.shell._inspect('pinfo', oname, detail_level=detail_level,
580 namespaces=namespaces)
580 namespaces=namespaces)
581
581
582 def magic_pdef(self, parameter_s='', namespaces=None):
582 def magic_pdef(self, parameter_s='', namespaces=None):
583 """Print the definition header for any callable object.
583 """Print the definition header for any callable object.
584
584
585 If the object is a class, print the constructor information."""
585 If the object is a class, print the constructor information."""
586 self._inspect('pdef',parameter_s, namespaces)
586 self._inspect('pdef',parameter_s, namespaces)
587
587
588 def magic_pdoc(self, parameter_s='', namespaces=None):
588 def magic_pdoc(self, parameter_s='', namespaces=None):
589 """Print the docstring for an object.
589 """Print the docstring for an object.
590
590
591 If the given object is a class, it will print both the class and the
591 If the given object is a class, it will print both the class and the
592 constructor docstrings."""
592 constructor docstrings."""
593 self._inspect('pdoc',parameter_s, namespaces)
593 self._inspect('pdoc',parameter_s, namespaces)
594
594
595 def magic_psource(self, parameter_s='', namespaces=None):
595 def magic_psource(self, parameter_s='', namespaces=None):
596 """Print (or run through pager) the source code for an object."""
596 """Print (or run through pager) the source code for an object."""
597 self._inspect('psource',parameter_s, namespaces)
597 self._inspect('psource',parameter_s, namespaces)
598
598
599 def magic_pfile(self, parameter_s=''):
599 def magic_pfile(self, parameter_s=''):
600 """Print (or run through pager) the file where an object is defined.
600 """Print (or run through pager) the file where an object is defined.
601
601
602 The file opens at the line where the object definition begins. IPython
602 The file opens at the line where the object definition begins. IPython
603 will honor the environment variable PAGER if set, and otherwise will
603 will honor the environment variable PAGER if set, and otherwise will
604 do its best to print the file in a convenient form.
604 do its best to print the file in a convenient form.
605
605
606 If the given argument is not an object currently defined, IPython will
606 If the given argument is not an object currently defined, IPython will
607 try to interpret it as a filename (automatically adding a .py extension
607 try to interpret it as a filename (automatically adding a .py extension
608 if needed). You can thus use %pfile as a syntax highlighting code
608 if needed). You can thus use %pfile as a syntax highlighting code
609 viewer."""
609 viewer."""
610
610
611 # first interpret argument as an object name
611 # first interpret argument as an object name
612 out = self._inspect('pfile',parameter_s)
612 out = self._inspect('pfile',parameter_s)
613 # if not, try the input as a filename
613 # if not, try the input as a filename
614 if out == 'not found':
614 if out == 'not found':
615 try:
615 try:
616 filename = get_py_filename(parameter_s)
616 filename = get_py_filename(parameter_s)
617 except IOError,msg:
617 except IOError,msg:
618 print msg
618 print msg
619 return
619 return
620 page.page(self.shell.inspector.format(file(filename).read()))
620 page.page(self.shell.inspector.format(file(filename).read()))
621
621
622 def magic_psearch(self, parameter_s=''):
622 def magic_psearch(self, parameter_s=''):
623 """Search for object in namespaces by wildcard.
623 """Search for object in namespaces by wildcard.
624
624
625 %psearch [options] PATTERN [OBJECT TYPE]
625 %psearch [options] PATTERN [OBJECT TYPE]
626
626
627 Note: ? can be used as a synonym for %psearch, at the beginning or at
627 Note: ? can be used as a synonym for %psearch, at the beginning or at
628 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
628 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
629 rest of the command line must be unchanged (options come first), so
629 rest of the command line must be unchanged (options come first), so
630 for example the following forms are equivalent
630 for example the following forms are equivalent
631
631
632 %psearch -i a* function
632 %psearch -i a* function
633 -i a* function?
633 -i a* function?
634 ?-i a* function
634 ?-i a* function
635
635
636 Arguments:
636 Arguments:
637
637
638 PATTERN
638 PATTERN
639
639
640 where PATTERN is a string containing * as a wildcard similar to its
640 where PATTERN is a string containing * as a wildcard similar to its
641 use in a shell. The pattern is matched in all namespaces on the
641 use in a shell. The pattern is matched in all namespaces on the
642 search path. By default objects starting with a single _ are not
642 search path. By default objects starting with a single _ are not
643 matched, many IPython generated objects have a single
643 matched, many IPython generated objects have a single
644 underscore. The default is case insensitive matching. Matching is
644 underscore. The default is case insensitive matching. Matching is
645 also done on the attributes of objects and not only on the objects
645 also done on the attributes of objects and not only on the objects
646 in a module.
646 in a module.
647
647
648 [OBJECT TYPE]
648 [OBJECT TYPE]
649
649
650 Is the name of a python type from the types module. The name is
650 Is the name of a python type from the types module. The name is
651 given in lowercase without the ending type, ex. StringType is
651 given in lowercase without the ending type, ex. StringType is
652 written string. By adding a type here only objects matching the
652 written string. By adding a type here only objects matching the
653 given type are matched. Using all here makes the pattern match all
653 given type are matched. Using all here makes the pattern match all
654 types (this is the default).
654 types (this is the default).
655
655
656 Options:
656 Options:
657
657
658 -a: makes the pattern match even objects whose names start with a
658 -a: makes the pattern match even objects whose names start with a
659 single underscore. These names are normally ommitted from the
659 single underscore. These names are normally ommitted from the
660 search.
660 search.
661
661
662 -i/-c: make the pattern case insensitive/sensitive. If neither of
662 -i/-c: make the pattern case insensitive/sensitive. If neither of
663 these options is given, the default is read from your ipythonrc
663 these options is given, the default is read from your ipythonrc
664 file. The option name which sets this value is
664 file. The option name which sets this value is
665 'wildcards_case_sensitive'. If this option is not specified in your
665 'wildcards_case_sensitive'. If this option is not specified in your
666 ipythonrc file, IPython's internal default is to do a case sensitive
666 ipythonrc file, IPython's internal default is to do a case sensitive
667 search.
667 search.
668
668
669 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
669 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
670 specifiy can be searched in any of the following namespaces:
670 specifiy can be searched in any of the following namespaces:
671 'builtin', 'user', 'user_global','internal', 'alias', where
671 'builtin', 'user', 'user_global','internal', 'alias', where
672 'builtin' and 'user' are the search defaults. Note that you should
672 'builtin' and 'user' are the search defaults. Note that you should
673 not use quotes when specifying namespaces.
673 not use quotes when specifying namespaces.
674
674
675 'Builtin' contains the python module builtin, 'user' contains all
675 'Builtin' contains the python module builtin, 'user' contains all
676 user data, 'alias' only contain the shell aliases and no python
676 user data, 'alias' only contain the shell aliases and no python
677 objects, 'internal' contains objects used by IPython. The
677 objects, 'internal' contains objects used by IPython. The
678 'user_global' namespace is only used by embedded IPython instances,
678 'user_global' namespace is only used by embedded IPython instances,
679 and it contains module-level globals. You can add namespaces to the
679 and it contains module-level globals. You can add namespaces to the
680 search with -s or exclude them with -e (these options can be given
680 search with -s or exclude them with -e (these options can be given
681 more than once).
681 more than once).
682
682
683 Examples:
683 Examples:
684
684
685 %psearch a* -> objects beginning with an a
685 %psearch a* -> objects beginning with an a
686 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
686 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
687 %psearch a* function -> all functions beginning with an a
687 %psearch a* function -> all functions beginning with an a
688 %psearch re.e* -> objects beginning with an e in module re
688 %psearch re.e* -> objects beginning with an e in module re
689 %psearch r*.e* -> objects that start with e in modules starting in r
689 %psearch r*.e* -> objects that start with e in modules starting in r
690 %psearch r*.* string -> all strings in modules beginning with r
690 %psearch r*.* string -> all strings in modules beginning with r
691
691
692 Case sensitve search:
692 Case sensitve search:
693
693
694 %psearch -c a* list all object beginning with lower case a
694 %psearch -c a* list all object beginning with lower case a
695
695
696 Show objects beginning with a single _:
696 Show objects beginning with a single _:
697
697
698 %psearch -a _* list objects beginning with a single underscore"""
698 %psearch -a _* list objects beginning with a single underscore"""
699 try:
699 try:
700 parameter_s = parameter_s.encode('ascii')
700 parameter_s = parameter_s.encode('ascii')
701 except UnicodeEncodeError:
701 except UnicodeEncodeError:
702 print 'Python identifiers can only contain ascii characters.'
702 print 'Python identifiers can only contain ascii characters.'
703 return
703 return
704
704
705 # default namespaces to be searched
705 # default namespaces to be searched
706 def_search = ['user','builtin']
706 def_search = ['user','builtin']
707
707
708 # Process options/args
708 # Process options/args
709 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
709 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
710 opt = opts.get
710 opt = opts.get
711 shell = self.shell
711 shell = self.shell
712 psearch = shell.inspector.psearch
712 psearch = shell.inspector.psearch
713
713
714 # select case options
714 # select case options
715 if opts.has_key('i'):
715 if opts.has_key('i'):
716 ignore_case = True
716 ignore_case = True
717 elif opts.has_key('c'):
717 elif opts.has_key('c'):
718 ignore_case = False
718 ignore_case = False
719 else:
719 else:
720 ignore_case = not shell.wildcards_case_sensitive
720 ignore_case = not shell.wildcards_case_sensitive
721
721
722 # Build list of namespaces to search from user options
722 # Build list of namespaces to search from user options
723 def_search.extend(opt('s',[]))
723 def_search.extend(opt('s',[]))
724 ns_exclude = ns_exclude=opt('e',[])
724 ns_exclude = ns_exclude=opt('e',[])
725 ns_search = [nm for nm in def_search if nm not in ns_exclude]
725 ns_search = [nm for nm in def_search if nm not in ns_exclude]
726
726
727 # Call the actual search
727 # Call the actual search
728 try:
728 try:
729 psearch(args,shell.ns_table,ns_search,
729 psearch(args,shell.ns_table,ns_search,
730 show_all=opt('a'),ignore_case=ignore_case)
730 show_all=opt('a'),ignore_case=ignore_case)
731 except:
731 except:
732 shell.showtraceback()
732 shell.showtraceback()
733
733
734 def magic_who_ls(self, parameter_s=''):
734 def magic_who_ls(self, parameter_s=''):
735 """Return a sorted list of all interactive variables.
735 """Return a sorted list of all interactive variables.
736
736
737 If arguments are given, only variables of types matching these
737 If arguments are given, only variables of types matching these
738 arguments are returned."""
738 arguments are returned."""
739
739
740 user_ns = self.shell.user_ns
740 user_ns = self.shell.user_ns
741 internal_ns = self.shell.internal_ns
741 internal_ns = self.shell.internal_ns
742 user_ns_hidden = self.shell.user_ns_hidden
742 user_ns_hidden = self.shell.user_ns_hidden
743 out = [ i for i in user_ns
743 out = [ i for i in user_ns
744 if not i.startswith('_') \
744 if not i.startswith('_') \
745 and not (i in internal_ns or i in user_ns_hidden) ]
745 and not (i in internal_ns or i in user_ns_hidden) ]
746
746
747 typelist = parameter_s.split()
747 typelist = parameter_s.split()
748 if typelist:
748 if typelist:
749 typeset = set(typelist)
749 typeset = set(typelist)
750 out = [i for i in out if type(i).__name__ in typeset]
750 out = [i for i in out if type(i).__name__ in typeset]
751
751
752 out.sort()
752 out.sort()
753 return out
753 return out
754
754
755 def magic_who(self, parameter_s=''):
755 def magic_who(self, parameter_s=''):
756 """Print all interactive variables, with some minimal formatting.
756 """Print all interactive variables, with some minimal formatting.
757
757
758 If any arguments are given, only variables whose type matches one of
758 If any arguments are given, only variables whose type matches one of
759 these are printed. For example:
759 these are printed. For example:
760
760
761 %who function str
761 %who function str
762
762
763 will only list functions and strings, excluding all other types of
763 will only list functions and strings, excluding all other types of
764 variables. To find the proper type names, simply use type(var) at a
764 variables. To find the proper type names, simply use type(var) at a
765 command line to see how python prints type names. For example:
765 command line to see how python prints type names. For example:
766
766
767 In [1]: type('hello')\\
767 In [1]: type('hello')\\
768 Out[1]: <type 'str'>
768 Out[1]: <type 'str'>
769
769
770 indicates that the type name for strings is 'str'.
770 indicates that the type name for strings is 'str'.
771
771
772 %who always excludes executed names loaded through your configuration
772 %who always excludes executed names loaded through your configuration
773 file and things which are internal to IPython.
773 file and things which are internal to IPython.
774
774
775 This is deliberate, as typically you may load many modules and the
775 This is deliberate, as typically you may load many modules and the
776 purpose of %who is to show you only what you've manually defined."""
776 purpose of %who is to show you only what you've manually defined."""
777
777
778 varlist = self.magic_who_ls(parameter_s)
778 varlist = self.magic_who_ls(parameter_s)
779 if not varlist:
779 if not varlist:
780 if parameter_s:
780 if parameter_s:
781 print 'No variables match your requested type.'
781 print 'No variables match your requested type.'
782 else:
782 else:
783 print 'Interactive namespace is empty.'
783 print 'Interactive namespace is empty.'
784 return
784 return
785
785
786 # if we have variables, move on...
786 # if we have variables, move on...
787 count = 0
787 count = 0
788 for i in varlist:
788 for i in varlist:
789 print i+'\t',
789 print i+'\t',
790 count += 1
790 count += 1
791 if count > 8:
791 if count > 8:
792 count = 0
792 count = 0
793 print
793 print
794 print
794 print
795
795
796 def magic_whos(self, parameter_s=''):
796 def magic_whos(self, parameter_s=''):
797 """Like %who, but gives some extra information about each variable.
797 """Like %who, but gives some extra information about each variable.
798
798
799 The same type filtering of %who can be applied here.
799 The same type filtering of %who can be applied here.
800
800
801 For all variables, the type is printed. Additionally it prints:
801 For all variables, the type is printed. Additionally it prints:
802
802
803 - For {},[],(): their length.
803 - For {},[],(): their length.
804
804
805 - For numpy and Numeric arrays, a summary with shape, number of
805 - For numpy and Numeric arrays, a summary with shape, number of
806 elements, typecode and size in memory.
806 elements, typecode and size in memory.
807
807
808 - Everything else: a string representation, snipping their middle if
808 - Everything else: a string representation, snipping their middle if
809 too long."""
809 too long."""
810
810
811 varnames = self.magic_who_ls(parameter_s)
811 varnames = self.magic_who_ls(parameter_s)
812 if not varnames:
812 if not varnames:
813 if parameter_s:
813 if parameter_s:
814 print 'No variables match your requested type.'
814 print 'No variables match your requested type.'
815 else:
815 else:
816 print 'Interactive namespace is empty.'
816 print 'Interactive namespace is empty.'
817 return
817 return
818
818
819 # if we have variables, move on...
819 # if we have variables, move on...
820
820
821 # for these types, show len() instead of data:
821 # for these types, show len() instead of data:
822 seq_types = [types.DictType,types.ListType,types.TupleType]
822 seq_types = [types.DictType,types.ListType,types.TupleType]
823
823
824 # for numpy/Numeric arrays, display summary info
824 # for numpy/Numeric arrays, display summary info
825 try:
825 try:
826 import numpy
826 import numpy
827 except ImportError:
827 except ImportError:
828 ndarray_type = None
828 ndarray_type = None
829 else:
829 else:
830 ndarray_type = numpy.ndarray.__name__
830 ndarray_type = numpy.ndarray.__name__
831 try:
831 try:
832 import Numeric
832 import Numeric
833 except ImportError:
833 except ImportError:
834 array_type = None
834 array_type = None
835 else:
835 else:
836 array_type = Numeric.ArrayType.__name__
836 array_type = Numeric.ArrayType.__name__
837
837
838 # Find all variable names and types so we can figure out column sizes
838 # Find all variable names and types so we can figure out column sizes
839 def get_vars(i):
839 def get_vars(i):
840 return self.shell.user_ns[i]
840 return self.shell.user_ns[i]
841
841
842 # some types are well known and can be shorter
842 # some types are well known and can be shorter
843 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
843 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
844 def type_name(v):
844 def type_name(v):
845 tn = type(v).__name__
845 tn = type(v).__name__
846 return abbrevs.get(tn,tn)
846 return abbrevs.get(tn,tn)
847
847
848 varlist = map(get_vars,varnames)
848 varlist = map(get_vars,varnames)
849
849
850 typelist = []
850 typelist = []
851 for vv in varlist:
851 for vv in varlist:
852 tt = type_name(vv)
852 tt = type_name(vv)
853
853
854 if tt=='instance':
854 if tt=='instance':
855 typelist.append( abbrevs.get(str(vv.__class__),
855 typelist.append( abbrevs.get(str(vv.__class__),
856 str(vv.__class__)))
856 str(vv.__class__)))
857 else:
857 else:
858 typelist.append(tt)
858 typelist.append(tt)
859
859
860 # column labels and # of spaces as separator
860 # column labels and # of spaces as separator
861 varlabel = 'Variable'
861 varlabel = 'Variable'
862 typelabel = 'Type'
862 typelabel = 'Type'
863 datalabel = 'Data/Info'
863 datalabel = 'Data/Info'
864 colsep = 3
864 colsep = 3
865 # variable format strings
865 # variable format strings
866 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
866 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
867 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
867 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
868 aformat = "%s: %s elems, type `%s`, %s bytes"
868 aformat = "%s: %s elems, type `%s`, %s bytes"
869 # find the size of the columns to format the output nicely
869 # find the size of the columns to format the output nicely
870 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
870 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
871 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
871 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
872 # table header
872 # table header
873 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
873 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
874 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
874 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
875 # and the table itself
875 # and the table itself
876 kb = 1024
876 kb = 1024
877 Mb = 1048576 # kb**2
877 Mb = 1048576 # kb**2
878 for vname,var,vtype in zip(varnames,varlist,typelist):
878 for vname,var,vtype in zip(varnames,varlist,typelist):
879 print itpl(vformat),
879 print itpl(vformat),
880 if vtype in seq_types:
880 if vtype in seq_types:
881 print len(var)
881 print len(var)
882 elif vtype in [array_type,ndarray_type]:
882 elif vtype in [array_type,ndarray_type]:
883 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
883 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
884 if vtype==ndarray_type:
884 if vtype==ndarray_type:
885 # numpy
885 # numpy
886 vsize = var.size
886 vsize = var.size
887 vbytes = vsize*var.itemsize
887 vbytes = vsize*var.itemsize
888 vdtype = var.dtype
888 vdtype = var.dtype
889 else:
889 else:
890 # Numeric
890 # Numeric
891 vsize = Numeric.size(var)
891 vsize = Numeric.size(var)
892 vbytes = vsize*var.itemsize()
892 vbytes = vsize*var.itemsize()
893 vdtype = var.typecode()
893 vdtype = var.typecode()
894
894
895 if vbytes < 100000:
895 if vbytes < 100000:
896 print aformat % (vshape,vsize,vdtype,vbytes)
896 print aformat % (vshape,vsize,vdtype,vbytes)
897 else:
897 else:
898 print aformat % (vshape,vsize,vdtype,vbytes),
898 print aformat % (vshape,vsize,vdtype,vbytes),
899 if vbytes < Mb:
899 if vbytes < Mb:
900 print '(%s kb)' % (vbytes/kb,)
900 print '(%s kb)' % (vbytes/kb,)
901 else:
901 else:
902 print '(%s Mb)' % (vbytes/Mb,)
902 print '(%s Mb)' % (vbytes/Mb,)
903 else:
903 else:
904 try:
904 try:
905 vstr = str(var)
905 vstr = str(var)
906 except UnicodeEncodeError:
906 except UnicodeEncodeError:
907 vstr = unicode(var).encode(sys.getdefaultencoding(),
907 vstr = unicode(var).encode(sys.getdefaultencoding(),
908 'backslashreplace')
908 'backslashreplace')
909 vstr = vstr.replace('\n','\\n')
909 vstr = vstr.replace('\n','\\n')
910 if len(vstr) < 50:
910 if len(vstr) < 50:
911 print vstr
911 print vstr
912 else:
912 else:
913 printpl(vfmt_short)
913 printpl(vfmt_short)
914
914
915 def magic_reset(self, parameter_s=''):
915 def magic_reset(self, parameter_s=''):
916 """Resets the namespace by removing all names defined by the user.
916 """Resets the namespace by removing all names defined by the user.
917
917
918 Input/Output history are left around in case you need them.
918 Input/Output history are left around in case you need them.
919
919
920 Parameters
920 Parameters
921 ----------
921 ----------
922 -y : force reset without asking for confirmation.
922 -y : force reset without asking for confirmation.
923
923
924 Examples
924 Examples
925 --------
925 --------
926 In [6]: a = 1
926 In [6]: a = 1
927
927
928 In [7]: a
928 In [7]: a
929 Out[7]: 1
929 Out[7]: 1
930
930
931 In [8]: 'a' in _ip.user_ns
931 In [8]: 'a' in _ip.user_ns
932 Out[8]: True
932 Out[8]: True
933
933
934 In [9]: %reset -f
934 In [9]: %reset -f
935
935
936 In [10]: 'a' in _ip.user_ns
936 In [10]: 'a' in _ip.user_ns
937 Out[10]: False
937 Out[10]: False
938 """
938 """
939
939
940 if parameter_s == '-f':
940 if parameter_s == '-f':
941 ans = True
941 ans = True
942 else:
942 else:
943 ans = self.shell.ask_yes_no(
943 ans = self.shell.ask_yes_no(
944 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
944 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
945 if not ans:
945 if not ans:
946 print 'Nothing done.'
946 print 'Nothing done.'
947 return
947 return
948 user_ns = self.shell.user_ns
948 user_ns = self.shell.user_ns
949 for i in self.magic_who_ls():
949 for i in self.magic_who_ls():
950 del(user_ns[i])
950 del(user_ns[i])
951
951
952 # Also flush the private list of module references kept for script
952 # Also flush the private list of module references kept for script
953 # execution protection
953 # execution protection
954 self.shell.clear_main_mod_cache()
954 self.shell.clear_main_mod_cache()
955
955
956 def magic_reset_selective(self, parameter_s=''):
956 def magic_reset_selective(self, parameter_s=''):
957 """Resets the namespace by removing names defined by the user.
957 """Resets the namespace by removing names defined by the user.
958
958
959 Input/Output history are left around in case you need them.
959 Input/Output history are left around in case you need them.
960
960
961 %reset_selective [-f] regex
961 %reset_selective [-f] regex
962
962
963 No action is taken if regex is not included
963 No action is taken if regex is not included
964
964
965 Options
965 Options
966 -f : force reset without asking for confirmation.
966 -f : force reset without asking for confirmation.
967
967
968 Examples
968 Examples
969 --------
969 --------
970
970
971 We first fully reset the namespace so your output looks identical to
971 We first fully reset the namespace so your output looks identical to
972 this example for pedagogical reasons; in practice you do not need a
972 this example for pedagogical reasons; in practice you do not need a
973 full reset.
973 full reset.
974
974
975 In [1]: %reset -f
975 In [1]: %reset -f
976
976
977 Now, with a clean namespace we can make a few variables and use
977 Now, with a clean namespace we can make a few variables and use
978 %reset_selective to only delete names that match our regexp:
978 %reset_selective to only delete names that match our regexp:
979
979
980 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
980 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
981
981
982 In [3]: who_ls
982 In [3]: who_ls
983 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
983 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
984
984
985 In [4]: %reset_selective -f b[2-3]m
985 In [4]: %reset_selective -f b[2-3]m
986
986
987 In [5]: who_ls
987 In [5]: who_ls
988 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
988 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
989
989
990 In [6]: %reset_selective -f d
990 In [6]: %reset_selective -f d
991
991
992 In [7]: who_ls
992 In [7]: who_ls
993 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
993 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
994
994
995 In [8]: %reset_selective -f c
995 In [8]: %reset_selective -f c
996
996
997 In [9]: who_ls
997 In [9]: who_ls
998 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
998 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
999
999
1000 In [10]: %reset_selective -f b
1000 In [10]: %reset_selective -f b
1001
1001
1002 In [11]: who_ls
1002 In [11]: who_ls
1003 Out[11]: ['a']
1003 Out[11]: ['a']
1004 """
1004 """
1005
1005
1006 opts, regex = self.parse_options(parameter_s,'f')
1006 opts, regex = self.parse_options(parameter_s,'f')
1007
1007
1008 if opts.has_key('f'):
1008 if opts.has_key('f'):
1009 ans = True
1009 ans = True
1010 else:
1010 else:
1011 ans = self.shell.ask_yes_no(
1011 ans = self.shell.ask_yes_no(
1012 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1012 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1013 if not ans:
1013 if not ans:
1014 print 'Nothing done.'
1014 print 'Nothing done.'
1015 return
1015 return
1016 user_ns = self.shell.user_ns
1016 user_ns = self.shell.user_ns
1017 if not regex:
1017 if not regex:
1018 print 'No regex pattern specified. Nothing done.'
1018 print 'No regex pattern specified. Nothing done.'
1019 return
1019 return
1020 else:
1020 else:
1021 try:
1021 try:
1022 m = re.compile(regex)
1022 m = re.compile(regex)
1023 except TypeError:
1023 except TypeError:
1024 raise TypeError('regex must be a string or compiled pattern')
1024 raise TypeError('regex must be a string or compiled pattern')
1025 for i in self.magic_who_ls():
1025 for i in self.magic_who_ls():
1026 if m.search(i):
1026 if m.search(i):
1027 del(user_ns[i])
1027 del(user_ns[i])
1028
1028
1029 def magic_logstart(self,parameter_s=''):
1029 def magic_logstart(self,parameter_s=''):
1030 """Start logging anywhere in a session.
1030 """Start logging anywhere in a session.
1031
1031
1032 %logstart [-o|-r|-t] [log_name [log_mode]]
1032 %logstart [-o|-r|-t] [log_name [log_mode]]
1033
1033
1034 If no name is given, it defaults to a file named 'ipython_log.py' in your
1034 If no name is given, it defaults to a file named 'ipython_log.py' in your
1035 current directory, in 'rotate' mode (see below).
1035 current directory, in 'rotate' mode (see below).
1036
1036
1037 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1037 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1038 history up to that point and then continues logging.
1038 history up to that point and then continues logging.
1039
1039
1040 %logstart takes a second optional parameter: logging mode. This can be one
1040 %logstart takes a second optional parameter: logging mode. This can be one
1041 of (note that the modes are given unquoted):\\
1041 of (note that the modes are given unquoted):\\
1042 append: well, that says it.\\
1042 append: well, that says it.\\
1043 backup: rename (if exists) to name~ and start name.\\
1043 backup: rename (if exists) to name~ and start name.\\
1044 global: single logfile in your home dir, appended to.\\
1044 global: single logfile in your home dir, appended to.\\
1045 over : overwrite existing log.\\
1045 over : overwrite existing log.\\
1046 rotate: create rotating logs name.1~, name.2~, etc.
1046 rotate: create rotating logs name.1~, name.2~, etc.
1047
1047
1048 Options:
1048 Options:
1049
1049
1050 -o: log also IPython's output. In this mode, all commands which
1050 -o: log also IPython's output. In this mode, all commands which
1051 generate an Out[NN] prompt are recorded to the logfile, right after
1051 generate an Out[NN] prompt are recorded to the logfile, right after
1052 their corresponding input line. The output lines are always
1052 their corresponding input line. The output lines are always
1053 prepended with a '#[Out]# ' marker, so that the log remains valid
1053 prepended with a '#[Out]# ' marker, so that the log remains valid
1054 Python code.
1054 Python code.
1055
1055
1056 Since this marker is always the same, filtering only the output from
1056 Since this marker is always the same, filtering only the output from
1057 a log is very easy, using for example a simple awk call:
1057 a log is very easy, using for example a simple awk call:
1058
1058
1059 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1059 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1060
1060
1061 -r: log 'raw' input. Normally, IPython's logs contain the processed
1061 -r: log 'raw' input. Normally, IPython's logs contain the processed
1062 input, so that user lines are logged in their final form, converted
1062 input, so that user lines are logged in their final form, converted
1063 into valid Python. For example, %Exit is logged as
1063 into valid Python. For example, %Exit is logged as
1064 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1064 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1065 exactly as typed, with no transformations applied.
1065 exactly as typed, with no transformations applied.
1066
1066
1067 -t: put timestamps before each input line logged (these are put in
1067 -t: put timestamps before each input line logged (these are put in
1068 comments)."""
1068 comments)."""
1069
1069
1070 opts,par = self.parse_options(parameter_s,'ort')
1070 opts,par = self.parse_options(parameter_s,'ort')
1071 log_output = 'o' in opts
1071 log_output = 'o' in opts
1072 log_raw_input = 'r' in opts
1072 log_raw_input = 'r' in opts
1073 timestamp = 't' in opts
1073 timestamp = 't' in opts
1074
1074
1075 logger = self.shell.logger
1075 logger = self.shell.logger
1076
1076
1077 # if no args are given, the defaults set in the logger constructor by
1077 # if no args are given, the defaults set in the logger constructor by
1078 # ipytohn remain valid
1078 # ipytohn remain valid
1079 if par:
1079 if par:
1080 try:
1080 try:
1081 logfname,logmode = par.split()
1081 logfname,logmode = par.split()
1082 except:
1082 except:
1083 logfname = par
1083 logfname = par
1084 logmode = 'backup'
1084 logmode = 'backup'
1085 else:
1085 else:
1086 logfname = logger.logfname
1086 logfname = logger.logfname
1087 logmode = logger.logmode
1087 logmode = logger.logmode
1088 # put logfname into rc struct as if it had been called on the command
1088 # put logfname into rc struct as if it had been called on the command
1089 # line, so it ends up saved in the log header Save it in case we need
1089 # line, so it ends up saved in the log header Save it in case we need
1090 # to restore it...
1090 # to restore it...
1091 old_logfile = self.shell.logfile
1091 old_logfile = self.shell.logfile
1092 if logfname:
1092 if logfname:
1093 logfname = os.path.expanduser(logfname)
1093 logfname = os.path.expanduser(logfname)
1094 self.shell.logfile = logfname
1094 self.shell.logfile = logfname
1095
1095
1096 loghead = '# IPython log file\n\n'
1096 loghead = '# IPython log file\n\n'
1097 try:
1097 try:
1098 started = logger.logstart(logfname,loghead,logmode,
1098 started = logger.logstart(logfname,loghead,logmode,
1099 log_output,timestamp,log_raw_input)
1099 log_output,timestamp,log_raw_input)
1100 except:
1100 except:
1101 self.shell.logfile = old_logfile
1101 self.shell.logfile = old_logfile
1102 warn("Couldn't start log: %s" % sys.exc_info()[1])
1102 warn("Couldn't start log: %s" % sys.exc_info()[1])
1103 else:
1103 else:
1104 # log input history up to this point, optionally interleaving
1104 # log input history up to this point, optionally interleaving
1105 # output if requested
1105 # output if requested
1106
1106
1107 if timestamp:
1107 if timestamp:
1108 # disable timestamping for the previous history, since we've
1108 # disable timestamping for the previous history, since we've
1109 # lost those already (no time machine here).
1109 # lost those already (no time machine here).
1110 logger.timestamp = False
1110 logger.timestamp = False
1111
1111
1112 if log_raw_input:
1112 if log_raw_input:
1113 input_hist = self.shell.input_hist_raw
1113 input_hist = self.shell.input_hist_raw
1114 else:
1114 else:
1115 input_hist = self.shell.input_hist
1115 input_hist = self.shell.input_hist
1116
1116
1117 if log_output:
1117 if log_output:
1118 log_write = logger.log_write
1118 log_write = logger.log_write
1119 output_hist = self.shell.output_hist
1119 output_hist = self.shell.output_hist
1120 for n in range(1,len(input_hist)-1):
1120 for n in range(1,len(input_hist)-1):
1121 log_write(input_hist[n].rstrip())
1121 log_write(input_hist[n].rstrip())
1122 if n in output_hist:
1122 if n in output_hist:
1123 log_write(repr(output_hist[n]),'output')
1123 log_write(repr(output_hist[n]),'output')
1124 else:
1124 else:
1125 logger.log_write(input_hist[1:])
1125 logger.log_write(input_hist[1:])
1126 if timestamp:
1126 if timestamp:
1127 # re-enable timestamping
1127 # re-enable timestamping
1128 logger.timestamp = True
1128 logger.timestamp = True
1129
1129
1130 print ('Activating auto-logging. '
1130 print ('Activating auto-logging. '
1131 'Current session state plus future input saved.')
1131 'Current session state plus future input saved.')
1132 logger.logstate()
1132 logger.logstate()
1133
1133
1134 def magic_logstop(self,parameter_s=''):
1134 def magic_logstop(self,parameter_s=''):
1135 """Fully stop logging and close log file.
1135 """Fully stop logging and close log file.
1136
1136
1137 In order to start logging again, a new %logstart call needs to be made,
1137 In order to start logging again, a new %logstart call needs to be made,
1138 possibly (though not necessarily) with a new filename, mode and other
1138 possibly (though not necessarily) with a new filename, mode and other
1139 options."""
1139 options."""
1140 self.logger.logstop()
1140 self.logger.logstop()
1141
1141
1142 def magic_logoff(self,parameter_s=''):
1142 def magic_logoff(self,parameter_s=''):
1143 """Temporarily stop logging.
1143 """Temporarily stop logging.
1144
1144
1145 You must have previously started logging."""
1145 You must have previously started logging."""
1146 self.shell.logger.switch_log(0)
1146 self.shell.logger.switch_log(0)
1147
1147
1148 def magic_logon(self,parameter_s=''):
1148 def magic_logon(self,parameter_s=''):
1149 """Restart logging.
1149 """Restart logging.
1150
1150
1151 This function is for restarting logging which you've temporarily
1151 This function is for restarting logging which you've temporarily
1152 stopped with %logoff. For starting logging for the first time, you
1152 stopped with %logoff. For starting logging for the first time, you
1153 must use the %logstart function, which allows you to specify an
1153 must use the %logstart function, which allows you to specify an
1154 optional log filename."""
1154 optional log filename."""
1155
1155
1156 self.shell.logger.switch_log(1)
1156 self.shell.logger.switch_log(1)
1157
1157
1158 def magic_logstate(self,parameter_s=''):
1158 def magic_logstate(self,parameter_s=''):
1159 """Print the status of the logging system."""
1159 """Print the status of the logging system."""
1160
1160
1161 self.shell.logger.logstate()
1161 self.shell.logger.logstate()
1162
1162
1163 def magic_pdb(self, parameter_s=''):
1163 def magic_pdb(self, parameter_s=''):
1164 """Control the automatic calling of the pdb interactive debugger.
1164 """Control the automatic calling of the pdb interactive debugger.
1165
1165
1166 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1166 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1167 argument it works as a toggle.
1167 argument it works as a toggle.
1168
1168
1169 When an exception is triggered, IPython can optionally call the
1169 When an exception is triggered, IPython can optionally call the
1170 interactive pdb debugger after the traceback printout. %pdb toggles
1170 interactive pdb debugger after the traceback printout. %pdb toggles
1171 this feature on and off.
1171 this feature on and off.
1172
1172
1173 The initial state of this feature is set in your ipythonrc
1173 The initial state of this feature is set in your ipythonrc
1174 configuration file (the variable is called 'pdb').
1174 configuration file (the variable is called 'pdb').
1175
1175
1176 If you want to just activate the debugger AFTER an exception has fired,
1176 If you want to just activate the debugger AFTER an exception has fired,
1177 without having to type '%pdb on' and rerunning your code, you can use
1177 without having to type '%pdb on' and rerunning your code, you can use
1178 the %debug magic."""
1178 the %debug magic."""
1179
1179
1180 par = parameter_s.strip().lower()
1180 par = parameter_s.strip().lower()
1181
1181
1182 if par:
1182 if par:
1183 try:
1183 try:
1184 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1184 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1185 except KeyError:
1185 except KeyError:
1186 print ('Incorrect argument. Use on/1, off/0, '
1186 print ('Incorrect argument. Use on/1, off/0, '
1187 'or nothing for a toggle.')
1187 'or nothing for a toggle.')
1188 return
1188 return
1189 else:
1189 else:
1190 # toggle
1190 # toggle
1191 new_pdb = not self.shell.call_pdb
1191 new_pdb = not self.shell.call_pdb
1192
1192
1193 # set on the shell
1193 # set on the shell
1194 self.shell.call_pdb = new_pdb
1194 self.shell.call_pdb = new_pdb
1195 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1195 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1196
1196
1197 def magic_debug(self, parameter_s=''):
1197 def magic_debug(self, parameter_s=''):
1198 """Activate the interactive debugger in post-mortem mode.
1198 """Activate the interactive debugger in post-mortem mode.
1199
1199
1200 If an exception has just occurred, this lets you inspect its stack
1200 If an exception has just occurred, this lets you inspect its stack
1201 frames interactively. Note that this will always work only on the last
1201 frames interactively. Note that this will always work only on the last
1202 traceback that occurred, so you must call this quickly after an
1202 traceback that occurred, so you must call this quickly after an
1203 exception that you wish to inspect has fired, because if another one
1203 exception that you wish to inspect has fired, because if another one
1204 occurs, it clobbers the previous one.
1204 occurs, it clobbers the previous one.
1205
1205
1206 If you want IPython to automatically do this on every exception, see
1206 If you want IPython to automatically do this on every exception, see
1207 the %pdb magic for more details.
1207 the %pdb magic for more details.
1208 """
1208 """
1209 self.shell.debugger(force=True)
1209 self.shell.debugger(force=True)
1210
1210
1211 @testdec.skip_doctest
1211 @testdec.skip_doctest
1212 def magic_prun(self, parameter_s ='',user_mode=1,
1212 def magic_prun(self, parameter_s ='',user_mode=1,
1213 opts=None,arg_lst=None,prog_ns=None):
1213 opts=None,arg_lst=None,prog_ns=None):
1214
1214
1215 """Run a statement through the python code profiler.
1215 """Run a statement through the python code profiler.
1216
1216
1217 Usage:
1217 Usage:
1218 %prun [options] statement
1218 %prun [options] statement
1219
1219
1220 The given statement (which doesn't require quote marks) is run via the
1220 The given statement (which doesn't require quote marks) is run via the
1221 python profiler in a manner similar to the profile.run() function.
1221 python profiler in a manner similar to the profile.run() function.
1222 Namespaces are internally managed to work correctly; profile.run
1222 Namespaces are internally managed to work correctly; profile.run
1223 cannot be used in IPython because it makes certain assumptions about
1223 cannot be used in IPython because it makes certain assumptions about
1224 namespaces which do not hold under IPython.
1224 namespaces which do not hold under IPython.
1225
1225
1226 Options:
1226 Options:
1227
1227
1228 -l <limit>: you can place restrictions on what or how much of the
1228 -l <limit>: you can place restrictions on what or how much of the
1229 profile gets printed. The limit value can be:
1229 profile gets printed. The limit value can be:
1230
1230
1231 * A string: only information for function names containing this string
1231 * A string: only information for function names containing this string
1232 is printed.
1232 is printed.
1233
1233
1234 * An integer: only these many lines are printed.
1234 * An integer: only these many lines are printed.
1235
1235
1236 * A float (between 0 and 1): this fraction of the report is printed
1236 * A float (between 0 and 1): this fraction of the report is printed
1237 (for example, use a limit of 0.4 to see the topmost 40% only).
1237 (for example, use a limit of 0.4 to see the topmost 40% only).
1238
1238
1239 You can combine several limits with repeated use of the option. For
1239 You can combine several limits with repeated use of the option. For
1240 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1240 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1241 information about class constructors.
1241 information about class constructors.
1242
1242
1243 -r: return the pstats.Stats object generated by the profiling. This
1243 -r: return the pstats.Stats object generated by the profiling. This
1244 object has all the information about the profile in it, and you can
1244 object has all the information about the profile in it, and you can
1245 later use it for further analysis or in other functions.
1245 later use it for further analysis or in other functions.
1246
1246
1247 -s <key>: sort profile by given key. You can provide more than one key
1247 -s <key>: sort profile by given key. You can provide more than one key
1248 by using the option several times: '-s key1 -s key2 -s key3...'. The
1248 by using the option several times: '-s key1 -s key2 -s key3...'. The
1249 default sorting key is 'time'.
1249 default sorting key is 'time'.
1250
1250
1251 The following is copied verbatim from the profile documentation
1251 The following is copied verbatim from the profile documentation
1252 referenced below:
1252 referenced below:
1253
1253
1254 When more than one key is provided, additional keys are used as
1254 When more than one key is provided, additional keys are used as
1255 secondary criteria when the there is equality in all keys selected
1255 secondary criteria when the there is equality in all keys selected
1256 before them.
1256 before them.
1257
1257
1258 Abbreviations can be used for any key names, as long as the
1258 Abbreviations can be used for any key names, as long as the
1259 abbreviation is unambiguous. The following are the keys currently
1259 abbreviation is unambiguous. The following are the keys currently
1260 defined:
1260 defined:
1261
1261
1262 Valid Arg Meaning
1262 Valid Arg Meaning
1263 "calls" call count
1263 "calls" call count
1264 "cumulative" cumulative time
1264 "cumulative" cumulative time
1265 "file" file name
1265 "file" file name
1266 "module" file name
1266 "module" file name
1267 "pcalls" primitive call count
1267 "pcalls" primitive call count
1268 "line" line number
1268 "line" line number
1269 "name" function name
1269 "name" function name
1270 "nfl" name/file/line
1270 "nfl" name/file/line
1271 "stdname" standard name
1271 "stdname" standard name
1272 "time" internal time
1272 "time" internal time
1273
1273
1274 Note that all sorts on statistics are in descending order (placing
1274 Note that all sorts on statistics are in descending order (placing
1275 most time consuming items first), where as name, file, and line number
1275 most time consuming items first), where as name, file, and line number
1276 searches are in ascending order (i.e., alphabetical). The subtle
1276 searches are in ascending order (i.e., alphabetical). The subtle
1277 distinction between "nfl" and "stdname" is that the standard name is a
1277 distinction between "nfl" and "stdname" is that the standard name is a
1278 sort of the name as printed, which means that the embedded line
1278 sort of the name as printed, which means that the embedded line
1279 numbers get compared in an odd way. For example, lines 3, 20, and 40
1279 numbers get compared in an odd way. For example, lines 3, 20, and 40
1280 would (if the file names were the same) appear in the string order
1280 would (if the file names were the same) appear in the string order
1281 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1281 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1282 line numbers. In fact, sort_stats("nfl") is the same as
1282 line numbers. In fact, sort_stats("nfl") is the same as
1283 sort_stats("name", "file", "line").
1283 sort_stats("name", "file", "line").
1284
1284
1285 -T <filename>: save profile results as shown on screen to a text
1285 -T <filename>: save profile results as shown on screen to a text
1286 file. The profile is still shown on screen.
1286 file. The profile is still shown on screen.
1287
1287
1288 -D <filename>: save (via dump_stats) profile statistics to given
1288 -D <filename>: save (via dump_stats) profile statistics to given
1289 filename. This data is in a format understod by the pstats module, and
1289 filename. This data is in a format understod by the pstats module, and
1290 is generated by a call to the dump_stats() method of profile
1290 is generated by a call to the dump_stats() method of profile
1291 objects. The profile is still shown on screen.
1291 objects. The profile is still shown on screen.
1292
1292
1293 If you want to run complete programs under the profiler's control, use
1293 If you want to run complete programs under the profiler's control, use
1294 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1294 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1295 contains profiler specific options as described here.
1295 contains profiler specific options as described here.
1296
1296
1297 You can read the complete documentation for the profile module with::
1297 You can read the complete documentation for the profile module with::
1298
1298
1299 In [1]: import profile; profile.help()
1299 In [1]: import profile; profile.help()
1300 """
1300 """
1301
1301
1302 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1302 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1303 # protect user quote marks
1303 # protect user quote marks
1304 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1304 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1305
1305
1306 if user_mode: # regular user call
1306 if user_mode: # regular user call
1307 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1307 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1308 list_all=1)
1308 list_all=1)
1309 namespace = self.shell.user_ns
1309 namespace = self.shell.user_ns
1310 else: # called to run a program by %run -p
1310 else: # called to run a program by %run -p
1311 try:
1311 try:
1312 filename = get_py_filename(arg_lst[0])
1312 filename = get_py_filename(arg_lst[0])
1313 except IOError,msg:
1313 except IOError,msg:
1314 error(msg)
1314 error(msg)
1315 return
1315 return
1316
1316
1317 arg_str = 'execfile(filename,prog_ns)'
1317 arg_str = 'execfile(filename,prog_ns)'
1318 namespace = locals()
1318 namespace = locals()
1319
1319
1320 opts.merge(opts_def)
1320 opts.merge(opts_def)
1321
1321
1322 prof = profile.Profile()
1322 prof = profile.Profile()
1323 try:
1323 try:
1324 prof = prof.runctx(arg_str,namespace,namespace)
1324 prof = prof.runctx(arg_str,namespace,namespace)
1325 sys_exit = ''
1325 sys_exit = ''
1326 except SystemExit:
1326 except SystemExit:
1327 sys_exit = """*** SystemExit exception caught in code being profiled."""
1327 sys_exit = """*** SystemExit exception caught in code being profiled."""
1328
1328
1329 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1329 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1330
1330
1331 lims = opts.l
1331 lims = opts.l
1332 if lims:
1332 if lims:
1333 lims = [] # rebuild lims with ints/floats/strings
1333 lims = [] # rebuild lims with ints/floats/strings
1334 for lim in opts.l:
1334 for lim in opts.l:
1335 try:
1335 try:
1336 lims.append(int(lim))
1336 lims.append(int(lim))
1337 except ValueError:
1337 except ValueError:
1338 try:
1338 try:
1339 lims.append(float(lim))
1339 lims.append(float(lim))
1340 except ValueError:
1340 except ValueError:
1341 lims.append(lim)
1341 lims.append(lim)
1342
1342
1343 # Trap output.
1343 # Trap output.
1344 stdout_trap = StringIO()
1344 stdout_trap = StringIO()
1345
1345
1346 if hasattr(stats,'stream'):
1346 if hasattr(stats,'stream'):
1347 # In newer versions of python, the stats object has a 'stream'
1347 # In newer versions of python, the stats object has a 'stream'
1348 # attribute to write into.
1348 # attribute to write into.
1349 stats.stream = stdout_trap
1349 stats.stream = stdout_trap
1350 stats.print_stats(*lims)
1350 stats.print_stats(*lims)
1351 else:
1351 else:
1352 # For older versions, we manually redirect stdout during printing
1352 # For older versions, we manually redirect stdout during printing
1353 sys_stdout = sys.stdout
1353 sys_stdout = sys.stdout
1354 try:
1354 try:
1355 sys.stdout = stdout_trap
1355 sys.stdout = stdout_trap
1356 stats.print_stats(*lims)
1356 stats.print_stats(*lims)
1357 finally:
1357 finally:
1358 sys.stdout = sys_stdout
1358 sys.stdout = sys_stdout
1359
1359
1360 output = stdout_trap.getvalue()
1360 output = stdout_trap.getvalue()
1361 output = output.rstrip()
1361 output = output.rstrip()
1362
1362
1363 page.page(output)
1363 page.page(output)
1364 print sys_exit,
1364 print sys_exit,
1365
1365
1366 dump_file = opts.D[0]
1366 dump_file = opts.D[0]
1367 text_file = opts.T[0]
1367 text_file = opts.T[0]
1368 if dump_file:
1368 if dump_file:
1369 prof.dump_stats(dump_file)
1369 prof.dump_stats(dump_file)
1370 print '\n*** Profile stats marshalled to file',\
1370 print '\n*** Profile stats marshalled to file',\
1371 `dump_file`+'.',sys_exit
1371 `dump_file`+'.',sys_exit
1372 if text_file:
1372 if text_file:
1373 pfile = file(text_file,'w')
1373 pfile = file(text_file,'w')
1374 pfile.write(output)
1374 pfile.write(output)
1375 pfile.close()
1375 pfile.close()
1376 print '\n*** Profile printout saved to text file',\
1376 print '\n*** Profile printout saved to text file',\
1377 `text_file`+'.',sys_exit
1377 `text_file`+'.',sys_exit
1378
1378
1379 if opts.has_key('r'):
1379 if opts.has_key('r'):
1380 return stats
1380 return stats
1381 else:
1381 else:
1382 return None
1382 return None
1383
1383
1384 @testdec.skip_doctest
1384 @testdec.skip_doctest
1385 def magic_run(self, parameter_s ='',runner=None,
1385 def magic_run(self, parameter_s ='',runner=None,
1386 file_finder=get_py_filename):
1386 file_finder=get_py_filename):
1387 """Run the named file inside IPython as a program.
1387 """Run the named file inside IPython as a program.
1388
1388
1389 Usage:\\
1389 Usage:\\
1390 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1390 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1391
1391
1392 Parameters after the filename are passed as command-line arguments to
1392 Parameters after the filename are passed as command-line arguments to
1393 the program (put in sys.argv). Then, control returns to IPython's
1393 the program (put in sys.argv). Then, control returns to IPython's
1394 prompt.
1394 prompt.
1395
1395
1396 This is similar to running at a system prompt:\\
1396 This is similar to running at a system prompt:\\
1397 $ python file args\\
1397 $ python file args\\
1398 but with the advantage of giving you IPython's tracebacks, and of
1398 but with the advantage of giving you IPython's tracebacks, and of
1399 loading all variables into your interactive namespace for further use
1399 loading all variables into your interactive namespace for further use
1400 (unless -p is used, see below).
1400 (unless -p is used, see below).
1401
1401
1402 The file is executed in a namespace initially consisting only of
1402 The file is executed in a namespace initially consisting only of
1403 __name__=='__main__' and sys.argv constructed as indicated. It thus
1403 __name__=='__main__' and sys.argv constructed as indicated. It thus
1404 sees its environment as if it were being run as a stand-alone program
1404 sees its environment as if it were being run as a stand-alone program
1405 (except for sharing global objects such as previously imported
1405 (except for sharing global objects such as previously imported
1406 modules). But after execution, the IPython interactive namespace gets
1406 modules). But after execution, the IPython interactive namespace gets
1407 updated with all variables defined in the program (except for __name__
1407 updated with all variables defined in the program (except for __name__
1408 and sys.argv). This allows for very convenient loading of code for
1408 and sys.argv). This allows for very convenient loading of code for
1409 interactive work, while giving each program a 'clean sheet' to run in.
1409 interactive work, while giving each program a 'clean sheet' to run in.
1410
1410
1411 Options:
1411 Options:
1412
1412
1413 -n: __name__ is NOT set to '__main__', but to the running file's name
1413 -n: __name__ is NOT set to '__main__', but to the running file's name
1414 without extension (as python does under import). This allows running
1414 without extension (as python does under import). This allows running
1415 scripts and reloading the definitions in them without calling code
1415 scripts and reloading the definitions in them without calling code
1416 protected by an ' if __name__ == "__main__" ' clause.
1416 protected by an ' if __name__ == "__main__" ' clause.
1417
1417
1418 -i: run the file in IPython's namespace instead of an empty one. This
1418 -i: run the file in IPython's namespace instead of an empty one. This
1419 is useful if you are experimenting with code written in a text editor
1419 is useful if you are experimenting with code written in a text editor
1420 which depends on variables defined interactively.
1420 which depends on variables defined interactively.
1421
1421
1422 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1422 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1423 being run. This is particularly useful if IPython is being used to
1423 being run. This is particularly useful if IPython is being used to
1424 run unittests, which always exit with a sys.exit() call. In such
1424 run unittests, which always exit with a sys.exit() call. In such
1425 cases you are interested in the output of the test results, not in
1425 cases you are interested in the output of the test results, not in
1426 seeing a traceback of the unittest module.
1426 seeing a traceback of the unittest module.
1427
1427
1428 -t: print timing information at the end of the run. IPython will give
1428 -t: print timing information at the end of the run. IPython will give
1429 you an estimated CPU time consumption for your script, which under
1429 you an estimated CPU time consumption for your script, which under
1430 Unix uses the resource module to avoid the wraparound problems of
1430 Unix uses the resource module to avoid the wraparound problems of
1431 time.clock(). Under Unix, an estimate of time spent on system tasks
1431 time.clock(). Under Unix, an estimate of time spent on system tasks
1432 is also given (for Windows platforms this is reported as 0.0).
1432 is also given (for Windows platforms this is reported as 0.0).
1433
1433
1434 If -t is given, an additional -N<N> option can be given, where <N>
1434 If -t is given, an additional -N<N> option can be given, where <N>
1435 must be an integer indicating how many times you want the script to
1435 must be an integer indicating how many times you want the script to
1436 run. The final timing report will include total and per run results.
1436 run. The final timing report will include total and per run results.
1437
1437
1438 For example (testing the script uniq_stable.py):
1438 For example (testing the script uniq_stable.py):
1439
1439
1440 In [1]: run -t uniq_stable
1440 In [1]: run -t uniq_stable
1441
1441
1442 IPython CPU timings (estimated):\\
1442 IPython CPU timings (estimated):\\
1443 User : 0.19597 s.\\
1443 User : 0.19597 s.\\
1444 System: 0.0 s.\\
1444 System: 0.0 s.\\
1445
1445
1446 In [2]: run -t -N5 uniq_stable
1446 In [2]: run -t -N5 uniq_stable
1447
1447
1448 IPython CPU timings (estimated):\\
1448 IPython CPU timings (estimated):\\
1449 Total runs performed: 5\\
1449 Total runs performed: 5\\
1450 Times : Total Per run\\
1450 Times : Total Per run\\
1451 User : 0.910862 s, 0.1821724 s.\\
1451 User : 0.910862 s, 0.1821724 s.\\
1452 System: 0.0 s, 0.0 s.
1452 System: 0.0 s, 0.0 s.
1453
1453
1454 -d: run your program under the control of pdb, the Python debugger.
1454 -d: run your program under the control of pdb, the Python debugger.
1455 This allows you to execute your program step by step, watch variables,
1455 This allows you to execute your program step by step, watch variables,
1456 etc. Internally, what IPython does is similar to calling:
1456 etc. Internally, what IPython does is similar to calling:
1457
1457
1458 pdb.run('execfile("YOURFILENAME")')
1458 pdb.run('execfile("YOURFILENAME")')
1459
1459
1460 with a breakpoint set on line 1 of your file. You can change the line
1460 with a breakpoint set on line 1 of your file. You can change the line
1461 number for this automatic breakpoint to be <N> by using the -bN option
1461 number for this automatic breakpoint to be <N> by using the -bN option
1462 (where N must be an integer). For example:
1462 (where N must be an integer). For example:
1463
1463
1464 %run -d -b40 myscript
1464 %run -d -b40 myscript
1465
1465
1466 will set the first breakpoint at line 40 in myscript.py. Note that
1466 will set the first breakpoint at line 40 in myscript.py. Note that
1467 the first breakpoint must be set on a line which actually does
1467 the first breakpoint must be set on a line which actually does
1468 something (not a comment or docstring) for it to stop execution.
1468 something (not a comment or docstring) for it to stop execution.
1469
1469
1470 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1470 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1471 first enter 'c' (without qoutes) to start execution up to the first
1471 first enter 'c' (without qoutes) to start execution up to the first
1472 breakpoint.
1472 breakpoint.
1473
1473
1474 Entering 'help' gives information about the use of the debugger. You
1474 Entering 'help' gives information about the use of the debugger. You
1475 can easily see pdb's full documentation with "import pdb;pdb.help()"
1475 can easily see pdb's full documentation with "import pdb;pdb.help()"
1476 at a prompt.
1476 at a prompt.
1477
1477
1478 -p: run program under the control of the Python profiler module (which
1478 -p: run program under the control of the Python profiler module (which
1479 prints a detailed report of execution times, function calls, etc).
1479 prints a detailed report of execution times, function calls, etc).
1480
1480
1481 You can pass other options after -p which affect the behavior of the
1481 You can pass other options after -p which affect the behavior of the
1482 profiler itself. See the docs for %prun for details.
1482 profiler itself. See the docs for %prun for details.
1483
1483
1484 In this mode, the program's variables do NOT propagate back to the
1484 In this mode, the program's variables do NOT propagate back to the
1485 IPython interactive namespace (because they remain in the namespace
1485 IPython interactive namespace (because they remain in the namespace
1486 where the profiler executes them).
1486 where the profiler executes them).
1487
1487
1488 Internally this triggers a call to %prun, see its documentation for
1488 Internally this triggers a call to %prun, see its documentation for
1489 details on the options available specifically for profiling.
1489 details on the options available specifically for profiling.
1490
1490
1491 There is one special usage for which the text above doesn't apply:
1491 There is one special usage for which the text above doesn't apply:
1492 if the filename ends with .ipy, the file is run as ipython script,
1492 if the filename ends with .ipy, the file is run as ipython script,
1493 just as if the commands were written on IPython prompt.
1493 just as if the commands were written on IPython prompt.
1494 """
1494 """
1495
1495
1496 # get arguments and set sys.argv for program to be run.
1496 # get arguments and set sys.argv for program to be run.
1497 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1497 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1498 mode='list',list_all=1)
1498 mode='list',list_all=1)
1499
1499
1500 try:
1500 try:
1501 filename = file_finder(arg_lst[0])
1501 filename = file_finder(arg_lst[0])
1502 except IndexError:
1502 except IndexError:
1503 warn('you must provide at least a filename.')
1503 warn('you must provide at least a filename.')
1504 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1504 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1505 return
1505 return
1506 except IOError,msg:
1506 except IOError,msg:
1507 error(msg)
1507 error(msg)
1508 return
1508 return
1509
1509
1510 if filename.lower().endswith('.ipy'):
1510 if filename.lower().endswith('.ipy'):
1511 self.shell.safe_execfile_ipy(filename)
1511 self.shell.safe_execfile_ipy(filename)
1512 return
1512 return
1513
1513
1514 # Control the response to exit() calls made by the script being run
1514 # Control the response to exit() calls made by the script being run
1515 exit_ignore = opts.has_key('e')
1515 exit_ignore = opts.has_key('e')
1516
1516
1517 # Make sure that the running script gets a proper sys.argv as if it
1517 # Make sure that the running script gets a proper sys.argv as if it
1518 # were run from a system shell.
1518 # were run from a system shell.
1519 save_argv = sys.argv # save it for later restoring
1519 save_argv = sys.argv # save it for later restoring
1520 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1520 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1521
1521
1522 if opts.has_key('i'):
1522 if opts.has_key('i'):
1523 # Run in user's interactive namespace
1523 # Run in user's interactive namespace
1524 prog_ns = self.shell.user_ns
1524 prog_ns = self.shell.user_ns
1525 __name__save = self.shell.user_ns['__name__']
1525 __name__save = self.shell.user_ns['__name__']
1526 prog_ns['__name__'] = '__main__'
1526 prog_ns['__name__'] = '__main__'
1527 main_mod = self.shell.new_main_mod(prog_ns)
1527 main_mod = self.shell.new_main_mod(prog_ns)
1528 else:
1528 else:
1529 # Run in a fresh, empty namespace
1529 # Run in a fresh, empty namespace
1530 if opts.has_key('n'):
1530 if opts.has_key('n'):
1531 name = os.path.splitext(os.path.basename(filename))[0]
1531 name = os.path.splitext(os.path.basename(filename))[0]
1532 else:
1532 else:
1533 name = '__main__'
1533 name = '__main__'
1534
1534
1535 main_mod = self.shell.new_main_mod()
1535 main_mod = self.shell.new_main_mod()
1536 prog_ns = main_mod.__dict__
1536 prog_ns = main_mod.__dict__
1537 prog_ns['__name__'] = name
1537 prog_ns['__name__'] = name
1538
1538
1539 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1539 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1540 # set the __file__ global in the script's namespace
1540 # set the __file__ global in the script's namespace
1541 prog_ns['__file__'] = filename
1541 prog_ns['__file__'] = filename
1542
1542
1543 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1543 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1544 # that, if we overwrite __main__, we replace it at the end
1544 # that, if we overwrite __main__, we replace it at the end
1545 main_mod_name = prog_ns['__name__']
1545 main_mod_name = prog_ns['__name__']
1546
1546
1547 if main_mod_name == '__main__':
1547 if main_mod_name == '__main__':
1548 restore_main = sys.modules['__main__']
1548 restore_main = sys.modules['__main__']
1549 else:
1549 else:
1550 restore_main = False
1550 restore_main = False
1551
1551
1552 # This needs to be undone at the end to prevent holding references to
1552 # This needs to be undone at the end to prevent holding references to
1553 # every single object ever created.
1553 # every single object ever created.
1554 sys.modules[main_mod_name] = main_mod
1554 sys.modules[main_mod_name] = main_mod
1555
1555
1556 stats = None
1556 stats = None
1557 try:
1557 try:
1558 self.shell.savehist()
1558 self.shell.savehist()
1559
1559
1560 if opts.has_key('p'):
1560 if opts.has_key('p'):
1561 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1561 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1562 else:
1562 else:
1563 if opts.has_key('d'):
1563 if opts.has_key('d'):
1564 deb = debugger.Pdb(self.shell.colors)
1564 deb = debugger.Pdb(self.shell.colors)
1565 # reset Breakpoint state, which is moronically kept
1565 # reset Breakpoint state, which is moronically kept
1566 # in a class
1566 # in a class
1567 bdb.Breakpoint.next = 1
1567 bdb.Breakpoint.next = 1
1568 bdb.Breakpoint.bplist = {}
1568 bdb.Breakpoint.bplist = {}
1569 bdb.Breakpoint.bpbynumber = [None]
1569 bdb.Breakpoint.bpbynumber = [None]
1570 # Set an initial breakpoint to stop execution
1570 # Set an initial breakpoint to stop execution
1571 maxtries = 10
1571 maxtries = 10
1572 bp = int(opts.get('b',[1])[0])
1572 bp = int(opts.get('b',[1])[0])
1573 checkline = deb.checkline(filename,bp)
1573 checkline = deb.checkline(filename,bp)
1574 if not checkline:
1574 if not checkline:
1575 for bp in range(bp+1,bp+maxtries+1):
1575 for bp in range(bp+1,bp+maxtries+1):
1576 if deb.checkline(filename,bp):
1576 if deb.checkline(filename,bp):
1577 break
1577 break
1578 else:
1578 else:
1579 msg = ("\nI failed to find a valid line to set "
1579 msg = ("\nI failed to find a valid line to set "
1580 "a breakpoint\n"
1580 "a breakpoint\n"
1581 "after trying up to line: %s.\n"
1581 "after trying up to line: %s.\n"
1582 "Please set a valid breakpoint manually "
1582 "Please set a valid breakpoint manually "
1583 "with the -b option." % bp)
1583 "with the -b option." % bp)
1584 error(msg)
1584 error(msg)
1585 return
1585 return
1586 # if we find a good linenumber, set the breakpoint
1586 # if we find a good linenumber, set the breakpoint
1587 deb.do_break('%s:%s' % (filename,bp))
1587 deb.do_break('%s:%s' % (filename,bp))
1588 # Start file run
1588 # Start file run
1589 print "NOTE: Enter 'c' at the",
1589 print "NOTE: Enter 'c' at the",
1590 print "%s prompt to start your script." % deb.prompt
1590 print "%s prompt to start your script." % deb.prompt
1591 try:
1591 try:
1592 deb.run('execfile("%s")' % filename,prog_ns)
1592 deb.run('execfile("%s")' % filename,prog_ns)
1593
1593
1594 except:
1594 except:
1595 etype, value, tb = sys.exc_info()
1595 etype, value, tb = sys.exc_info()
1596 # Skip three frames in the traceback: the %run one,
1596 # Skip three frames in the traceback: the %run one,
1597 # one inside bdb.py, and the command-line typed by the
1597 # one inside bdb.py, and the command-line typed by the
1598 # user (run by exec in pdb itself).
1598 # user (run by exec in pdb itself).
1599 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1599 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1600 else:
1600 else:
1601 if runner is None:
1601 if runner is None:
1602 runner = self.shell.safe_execfile
1602 runner = self.shell.safe_execfile
1603 if opts.has_key('t'):
1603 if opts.has_key('t'):
1604 # timed execution
1604 # timed execution
1605 try:
1605 try:
1606 nruns = int(opts['N'][0])
1606 nruns = int(opts['N'][0])
1607 if nruns < 1:
1607 if nruns < 1:
1608 error('Number of runs must be >=1')
1608 error('Number of runs must be >=1')
1609 return
1609 return
1610 except (KeyError):
1610 except (KeyError):
1611 nruns = 1
1611 nruns = 1
1612 if nruns == 1:
1612 if nruns == 1:
1613 t0 = clock2()
1613 t0 = clock2()
1614 runner(filename,prog_ns,prog_ns,
1614 runner(filename,prog_ns,prog_ns,
1615 exit_ignore=exit_ignore)
1615 exit_ignore=exit_ignore)
1616 t1 = clock2()
1616 t1 = clock2()
1617 t_usr = t1[0]-t0[0]
1617 t_usr = t1[0]-t0[0]
1618 t_sys = t1[1]-t0[1]
1618 t_sys = t1[1]-t0[1]
1619 print "\nIPython CPU timings (estimated):"
1619 print "\nIPython CPU timings (estimated):"
1620 print " User : %10s s." % t_usr
1620 print " User : %10s s." % t_usr
1621 print " System: %10s s." % t_sys
1621 print " System: %10s s." % t_sys
1622 else:
1622 else:
1623 runs = range(nruns)
1623 runs = range(nruns)
1624 t0 = clock2()
1624 t0 = clock2()
1625 for nr in runs:
1625 for nr in runs:
1626 runner(filename,prog_ns,prog_ns,
1626 runner(filename,prog_ns,prog_ns,
1627 exit_ignore=exit_ignore)
1627 exit_ignore=exit_ignore)
1628 t1 = clock2()
1628 t1 = clock2()
1629 t_usr = t1[0]-t0[0]
1629 t_usr = t1[0]-t0[0]
1630 t_sys = t1[1]-t0[1]
1630 t_sys = t1[1]-t0[1]
1631 print "\nIPython CPU timings (estimated):"
1631 print "\nIPython CPU timings (estimated):"
1632 print "Total runs performed:",nruns
1632 print "Total runs performed:",nruns
1633 print " Times : %10s %10s" % ('Total','Per run')
1633 print " Times : %10s %10s" % ('Total','Per run')
1634 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1634 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1635 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1635 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1636
1636
1637 else:
1637 else:
1638 # regular execution
1638 # regular execution
1639 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1639 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1640
1640
1641 if opts.has_key('i'):
1641 if opts.has_key('i'):
1642 self.shell.user_ns['__name__'] = __name__save
1642 self.shell.user_ns['__name__'] = __name__save
1643 else:
1643 else:
1644 # The shell MUST hold a reference to prog_ns so after %run
1644 # The shell MUST hold a reference to prog_ns so after %run
1645 # exits, the python deletion mechanism doesn't zero it out
1645 # exits, the python deletion mechanism doesn't zero it out
1646 # (leaving dangling references).
1646 # (leaving dangling references).
1647 self.shell.cache_main_mod(prog_ns,filename)
1647 self.shell.cache_main_mod(prog_ns,filename)
1648 # update IPython interactive namespace
1648 # update IPython interactive namespace
1649
1649
1650 # Some forms of read errors on the file may mean the
1650 # Some forms of read errors on the file may mean the
1651 # __name__ key was never set; using pop we don't have to
1651 # __name__ key was never set; using pop we don't have to
1652 # worry about a possible KeyError.
1652 # worry about a possible KeyError.
1653 prog_ns.pop('__name__', None)
1653 prog_ns.pop('__name__', None)
1654
1654
1655 self.shell.user_ns.update(prog_ns)
1655 self.shell.user_ns.update(prog_ns)
1656 finally:
1656 finally:
1657 # It's a bit of a mystery why, but __builtins__ can change from
1657 # It's a bit of a mystery why, but __builtins__ can change from
1658 # being a module to becoming a dict missing some key data after
1658 # being a module to becoming a dict missing some key data after
1659 # %run. As best I can see, this is NOT something IPython is doing
1659 # %run. As best I can see, this is NOT something IPython is doing
1660 # at all, and similar problems have been reported before:
1660 # at all, and similar problems have been reported before:
1661 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1661 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1662 # Since this seems to be done by the interpreter itself, the best
1662 # Since this seems to be done by the interpreter itself, the best
1663 # we can do is to at least restore __builtins__ for the user on
1663 # we can do is to at least restore __builtins__ for the user on
1664 # exit.
1664 # exit.
1665 self.shell.user_ns['__builtins__'] = __builtin__
1665 self.shell.user_ns['__builtins__'] = __builtin__
1666
1666
1667 # Ensure key global structures are restored
1667 # Ensure key global structures are restored
1668 sys.argv = save_argv
1668 sys.argv = save_argv
1669 if restore_main:
1669 if restore_main:
1670 sys.modules['__main__'] = restore_main
1670 sys.modules['__main__'] = restore_main
1671 else:
1671 else:
1672 # Remove from sys.modules the reference to main_mod we'd
1672 # Remove from sys.modules the reference to main_mod we'd
1673 # added. Otherwise it will trap references to objects
1673 # added. Otherwise it will trap references to objects
1674 # contained therein.
1674 # contained therein.
1675 del sys.modules[main_mod_name]
1675 del sys.modules[main_mod_name]
1676
1676
1677 self.shell.reloadhist()
1677 self.shell.reloadhist()
1678
1678
1679 return stats
1679 return stats
1680
1680
1681 @testdec.skip_doctest
1681 @testdec.skip_doctest
1682 def magic_timeit(self, parameter_s =''):
1682 def magic_timeit(self, parameter_s =''):
1683 """Time execution of a Python statement or expression
1683 """Time execution of a Python statement or expression
1684
1684
1685 Usage:\\
1685 Usage:\\
1686 %timeit [-n<N> -r<R> [-t|-c]] statement
1686 %timeit [-n<N> -r<R> [-t|-c]] statement
1687
1687
1688 Time execution of a Python statement or expression using the timeit
1688 Time execution of a Python statement or expression using the timeit
1689 module.
1689 module.
1690
1690
1691 Options:
1691 Options:
1692 -n<N>: execute the given statement <N> times in a loop. If this value
1692 -n<N>: execute the given statement <N> times in a loop. If this value
1693 is not given, a fitting value is chosen.
1693 is not given, a fitting value is chosen.
1694
1694
1695 -r<R>: repeat the loop iteration <R> times and take the best result.
1695 -r<R>: repeat the loop iteration <R> times and take the best result.
1696 Default: 3
1696 Default: 3
1697
1697
1698 -t: use time.time to measure the time, which is the default on Unix.
1698 -t: use time.time to measure the time, which is the default on Unix.
1699 This function measures wall time.
1699 This function measures wall time.
1700
1700
1701 -c: use time.clock to measure the time, which is the default on
1701 -c: use time.clock to measure the time, which is the default on
1702 Windows and measures wall time. On Unix, resource.getrusage is used
1702 Windows and measures wall time. On Unix, resource.getrusage is used
1703 instead and returns the CPU user time.
1703 instead and returns the CPU user time.
1704
1704
1705 -p<P>: use a precision of <P> digits to display the timing result.
1705 -p<P>: use a precision of <P> digits to display the timing result.
1706 Default: 3
1706 Default: 3
1707
1707
1708
1708
1709 Examples:
1709 Examples:
1710
1710
1711 In [1]: %timeit pass
1711 In [1]: %timeit pass
1712 10000000 loops, best of 3: 53.3 ns per loop
1712 10000000 loops, best of 3: 53.3 ns per loop
1713
1713
1714 In [2]: u = None
1714 In [2]: u = None
1715
1715
1716 In [3]: %timeit u is None
1716 In [3]: %timeit u is None
1717 10000000 loops, best of 3: 184 ns per loop
1717 10000000 loops, best of 3: 184 ns per loop
1718
1718
1719 In [4]: %timeit -r 4 u == None
1719 In [4]: %timeit -r 4 u == None
1720 1000000 loops, best of 4: 242 ns per loop
1720 1000000 loops, best of 4: 242 ns per loop
1721
1721
1722 In [5]: import time
1722 In [5]: import time
1723
1723
1724 In [6]: %timeit -n1 time.sleep(2)
1724 In [6]: %timeit -n1 time.sleep(2)
1725 1 loops, best of 3: 2 s per loop
1725 1 loops, best of 3: 2 s per loop
1726
1726
1727
1727
1728 The times reported by %timeit will be slightly higher than those
1728 The times reported by %timeit will be slightly higher than those
1729 reported by the timeit.py script when variables are accessed. This is
1729 reported by the timeit.py script when variables are accessed. This is
1730 due to the fact that %timeit executes the statement in the namespace
1730 due to the fact that %timeit executes the statement in the namespace
1731 of the shell, compared with timeit.py, which uses a single setup
1731 of the shell, compared with timeit.py, which uses a single setup
1732 statement to import function or create variables. Generally, the bias
1732 statement to import function or create variables. Generally, the bias
1733 does not matter as long as results from timeit.py are not mixed with
1733 does not matter as long as results from timeit.py are not mixed with
1734 those from %timeit."""
1734 those from %timeit."""
1735
1735
1736 import timeit
1736 import timeit
1737 import math
1737 import math
1738
1738
1739 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1739 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1740 # certain terminals. Until we figure out a robust way of
1740 # certain terminals. Until we figure out a robust way of
1741 # auto-detecting if the terminal can deal with it, use plain 'us' for
1741 # auto-detecting if the terminal can deal with it, use plain 'us' for
1742 # microseconds. I am really NOT happy about disabling the proper
1742 # microseconds. I am really NOT happy about disabling the proper
1743 # 'micro' prefix, but crashing is worse... If anyone knows what the
1743 # 'micro' prefix, but crashing is worse... If anyone knows what the
1744 # right solution for this is, I'm all ears...
1744 # right solution for this is, I'm all ears...
1745 #
1745 #
1746 # Note: using
1746 # Note: using
1747 #
1747 #
1748 # s = u'\xb5'
1748 # s = u'\xb5'
1749 # s.encode(sys.getdefaultencoding())
1749 # s.encode(sys.getdefaultencoding())
1750 #
1750 #
1751 # is not sufficient, as I've seen terminals where that fails but
1751 # is not sufficient, as I've seen terminals where that fails but
1752 # print s
1752 # print s
1753 #
1753 #
1754 # succeeds
1754 # succeeds
1755 #
1755 #
1756 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1756 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1757
1757
1758 #units = [u"s", u"ms",u'\xb5',"ns"]
1758 #units = [u"s", u"ms",u'\xb5',"ns"]
1759 units = [u"s", u"ms",u'us',"ns"]
1759 units = [u"s", u"ms",u'us',"ns"]
1760
1760
1761 scaling = [1, 1e3, 1e6, 1e9]
1761 scaling = [1, 1e3, 1e6, 1e9]
1762
1762
1763 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1763 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1764 posix=False)
1764 posix=False)
1765 if stmt == "":
1765 if stmt == "":
1766 return
1766 return
1767 timefunc = timeit.default_timer
1767 timefunc = timeit.default_timer
1768 number = int(getattr(opts, "n", 0))
1768 number = int(getattr(opts, "n", 0))
1769 repeat = int(getattr(opts, "r", timeit.default_repeat))
1769 repeat = int(getattr(opts, "r", timeit.default_repeat))
1770 precision = int(getattr(opts, "p", 3))
1770 precision = int(getattr(opts, "p", 3))
1771 if hasattr(opts, "t"):
1771 if hasattr(opts, "t"):
1772 timefunc = time.time
1772 timefunc = time.time
1773 if hasattr(opts, "c"):
1773 if hasattr(opts, "c"):
1774 timefunc = clock
1774 timefunc = clock
1775
1775
1776 timer = timeit.Timer(timer=timefunc)
1776 timer = timeit.Timer(timer=timefunc)
1777 # this code has tight coupling to the inner workings of timeit.Timer,
1777 # this code has tight coupling to the inner workings of timeit.Timer,
1778 # but is there a better way to achieve that the code stmt has access
1778 # but is there a better way to achieve that the code stmt has access
1779 # to the shell namespace?
1779 # to the shell namespace?
1780
1780
1781 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1781 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1782 'setup': "pass"}
1782 'setup': "pass"}
1783 # Track compilation time so it can be reported if too long
1783 # Track compilation time so it can be reported if too long
1784 # Minimum time above which compilation time will be reported
1784 # Minimum time above which compilation time will be reported
1785 tc_min = 0.1
1785 tc_min = 0.1
1786
1786
1787 t0 = clock()
1787 t0 = clock()
1788 code = compile(src, "<magic-timeit>", "exec")
1788 code = compile(src, "<magic-timeit>", "exec")
1789 tc = clock()-t0
1789 tc = clock()-t0
1790
1790
1791 ns = {}
1791 ns = {}
1792 exec code in self.shell.user_ns, ns
1792 exec code in self.shell.user_ns, ns
1793 timer.inner = ns["inner"]
1793 timer.inner = ns["inner"]
1794
1794
1795 if number == 0:
1795 if number == 0:
1796 # determine number so that 0.2 <= total time < 2.0
1796 # determine number so that 0.2 <= total time < 2.0
1797 number = 1
1797 number = 1
1798 for i in range(1, 10):
1798 for i in range(1, 10):
1799 if timer.timeit(number) >= 0.2:
1799 if timer.timeit(number) >= 0.2:
1800 break
1800 break
1801 number *= 10
1801 number *= 10
1802
1802
1803 best = min(timer.repeat(repeat, number)) / number
1803 best = min(timer.repeat(repeat, number)) / number
1804
1804
1805 if best > 0.0 and best < 1000.0:
1805 if best > 0.0 and best < 1000.0:
1806 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1806 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1807 elif best >= 1000.0:
1807 elif best >= 1000.0:
1808 order = 0
1808 order = 0
1809 else:
1809 else:
1810 order = 3
1810 order = 3
1811 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1811 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1812 precision,
1812 precision,
1813 best * scaling[order],
1813 best * scaling[order],
1814 units[order])
1814 units[order])
1815 if tc > tc_min:
1815 if tc > tc_min:
1816 print "Compiler time: %.2f s" % tc
1816 print "Compiler time: %.2f s" % tc
1817
1817
1818 @testdec.skip_doctest
1818 @testdec.skip_doctest
1819 def magic_time(self,parameter_s = ''):
1819 def magic_time(self,parameter_s = ''):
1820 """Time execution of a Python statement or expression.
1820 """Time execution of a Python statement or expression.
1821
1821
1822 The CPU and wall clock times are printed, and the value of the
1822 The CPU and wall clock times are printed, and the value of the
1823 expression (if any) is returned. Note that under Win32, system time
1823 expression (if any) is returned. Note that under Win32, system time
1824 is always reported as 0, since it can not be measured.
1824 is always reported as 0, since it can not be measured.
1825
1825
1826 This function provides very basic timing functionality. In Python
1826 This function provides very basic timing functionality. In Python
1827 2.3, the timeit module offers more control and sophistication, so this
1827 2.3, the timeit module offers more control and sophistication, so this
1828 could be rewritten to use it (patches welcome).
1828 could be rewritten to use it (patches welcome).
1829
1829
1830 Some examples:
1830 Some examples:
1831
1831
1832 In [1]: time 2**128
1832 In [1]: time 2**128
1833 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1833 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1834 Wall time: 0.00
1834 Wall time: 0.00
1835 Out[1]: 340282366920938463463374607431768211456L
1835 Out[1]: 340282366920938463463374607431768211456L
1836
1836
1837 In [2]: n = 1000000
1837 In [2]: n = 1000000
1838
1838
1839 In [3]: time sum(range(n))
1839 In [3]: time sum(range(n))
1840 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1840 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1841 Wall time: 1.37
1841 Wall time: 1.37
1842 Out[3]: 499999500000L
1842 Out[3]: 499999500000L
1843
1843
1844 In [4]: time print 'hello world'
1844 In [4]: time print 'hello world'
1845 hello world
1845 hello world
1846 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1846 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1847 Wall time: 0.00
1847 Wall time: 0.00
1848
1848
1849 Note that the time needed by Python to compile the given expression
1849 Note that the time needed by Python to compile the given expression
1850 will be reported if it is more than 0.1s. In this example, the
1850 will be reported if it is more than 0.1s. In this example, the
1851 actual exponentiation is done by Python at compilation time, so while
1851 actual exponentiation is done by Python at compilation time, so while
1852 the expression can take a noticeable amount of time to compute, that
1852 the expression can take a noticeable amount of time to compute, that
1853 time is purely due to the compilation:
1853 time is purely due to the compilation:
1854
1854
1855 In [5]: time 3**9999;
1855 In [5]: time 3**9999;
1856 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1856 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1857 Wall time: 0.00 s
1857 Wall time: 0.00 s
1858
1858
1859 In [6]: time 3**999999;
1859 In [6]: time 3**999999;
1860 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1860 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1861 Wall time: 0.00 s
1861 Wall time: 0.00 s
1862 Compiler : 0.78 s
1862 Compiler : 0.78 s
1863 """
1863 """
1864
1864
1865 # fail immediately if the given expression can't be compiled
1865 # fail immediately if the given expression can't be compiled
1866
1866
1867 expr = self.shell.prefilter(parameter_s,False)
1867 expr = self.shell.prefilter(parameter_s,False)
1868
1868
1869 # Minimum time above which compilation time will be reported
1869 # Minimum time above which compilation time will be reported
1870 tc_min = 0.1
1870 tc_min = 0.1
1871
1871
1872 try:
1872 try:
1873 mode = 'eval'
1873 mode = 'eval'
1874 t0 = clock()
1874 t0 = clock()
1875 code = compile(expr,'<timed eval>',mode)
1875 code = compile(expr,'<timed eval>',mode)
1876 tc = clock()-t0
1876 tc = clock()-t0
1877 except SyntaxError:
1877 except SyntaxError:
1878 mode = 'exec'
1878 mode = 'exec'
1879 t0 = clock()
1879 t0 = clock()
1880 code = compile(expr,'<timed exec>',mode)
1880 code = compile(expr,'<timed exec>',mode)
1881 tc = clock()-t0
1881 tc = clock()-t0
1882 # skew measurement as little as possible
1882 # skew measurement as little as possible
1883 glob = self.shell.user_ns
1883 glob = self.shell.user_ns
1884 clk = clock2
1884 clk = clock2
1885 wtime = time.time
1885 wtime = time.time
1886 # time execution
1886 # time execution
1887 wall_st = wtime()
1887 wall_st = wtime()
1888 if mode=='eval':
1888 if mode=='eval':
1889 st = clk()
1889 st = clk()
1890 out = eval(code,glob)
1890 out = eval(code,glob)
1891 end = clk()
1891 end = clk()
1892 else:
1892 else:
1893 st = clk()
1893 st = clk()
1894 exec code in glob
1894 exec code in glob
1895 end = clk()
1895 end = clk()
1896 out = None
1896 out = None
1897 wall_end = wtime()
1897 wall_end = wtime()
1898 # Compute actual times and report
1898 # Compute actual times and report
1899 wall_time = wall_end-wall_st
1899 wall_time = wall_end-wall_st
1900 cpu_user = end[0]-st[0]
1900 cpu_user = end[0]-st[0]
1901 cpu_sys = end[1]-st[1]
1901 cpu_sys = end[1]-st[1]
1902 cpu_tot = cpu_user+cpu_sys
1902 cpu_tot = cpu_user+cpu_sys
1903 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1903 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1904 (cpu_user,cpu_sys,cpu_tot)
1904 (cpu_user,cpu_sys,cpu_tot)
1905 print "Wall time: %.2f s" % wall_time
1905 print "Wall time: %.2f s" % wall_time
1906 if tc > tc_min:
1906 if tc > tc_min:
1907 print "Compiler : %.2f s" % tc
1907 print "Compiler : %.2f s" % tc
1908 return out
1908 return out
1909
1909
1910 @testdec.skip_doctest
1910 @testdec.skip_doctest
1911 def magic_macro(self,parameter_s = ''):
1911 def magic_macro(self,parameter_s = ''):
1912 """Define a set of input lines as a macro for future re-execution.
1912 """Define a set of input lines as a macro for future re-execution.
1913
1913
1914 Usage:\\
1914 Usage:\\
1915 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1915 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1916
1916
1917 Options:
1917 Options:
1918
1918
1919 -r: use 'raw' input. By default, the 'processed' history is used,
1919 -r: use 'raw' input. By default, the 'processed' history is used,
1920 so that magics are loaded in their transformed version to valid
1920 so that magics are loaded in their transformed version to valid
1921 Python. If this option is given, the raw input as typed as the
1921 Python. If this option is given, the raw input as typed as the
1922 command line is used instead.
1922 command line is used instead.
1923
1923
1924 This will define a global variable called `name` which is a string
1924 This will define a global variable called `name` which is a string
1925 made of joining the slices and lines you specify (n1,n2,... numbers
1925 made of joining the slices and lines you specify (n1,n2,... numbers
1926 above) from your input history into a single string. This variable
1926 above) from your input history into a single string. This variable
1927 acts like an automatic function which re-executes those lines as if
1927 acts like an automatic function which re-executes those lines as if
1928 you had typed them. You just type 'name' at the prompt and the code
1928 you had typed them. You just type 'name' at the prompt and the code
1929 executes.
1929 executes.
1930
1930
1931 The notation for indicating number ranges is: n1-n2 means 'use line
1931 The notation for indicating number ranges is: n1-n2 means 'use line
1932 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1932 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1933 using the lines numbered 5,6 and 7.
1933 using the lines numbered 5,6 and 7.
1934
1934
1935 Note: as a 'hidden' feature, you can also use traditional python slice
1935 Note: as a 'hidden' feature, you can also use traditional python slice
1936 notation, where N:M means numbers N through M-1.
1936 notation, where N:M means numbers N through M-1.
1937
1937
1938 For example, if your history contains (%hist prints it):
1938 For example, if your history contains (%hist prints it):
1939
1939
1940 44: x=1
1940 44: x=1
1941 45: y=3
1941 45: y=3
1942 46: z=x+y
1942 46: z=x+y
1943 47: print x
1943 47: print x
1944 48: a=5
1944 48: a=5
1945 49: print 'x',x,'y',y
1945 49: print 'x',x,'y',y
1946
1946
1947 you can create a macro with lines 44 through 47 (included) and line 49
1947 you can create a macro with lines 44 through 47 (included) and line 49
1948 called my_macro with:
1948 called my_macro with:
1949
1949
1950 In [55]: %macro my_macro 44-47 49
1950 In [55]: %macro my_macro 44-47 49
1951
1951
1952 Now, typing `my_macro` (without quotes) will re-execute all this code
1952 Now, typing `my_macro` (without quotes) will re-execute all this code
1953 in one pass.
1953 in one pass.
1954
1954
1955 You don't need to give the line-numbers in order, and any given line
1955 You don't need to give the line-numbers in order, and any given line
1956 number can appear multiple times. You can assemble macros with any
1956 number can appear multiple times. You can assemble macros with any
1957 lines from your input history in any order.
1957 lines from your input history in any order.
1958
1958
1959 The macro is a simple object which holds its value in an attribute,
1959 The macro is a simple object which holds its value in an attribute,
1960 but IPython's display system checks for macros and executes them as
1960 but IPython's display system checks for macros and executes them as
1961 code instead of printing them when you type their name.
1961 code instead of printing them when you type their name.
1962
1962
1963 You can view a macro's contents by explicitly printing it with:
1963 You can view a macro's contents by explicitly printing it with:
1964
1964
1965 'print macro_name'.
1965 'print macro_name'.
1966
1966
1967 For one-off cases which DON'T contain magic function calls in them you
1967 For one-off cases which DON'T contain magic function calls in them you
1968 can obtain similar results by explicitly executing slices from your
1968 can obtain similar results by explicitly executing slices from your
1969 input history with:
1969 input history with:
1970
1970
1971 In [60]: exec In[44:48]+In[49]"""
1971 In [60]: exec In[44:48]+In[49]"""
1972
1972
1973 opts,args = self.parse_options(parameter_s,'r',mode='list')
1973 opts,args = self.parse_options(parameter_s,'r',mode='list')
1974 if not args:
1974 if not args:
1975 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1975 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1976 macs.sort()
1976 macs.sort()
1977 return macs
1977 return macs
1978 if len(args) == 1:
1978 if len(args) == 1:
1979 raise UsageError(
1979 raise UsageError(
1980 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1980 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1981 name,ranges = args[0], args[1:]
1981 name,ranges = args[0], args[1:]
1982
1982
1983 #print 'rng',ranges # dbg
1983 #print 'rng',ranges # dbg
1984 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1984 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1985 macro = Macro(lines)
1985 macro = Macro(lines)
1986 self.shell.define_macro(name, macro)
1986 self.shell.define_macro(name, macro)
1987 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1987 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1988 print 'Macro contents:'
1988 print 'Macro contents:'
1989 print macro,
1989 print macro,
1990
1990
1991 def magic_save(self,parameter_s = ''):
1991 def magic_save(self,parameter_s = ''):
1992 """Save a set of lines to a given filename.
1992 """Save a set of lines to a given filename.
1993
1993
1994 Usage:\\
1994 Usage:\\
1995 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1995 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1996
1996
1997 Options:
1997 Options:
1998
1998
1999 -r: use 'raw' input. By default, the 'processed' history is used,
1999 -r: use 'raw' input. By default, the 'processed' history is used,
2000 so that magics are loaded in their transformed version to valid
2000 so that magics are loaded in their transformed version to valid
2001 Python. If this option is given, the raw input as typed as the
2001 Python. If this option is given, the raw input as typed as the
2002 command line is used instead.
2002 command line is used instead.
2003
2003
2004 This function uses the same syntax as %macro for line extraction, but
2004 This function uses the same syntax as %macro for line extraction, but
2005 instead of creating a macro it saves the resulting string to the
2005 instead of creating a macro it saves the resulting string to the
2006 filename you specify.
2006 filename you specify.
2007
2007
2008 It adds a '.py' extension to the file if you don't do so yourself, and
2008 It adds a '.py' extension to the file if you don't do so yourself, and
2009 it asks for confirmation before overwriting existing files."""
2009 it asks for confirmation before overwriting existing files."""
2010
2010
2011 opts,args = self.parse_options(parameter_s,'r',mode='list')
2011 opts,args = self.parse_options(parameter_s,'r',mode='list')
2012 fname,ranges = args[0], args[1:]
2012 fname,ranges = args[0], args[1:]
2013 if not fname.endswith('.py'):
2013 if not fname.endswith('.py'):
2014 fname += '.py'
2014 fname += '.py'
2015 if os.path.isfile(fname):
2015 if os.path.isfile(fname):
2016 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2016 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2017 if ans.lower() not in ['y','yes']:
2017 if ans.lower() not in ['y','yes']:
2018 print 'Operation cancelled.'
2018 print 'Operation cancelled.'
2019 return
2019 return
2020 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2020 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2021 f = file(fname,'w')
2021 f = file(fname,'w')
2022 f.write(cmds)
2022 f.write(cmds)
2023 f.close()
2023 f.close()
2024 print 'The following commands were written to file `%s`:' % fname
2024 print 'The following commands were written to file `%s`:' % fname
2025 print cmds
2025 print cmds
2026
2026
2027 def _edit_macro(self,mname,macro):
2027 def _edit_macro(self,mname,macro):
2028 """open an editor with the macro data in a file"""
2028 """open an editor with the macro data in a file"""
2029 filename = self.shell.mktempfile(macro.value)
2029 filename = self.shell.mktempfile(macro.value)
2030 self.shell.hooks.editor(filename)
2030 self.shell.hooks.editor(filename)
2031
2031
2032 # and make a new macro object, to replace the old one
2032 # and make a new macro object, to replace the old one
2033 mfile = open(filename)
2033 mfile = open(filename)
2034 mvalue = mfile.read()
2034 mvalue = mfile.read()
2035 mfile.close()
2035 mfile.close()
2036 self.shell.user_ns[mname] = Macro(mvalue)
2036 self.shell.user_ns[mname] = Macro(mvalue)
2037
2037
2038 def magic_ed(self,parameter_s=''):
2038 def magic_ed(self,parameter_s=''):
2039 """Alias to %edit."""
2039 """Alias to %edit."""
2040 return self.magic_edit(parameter_s)
2040 return self.magic_edit(parameter_s)
2041
2041
2042 @testdec.skip_doctest
2042 @testdec.skip_doctest
2043 def magic_edit(self,parameter_s='',last_call=['','']):
2043 def magic_edit(self,parameter_s='',last_call=['','']):
2044 """Bring up an editor and execute the resulting code.
2044 """Bring up an editor and execute the resulting code.
2045
2045
2046 Usage:
2046 Usage:
2047 %edit [options] [args]
2047 %edit [options] [args]
2048
2048
2049 %edit runs IPython's editor hook. The default version of this hook is
2049 %edit runs IPython's editor hook. The default version of this hook is
2050 set to call the __IPYTHON__.rc.editor command. This is read from your
2050 set to call the __IPYTHON__.rc.editor command. This is read from your
2051 environment variable $EDITOR. If this isn't found, it will default to
2051 environment variable $EDITOR. If this isn't found, it will default to
2052 vi under Linux/Unix and to notepad under Windows. See the end of this
2052 vi under Linux/Unix and to notepad under Windows. See the end of this
2053 docstring for how to change the editor hook.
2053 docstring for how to change the editor hook.
2054
2054
2055 You can also set the value of this editor via the command line option
2055 You can also set the value of this editor via the command line option
2056 '-editor' or in your ipythonrc file. This is useful if you wish to use
2056 '-editor' or in your ipythonrc file. This is useful if you wish to use
2057 specifically for IPython an editor different from your typical default
2057 specifically for IPython an editor different from your typical default
2058 (and for Windows users who typically don't set environment variables).
2058 (and for Windows users who typically don't set environment variables).
2059
2059
2060 This command allows you to conveniently edit multi-line code right in
2060 This command allows you to conveniently edit multi-line code right in
2061 your IPython session.
2061 your IPython session.
2062
2062
2063 If called without arguments, %edit opens up an empty editor with a
2063 If called without arguments, %edit opens up an empty editor with a
2064 temporary file and will execute the contents of this file when you
2064 temporary file and will execute the contents of this file when you
2065 close it (don't forget to save it!).
2065 close it (don't forget to save it!).
2066
2066
2067
2067
2068 Options:
2068 Options:
2069
2069
2070 -n <number>: open the editor at a specified line number. By default,
2070 -n <number>: open the editor at a specified line number. By default,
2071 the IPython editor hook uses the unix syntax 'editor +N filename', but
2071 the IPython editor hook uses the unix syntax 'editor +N filename', but
2072 you can configure this by providing your own modified hook if your
2072 you can configure this by providing your own modified hook if your
2073 favorite editor supports line-number specifications with a different
2073 favorite editor supports line-number specifications with a different
2074 syntax.
2074 syntax.
2075
2075
2076 -p: this will call the editor with the same data as the previous time
2076 -p: this will call the editor with the same data as the previous time
2077 it was used, regardless of how long ago (in your current session) it
2077 it was used, regardless of how long ago (in your current session) it
2078 was.
2078 was.
2079
2079
2080 -r: use 'raw' input. This option only applies to input taken from the
2080 -r: use 'raw' input. This option only applies to input taken from the
2081 user's history. By default, the 'processed' history is used, so that
2081 user's history. By default, the 'processed' history is used, so that
2082 magics are loaded in their transformed version to valid Python. If
2082 magics are loaded in their transformed version to valid Python. If
2083 this option is given, the raw input as typed as the command line is
2083 this option is given, the raw input as typed as the command line is
2084 used instead. When you exit the editor, it will be executed by
2084 used instead. When you exit the editor, it will be executed by
2085 IPython's own processor.
2085 IPython's own processor.
2086
2086
2087 -x: do not execute the edited code immediately upon exit. This is
2087 -x: do not execute the edited code immediately upon exit. This is
2088 mainly useful if you are editing programs which need to be called with
2088 mainly useful if you are editing programs which need to be called with
2089 command line arguments, which you can then do using %run.
2089 command line arguments, which you can then do using %run.
2090
2090
2091
2091
2092 Arguments:
2092 Arguments:
2093
2093
2094 If arguments are given, the following possibilites exist:
2094 If arguments are given, the following possibilites exist:
2095
2095
2096 - The arguments are numbers or pairs of colon-separated numbers (like
2096 - The arguments are numbers or pairs of colon-separated numbers (like
2097 1 4:8 9). These are interpreted as lines of previous input to be
2097 1 4:8 9). These are interpreted as lines of previous input to be
2098 loaded into the editor. The syntax is the same of the %macro command.
2098 loaded into the editor. The syntax is the same of the %macro command.
2099
2099
2100 - If the argument doesn't start with a number, it is evaluated as a
2100 - If the argument doesn't start with a number, it is evaluated as a
2101 variable and its contents loaded into the editor. You can thus edit
2101 variable and its contents loaded into the editor. You can thus edit
2102 any string which contains python code (including the result of
2102 any string which contains python code (including the result of
2103 previous edits).
2103 previous edits).
2104
2104
2105 - If the argument is the name of an object (other than a string),
2105 - If the argument is the name of an object (other than a string),
2106 IPython will try to locate the file where it was defined and open the
2106 IPython will try to locate the file where it was defined and open the
2107 editor at the point where it is defined. You can use `%edit function`
2107 editor at the point where it is defined. You can use `%edit function`
2108 to load an editor exactly at the point where 'function' is defined,
2108 to load an editor exactly at the point where 'function' is defined,
2109 edit it and have the file be executed automatically.
2109 edit it and have the file be executed automatically.
2110
2110
2111 If the object is a macro (see %macro for details), this opens up your
2111 If the object is a macro (see %macro for details), this opens up your
2112 specified editor with a temporary file containing the macro's data.
2112 specified editor with a temporary file containing the macro's data.
2113 Upon exit, the macro is reloaded with the contents of the file.
2113 Upon exit, the macro is reloaded with the contents of the file.
2114
2114
2115 Note: opening at an exact line is only supported under Unix, and some
2115 Note: opening at an exact line is only supported under Unix, and some
2116 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2116 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2117 '+NUMBER' parameter necessary for this feature. Good editors like
2117 '+NUMBER' parameter necessary for this feature. Good editors like
2118 (X)Emacs, vi, jed, pico and joe all do.
2118 (X)Emacs, vi, jed, pico and joe all do.
2119
2119
2120 - If the argument is not found as a variable, IPython will look for a
2120 - If the argument is not found as a variable, IPython will look for a
2121 file with that name (adding .py if necessary) and load it into the
2121 file with that name (adding .py if necessary) and load it into the
2122 editor. It will execute its contents with execfile() when you exit,
2122 editor. It will execute its contents with execfile() when you exit,
2123 loading any code in the file into your interactive namespace.
2123 loading any code in the file into your interactive namespace.
2124
2124
2125 After executing your code, %edit will return as output the code you
2125 After executing your code, %edit will return as output the code you
2126 typed in the editor (except when it was an existing file). This way
2126 typed in the editor (except when it was an existing file). This way
2127 you can reload the code in further invocations of %edit as a variable,
2127 you can reload the code in further invocations of %edit as a variable,
2128 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2128 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2129 the output.
2129 the output.
2130
2130
2131 Note that %edit is also available through the alias %ed.
2131 Note that %edit is also available through the alias %ed.
2132
2132
2133 This is an example of creating a simple function inside the editor and
2133 This is an example of creating a simple function inside the editor and
2134 then modifying it. First, start up the editor:
2134 then modifying it. First, start up the editor:
2135
2135
2136 In [1]: ed
2136 In [1]: ed
2137 Editing... done. Executing edited code...
2137 Editing... done. Executing edited code...
2138 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2138 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2139
2139
2140 We can then call the function foo():
2140 We can then call the function foo():
2141
2141
2142 In [2]: foo()
2142 In [2]: foo()
2143 foo() was defined in an editing session
2143 foo() was defined in an editing session
2144
2144
2145 Now we edit foo. IPython automatically loads the editor with the
2145 Now we edit foo. IPython automatically loads the editor with the
2146 (temporary) file where foo() was previously defined:
2146 (temporary) file where foo() was previously defined:
2147
2147
2148 In [3]: ed foo
2148 In [3]: ed foo
2149 Editing... done. Executing edited code...
2149 Editing... done. Executing edited code...
2150
2150
2151 And if we call foo() again we get the modified version:
2151 And if we call foo() again we get the modified version:
2152
2152
2153 In [4]: foo()
2153 In [4]: foo()
2154 foo() has now been changed!
2154 foo() has now been changed!
2155
2155
2156 Here is an example of how to edit a code snippet successive
2156 Here is an example of how to edit a code snippet successive
2157 times. First we call the editor:
2157 times. First we call the editor:
2158
2158
2159 In [5]: ed
2159 In [5]: ed
2160 Editing... done. Executing edited code...
2160 Editing... done. Executing edited code...
2161 hello
2161 hello
2162 Out[5]: "print 'hello'n"
2162 Out[5]: "print 'hello'n"
2163
2163
2164 Now we call it again with the previous output (stored in _):
2164 Now we call it again with the previous output (stored in _):
2165
2165
2166 In [6]: ed _
2166 In [6]: ed _
2167 Editing... done. Executing edited code...
2167 Editing... done. Executing edited code...
2168 hello world
2168 hello world
2169 Out[6]: "print 'hello world'n"
2169 Out[6]: "print 'hello world'n"
2170
2170
2171 Now we call it with the output #8 (stored in _8, also as Out[8]):
2171 Now we call it with the output #8 (stored in _8, also as Out[8]):
2172
2172
2173 In [7]: ed _8
2173 In [7]: ed _8
2174 Editing... done. Executing edited code...
2174 Editing... done. Executing edited code...
2175 hello again
2175 hello again
2176 Out[7]: "print 'hello again'n"
2176 Out[7]: "print 'hello again'n"
2177
2177
2178
2178
2179 Changing the default editor hook:
2179 Changing the default editor hook:
2180
2180
2181 If you wish to write your own editor hook, you can put it in a
2181 If you wish to write your own editor hook, you can put it in a
2182 configuration file which you load at startup time. The default hook
2182 configuration file which you load at startup time. The default hook
2183 is defined in the IPython.core.hooks module, and you can use that as a
2183 is defined in the IPython.core.hooks module, and you can use that as a
2184 starting example for further modifications. That file also has
2184 starting example for further modifications. That file also has
2185 general instructions on how to set a new hook for use once you've
2185 general instructions on how to set a new hook for use once you've
2186 defined it."""
2186 defined it."""
2187
2187
2188 # FIXME: This function has become a convoluted mess. It needs a
2188 # FIXME: This function has become a convoluted mess. It needs a
2189 # ground-up rewrite with clean, simple logic.
2189 # ground-up rewrite with clean, simple logic.
2190
2190
2191 def make_filename(arg):
2191 def make_filename(arg):
2192 "Make a filename from the given args"
2192 "Make a filename from the given args"
2193 try:
2193 try:
2194 filename = get_py_filename(arg)
2194 filename = get_py_filename(arg)
2195 except IOError:
2195 except IOError:
2196 if args.endswith('.py'):
2196 if args.endswith('.py'):
2197 filename = arg
2197 filename = arg
2198 else:
2198 else:
2199 filename = None
2199 filename = None
2200 return filename
2200 return filename
2201
2201
2202 # custom exceptions
2202 # custom exceptions
2203 class DataIsObject(Exception): pass
2203 class DataIsObject(Exception): pass
2204
2204
2205 opts,args = self.parse_options(parameter_s,'prxn:')
2205 opts,args = self.parse_options(parameter_s,'prxn:')
2206 # Set a few locals from the options for convenience:
2206 # Set a few locals from the options for convenience:
2207 opts_p = opts.has_key('p')
2207 opts_p = opts.has_key('p')
2208 opts_r = opts.has_key('r')
2208 opts_r = opts.has_key('r')
2209
2209
2210 # Default line number value
2210 # Default line number value
2211 lineno = opts.get('n',None)
2211 lineno = opts.get('n',None)
2212
2212
2213 if opts_p:
2213 if opts_p:
2214 args = '_%s' % last_call[0]
2214 args = '_%s' % last_call[0]
2215 if not self.shell.user_ns.has_key(args):
2215 if not self.shell.user_ns.has_key(args):
2216 args = last_call[1]
2216 args = last_call[1]
2217
2217
2218 # use last_call to remember the state of the previous call, but don't
2218 # use last_call to remember the state of the previous call, but don't
2219 # let it be clobbered by successive '-p' calls.
2219 # let it be clobbered by successive '-p' calls.
2220 try:
2220 try:
2221 last_call[0] = self.shell.displayhook.prompt_count
2221 last_call[0] = self.shell.displayhook.prompt_count
2222 if not opts_p:
2222 if not opts_p:
2223 last_call[1] = parameter_s
2223 last_call[1] = parameter_s
2224 except:
2224 except:
2225 pass
2225 pass
2226
2226
2227 # by default this is done with temp files, except when the given
2227 # by default this is done with temp files, except when the given
2228 # arg is a filename
2228 # arg is a filename
2229 use_temp = 1
2229 use_temp = 1
2230
2230
2231 if re.match(r'\d',args):
2231 if re.match(r'\d',args):
2232 # Mode where user specifies ranges of lines, like in %macro.
2232 # Mode where user specifies ranges of lines, like in %macro.
2233 # This means that you can't edit files whose names begin with
2233 # This means that you can't edit files whose names begin with
2234 # numbers this way. Tough.
2234 # numbers this way. Tough.
2235 ranges = args.split()
2235 ranges = args.split()
2236 data = ''.join(self.extract_input_slices(ranges,opts_r))
2236 data = ''.join(self.extract_input_slices(ranges,opts_r))
2237 elif args.endswith('.py'):
2237 elif args.endswith('.py'):
2238 filename = make_filename(args)
2238 filename = make_filename(args)
2239 data = ''
2239 data = ''
2240 use_temp = 0
2240 use_temp = 0
2241 elif args:
2241 elif args:
2242 try:
2242 try:
2243 # Load the parameter given as a variable. If not a string,
2243 # Load the parameter given as a variable. If not a string,
2244 # process it as an object instead (below)
2244 # process it as an object instead (below)
2245
2245
2246 #print '*** args',args,'type',type(args) # dbg
2246 #print '*** args',args,'type',type(args) # dbg
2247 data = eval(args,self.shell.user_ns)
2247 data = eval(args,self.shell.user_ns)
2248 if not type(data) in StringTypes:
2248 if not type(data) in StringTypes:
2249 raise DataIsObject
2249 raise DataIsObject
2250
2250
2251 except (NameError,SyntaxError):
2251 except (NameError,SyntaxError):
2252 # given argument is not a variable, try as a filename
2252 # given argument is not a variable, try as a filename
2253 filename = make_filename(args)
2253 filename = make_filename(args)
2254 if filename is None:
2254 if filename is None:
2255 warn("Argument given (%s) can't be found as a variable "
2255 warn("Argument given (%s) can't be found as a variable "
2256 "or as a filename." % args)
2256 "or as a filename." % args)
2257 return
2257 return
2258
2258
2259 data = ''
2259 data = ''
2260 use_temp = 0
2260 use_temp = 0
2261 except DataIsObject:
2261 except DataIsObject:
2262
2262
2263 # macros have a special edit function
2263 # macros have a special edit function
2264 if isinstance(data,Macro):
2264 if isinstance(data,Macro):
2265 self._edit_macro(args,data)
2265 self._edit_macro(args,data)
2266 return
2266 return
2267
2267
2268 # For objects, try to edit the file where they are defined
2268 # For objects, try to edit the file where they are defined
2269 try:
2269 try:
2270 filename = inspect.getabsfile(data)
2270 filename = inspect.getabsfile(data)
2271 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2271 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2272 # class created by %edit? Try to find source
2272 # class created by %edit? Try to find source
2273 # by looking for method definitions instead, the
2273 # by looking for method definitions instead, the
2274 # __module__ in those classes is FakeModule.
2274 # __module__ in those classes is FakeModule.
2275 attrs = [getattr(data, aname) for aname in dir(data)]
2275 attrs = [getattr(data, aname) for aname in dir(data)]
2276 for attr in attrs:
2276 for attr in attrs:
2277 if not inspect.ismethod(attr):
2277 if not inspect.ismethod(attr):
2278 continue
2278 continue
2279 filename = inspect.getabsfile(attr)
2279 filename = inspect.getabsfile(attr)
2280 if filename and 'fakemodule' not in filename.lower():
2280 if filename and 'fakemodule' not in filename.lower():
2281 # change the attribute to be the edit target instead
2281 # change the attribute to be the edit target instead
2282 data = attr
2282 data = attr
2283 break
2283 break
2284
2284
2285 datafile = 1
2285 datafile = 1
2286 except TypeError:
2286 except TypeError:
2287 filename = make_filename(args)
2287 filename = make_filename(args)
2288 datafile = 1
2288 datafile = 1
2289 warn('Could not find file where `%s` is defined.\n'
2289 warn('Could not find file where `%s` is defined.\n'
2290 'Opening a file named `%s`' % (args,filename))
2290 'Opening a file named `%s`' % (args,filename))
2291 # Now, make sure we can actually read the source (if it was in
2291 # Now, make sure we can actually read the source (if it was in
2292 # a temp file it's gone by now).
2292 # a temp file it's gone by now).
2293 if datafile:
2293 if datafile:
2294 try:
2294 try:
2295 if lineno is None:
2295 if lineno is None:
2296 lineno = inspect.getsourcelines(data)[1]
2296 lineno = inspect.getsourcelines(data)[1]
2297 except IOError:
2297 except IOError:
2298 filename = make_filename(args)
2298 filename = make_filename(args)
2299 if filename is None:
2299 if filename is None:
2300 warn('The file `%s` where `%s` was defined cannot '
2300 warn('The file `%s` where `%s` was defined cannot '
2301 'be read.' % (filename,data))
2301 'be read.' % (filename,data))
2302 return
2302 return
2303 use_temp = 0
2303 use_temp = 0
2304 else:
2304 else:
2305 data = ''
2305 data = ''
2306
2306
2307 if use_temp:
2307 if use_temp:
2308 filename = self.shell.mktempfile(data)
2308 filename = self.shell.mktempfile(data)
2309 print 'IPython will make a temporary file named:',filename
2309 print 'IPython will make a temporary file named:',filename
2310
2310
2311 # do actual editing here
2311 # do actual editing here
2312 print 'Editing...',
2312 print 'Editing...',
2313 sys.stdout.flush()
2313 sys.stdout.flush()
2314 try:
2314 try:
2315 # Quote filenames that may have spaces in them
2315 # Quote filenames that may have spaces in them
2316 if ' ' in filename:
2316 if ' ' in filename:
2317 filename = "%s" % filename
2317 filename = "%s" % filename
2318 self.shell.hooks.editor(filename,lineno)
2318 self.shell.hooks.editor(filename,lineno)
2319 except TryNext:
2319 except TryNext:
2320 warn('Could not open editor')
2320 warn('Could not open editor')
2321 return
2321 return
2322
2322
2323 # XXX TODO: should this be generalized for all string vars?
2323 # XXX TODO: should this be generalized for all string vars?
2324 # For now, this is special-cased to blocks created by cpaste
2324 # For now, this is special-cased to blocks created by cpaste
2325 if args.strip() == 'pasted_block':
2325 if args.strip() == 'pasted_block':
2326 self.shell.user_ns['pasted_block'] = file_read(filename)
2326 self.shell.user_ns['pasted_block'] = file_read(filename)
2327
2327
2328 if opts.has_key('x'): # -x prevents actual execution
2328 if opts.has_key('x'): # -x prevents actual execution
2329 print
2329 print
2330 else:
2330 else:
2331 print 'done. Executing edited code...'
2331 print 'done. Executing edited code...'
2332 if opts_r:
2332 if opts_r:
2333 self.shell.runlines(file_read(filename))
2333 self.shell.runlines(file_read(filename))
2334 else:
2334 else:
2335 self.shell.safe_execfile(filename,self.shell.user_ns,
2335 self.shell.safe_execfile(filename,self.shell.user_ns,
2336 self.shell.user_ns)
2336 self.shell.user_ns)
2337
2337
2338
2338
2339 if use_temp:
2339 if use_temp:
2340 try:
2340 try:
2341 return open(filename).read()
2341 return open(filename).read()
2342 except IOError,msg:
2342 except IOError,msg:
2343 if msg.filename == filename:
2343 if msg.filename == filename:
2344 warn('File not found. Did you forget to save?')
2344 warn('File not found. Did you forget to save?')
2345 return
2345 return
2346 else:
2346 else:
2347 self.shell.showtraceback()
2347 self.shell.showtraceback()
2348
2348
2349 def magic_xmode(self,parameter_s = ''):
2349 def magic_xmode(self,parameter_s = ''):
2350 """Switch modes for the exception handlers.
2350 """Switch modes for the exception handlers.
2351
2351
2352 Valid modes: Plain, Context and Verbose.
2352 Valid modes: Plain, Context and Verbose.
2353
2353
2354 If called without arguments, acts as a toggle."""
2354 If called without arguments, acts as a toggle."""
2355
2355
2356 def xmode_switch_err(name):
2356 def xmode_switch_err(name):
2357 warn('Error changing %s exception modes.\n%s' %
2357 warn('Error changing %s exception modes.\n%s' %
2358 (name,sys.exc_info()[1]))
2358 (name,sys.exc_info()[1]))
2359
2359
2360 shell = self.shell
2360 shell = self.shell
2361 new_mode = parameter_s.strip().capitalize()
2361 new_mode = parameter_s.strip().capitalize()
2362 try:
2362 try:
2363 shell.InteractiveTB.set_mode(mode=new_mode)
2363 shell.InteractiveTB.set_mode(mode=new_mode)
2364 print 'Exception reporting mode:',shell.InteractiveTB.mode
2364 print 'Exception reporting mode:',shell.InteractiveTB.mode
2365 except:
2365 except:
2366 xmode_switch_err('user')
2366 xmode_switch_err('user')
2367
2367
2368 def magic_colors(self,parameter_s = ''):
2368 def magic_colors(self,parameter_s = ''):
2369 """Switch color scheme for prompts, info system and exception handlers.
2369 """Switch color scheme for prompts, info system and exception handlers.
2370
2370
2371 Currently implemented schemes: NoColor, Linux, LightBG.
2371 Currently implemented schemes: NoColor, Linux, LightBG.
2372
2372
2373 Color scheme names are not case-sensitive."""
2373 Color scheme names are not case-sensitive."""
2374
2374
2375 def color_switch_err(name):
2375 def color_switch_err(name):
2376 warn('Error changing %s color schemes.\n%s' %
2376 warn('Error changing %s color schemes.\n%s' %
2377 (name,sys.exc_info()[1]))
2377 (name,sys.exc_info()[1]))
2378
2378
2379
2379
2380 new_scheme = parameter_s.strip()
2380 new_scheme = parameter_s.strip()
2381 if not new_scheme:
2381 if not new_scheme:
2382 raise UsageError(
2382 raise UsageError(
2383 "%colors: you must specify a color scheme. See '%colors?'")
2383 "%colors: you must specify a color scheme. See '%colors?'")
2384 return
2384 return
2385 # local shortcut
2385 # local shortcut
2386 shell = self.shell
2386 shell = self.shell
2387
2387
2388 import IPython.utils.rlineimpl as readline
2388 import IPython.utils.rlineimpl as readline
2389
2389
2390 if not readline.have_readline and sys.platform == "win32":
2390 if not readline.have_readline and sys.platform == "win32":
2391 msg = """\
2391 msg = """\
2392 Proper color support under MS Windows requires the pyreadline library.
2392 Proper color support under MS Windows requires the pyreadline library.
2393 You can find it at:
2393 You can find it at:
2394 http://ipython.scipy.org/moin/PyReadline/Intro
2394 http://ipython.scipy.org/moin/PyReadline/Intro
2395 Gary's readline needs the ctypes module, from:
2395 Gary's readline needs the ctypes module, from:
2396 http://starship.python.net/crew/theller/ctypes
2396 http://starship.python.net/crew/theller/ctypes
2397 (Note that ctypes is already part of Python versions 2.5 and newer).
2397 (Note that ctypes is already part of Python versions 2.5 and newer).
2398
2398
2399 Defaulting color scheme to 'NoColor'"""
2399 Defaulting color scheme to 'NoColor'"""
2400 new_scheme = 'NoColor'
2400 new_scheme = 'NoColor'
2401 warn(msg)
2401 warn(msg)
2402
2402
2403 # readline option is 0
2403 # readline option is 0
2404 if not shell.has_readline:
2404 if not shell.has_readline:
2405 new_scheme = 'NoColor'
2405 new_scheme = 'NoColor'
2406
2406
2407 # Set prompt colors
2407 # Set prompt colors
2408 try:
2408 try:
2409 shell.displayhook.set_colors(new_scheme)
2409 shell.displayhook.set_colors(new_scheme)
2410 except:
2410 except:
2411 color_switch_err('prompt')
2411 color_switch_err('prompt')
2412 else:
2412 else:
2413 shell.colors = \
2413 shell.colors = \
2414 shell.displayhook.color_table.active_scheme_name
2414 shell.displayhook.color_table.active_scheme_name
2415 # Set exception colors
2415 # Set exception colors
2416 try:
2416 try:
2417 shell.InteractiveTB.set_colors(scheme = new_scheme)
2417 shell.InteractiveTB.set_colors(scheme = new_scheme)
2418 shell.SyntaxTB.set_colors(scheme = new_scheme)
2418 shell.SyntaxTB.set_colors(scheme = new_scheme)
2419 except:
2419 except:
2420 color_switch_err('exception')
2420 color_switch_err('exception')
2421
2421
2422 # Set info (for 'object?') colors
2422 # Set info (for 'object?') colors
2423 if shell.color_info:
2423 if shell.color_info:
2424 try:
2424 try:
2425 shell.inspector.set_active_scheme(new_scheme)
2425 shell.inspector.set_active_scheme(new_scheme)
2426 except:
2426 except:
2427 color_switch_err('object inspector')
2427 color_switch_err('object inspector')
2428 else:
2428 else:
2429 shell.inspector.set_active_scheme('NoColor')
2429 shell.inspector.set_active_scheme('NoColor')
2430
2430
2431 def magic_color_info(self,parameter_s = ''):
2431 def magic_color_info(self,parameter_s = ''):
2432 """Toggle color_info.
2432 """Toggle color_info.
2433
2433
2434 The color_info configuration parameter controls whether colors are
2434 The color_info configuration parameter controls whether colors are
2435 used for displaying object details (by things like %psource, %pfile or
2435 used for displaying object details (by things like %psource, %pfile or
2436 the '?' system). This function toggles this value with each call.
2436 the '?' system). This function toggles this value with each call.
2437
2437
2438 Note that unless you have a fairly recent pager (less works better
2438 Note that unless you have a fairly recent pager (less works better
2439 than more) in your system, using colored object information displays
2439 than more) in your system, using colored object information displays
2440 will not work properly. Test it and see."""
2440 will not work properly. Test it and see."""
2441
2441
2442 self.shell.color_info = not self.shell.color_info
2442 self.shell.color_info = not self.shell.color_info
2443 self.magic_colors(self.shell.colors)
2443 self.magic_colors(self.shell.colors)
2444 print 'Object introspection functions have now coloring:',
2444 print 'Object introspection functions have now coloring:',
2445 print ['OFF','ON'][int(self.shell.color_info)]
2445 print ['OFF','ON'][int(self.shell.color_info)]
2446
2446
2447 def magic_Pprint(self, parameter_s=''):
2447 def magic_Pprint(self, parameter_s=''):
2448 """Toggle pretty printing on/off."""
2448 """Toggle pretty printing on/off."""
2449
2449
2450 self.shell.pprint = 1 - self.shell.pprint
2450 self.shell.pprint = 1 - self.shell.pprint
2451 print 'Pretty printing has been turned', \
2451 print 'Pretty printing has been turned', \
2452 ['OFF','ON'][self.shell.pprint]
2452 ['OFF','ON'][self.shell.pprint]
2453
2453
2454 def magic_Exit(self, parameter_s=''):
2454 def magic_Exit(self, parameter_s=''):
2455 """Exit IPython."""
2455 """Exit IPython."""
2456
2456
2457 self.shell.ask_exit()
2457 self.shell.ask_exit()
2458
2458
2459 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2459 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2460 magic_exit = magic_quit = magic_Quit = magic_Exit
2460 magic_exit = magic_quit = magic_Quit = magic_Exit
2461
2461
2462 #......................................................................
2462 #......................................................................
2463 # Functions to implement unix shell-type things
2463 # Functions to implement unix shell-type things
2464
2464
2465 @testdec.skip_doctest
2465 @testdec.skip_doctest
2466 def magic_alias(self, parameter_s = ''):
2466 def magic_alias(self, parameter_s = ''):
2467 """Define an alias for a system command.
2467 """Define an alias for a system command.
2468
2468
2469 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2469 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2470
2470
2471 Then, typing 'alias_name params' will execute the system command 'cmd
2471 Then, typing 'alias_name params' will execute the system command 'cmd
2472 params' (from your underlying operating system).
2472 params' (from your underlying operating system).
2473
2473
2474 Aliases have lower precedence than magic functions and Python normal
2474 Aliases have lower precedence than magic functions and Python normal
2475 variables, so if 'foo' is both a Python variable and an alias, the
2475 variables, so if 'foo' is both a Python variable and an alias, the
2476 alias can not be executed until 'del foo' removes the Python variable.
2476 alias can not be executed until 'del foo' removes the Python variable.
2477
2477
2478 You can use the %l specifier in an alias definition to represent the
2478 You can use the %l specifier in an alias definition to represent the
2479 whole line when the alias is called. For example:
2479 whole line when the alias is called. For example:
2480
2480
2481 In [2]: alias bracket echo "Input in brackets: <%l>"
2481 In [2]: alias bracket echo "Input in brackets: <%l>"
2482 In [3]: bracket hello world
2482 In [3]: bracket hello world
2483 Input in brackets: <hello world>
2483 Input in brackets: <hello world>
2484
2484
2485 You can also define aliases with parameters using %s specifiers (one
2485 You can also define aliases with parameters using %s specifiers (one
2486 per parameter):
2486 per parameter):
2487
2487
2488 In [1]: alias parts echo first %s second %s
2488 In [1]: alias parts echo first %s second %s
2489 In [2]: %parts A B
2489 In [2]: %parts A B
2490 first A second B
2490 first A second B
2491 In [3]: %parts A
2491 In [3]: %parts A
2492 Incorrect number of arguments: 2 expected.
2492 Incorrect number of arguments: 2 expected.
2493 parts is an alias to: 'echo first %s second %s'
2493 parts is an alias to: 'echo first %s second %s'
2494
2494
2495 Note that %l and %s are mutually exclusive. You can only use one or
2495 Note that %l and %s are mutually exclusive. You can only use one or
2496 the other in your aliases.
2496 the other in your aliases.
2497
2497
2498 Aliases expand Python variables just like system calls using ! or !!
2498 Aliases expand Python variables just like system calls using ! or !!
2499 do: all expressions prefixed with '$' get expanded. For details of
2499 do: all expressions prefixed with '$' get expanded. For details of
2500 the semantic rules, see PEP-215:
2500 the semantic rules, see PEP-215:
2501 http://www.python.org/peps/pep-0215.html. This is the library used by
2501 http://www.python.org/peps/pep-0215.html. This is the library used by
2502 IPython for variable expansion. If you want to access a true shell
2502 IPython for variable expansion. If you want to access a true shell
2503 variable, an extra $ is necessary to prevent its expansion by IPython:
2503 variable, an extra $ is necessary to prevent its expansion by IPython:
2504
2504
2505 In [6]: alias show echo
2505 In [6]: alias show echo
2506 In [7]: PATH='A Python string'
2506 In [7]: PATH='A Python string'
2507 In [8]: show $PATH
2507 In [8]: show $PATH
2508 A Python string
2508 A Python string
2509 In [9]: show $$PATH
2509 In [9]: show $$PATH
2510 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2510 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2511
2511
2512 You can use the alias facility to acess all of $PATH. See the %rehash
2512 You can use the alias facility to acess all of $PATH. See the %rehash
2513 and %rehashx functions, which automatically create aliases for the
2513 and %rehashx functions, which automatically create aliases for the
2514 contents of your $PATH.
2514 contents of your $PATH.
2515
2515
2516 If called with no parameters, %alias prints the current alias table."""
2516 If called with no parameters, %alias prints the current alias table."""
2517
2517
2518 par = parameter_s.strip()
2518 par = parameter_s.strip()
2519 if not par:
2519 if not par:
2520 stored = self.db.get('stored_aliases', {} )
2520 stored = self.db.get('stored_aliases', {} )
2521 aliases = sorted(self.shell.alias_manager.aliases)
2521 aliases = sorted(self.shell.alias_manager.aliases)
2522 # for k, v in stored:
2522 # for k, v in stored:
2523 # atab.append(k, v[0])
2523 # atab.append(k, v[0])
2524
2524
2525 print "Total number of aliases:", len(aliases)
2525 print "Total number of aliases:", len(aliases)
2526 return aliases
2526 return aliases
2527
2527
2528 # Now try to define a new one
2528 # Now try to define a new one
2529 try:
2529 try:
2530 alias,cmd = par.split(None, 1)
2530 alias,cmd = par.split(None, 1)
2531 except:
2531 except:
2532 print oinspect.getdoc(self.magic_alias)
2532 print oinspect.getdoc(self.magic_alias)
2533 else:
2533 else:
2534 self.shell.alias_manager.soft_define_alias(alias, cmd)
2534 self.shell.alias_manager.soft_define_alias(alias, cmd)
2535 # end magic_alias
2535 # end magic_alias
2536
2536
2537 def magic_unalias(self, parameter_s = ''):
2537 def magic_unalias(self, parameter_s = ''):
2538 """Remove an alias"""
2538 """Remove an alias"""
2539
2539
2540 aname = parameter_s.strip()
2540 aname = parameter_s.strip()
2541 self.shell.alias_manager.undefine_alias(aname)
2541 self.shell.alias_manager.undefine_alias(aname)
2542 stored = self.db.get('stored_aliases', {} )
2542 stored = self.db.get('stored_aliases', {} )
2543 if aname in stored:
2543 if aname in stored:
2544 print "Removing %stored alias",aname
2544 print "Removing %stored alias",aname
2545 del stored[aname]
2545 del stored[aname]
2546 self.db['stored_aliases'] = stored
2546 self.db['stored_aliases'] = stored
2547
2547
2548
2548
2549 def magic_rehashx(self, parameter_s = ''):
2549 def magic_rehashx(self, parameter_s = ''):
2550 """Update the alias table with all executable files in $PATH.
2550 """Update the alias table with all executable files in $PATH.
2551
2551
2552 This version explicitly checks that every entry in $PATH is a file
2552 This version explicitly checks that every entry in $PATH is a file
2553 with execute access (os.X_OK), so it is much slower than %rehash.
2553 with execute access (os.X_OK), so it is much slower than %rehash.
2554
2554
2555 Under Windows, it checks executability as a match agains a
2555 Under Windows, it checks executability as a match agains a
2556 '|'-separated string of extensions, stored in the IPython config
2556 '|'-separated string of extensions, stored in the IPython config
2557 variable win_exec_ext. This defaults to 'exe|com|bat'.
2557 variable win_exec_ext. This defaults to 'exe|com|bat'.
2558
2558
2559 This function also resets the root module cache of module completer,
2559 This function also resets the root module cache of module completer,
2560 used on slow filesystems.
2560 used on slow filesystems.
2561 """
2561 """
2562 from IPython.core.alias import InvalidAliasError
2562 from IPython.core.alias import InvalidAliasError
2563
2563
2564 # for the benefit of module completer in ipy_completers.py
2564 # for the benefit of module completer in ipy_completers.py
2565 del self.db['rootmodules']
2565 del self.db['rootmodules']
2566
2566
2567 path = [os.path.abspath(os.path.expanduser(p)) for p in
2567 path = [os.path.abspath(os.path.expanduser(p)) for p in
2568 os.environ.get('PATH','').split(os.pathsep)]
2568 os.environ.get('PATH','').split(os.pathsep)]
2569 path = filter(os.path.isdir,path)
2569 path = filter(os.path.isdir,path)
2570
2570
2571 syscmdlist = []
2571 syscmdlist = []
2572 # Now define isexec in a cross platform manner.
2572 # Now define isexec in a cross platform manner.
2573 if os.name == 'posix':
2573 if os.name == 'posix':
2574 isexec = lambda fname:os.path.isfile(fname) and \
2574 isexec = lambda fname:os.path.isfile(fname) and \
2575 os.access(fname,os.X_OK)
2575 os.access(fname,os.X_OK)
2576 else:
2576 else:
2577 try:
2577 try:
2578 winext = os.environ['pathext'].replace(';','|').replace('.','')
2578 winext = os.environ['pathext'].replace(';','|').replace('.','')
2579 except KeyError:
2579 except KeyError:
2580 winext = 'exe|com|bat|py'
2580 winext = 'exe|com|bat|py'
2581 if 'py' not in winext:
2581 if 'py' not in winext:
2582 winext += '|py'
2582 winext += '|py'
2583 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2583 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2584 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2584 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2585 savedir = os.getcwd()
2585 savedir = os.getcwd()
2586
2586
2587 # Now walk the paths looking for executables to alias.
2587 # Now walk the paths looking for executables to alias.
2588 try:
2588 try:
2589 # write the whole loop for posix/Windows so we don't have an if in
2589 # write the whole loop for posix/Windows so we don't have an if in
2590 # the innermost part
2590 # the innermost part
2591 if os.name == 'posix':
2591 if os.name == 'posix':
2592 for pdir in path:
2592 for pdir in path:
2593 os.chdir(pdir)
2593 os.chdir(pdir)
2594 for ff in os.listdir(pdir):
2594 for ff in os.listdir(pdir):
2595 if isexec(ff):
2595 if isexec(ff):
2596 try:
2596 try:
2597 # Removes dots from the name since ipython
2597 # Removes dots from the name since ipython
2598 # will assume names with dots to be python.
2598 # will assume names with dots to be python.
2599 self.shell.alias_manager.define_alias(
2599 self.shell.alias_manager.define_alias(
2600 ff.replace('.',''), ff)
2600 ff.replace('.',''), ff)
2601 except InvalidAliasError:
2601 except InvalidAliasError:
2602 pass
2602 pass
2603 else:
2603 else:
2604 syscmdlist.append(ff)
2604 syscmdlist.append(ff)
2605 else:
2605 else:
2606 no_alias = self.shell.alias_manager.no_alias
2606 no_alias = self.shell.alias_manager.no_alias
2607 for pdir in path:
2607 for pdir in path:
2608 os.chdir(pdir)
2608 os.chdir(pdir)
2609 for ff in os.listdir(pdir):
2609 for ff in os.listdir(pdir):
2610 base, ext = os.path.splitext(ff)
2610 base, ext = os.path.splitext(ff)
2611 if isexec(ff) and base.lower() not in no_alias:
2611 if isexec(ff) and base.lower() not in no_alias:
2612 if ext.lower() == '.exe':
2612 if ext.lower() == '.exe':
2613 ff = base
2613 ff = base
2614 try:
2614 try:
2615 # Removes dots from the name since ipython
2615 # Removes dots from the name since ipython
2616 # will assume names with dots to be python.
2616 # will assume names with dots to be python.
2617 self.shell.alias_manager.define_alias(
2617 self.shell.alias_manager.define_alias(
2618 base.lower().replace('.',''), ff)
2618 base.lower().replace('.',''), ff)
2619 except InvalidAliasError:
2619 except InvalidAliasError:
2620 pass
2620 pass
2621 syscmdlist.append(ff)
2621 syscmdlist.append(ff)
2622 db = self.db
2622 db = self.db
2623 db['syscmdlist'] = syscmdlist
2623 db['syscmdlist'] = syscmdlist
2624 finally:
2624 finally:
2625 os.chdir(savedir)
2625 os.chdir(savedir)
2626
2626
2627 def magic_pwd(self, parameter_s = ''):
2627 def magic_pwd(self, parameter_s = ''):
2628 """Return the current working directory path."""
2628 """Return the current working directory path."""
2629 return os.getcwd()
2629 return os.getcwd()
2630
2630
2631 def magic_cd(self, parameter_s=''):
2631 def magic_cd(self, parameter_s=''):
2632 """Change the current working directory.
2632 """Change the current working directory.
2633
2633
2634 This command automatically maintains an internal list of directories
2634 This command automatically maintains an internal list of directories
2635 you visit during your IPython session, in the variable _dh. The
2635 you visit during your IPython session, in the variable _dh. The
2636 command %dhist shows this history nicely formatted. You can also
2636 command %dhist shows this history nicely formatted. You can also
2637 do 'cd -<tab>' to see directory history conveniently.
2637 do 'cd -<tab>' to see directory history conveniently.
2638
2638
2639 Usage:
2639 Usage:
2640
2640
2641 cd 'dir': changes to directory 'dir'.
2641 cd 'dir': changes to directory 'dir'.
2642
2642
2643 cd -: changes to the last visited directory.
2643 cd -: changes to the last visited directory.
2644
2644
2645 cd -<n>: changes to the n-th directory in the directory history.
2645 cd -<n>: changes to the n-th directory in the directory history.
2646
2646
2647 cd --foo: change to directory that matches 'foo' in history
2647 cd --foo: change to directory that matches 'foo' in history
2648
2648
2649 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2649 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2650 (note: cd <bookmark_name> is enough if there is no
2650 (note: cd <bookmark_name> is enough if there is no
2651 directory <bookmark_name>, but a bookmark with the name exists.)
2651 directory <bookmark_name>, but a bookmark with the name exists.)
2652 'cd -b <tab>' allows you to tab-complete bookmark names.
2652 'cd -b <tab>' allows you to tab-complete bookmark names.
2653
2653
2654 Options:
2654 Options:
2655
2655
2656 -q: quiet. Do not print the working directory after the cd command is
2656 -q: quiet. Do not print the working directory after the cd command is
2657 executed. By default IPython's cd command does print this directory,
2657 executed. By default IPython's cd command does print this directory,
2658 since the default prompts do not display path information.
2658 since the default prompts do not display path information.
2659
2659
2660 Note that !cd doesn't work for this purpose because the shell where
2660 Note that !cd doesn't work for this purpose because the shell where
2661 !command runs is immediately discarded after executing 'command'."""
2661 !command runs is immediately discarded after executing 'command'."""
2662
2662
2663 parameter_s = parameter_s.strip()
2663 parameter_s = parameter_s.strip()
2664 #bkms = self.shell.persist.get("bookmarks",{})
2664 #bkms = self.shell.persist.get("bookmarks",{})
2665
2665
2666 oldcwd = os.getcwd()
2666 oldcwd = os.getcwd()
2667 numcd = re.match(r'(-)(\d+)$',parameter_s)
2667 numcd = re.match(r'(-)(\d+)$',parameter_s)
2668 # jump in directory history by number
2668 # jump in directory history by number
2669 if numcd:
2669 if numcd:
2670 nn = int(numcd.group(2))
2670 nn = int(numcd.group(2))
2671 try:
2671 try:
2672 ps = self.shell.user_ns['_dh'][nn]
2672 ps = self.shell.user_ns['_dh'][nn]
2673 except IndexError:
2673 except IndexError:
2674 print 'The requested directory does not exist in history.'
2674 print 'The requested directory does not exist in history.'
2675 return
2675 return
2676 else:
2676 else:
2677 opts = {}
2677 opts = {}
2678 elif parameter_s.startswith('--'):
2678 elif parameter_s.startswith('--'):
2679 ps = None
2679 ps = None
2680 fallback = None
2680 fallback = None
2681 pat = parameter_s[2:]
2681 pat = parameter_s[2:]
2682 dh = self.shell.user_ns['_dh']
2682 dh = self.shell.user_ns['_dh']
2683 # first search only by basename (last component)
2683 # first search only by basename (last component)
2684 for ent in reversed(dh):
2684 for ent in reversed(dh):
2685 if pat in os.path.basename(ent) and os.path.isdir(ent):
2685 if pat in os.path.basename(ent) and os.path.isdir(ent):
2686 ps = ent
2686 ps = ent
2687 break
2687 break
2688
2688
2689 if fallback is None and pat in ent and os.path.isdir(ent):
2689 if fallback is None and pat in ent and os.path.isdir(ent):
2690 fallback = ent
2690 fallback = ent
2691
2691
2692 # if we have no last part match, pick the first full path match
2692 # if we have no last part match, pick the first full path match
2693 if ps is None:
2693 if ps is None:
2694 ps = fallback
2694 ps = fallback
2695
2695
2696 if ps is None:
2696 if ps is None:
2697 print "No matching entry in directory history"
2697 print "No matching entry in directory history"
2698 return
2698 return
2699 else:
2699 else:
2700 opts = {}
2700 opts = {}
2701
2701
2702
2702
2703 else:
2703 else:
2704 #turn all non-space-escaping backslashes to slashes,
2704 #turn all non-space-escaping backslashes to slashes,
2705 # for c:\windows\directory\names\
2705 # for c:\windows\directory\names\
2706 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2706 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2707 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2707 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2708 # jump to previous
2708 # jump to previous
2709 if ps == '-':
2709 if ps == '-':
2710 try:
2710 try:
2711 ps = self.shell.user_ns['_dh'][-2]
2711 ps = self.shell.user_ns['_dh'][-2]
2712 except IndexError:
2712 except IndexError:
2713 raise UsageError('%cd -: No previous directory to change to.')
2713 raise UsageError('%cd -: No previous directory to change to.')
2714 # jump to bookmark if needed
2714 # jump to bookmark if needed
2715 else:
2715 else:
2716 if not os.path.isdir(ps) or opts.has_key('b'):
2716 if not os.path.isdir(ps) or opts.has_key('b'):
2717 bkms = self.db.get('bookmarks', {})
2717 bkms = self.db.get('bookmarks', {})
2718
2718
2719 if bkms.has_key(ps):
2719 if bkms.has_key(ps):
2720 target = bkms[ps]
2720 target = bkms[ps]
2721 print '(bookmark:%s) -> %s' % (ps,target)
2721 print '(bookmark:%s) -> %s' % (ps,target)
2722 ps = target
2722 ps = target
2723 else:
2723 else:
2724 if opts.has_key('b'):
2724 if opts.has_key('b'):
2725 raise UsageError("Bookmark '%s' not found. "
2725 raise UsageError("Bookmark '%s' not found. "
2726 "Use '%%bookmark -l' to see your bookmarks." % ps)
2726 "Use '%%bookmark -l' to see your bookmarks." % ps)
2727
2727
2728 # at this point ps should point to the target dir
2728 # at this point ps should point to the target dir
2729 if ps:
2729 if ps:
2730 try:
2730 try:
2731 os.chdir(os.path.expanduser(ps))
2731 os.chdir(os.path.expanduser(ps))
2732 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2732 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2733 set_term_title('IPython: ' + abbrev_cwd())
2733 set_term_title('IPython: ' + abbrev_cwd())
2734 except OSError:
2734 except OSError:
2735 print sys.exc_info()[1]
2735 print sys.exc_info()[1]
2736 else:
2736 else:
2737 cwd = os.getcwd()
2737 cwd = os.getcwd()
2738 dhist = self.shell.user_ns['_dh']
2738 dhist = self.shell.user_ns['_dh']
2739 if oldcwd != cwd:
2739 if oldcwd != cwd:
2740 dhist.append(cwd)
2740 dhist.append(cwd)
2741 self.db['dhist'] = compress_dhist(dhist)[-100:]
2741 self.db['dhist'] = compress_dhist(dhist)[-100:]
2742
2742
2743 else:
2743 else:
2744 os.chdir(self.shell.home_dir)
2744 os.chdir(self.shell.home_dir)
2745 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2745 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2746 set_term_title('IPython: ' + '~')
2746 set_term_title('IPython: ' + '~')
2747 cwd = os.getcwd()
2747 cwd = os.getcwd()
2748 dhist = self.shell.user_ns['_dh']
2748 dhist = self.shell.user_ns['_dh']
2749
2749
2750 if oldcwd != cwd:
2750 if oldcwd != cwd:
2751 dhist.append(cwd)
2751 dhist.append(cwd)
2752 self.db['dhist'] = compress_dhist(dhist)[-100:]
2752 self.db['dhist'] = compress_dhist(dhist)[-100:]
2753 if not 'q' in opts and self.shell.user_ns['_dh']:
2753 if not 'q' in opts and self.shell.user_ns['_dh']:
2754 print self.shell.user_ns['_dh'][-1]
2754 print self.shell.user_ns['_dh'][-1]
2755
2755
2756
2756
2757 def magic_env(self, parameter_s=''):
2757 def magic_env(self, parameter_s=''):
2758 """List environment variables."""
2758 """List environment variables."""
2759
2759
2760 return os.environ.data
2760 return os.environ.data
2761
2761
2762 def magic_pushd(self, parameter_s=''):
2762 def magic_pushd(self, parameter_s=''):
2763 """Place the current dir on stack and change directory.
2763 """Place the current dir on stack and change directory.
2764
2764
2765 Usage:\\
2765 Usage:\\
2766 %pushd ['dirname']
2766 %pushd ['dirname']
2767 """
2767 """
2768
2768
2769 dir_s = self.shell.dir_stack
2769 dir_s = self.shell.dir_stack
2770 tgt = os.path.expanduser(parameter_s)
2770 tgt = os.path.expanduser(parameter_s)
2771 cwd = os.getcwd().replace(self.home_dir,'~')
2771 cwd = os.getcwd().replace(self.home_dir,'~')
2772 if tgt:
2772 if tgt:
2773 self.magic_cd(parameter_s)
2773 self.magic_cd(parameter_s)
2774 dir_s.insert(0,cwd)
2774 dir_s.insert(0,cwd)
2775 return self.magic_dirs()
2775 return self.magic_dirs()
2776
2776
2777 def magic_popd(self, parameter_s=''):
2777 def magic_popd(self, parameter_s=''):
2778 """Change to directory popped off the top of the stack.
2778 """Change to directory popped off the top of the stack.
2779 """
2779 """
2780 if not self.shell.dir_stack:
2780 if not self.shell.dir_stack:
2781 raise UsageError("%popd on empty stack")
2781 raise UsageError("%popd on empty stack")
2782 top = self.shell.dir_stack.pop(0)
2782 top = self.shell.dir_stack.pop(0)
2783 self.magic_cd(top)
2783 self.magic_cd(top)
2784 print "popd ->",top
2784 print "popd ->",top
2785
2785
2786 def magic_dirs(self, parameter_s=''):
2786 def magic_dirs(self, parameter_s=''):
2787 """Return the current directory stack."""
2787 """Return the current directory stack."""
2788
2788
2789 return self.shell.dir_stack
2789 return self.shell.dir_stack
2790
2790
2791 def magic_dhist(self, parameter_s=''):
2791 def magic_dhist(self, parameter_s=''):
2792 """Print your history of visited directories.
2792 """Print your history of visited directories.
2793
2793
2794 %dhist -> print full history\\
2794 %dhist -> print full history\\
2795 %dhist n -> print last n entries only\\
2795 %dhist n -> print last n entries only\\
2796 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2796 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2797
2797
2798 This history is automatically maintained by the %cd command, and
2798 This history is automatically maintained by the %cd command, and
2799 always available as the global list variable _dh. You can use %cd -<n>
2799 always available as the global list variable _dh. You can use %cd -<n>
2800 to go to directory number <n>.
2800 to go to directory number <n>.
2801
2801
2802 Note that most of time, you should view directory history by entering
2802 Note that most of time, you should view directory history by entering
2803 cd -<TAB>.
2803 cd -<TAB>.
2804
2804
2805 """
2805 """
2806
2806
2807 dh = self.shell.user_ns['_dh']
2807 dh = self.shell.user_ns['_dh']
2808 if parameter_s:
2808 if parameter_s:
2809 try:
2809 try:
2810 args = map(int,parameter_s.split())
2810 args = map(int,parameter_s.split())
2811 except:
2811 except:
2812 self.arg_err(Magic.magic_dhist)
2812 self.arg_err(Magic.magic_dhist)
2813 return
2813 return
2814 if len(args) == 1:
2814 if len(args) == 1:
2815 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2815 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2816 elif len(args) == 2:
2816 elif len(args) == 2:
2817 ini,fin = args
2817 ini,fin = args
2818 else:
2818 else:
2819 self.arg_err(Magic.magic_dhist)
2819 self.arg_err(Magic.magic_dhist)
2820 return
2820 return
2821 else:
2821 else:
2822 ini,fin = 0,len(dh)
2822 ini,fin = 0,len(dh)
2823 nlprint(dh,
2823 nlprint(dh,
2824 header = 'Directory history (kept in _dh)',
2824 header = 'Directory history (kept in _dh)',
2825 start=ini,stop=fin)
2825 start=ini,stop=fin)
2826
2826
2827 @testdec.skip_doctest
2827 @testdec.skip_doctest
2828 def magic_sc(self, parameter_s=''):
2828 def magic_sc(self, parameter_s=''):
2829 """Shell capture - execute a shell command and capture its output.
2829 """Shell capture - execute a shell command and capture its output.
2830
2830
2831 DEPRECATED. Suboptimal, retained for backwards compatibility.
2831 DEPRECATED. Suboptimal, retained for backwards compatibility.
2832
2832
2833 You should use the form 'var = !command' instead. Example:
2833 You should use the form 'var = !command' instead. Example:
2834
2834
2835 "%sc -l myfiles = ls ~" should now be written as
2835 "%sc -l myfiles = ls ~" should now be written as
2836
2836
2837 "myfiles = !ls ~"
2837 "myfiles = !ls ~"
2838
2838
2839 myfiles.s, myfiles.l and myfiles.n still apply as documented
2839 myfiles.s, myfiles.l and myfiles.n still apply as documented
2840 below.
2840 below.
2841
2841
2842 --
2842 --
2843 %sc [options] varname=command
2843 %sc [options] varname=command
2844
2844
2845 IPython will run the given command using commands.getoutput(), and
2845 IPython will run the given command using commands.getoutput(), and
2846 will then update the user's interactive namespace with a variable
2846 will then update the user's interactive namespace with a variable
2847 called varname, containing the value of the call. Your command can
2847 called varname, containing the value of the call. Your command can
2848 contain shell wildcards, pipes, etc.
2848 contain shell wildcards, pipes, etc.
2849
2849
2850 The '=' sign in the syntax is mandatory, and the variable name you
2850 The '=' sign in the syntax is mandatory, and the variable name you
2851 supply must follow Python's standard conventions for valid names.
2851 supply must follow Python's standard conventions for valid names.
2852
2852
2853 (A special format without variable name exists for internal use)
2853 (A special format without variable name exists for internal use)
2854
2854
2855 Options:
2855 Options:
2856
2856
2857 -l: list output. Split the output on newlines into a list before
2857 -l: list output. Split the output on newlines into a list before
2858 assigning it to the given variable. By default the output is stored
2858 assigning it to the given variable. By default the output is stored
2859 as a single string.
2859 as a single string.
2860
2860
2861 -v: verbose. Print the contents of the variable.
2861 -v: verbose. Print the contents of the variable.
2862
2862
2863 In most cases you should not need to split as a list, because the
2863 In most cases you should not need to split as a list, because the
2864 returned value is a special type of string which can automatically
2864 returned value is a special type of string which can automatically
2865 provide its contents either as a list (split on newlines) or as a
2865 provide its contents either as a list (split on newlines) or as a
2866 space-separated string. These are convenient, respectively, either
2866 space-separated string. These are convenient, respectively, either
2867 for sequential processing or to be passed to a shell command.
2867 for sequential processing or to be passed to a shell command.
2868
2868
2869 For example:
2869 For example:
2870
2870
2871 # all-random
2871 # all-random
2872
2872
2873 # Capture into variable a
2873 # Capture into variable a
2874 In [1]: sc a=ls *py
2874 In [1]: sc a=ls *py
2875
2875
2876 # a is a string with embedded newlines
2876 # a is a string with embedded newlines
2877 In [2]: a
2877 In [2]: a
2878 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2878 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2879
2879
2880 # which can be seen as a list:
2880 # which can be seen as a list:
2881 In [3]: a.l
2881 In [3]: a.l
2882 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2882 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2883
2883
2884 # or as a whitespace-separated string:
2884 # or as a whitespace-separated string:
2885 In [4]: a.s
2885 In [4]: a.s
2886 Out[4]: 'setup.py win32_manual_post_install.py'
2886 Out[4]: 'setup.py win32_manual_post_install.py'
2887
2887
2888 # a.s is useful to pass as a single command line:
2888 # a.s is useful to pass as a single command line:
2889 In [5]: !wc -l $a.s
2889 In [5]: !wc -l $a.s
2890 146 setup.py
2890 146 setup.py
2891 130 win32_manual_post_install.py
2891 130 win32_manual_post_install.py
2892 276 total
2892 276 total
2893
2893
2894 # while the list form is useful to loop over:
2894 # while the list form is useful to loop over:
2895 In [6]: for f in a.l:
2895 In [6]: for f in a.l:
2896 ...: !wc -l $f
2896 ...: !wc -l $f
2897 ...:
2897 ...:
2898 146 setup.py
2898 146 setup.py
2899 130 win32_manual_post_install.py
2899 130 win32_manual_post_install.py
2900
2900
2901 Similiarly, the lists returned by the -l option are also special, in
2901 Similiarly, the lists returned by the -l option are also special, in
2902 the sense that you can equally invoke the .s attribute on them to
2902 the sense that you can equally invoke the .s attribute on them to
2903 automatically get a whitespace-separated string from their contents:
2903 automatically get a whitespace-separated string from their contents:
2904
2904
2905 In [7]: sc -l b=ls *py
2905 In [7]: sc -l b=ls *py
2906
2906
2907 In [8]: b
2907 In [8]: b
2908 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2908 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2909
2909
2910 In [9]: b.s
2910 In [9]: b.s
2911 Out[9]: 'setup.py win32_manual_post_install.py'
2911 Out[9]: 'setup.py win32_manual_post_install.py'
2912
2912
2913 In summary, both the lists and strings used for ouptut capture have
2913 In summary, both the lists and strings used for ouptut capture have
2914 the following special attributes:
2914 the following special attributes:
2915
2915
2916 .l (or .list) : value as list.
2916 .l (or .list) : value as list.
2917 .n (or .nlstr): value as newline-separated string.
2917 .n (or .nlstr): value as newline-separated string.
2918 .s (or .spstr): value as space-separated string.
2918 .s (or .spstr): value as space-separated string.
2919 """
2919 """
2920
2920
2921 opts,args = self.parse_options(parameter_s,'lv')
2921 opts,args = self.parse_options(parameter_s,'lv')
2922 # Try to get a variable name and command to run
2922 # Try to get a variable name and command to run
2923 try:
2923 try:
2924 # the variable name must be obtained from the parse_options
2924 # the variable name must be obtained from the parse_options
2925 # output, which uses shlex.split to strip options out.
2925 # output, which uses shlex.split to strip options out.
2926 var,_ = args.split('=',1)
2926 var,_ = args.split('=',1)
2927 var = var.strip()
2927 var = var.strip()
2928 # But the the command has to be extracted from the original input
2928 # But the the command has to be extracted from the original input
2929 # parameter_s, not on what parse_options returns, to avoid the
2929 # parameter_s, not on what parse_options returns, to avoid the
2930 # quote stripping which shlex.split performs on it.
2930 # quote stripping which shlex.split performs on it.
2931 _,cmd = parameter_s.split('=',1)
2931 _,cmd = parameter_s.split('=',1)
2932 except ValueError:
2932 except ValueError:
2933 var,cmd = '',''
2933 var,cmd = '',''
2934 # If all looks ok, proceed
2934 # If all looks ok, proceed
2935 out = self.shell.getoutput(cmd)
2935 out = self.shell.getoutput(cmd)
2936 if opts.has_key('l'):
2936 if opts.has_key('l'):
2937 out = SList(out.split('\n'))
2937 out = SList(out.split('\n'))
2938 else:
2938 else:
2939 out = LSString(out)
2939 out = LSString(out)
2940 if opts.has_key('v'):
2940 if opts.has_key('v'):
2941 print '%s ==\n%s' % (var,pformat(out))
2941 print '%s ==\n%s' % (var,pformat(out))
2942 if var:
2942 if var:
2943 self.shell.user_ns.update({var:out})
2943 self.shell.user_ns.update({var:out})
2944 else:
2944 else:
2945 return out
2945 return out
2946
2946
2947 def magic_sx(self, parameter_s=''):
2947 def magic_sx(self, parameter_s=''):
2948 """Shell execute - run a shell command and capture its output.
2948 """Shell execute - run a shell command and capture its output.
2949
2949
2950 %sx command
2950 %sx command
2951
2951
2952 IPython will run the given command using commands.getoutput(), and
2952 IPython will run the given command using commands.getoutput(), and
2953 return the result formatted as a list (split on '\\n'). Since the
2953 return the result formatted as a list (split on '\\n'). Since the
2954 output is _returned_, it will be stored in ipython's regular output
2954 output is _returned_, it will be stored in ipython's regular output
2955 cache Out[N] and in the '_N' automatic variables.
2955 cache Out[N] and in the '_N' automatic variables.
2956
2956
2957 Notes:
2957 Notes:
2958
2958
2959 1) If an input line begins with '!!', then %sx is automatically
2959 1) If an input line begins with '!!', then %sx is automatically
2960 invoked. That is, while:
2960 invoked. That is, while:
2961 !ls
2961 !ls
2962 causes ipython to simply issue system('ls'), typing
2962 causes ipython to simply issue system('ls'), typing
2963 !!ls
2963 !!ls
2964 is a shorthand equivalent to:
2964 is a shorthand equivalent to:
2965 %sx ls
2965 %sx ls
2966
2966
2967 2) %sx differs from %sc in that %sx automatically splits into a list,
2967 2) %sx differs from %sc in that %sx automatically splits into a list,
2968 like '%sc -l'. The reason for this is to make it as easy as possible
2968 like '%sc -l'. The reason for this is to make it as easy as possible
2969 to process line-oriented shell output via further python commands.
2969 to process line-oriented shell output via further python commands.
2970 %sc is meant to provide much finer control, but requires more
2970 %sc is meant to provide much finer control, but requires more
2971 typing.
2971 typing.
2972
2972
2973 3) Just like %sc -l, this is a list with special attributes:
2973 3) Just like %sc -l, this is a list with special attributes:
2974
2974
2975 .l (or .list) : value as list.
2975 .l (or .list) : value as list.
2976 .n (or .nlstr): value as newline-separated string.
2976 .n (or .nlstr): value as newline-separated string.
2977 .s (or .spstr): value as whitespace-separated string.
2977 .s (or .spstr): value as whitespace-separated string.
2978
2978
2979 This is very useful when trying to use such lists as arguments to
2979 This is very useful when trying to use such lists as arguments to
2980 system commands."""
2980 system commands."""
2981
2981
2982 if parameter_s:
2982 if parameter_s:
2983 out = self.shell.getoutput(parameter_s)
2983 out = self.shell.getoutput(parameter_s)
2984 if out is not None:
2984 if out is not None:
2985 return SList(out.splitlines())
2985 return SList(out.splitlines())
2986
2986
2987 def magic_r(self, parameter_s=''):
2987 def magic_r(self, parameter_s=''):
2988 """Repeat previous input.
2988 """Repeat previous input.
2989
2989
2990 Note: Consider using the more powerfull %rep instead!
2990 Note: Consider using the more powerfull %rep instead!
2991
2991
2992 If given an argument, repeats the previous command which starts with
2992 If given an argument, repeats the previous command which starts with
2993 the same string, otherwise it just repeats the previous input.
2993 the same string, otherwise it just repeats the previous input.
2994
2994
2995 Shell escaped commands (with ! as first character) are not recognized
2995 Shell escaped commands (with ! as first character) are not recognized
2996 by this system, only pure python code and magic commands.
2996 by this system, only pure python code and magic commands.
2997 """
2997 """
2998
2998
2999 start = parameter_s.strip()
2999 start = parameter_s.strip()
3000 esc_magic = ESC_MAGIC
3000 esc_magic = ESC_MAGIC
3001 # Identify magic commands even if automagic is on (which means
3001 # Identify magic commands even if automagic is on (which means
3002 # the in-memory version is different from that typed by the user).
3002 # the in-memory version is different from that typed by the user).
3003 if self.shell.automagic:
3003 if self.shell.automagic:
3004 start_magic = esc_magic+start
3004 start_magic = esc_magic+start
3005 else:
3005 else:
3006 start_magic = start
3006 start_magic = start
3007 # Look through the input history in reverse
3007 # Look through the input history in reverse
3008 for n in range(len(self.shell.input_hist)-2,0,-1):
3008 for n in range(len(self.shell.input_hist)-2,0,-1):
3009 input = self.shell.input_hist[n]
3009 input = self.shell.input_hist[n]
3010 # skip plain 'r' lines so we don't recurse to infinity
3010 # skip plain 'r' lines so we don't recurse to infinity
3011 if input != '_ip.magic("r")\n' and \
3011 if input != '_ip.magic("r")\n' and \
3012 (input.startswith(start) or input.startswith(start_magic)):
3012 (input.startswith(start) or input.startswith(start_magic)):
3013 #print 'match',`input` # dbg
3013 #print 'match',`input` # dbg
3014 print 'Executing:',input,
3014 print 'Executing:',input,
3015 self.shell.runlines(input)
3015 self.shell.runlines(input)
3016 return
3016 return
3017 print 'No previous input matching `%s` found.' % start
3017 print 'No previous input matching `%s` found.' % start
3018
3018
3019
3019
3020 def magic_bookmark(self, parameter_s=''):
3020 def magic_bookmark(self, parameter_s=''):
3021 """Manage IPython's bookmark system.
3021 """Manage IPython's bookmark system.
3022
3022
3023 %bookmark <name> - set bookmark to current dir
3023 %bookmark <name> - set bookmark to current dir
3024 %bookmark <name> <dir> - set bookmark to <dir>
3024 %bookmark <name> <dir> - set bookmark to <dir>
3025 %bookmark -l - list all bookmarks
3025 %bookmark -l - list all bookmarks
3026 %bookmark -d <name> - remove bookmark
3026 %bookmark -d <name> - remove bookmark
3027 %bookmark -r - remove all bookmarks
3027 %bookmark -r - remove all bookmarks
3028
3028
3029 You can later on access a bookmarked folder with:
3029 You can later on access a bookmarked folder with:
3030 %cd -b <name>
3030 %cd -b <name>
3031 or simply '%cd <name>' if there is no directory called <name> AND
3031 or simply '%cd <name>' if there is no directory called <name> AND
3032 there is such a bookmark defined.
3032 there is such a bookmark defined.
3033
3033
3034 Your bookmarks persist through IPython sessions, but they are
3034 Your bookmarks persist through IPython sessions, but they are
3035 associated with each profile."""
3035 associated with each profile."""
3036
3036
3037 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3037 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3038 if len(args) > 2:
3038 if len(args) > 2:
3039 raise UsageError("%bookmark: too many arguments")
3039 raise UsageError("%bookmark: too many arguments")
3040
3040
3041 bkms = self.db.get('bookmarks',{})
3041 bkms = self.db.get('bookmarks',{})
3042
3042
3043 if opts.has_key('d'):
3043 if opts.has_key('d'):
3044 try:
3044 try:
3045 todel = args[0]
3045 todel = args[0]
3046 except IndexError:
3046 except IndexError:
3047 raise UsageError(
3047 raise UsageError(
3048 "%bookmark -d: must provide a bookmark to delete")
3048 "%bookmark -d: must provide a bookmark to delete")
3049 else:
3049 else:
3050 try:
3050 try:
3051 del bkms[todel]
3051 del bkms[todel]
3052 except KeyError:
3052 except KeyError:
3053 raise UsageError(
3053 raise UsageError(
3054 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3054 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3055
3055
3056 elif opts.has_key('r'):
3056 elif opts.has_key('r'):
3057 bkms = {}
3057 bkms = {}
3058 elif opts.has_key('l'):
3058 elif opts.has_key('l'):
3059 bks = bkms.keys()
3059 bks = bkms.keys()
3060 bks.sort()
3060 bks.sort()
3061 if bks:
3061 if bks:
3062 size = max(map(len,bks))
3062 size = max(map(len,bks))
3063 else:
3063 else:
3064 size = 0
3064 size = 0
3065 fmt = '%-'+str(size)+'s -> %s'
3065 fmt = '%-'+str(size)+'s -> %s'
3066 print 'Current bookmarks:'
3066 print 'Current bookmarks:'
3067 for bk in bks:
3067 for bk in bks:
3068 print fmt % (bk,bkms[bk])
3068 print fmt % (bk,bkms[bk])
3069 else:
3069 else:
3070 if not args:
3070 if not args:
3071 raise UsageError("%bookmark: You must specify the bookmark name")
3071 raise UsageError("%bookmark: You must specify the bookmark name")
3072 elif len(args)==1:
3072 elif len(args)==1:
3073 bkms[args[0]] = os.getcwd()
3073 bkms[args[0]] = os.getcwd()
3074 elif len(args)==2:
3074 elif len(args)==2:
3075 bkms[args[0]] = args[1]
3075 bkms[args[0]] = args[1]
3076 self.db['bookmarks'] = bkms
3076 self.db['bookmarks'] = bkms
3077
3077
3078 def magic_pycat(self, parameter_s=''):
3078 def magic_pycat(self, parameter_s=''):
3079 """Show a syntax-highlighted file through a pager.
3079 """Show a syntax-highlighted file through a pager.
3080
3080
3081 This magic is similar to the cat utility, but it will assume the file
3081 This magic is similar to the cat utility, but it will assume the file
3082 to be Python source and will show it with syntax highlighting. """
3082 to be Python source and will show it with syntax highlighting. """
3083
3083
3084 try:
3084 try:
3085 filename = get_py_filename(parameter_s)
3085 filename = get_py_filename(parameter_s)
3086 cont = file_read(filename)
3086 cont = file_read(filename)
3087 except IOError:
3087 except IOError:
3088 try:
3088 try:
3089 cont = eval(parameter_s,self.user_ns)
3089 cont = eval(parameter_s,self.user_ns)
3090 except NameError:
3090 except NameError:
3091 cont = None
3091 cont = None
3092 if cont is None:
3092 if cont is None:
3093 print "Error: no such file or variable"
3093 print "Error: no such file or variable"
3094 return
3094 return
3095
3095
3096 page.page(self.shell.pycolorize(cont))
3096 page.page(self.shell.pycolorize(cont))
3097
3097
3098 def _rerun_pasted(self):
3098 def _rerun_pasted(self):
3099 """ Rerun a previously pasted command.
3099 """ Rerun a previously pasted command.
3100 """
3100 """
3101 b = self.user_ns.get('pasted_block', None)
3101 b = self.user_ns.get('pasted_block', None)
3102 if b is None:
3102 if b is None:
3103 raise UsageError('No previous pasted block available')
3103 raise UsageError('No previous pasted block available')
3104 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3104 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3105 exec b in self.user_ns
3105 exec b in self.user_ns
3106
3106
3107 def _get_pasted_lines(self, sentinel):
3107 def _get_pasted_lines(self, sentinel):
3108 """ Yield pasted lines until the user enters the given sentinel value.
3108 """ Yield pasted lines until the user enters the given sentinel value.
3109 """
3109 """
3110 from IPython.core import interactiveshell
3110 from IPython.core import interactiveshell
3111 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3111 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3112 while True:
3112 while True:
3113 l = interactiveshell.raw_input_original(':')
3113 l = interactiveshell.raw_input_original(':')
3114 if l == sentinel:
3114 if l == sentinel:
3115 return
3115 return
3116 else:
3116 else:
3117 yield l
3117 yield l
3118
3118
3119 def _strip_pasted_lines_for_code(self, raw_lines):
3119 def _strip_pasted_lines_for_code(self, raw_lines):
3120 """ Strip non-code parts of a sequence of lines to return a block of
3120 """ Strip non-code parts of a sequence of lines to return a block of
3121 code.
3121 code.
3122 """
3122 """
3123 # Regular expressions that declare text we strip from the input:
3123 # Regular expressions that declare text we strip from the input:
3124 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3124 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3125 r'^\s*(\s?>)+', # Python input prompt
3125 r'^\s*(\s?>)+', # Python input prompt
3126 r'^\s*\.{3,}', # Continuation prompts
3126 r'^\s*\.{3,}', # Continuation prompts
3127 r'^\++',
3127 r'^\++',
3128 ]
3128 ]
3129
3129
3130 strip_from_start = map(re.compile,strip_re)
3130 strip_from_start = map(re.compile,strip_re)
3131
3131
3132 lines = []
3132 lines = []
3133 for l in raw_lines:
3133 for l in raw_lines:
3134 for pat in strip_from_start:
3134 for pat in strip_from_start:
3135 l = pat.sub('',l)
3135 l = pat.sub('',l)
3136 lines.append(l)
3136 lines.append(l)
3137
3137
3138 block = "\n".join(lines) + '\n'
3138 block = "\n".join(lines) + '\n'
3139 #print "block:\n",block
3139 #print "block:\n",block
3140 return block
3140 return block
3141
3141
3142 def _execute_block(self, block, par):
3142 def _execute_block(self, block, par):
3143 """ Execute a block, or store it in a variable, per the user's request.
3143 """ Execute a block, or store it in a variable, per the user's request.
3144 """
3144 """
3145 if not par:
3145 if not par:
3146 b = textwrap.dedent(block)
3146 b = textwrap.dedent(block)
3147 self.user_ns['pasted_block'] = b
3147 self.user_ns['pasted_block'] = b
3148 exec b in self.user_ns
3148 exec b in self.user_ns
3149 else:
3149 else:
3150 self.user_ns[par] = SList(block.splitlines())
3150 self.user_ns[par] = SList(block.splitlines())
3151 print "Block assigned to '%s'" % par
3151 print "Block assigned to '%s'" % par
3152
3152
3153 def magic_cpaste(self, parameter_s=''):
3153 def magic_cpaste(self, parameter_s=''):
3154 """Allows you to paste & execute a pre-formatted code block from clipboard.
3154 """Allows you to paste & execute a pre-formatted code block from clipboard.
3155
3155
3156 You must terminate the block with '--' (two minus-signs) alone on the
3156 You must terminate the block with '--' (two minus-signs) alone on the
3157 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3157 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3158 is the new sentinel for this operation)
3158 is the new sentinel for this operation)
3159
3159
3160 The block is dedented prior to execution to enable execution of method
3160 The block is dedented prior to execution to enable execution of method
3161 definitions. '>' and '+' characters at the beginning of a line are
3161 definitions. '>' and '+' characters at the beginning of a line are
3162 ignored, to allow pasting directly from e-mails, diff files and
3162 ignored, to allow pasting directly from e-mails, diff files and
3163 doctests (the '...' continuation prompt is also stripped). The
3163 doctests (the '...' continuation prompt is also stripped). The
3164 executed block is also assigned to variable named 'pasted_block' for
3164 executed block is also assigned to variable named 'pasted_block' for
3165 later editing with '%edit pasted_block'.
3165 later editing with '%edit pasted_block'.
3166
3166
3167 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3167 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3168 This assigns the pasted block to variable 'foo' as string, without
3168 This assigns the pasted block to variable 'foo' as string, without
3169 dedenting or executing it (preceding >>> and + is still stripped)
3169 dedenting or executing it (preceding >>> and + is still stripped)
3170
3170
3171 '%cpaste -r' re-executes the block previously entered by cpaste.
3171 '%cpaste -r' re-executes the block previously entered by cpaste.
3172
3172
3173 Do not be alarmed by garbled output on Windows (it's a readline bug).
3173 Do not be alarmed by garbled output on Windows (it's a readline bug).
3174 Just press enter and type -- (and press enter again) and the block
3174 Just press enter and type -- (and press enter again) and the block
3175 will be what was just pasted.
3175 will be what was just pasted.
3176
3176
3177 IPython statements (magics, shell escapes) are not supported (yet).
3177 IPython statements (magics, shell escapes) are not supported (yet).
3178
3178
3179 See also
3179 See also
3180 --------
3180 --------
3181 paste: automatically pull code from clipboard.
3181 paste: automatically pull code from clipboard.
3182 """
3182 """
3183
3183
3184 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3184 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3185 par = args.strip()
3185 par = args.strip()
3186 if opts.has_key('r'):
3186 if opts.has_key('r'):
3187 self._rerun_pasted()
3187 self._rerun_pasted()
3188 return
3188 return
3189
3189
3190 sentinel = opts.get('s','--')
3190 sentinel = opts.get('s','--')
3191
3191
3192 block = self._strip_pasted_lines_for_code(
3192 block = self._strip_pasted_lines_for_code(
3193 self._get_pasted_lines(sentinel))
3193 self._get_pasted_lines(sentinel))
3194
3194
3195 self._execute_block(block, par)
3195 self._execute_block(block, par)
3196
3196
3197 def magic_paste(self, parameter_s=''):
3197 def magic_paste(self, parameter_s=''):
3198 """Allows you to paste & execute a pre-formatted code block from clipboard.
3198 """Allows you to paste & execute a pre-formatted code block from clipboard.
3199
3199
3200 The text is pulled directly from the clipboard without user
3200 The text is pulled directly from the clipboard without user
3201 intervention and printed back on the screen before execution (unless
3201 intervention and printed back on the screen before execution (unless
3202 the -q flag is given to force quiet mode).
3202 the -q flag is given to force quiet mode).
3203
3203
3204 The block is dedented prior to execution to enable execution of method
3204 The block is dedented prior to execution to enable execution of method
3205 definitions. '>' and '+' characters at the beginning of a line are
3205 definitions. '>' and '+' characters at the beginning of a line are
3206 ignored, to allow pasting directly from e-mails, diff files and
3206 ignored, to allow pasting directly from e-mails, diff files and
3207 doctests (the '...' continuation prompt is also stripped). The
3207 doctests (the '...' continuation prompt is also stripped). The
3208 executed block is also assigned to variable named 'pasted_block' for
3208 executed block is also assigned to variable named 'pasted_block' for
3209 later editing with '%edit pasted_block'.
3209 later editing with '%edit pasted_block'.
3210
3210
3211 You can also pass a variable name as an argument, e.g. '%paste foo'.
3211 You can also pass a variable name as an argument, e.g. '%paste foo'.
3212 This assigns the pasted block to variable 'foo' as string, without
3212 This assigns the pasted block to variable 'foo' as string, without
3213 dedenting or executing it (preceding >>> and + is still stripped)
3213 dedenting or executing it (preceding >>> and + is still stripped)
3214
3214
3215 Options
3215 Options
3216 -------
3216 -------
3217
3217
3218 -r: re-executes the block previously entered by cpaste.
3218 -r: re-executes the block previously entered by cpaste.
3219
3219
3220 -q: quiet mode: do not echo the pasted text back to the terminal.
3220 -q: quiet mode: do not echo the pasted text back to the terminal.
3221
3221
3222 IPython statements (magics, shell escapes) are not supported (yet).
3222 IPython statements (magics, shell escapes) are not supported (yet).
3223
3223
3224 See also
3224 See also
3225 --------
3225 --------
3226 cpaste: manually paste code into terminal until you mark its end.
3226 cpaste: manually paste code into terminal until you mark its end.
3227 """
3227 """
3228 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3228 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3229 par = args.strip()
3229 par = args.strip()
3230 if opts.has_key('r'):
3230 if opts.has_key('r'):
3231 self._rerun_pasted()
3231 self._rerun_pasted()
3232 return
3232 return
3233
3233
3234 text = self.shell.hooks.clipboard_get()
3234 text = self.shell.hooks.clipboard_get()
3235 block = self._strip_pasted_lines_for_code(text.splitlines())
3235 block = self._strip_pasted_lines_for_code(text.splitlines())
3236
3236
3237 # By default, echo back to terminal unless quiet mode is requested
3237 # By default, echo back to terminal unless quiet mode is requested
3238 if not opts.has_key('q'):
3238 if not opts.has_key('q'):
3239 write = self.shell.write
3239 write = self.shell.write
3240 write(self.shell.pycolorize(block))
3240 write(self.shell.pycolorize(block))
3241 if not block.endswith('\n'):
3241 if not block.endswith('\n'):
3242 write('\n')
3242 write('\n')
3243 write("## -- End pasted text --\n")
3243 write("## -- End pasted text --\n")
3244
3244
3245 self._execute_block(block, par)
3245 self._execute_block(block, par)
3246
3246
3247 def magic_quickref(self,arg):
3247 def magic_quickref(self,arg):
3248 """ Show a quick reference sheet """
3248 """ Show a quick reference sheet """
3249 import IPython.core.usage
3249 import IPython.core.usage
3250 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3250 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3251
3251
3252 page.page(qr)
3252 page.page(qr)
3253
3253
3254 def magic_doctest_mode(self,parameter_s=''):
3254 def magic_doctest_mode(self,parameter_s=''):
3255 """Toggle doctest mode on and off.
3255 """Toggle doctest mode on and off.
3256
3256
3257 This mode allows you to toggle the prompt behavior between normal
3257 This mode is intended to make IPython behave as much as possible like a
3258 IPython prompts and ones that are as similar to the default IPython
3258 plain Python shell, from the perspective of how its prompts, exceptions
3259 interpreter as possible.
3259 and output look. This makes it easy to copy and paste parts of a
3260
3260 session into doctests. It does so by:
3261 It also supports the pasting of code snippets that have leading '>>>'
3261
3262 and '...' prompts in them. This means that you can paste doctests from
3262 - Changing the prompts to the classic ``>>>`` ones.
3263 files or docstrings (even if they have leading whitespace), and the
3263 - Changing the exception reporting mode to 'Plain'.
3264 code will execute correctly. You can then use '%history -tn' to see
3264 - Disabling pretty-printing of output.
3265 the translated history without line numbers; this will give you the
3265
3266 Note that IPython also supports the pasting of code snippets that have
3267 leading '>>>' and '...' prompts in them. This means that you can paste
3268 doctests from files or docstrings (even if they have leading
3269 whitespace), and the code will execute correctly. You can then use
3270 '%history -t' to see the translated history; this will give you the
3266 input after removal of all the leading prompts and whitespace, which
3271 input after removal of all the leading prompts and whitespace, which
3267 can be pasted back into an editor.
3272 can be pasted back into an editor.
3268
3273
3269 With these features, you can switch into this mode easily whenever you
3274 With these features, you can switch into this mode easily whenever you
3270 need to do testing and changes to doctests, without having to leave
3275 need to do testing and changes to doctests, without having to leave
3271 your existing IPython session.
3276 your existing IPython session.
3272 """
3277 """
3273
3278
3274 from IPython.utils.ipstruct import Struct
3279 from IPython.utils.ipstruct import Struct
3275
3280
3276 # Shorthands
3281 # Shorthands
3277 shell = self.shell
3282 shell = self.shell
3278 oc = shell.displayhook
3283 oc = shell.displayhook
3279 meta = shell.meta
3284 meta = shell.meta
3280 # dstore is a data store kept in the instance metadata bag to track any
3285 # dstore is a data store kept in the instance metadata bag to track any
3281 # changes we make, so we can undo them later.
3286 # changes we make, so we can undo them later.
3282 dstore = meta.setdefault('doctest_mode',Struct())
3287 dstore = meta.setdefault('doctest_mode',Struct())
3283 save_dstore = dstore.setdefault
3288 save_dstore = dstore.setdefault
3284
3289
3285 # save a few values we'll need to recover later
3290 # save a few values we'll need to recover later
3286 mode = save_dstore('mode',False)
3291 mode = save_dstore('mode',False)
3287 save_dstore('rc_pprint',shell.pprint)
3292 save_dstore('rc_pprint',shell.pprint)
3288 save_dstore('xmode',shell.InteractiveTB.mode)
3293 save_dstore('xmode',shell.InteractiveTB.mode)
3289 save_dstore('rc_separate_out',shell.separate_out)
3294 save_dstore('rc_separate_out',shell.separate_out)
3290 save_dstore('rc_separate_out2',shell.separate_out2)
3295 save_dstore('rc_separate_out2',shell.separate_out2)
3291 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3296 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3292 save_dstore('rc_separate_in',shell.separate_in)
3297 save_dstore('rc_separate_in',shell.separate_in)
3293
3298
3294 if mode == False:
3299 if mode == False:
3295 # turn on
3300 # turn on
3296 oc.prompt1.p_template = '>>> '
3301 oc.prompt1.p_template = '>>> '
3297 oc.prompt2.p_template = '... '
3302 oc.prompt2.p_template = '... '
3298 oc.prompt_out.p_template = ''
3303 oc.prompt_out.p_template = ''
3299
3304
3300 # Prompt separators like plain python
3305 # Prompt separators like plain python
3301 oc.input_sep = oc.prompt1.sep = ''
3306 oc.input_sep = oc.prompt1.sep = ''
3302 oc.output_sep = ''
3307 oc.output_sep = ''
3303 oc.output_sep2 = ''
3308 oc.output_sep2 = ''
3304
3309
3305 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3310 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3306 oc.prompt_out.pad_left = False
3311 oc.prompt_out.pad_left = False
3307
3312
3308 shell.pprint = False
3313 shell.pprint = False
3309
3314
3310 shell.magic_xmode('Plain')
3315 shell.magic_xmode('Plain')
3311
3312 else:
3316 else:
3313 # turn off
3317 # turn off
3314 oc.prompt1.p_template = shell.prompt_in1
3318 oc.prompt1.p_template = shell.prompt_in1
3315 oc.prompt2.p_template = shell.prompt_in2
3319 oc.prompt2.p_template = shell.prompt_in2
3316 oc.prompt_out.p_template = shell.prompt_out
3320 oc.prompt_out.p_template = shell.prompt_out
3317
3321
3318 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3322 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3319
3323
3320 oc.output_sep = dstore.rc_separate_out
3324 oc.output_sep = dstore.rc_separate_out
3321 oc.output_sep2 = dstore.rc_separate_out2
3325 oc.output_sep2 = dstore.rc_separate_out2
3322
3326
3323 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3327 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3324 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3328 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3325
3329
3326 shell.pprint = dstore.rc_pprint
3330 shell.pprint = dstore.rc_pprint
3327
3331
3328 shell.magic_xmode(dstore.xmode)
3332 shell.magic_xmode(dstore.xmode)
3329
3333
3330 # Store new mode and inform
3334 # Store new mode and inform
3331 dstore.mode = bool(1-int(mode))
3335 dstore.mode = bool(1-int(mode))
3332 print 'Doctest mode is:',
3336 mode_label = ['OFF','ON'][dstore.mode]
3333 print ['OFF','ON'][dstore.mode]
3337 print 'Doctest mode is:', mode_label
3334
3338
3335 def magic_gui(self, parameter_s=''):
3339 def magic_gui(self, parameter_s=''):
3336 """Enable or disable IPython GUI event loop integration.
3340 """Enable or disable IPython GUI event loop integration.
3337
3341
3338 %gui [GUINAME]
3342 %gui [GUINAME]
3339
3343
3340 This magic replaces IPython's threaded shells that were activated
3344 This magic replaces IPython's threaded shells that were activated
3341 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3345 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3342 can now be enabled, disabled and swtiched at runtime and keyboard
3346 can now be enabled, disabled and swtiched at runtime and keyboard
3343 interrupts should work without any problems. The following toolkits
3347 interrupts should work without any problems. The following toolkits
3344 are supported: wxPython, PyQt4, PyGTK, and Tk::
3348 are supported: wxPython, PyQt4, PyGTK, and Tk::
3345
3349
3346 %gui wx # enable wxPython event loop integration
3350 %gui wx # enable wxPython event loop integration
3347 %gui qt4|qt # enable PyQt4 event loop integration
3351 %gui qt4|qt # enable PyQt4 event loop integration
3348 %gui gtk # enable PyGTK event loop integration
3352 %gui gtk # enable PyGTK event loop integration
3349 %gui tk # enable Tk event loop integration
3353 %gui tk # enable Tk event loop integration
3350 %gui # disable all event loop integration
3354 %gui # disable all event loop integration
3351
3355
3352 WARNING: after any of these has been called you can simply create
3356 WARNING: after any of these has been called you can simply create
3353 an application object, but DO NOT start the event loop yourself, as
3357 an application object, but DO NOT start the event loop yourself, as
3354 we have already handled that.
3358 we have already handled that.
3355 """
3359 """
3356 from IPython.lib.inputhook import enable_gui
3360 from IPython.lib.inputhook import enable_gui
3357 opts, arg = self.parse_options(parameter_s='')
3361 opts, arg = self.parse_options(parameter_s='')
3358 if arg=='': arg = None
3362 if arg=='': arg = None
3359 return enable_gui(arg)
3363 return enable_gui(arg)
3360
3364
3361 def magic_load_ext(self, module_str):
3365 def magic_load_ext(self, module_str):
3362 """Load an IPython extension by its module name."""
3366 """Load an IPython extension by its module name."""
3363 return self.extension_manager.load_extension(module_str)
3367 return self.extension_manager.load_extension(module_str)
3364
3368
3365 def magic_unload_ext(self, module_str):
3369 def magic_unload_ext(self, module_str):
3366 """Unload an IPython extension by its module name."""
3370 """Unload an IPython extension by its module name."""
3367 self.extension_manager.unload_extension(module_str)
3371 self.extension_manager.unload_extension(module_str)
3368
3372
3369 def magic_reload_ext(self, module_str):
3373 def magic_reload_ext(self, module_str):
3370 """Reload an IPython extension by its module name."""
3374 """Reload an IPython extension by its module name."""
3371 self.extension_manager.reload_extension(module_str)
3375 self.extension_manager.reload_extension(module_str)
3372
3376
3373 @testdec.skip_doctest
3377 @testdec.skip_doctest
3374 def magic_install_profiles(self, s):
3378 def magic_install_profiles(self, s):
3375 """Install the default IPython profiles into the .ipython dir.
3379 """Install the default IPython profiles into the .ipython dir.
3376
3380
3377 If the default profiles have already been installed, they will not
3381 If the default profiles have already been installed, they will not
3378 be overwritten. You can force overwriting them by using the ``-o``
3382 be overwritten. You can force overwriting them by using the ``-o``
3379 option::
3383 option::
3380
3384
3381 In [1]: %install_profiles -o
3385 In [1]: %install_profiles -o
3382 """
3386 """
3383 if '-o' in s:
3387 if '-o' in s:
3384 overwrite = True
3388 overwrite = True
3385 else:
3389 else:
3386 overwrite = False
3390 overwrite = False
3387 from IPython.config import profile
3391 from IPython.config import profile
3388 profile_dir = os.path.split(profile.__file__)[0]
3392 profile_dir = os.path.split(profile.__file__)[0]
3389 ipython_dir = self.ipython_dir
3393 ipython_dir = self.ipython_dir
3390 files = os.listdir(profile_dir)
3394 files = os.listdir(profile_dir)
3391
3395
3392 to_install = []
3396 to_install = []
3393 for f in files:
3397 for f in files:
3394 if f.startswith('ipython_config'):
3398 if f.startswith('ipython_config'):
3395 src = os.path.join(profile_dir, f)
3399 src = os.path.join(profile_dir, f)
3396 dst = os.path.join(ipython_dir, f)
3400 dst = os.path.join(ipython_dir, f)
3397 if (not os.path.isfile(dst)) or overwrite:
3401 if (not os.path.isfile(dst)) or overwrite:
3398 to_install.append((f, src, dst))
3402 to_install.append((f, src, dst))
3399 if len(to_install)>0:
3403 if len(to_install)>0:
3400 print "Installing profiles to: ", ipython_dir
3404 print "Installing profiles to: ", ipython_dir
3401 for (f, src, dst) in to_install:
3405 for (f, src, dst) in to_install:
3402 shutil.copy(src, dst)
3406 shutil.copy(src, dst)
3403 print " %s" % f
3407 print " %s" % f
3404
3408
3405 def magic_install_default_config(self, s):
3409 def magic_install_default_config(self, s):
3406 """Install IPython's default config file into the .ipython dir.
3410 """Install IPython's default config file into the .ipython dir.
3407
3411
3408 If the default config file (:file:`ipython_config.py`) is already
3412 If the default config file (:file:`ipython_config.py`) is already
3409 installed, it will not be overwritten. You can force overwriting
3413 installed, it will not be overwritten. You can force overwriting
3410 by using the ``-o`` option::
3414 by using the ``-o`` option::
3411
3415
3412 In [1]: %install_default_config
3416 In [1]: %install_default_config
3413 """
3417 """
3414 if '-o' in s:
3418 if '-o' in s:
3415 overwrite = True
3419 overwrite = True
3416 else:
3420 else:
3417 overwrite = False
3421 overwrite = False
3418 from IPython.config import default
3422 from IPython.config import default
3419 config_dir = os.path.split(default.__file__)[0]
3423 config_dir = os.path.split(default.__file__)[0]
3420 ipython_dir = self.ipython_dir
3424 ipython_dir = self.ipython_dir
3421 default_config_file_name = 'ipython_config.py'
3425 default_config_file_name = 'ipython_config.py'
3422 src = os.path.join(config_dir, default_config_file_name)
3426 src = os.path.join(config_dir, default_config_file_name)
3423 dst = os.path.join(ipython_dir, default_config_file_name)
3427 dst = os.path.join(ipython_dir, default_config_file_name)
3424 if (not os.path.isfile(dst)) or overwrite:
3428 if (not os.path.isfile(dst)) or overwrite:
3425 shutil.copy(src, dst)
3429 shutil.copy(src, dst)
3426 print "Installing default config file: %s" % dst
3430 print "Installing default config file: %s" % dst
3427
3431
3428 # Pylab support: simple wrappers that activate pylab, load gui input
3432 # Pylab support: simple wrappers that activate pylab, load gui input
3429 # handling and modify slightly %run
3433 # handling and modify slightly %run
3430
3434
3431 @testdec.skip_doctest
3435 @testdec.skip_doctest
3432 def _pylab_magic_run(self, parameter_s=''):
3436 def _pylab_magic_run(self, parameter_s=''):
3433 Magic.magic_run(self, parameter_s,
3437 Magic.magic_run(self, parameter_s,
3434 runner=mpl_runner(self.shell.safe_execfile))
3438 runner=mpl_runner(self.shell.safe_execfile))
3435
3439
3436 _pylab_magic_run.__doc__ = magic_run.__doc__
3440 _pylab_magic_run.__doc__ = magic_run.__doc__
3437
3441
3438 @testdec.skip_doctest
3442 @testdec.skip_doctest
3439 def magic_pylab(self, s):
3443 def magic_pylab(self, s):
3440 """Load numpy and matplotlib to work interactively.
3444 """Load numpy and matplotlib to work interactively.
3441
3445
3442 %pylab [GUINAME]
3446 %pylab [GUINAME]
3443
3447
3444 This function lets you activate pylab (matplotlib, numpy and
3448 This function lets you activate pylab (matplotlib, numpy and
3445 interactive support) at any point during an IPython session.
3449 interactive support) at any point during an IPython session.
3446
3450
3447 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3451 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3448 pylab and mlab, as well as all names from numpy and pylab.
3452 pylab and mlab, as well as all names from numpy and pylab.
3449
3453
3450 Parameters
3454 Parameters
3451 ----------
3455 ----------
3452 guiname : optional
3456 guiname : optional
3453 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3457 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3454 'tk'). If given, the corresponding Matplotlib backend is used,
3458 'tk'). If given, the corresponding Matplotlib backend is used,
3455 otherwise matplotlib's default (which you can override in your
3459 otherwise matplotlib's default (which you can override in your
3456 matplotlib config file) is used.
3460 matplotlib config file) is used.
3457
3461
3458 Examples
3462 Examples
3459 --------
3463 --------
3460 In this case, where the MPL default is TkAgg:
3464 In this case, where the MPL default is TkAgg:
3461 In [2]: %pylab
3465 In [2]: %pylab
3462
3466
3463 Welcome to pylab, a matplotlib-based Python environment.
3467 Welcome to pylab, a matplotlib-based Python environment.
3464 Backend in use: TkAgg
3468 Backend in use: TkAgg
3465 For more information, type 'help(pylab)'.
3469 For more information, type 'help(pylab)'.
3466
3470
3467 But you can explicitly request a different backend:
3471 But you can explicitly request a different backend:
3468 In [3]: %pylab qt
3472 In [3]: %pylab qt
3469
3473
3470 Welcome to pylab, a matplotlib-based Python environment.
3474 Welcome to pylab, a matplotlib-based Python environment.
3471 Backend in use: Qt4Agg
3475 Backend in use: Qt4Agg
3472 For more information, type 'help(pylab)'.
3476 For more information, type 'help(pylab)'.
3473 """
3477 """
3474 self.shell.enable_pylab(s)
3478 self.shell.enable_pylab(s)
3475
3479
3476 def magic_tb(self, s):
3480 def magic_tb(self, s):
3477 """Print the last traceback with the currently active exception mode.
3481 """Print the last traceback with the currently active exception mode.
3478
3482
3479 See %xmode for changing exception reporting modes."""
3483 See %xmode for changing exception reporting modes."""
3480 self.shell.showtraceback()
3484 self.shell.showtraceback()
3481
3485
3482 # end Magic
3486 # end Magic
@@ -1,426 +1,485 b''
1 """A ZMQ-based subclass of InteractiveShell.
1 """A ZMQ-based subclass of InteractiveShell.
2
2
3 This code is meant to ease the refactoring of the base InteractiveShell into
3 This code is meant to ease the refactoring of the base InteractiveShell into
4 something with a cleaner architecture for 2-process use, without actually
4 something with a cleaner architecture for 2-process use, without actually
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 we subclass and override what we want to fix. Once this is working well, we
6 we subclass and override what we want to fix. Once this is working well, we
7 can go back to the base class and refactor the code for a cleaner inheritance
7 can go back to the base class and refactor the code for a cleaner inheritance
8 implementation that doesn't rely on so much monkeypatching.
8 implementation that doesn't rely on so much monkeypatching.
9
9
10 But this lets us maintain a fully working IPython as we develop the new
10 But this lets us maintain a fully working IPython as we develop the new
11 machinery. This should thus be thought of as scaffolding.
11 machinery. This should thus be thought of as scaffolding.
12 """
12 """
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Stdlib
18 # Stdlib
19 import inspect
19 import inspect
20 import os
20 import os
21 import re
21 import re
22
22
23 # Our own
23 # Our own
24 from IPython.core.interactiveshell import (
24 from IPython.core.interactiveshell import (
25 InteractiveShell, InteractiveShellABC
25 InteractiveShell, InteractiveShellABC
26 )
26 )
27 from IPython.core.displayhook import DisplayHook
27 from IPython.core.displayhook import DisplayHook
28 from IPython.core.macro import Macro
28 from IPython.core.macro import Macro
29 from IPython.utils.path import get_py_filename
29 from IPython.utils.path import get_py_filename
30 from IPython.utils.text import StringTypes
30 from IPython.utils.text import StringTypes
31 from IPython.utils.traitlets import Instance, Type, Dict
31 from IPython.utils.traitlets import Instance, Type, Dict
32 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
33 from IPython.zmq.session import extract_header
33 from IPython.zmq.session import extract_header
34 from IPython.core.payloadpage import install_payload_page
34 from IPython.core.payloadpage import install_payload_page
35 from session import Session
35 from session import Session
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Globals and side-effects
38 # Globals and side-effects
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41 # Install the payload version of page.
41 # Install the payload version of page.
42 install_payload_page()
42 install_payload_page()
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # Functions and classes
45 # Functions and classes
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 class ZMQDisplayHook(DisplayHook):
48 class ZMQDisplayHook(DisplayHook):
49
49
50 session = Instance(Session)
50 session = Instance(Session)
51 pub_socket = Instance('zmq.Socket')
51 pub_socket = Instance('zmq.Socket')
52 parent_header = Dict({})
52 parent_header = Dict({})
53
53
54 def set_parent(self, parent):
54 def set_parent(self, parent):
55 """Set the parent for outbound messages."""
55 """Set the parent for outbound messages."""
56 self.parent_header = extract_header(parent)
56 self.parent_header = extract_header(parent)
57
57
58 def start_displayhook(self):
58 def start_displayhook(self):
59 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
59 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
60
60
61 def write_output_prompt(self):
61 def write_output_prompt(self):
62 """Write the output prompt."""
62 """Write the output prompt."""
63 if self.do_full_cache:
63 if self.do_full_cache:
64 self.msg['content']['execution_count'] = self.prompt_count
64 self.msg['content']['execution_count'] = self.prompt_count
65
65
66 def write_result_repr(self, result_repr):
66 def write_result_repr(self, result_repr):
67 self.msg['content']['data'] = result_repr
67 self.msg['content']['data'] = result_repr
68
68
69 def finish_displayhook(self):
69 def finish_displayhook(self):
70 """Finish up all displayhook activities."""
70 """Finish up all displayhook activities."""
71 self.pub_socket.send_json(self.msg)
71 self.pub_socket.send_json(self.msg)
72 self.msg = None
72 self.msg = None
73
73
74
74
75 class ZMQInteractiveShell(InteractiveShell):
75 class ZMQInteractiveShell(InteractiveShell):
76 """A subclass of InteractiveShell for ZMQ."""
76 """A subclass of InteractiveShell for ZMQ."""
77
77
78 displayhook_class = Type(ZMQDisplayHook)
78 displayhook_class = Type(ZMQDisplayHook)
79
79
80 def init_io(self):
80 def init_io(self):
81 # This will just use sys.stdout and sys.stderr. If you want to
81 # This will just use sys.stdout and sys.stderr. If you want to
82 # override sys.stdout and sys.stderr themselves, you need to do that
82 # override sys.stdout and sys.stderr themselves, you need to do that
83 # *before* instantiating this class, because Term holds onto
83 # *before* instantiating this class, because Term holds onto
84 # references to the underlying streams.
84 # references to the underlying streams.
85 import IPython.utils.io
85 import IPython.utils.io
86 Term = IPython.utils.io.IOTerm()
86 Term = IPython.utils.io.IOTerm()
87 IPython.utils.io.Term = Term
87 IPython.utils.io.Term = Term
88
88
89 def magic_doctest_mode(self,parameter_s=''):
90 """Toggle doctest mode on and off.
91
92 This mode is intended to make IPython behave as much as possible like a
93 plain Python shell, from the perspective of how its prompts, exceptions
94 and output look. This makes it easy to copy and paste parts of a
95 session into doctests. It does so by:
96
97 - Changing the prompts to the classic ``>>>`` ones.
98 - Changing the exception reporting mode to 'Plain'.
99 - Disabling pretty-printing of output.
100
101 Note that IPython also supports the pasting of code snippets that have
102 leading '>>>' and '...' prompts in them. This means that you can paste
103 doctests from files or docstrings (even if they have leading
104 whitespace), and the code will execute correctly. You can then use
105 '%history -t' to see the translated history; this will give you the
106 input after removal of all the leading prompts and whitespace, which
107 can be pasted back into an editor.
108
109 With these features, you can switch into this mode easily whenever you
110 need to do testing and changes to doctests, without having to leave
111 your existing IPython session.
112 """
113
114 from IPython.utils.ipstruct import Struct
115
116 # Shorthands
117 shell = self.shell
118 # dstore is a data store kept in the instance metadata bag to track any
119 # changes we make, so we can undo them later.
120 dstore = shell.meta.setdefault('doctest_mode', Struct())
121 save_dstore = dstore.setdefault
122
123 # save a few values we'll need to recover later
124 mode = save_dstore('mode', False)
125 save_dstore('rc_pprint', shell.pprint)
126 save_dstore('xmode', shell.InteractiveTB.mode)
127
128 if mode == False:
129 # turn on
130 shell.pprint = False
131 shell.magic_xmode('Plain')
132 else:
133 # turn off
134 shell.pprint = dstore.rc_pprint
135 shell.magic_xmode(dstore.xmode)
136
137 # Store new mode and inform on console
138 dstore.mode = bool(1-int(mode))
139 mode_label = ['OFF','ON'][dstore.mode]
140 print('Doctest mode is:', mode_label)
141
142 # Send the payload back so that clients can modify their prompt display
143 payload = dict(
144 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
145 mode=dstore.mode)
146 self.payload_manager.write_payload(payload)
147
89 def magic_edit(self,parameter_s='',last_call=['','']):
148 def magic_edit(self,parameter_s='',last_call=['','']):
90 """Bring up an editor and execute the resulting code.
149 """Bring up an editor and execute the resulting code.
91
150
92 Usage:
151 Usage:
93 %edit [options] [args]
152 %edit [options] [args]
94
153
95 %edit runs IPython's editor hook. The default version of this hook is
154 %edit runs IPython's editor hook. The default version of this hook is
96 set to call the __IPYTHON__.rc.editor command. This is read from your
155 set to call the __IPYTHON__.rc.editor command. This is read from your
97 environment variable $EDITOR. If this isn't found, it will default to
156 environment variable $EDITOR. If this isn't found, it will default to
98 vi under Linux/Unix and to notepad under Windows. See the end of this
157 vi under Linux/Unix and to notepad under Windows. See the end of this
99 docstring for how to change the editor hook.
158 docstring for how to change the editor hook.
100
159
101 You can also set the value of this editor via the command line option
160 You can also set the value of this editor via the command line option
102 '-editor' or in your ipythonrc file. This is useful if you wish to use
161 '-editor' or in your ipythonrc file. This is useful if you wish to use
103 specifically for IPython an editor different from your typical default
162 specifically for IPython an editor different from your typical default
104 (and for Windows users who typically don't set environment variables).
163 (and for Windows users who typically don't set environment variables).
105
164
106 This command allows you to conveniently edit multi-line code right in
165 This command allows you to conveniently edit multi-line code right in
107 your IPython session.
166 your IPython session.
108
167
109 If called without arguments, %edit opens up an empty editor with a
168 If called without arguments, %edit opens up an empty editor with a
110 temporary file and will execute the contents of this file when you
169 temporary file and will execute the contents of this file when you
111 close it (don't forget to save it!).
170 close it (don't forget to save it!).
112
171
113
172
114 Options:
173 Options:
115
174
116 -n <number>: open the editor at a specified line number. By default,
175 -n <number>: open the editor at a specified line number. By default,
117 the IPython editor hook uses the unix syntax 'editor +N filename', but
176 the IPython editor hook uses the unix syntax 'editor +N filename', but
118 you can configure this by providing your own modified hook if your
177 you can configure this by providing your own modified hook if your
119 favorite editor supports line-number specifications with a different
178 favorite editor supports line-number specifications with a different
120 syntax.
179 syntax.
121
180
122 -p: this will call the editor with the same data as the previous time
181 -p: this will call the editor with the same data as the previous time
123 it was used, regardless of how long ago (in your current session) it
182 it was used, regardless of how long ago (in your current session) it
124 was.
183 was.
125
184
126 -r: use 'raw' input. This option only applies to input taken from the
185 -r: use 'raw' input. This option only applies to input taken from the
127 user's history. By default, the 'processed' history is used, so that
186 user's history. By default, the 'processed' history is used, so that
128 magics are loaded in their transformed version to valid Python. If
187 magics are loaded in their transformed version to valid Python. If
129 this option is given, the raw input as typed as the command line is
188 this option is given, the raw input as typed as the command line is
130 used instead. When you exit the editor, it will be executed by
189 used instead. When you exit the editor, it will be executed by
131 IPython's own processor.
190 IPython's own processor.
132
191
133 -x: do not execute the edited code immediately upon exit. This is
192 -x: do not execute the edited code immediately upon exit. This is
134 mainly useful if you are editing programs which need to be called with
193 mainly useful if you are editing programs which need to be called with
135 command line arguments, which you can then do using %run.
194 command line arguments, which you can then do using %run.
136
195
137
196
138 Arguments:
197 Arguments:
139
198
140 If arguments are given, the following possibilites exist:
199 If arguments are given, the following possibilites exist:
141
200
142 - The arguments are numbers or pairs of colon-separated numbers (like
201 - The arguments are numbers or pairs of colon-separated numbers (like
143 1 4:8 9). These are interpreted as lines of previous input to be
202 1 4:8 9). These are interpreted as lines of previous input to be
144 loaded into the editor. The syntax is the same of the %macro command.
203 loaded into the editor. The syntax is the same of the %macro command.
145
204
146 - If the argument doesn't start with a number, it is evaluated as a
205 - If the argument doesn't start with a number, it is evaluated as a
147 variable and its contents loaded into the editor. You can thus edit
206 variable and its contents loaded into the editor. You can thus edit
148 any string which contains python code (including the result of
207 any string which contains python code (including the result of
149 previous edits).
208 previous edits).
150
209
151 - If the argument is the name of an object (other than a string),
210 - If the argument is the name of an object (other than a string),
152 IPython will try to locate the file where it was defined and open the
211 IPython will try to locate the file where it was defined and open the
153 editor at the point where it is defined. You can use `%edit function`
212 editor at the point where it is defined. You can use `%edit function`
154 to load an editor exactly at the point where 'function' is defined,
213 to load an editor exactly at the point where 'function' is defined,
155 edit it and have the file be executed automatically.
214 edit it and have the file be executed automatically.
156
215
157 If the object is a macro (see %macro for details), this opens up your
216 If the object is a macro (see %macro for details), this opens up your
158 specified editor with a temporary file containing the macro's data.
217 specified editor with a temporary file containing the macro's data.
159 Upon exit, the macro is reloaded with the contents of the file.
218 Upon exit, the macro is reloaded with the contents of the file.
160
219
161 Note: opening at an exact line is only supported under Unix, and some
220 Note: opening at an exact line is only supported under Unix, and some
162 editors (like kedit and gedit up to Gnome 2.8) do not understand the
221 editors (like kedit and gedit up to Gnome 2.8) do not understand the
163 '+NUMBER' parameter necessary for this feature. Good editors like
222 '+NUMBER' parameter necessary for this feature. Good editors like
164 (X)Emacs, vi, jed, pico and joe all do.
223 (X)Emacs, vi, jed, pico and joe all do.
165
224
166 - If the argument is not found as a variable, IPython will look for a
225 - If the argument is not found as a variable, IPython will look for a
167 file with that name (adding .py if necessary) and load it into the
226 file with that name (adding .py if necessary) and load it into the
168 editor. It will execute its contents with execfile() when you exit,
227 editor. It will execute its contents with execfile() when you exit,
169 loading any code in the file into your interactive namespace.
228 loading any code in the file into your interactive namespace.
170
229
171 After executing your code, %edit will return as output the code you
230 After executing your code, %edit will return as output the code you
172 typed in the editor (except when it was an existing file). This way
231 typed in the editor (except when it was an existing file). This way
173 you can reload the code in further invocations of %edit as a variable,
232 you can reload the code in further invocations of %edit as a variable,
174 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
233 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
175 the output.
234 the output.
176
235
177 Note that %edit is also available through the alias %ed.
236 Note that %edit is also available through the alias %ed.
178
237
179 This is an example of creating a simple function inside the editor and
238 This is an example of creating a simple function inside the editor and
180 then modifying it. First, start up the editor:
239 then modifying it. First, start up the editor:
181
240
182 In [1]: ed
241 In [1]: ed
183 Editing... done. Executing edited code...
242 Editing... done. Executing edited code...
184 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
243 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
185
244
186 We can then call the function foo():
245 We can then call the function foo():
187
246
188 In [2]: foo()
247 In [2]: foo()
189 foo() was defined in an editing session
248 foo() was defined in an editing session
190
249
191 Now we edit foo. IPython automatically loads the editor with the
250 Now we edit foo. IPython automatically loads the editor with the
192 (temporary) file where foo() was previously defined:
251 (temporary) file where foo() was previously defined:
193
252
194 In [3]: ed foo
253 In [3]: ed foo
195 Editing... done. Executing edited code...
254 Editing... done. Executing edited code...
196
255
197 And if we call foo() again we get the modified version:
256 And if we call foo() again we get the modified version:
198
257
199 In [4]: foo()
258 In [4]: foo()
200 foo() has now been changed!
259 foo() has now been changed!
201
260
202 Here is an example of how to edit a code snippet successive
261 Here is an example of how to edit a code snippet successive
203 times. First we call the editor:
262 times. First we call the editor:
204
263
205 In [5]: ed
264 In [5]: ed
206 Editing... done. Executing edited code...
265 Editing... done. Executing edited code...
207 hello
266 hello
208 Out[5]: "print 'hello'n"
267 Out[5]: "print 'hello'n"
209
268
210 Now we call it again with the previous output (stored in _):
269 Now we call it again with the previous output (stored in _):
211
270
212 In [6]: ed _
271 In [6]: ed _
213 Editing... done. Executing edited code...
272 Editing... done. Executing edited code...
214 hello world
273 hello world
215 Out[6]: "print 'hello world'n"
274 Out[6]: "print 'hello world'n"
216
275
217 Now we call it with the output #8 (stored in _8, also as Out[8]):
276 Now we call it with the output #8 (stored in _8, also as Out[8]):
218
277
219 In [7]: ed _8
278 In [7]: ed _8
220 Editing... done. Executing edited code...
279 Editing... done. Executing edited code...
221 hello again
280 hello again
222 Out[7]: "print 'hello again'n"
281 Out[7]: "print 'hello again'n"
223
282
224
283
225 Changing the default editor hook:
284 Changing the default editor hook:
226
285
227 If you wish to write your own editor hook, you can put it in a
286 If you wish to write your own editor hook, you can put it in a
228 configuration file which you load at startup time. The default hook
287 configuration file which you load at startup time. The default hook
229 is defined in the IPython.core.hooks module, and you can use that as a
288 is defined in the IPython.core.hooks module, and you can use that as a
230 starting example for further modifications. That file also has
289 starting example for further modifications. That file also has
231 general instructions on how to set a new hook for use once you've
290 general instructions on how to set a new hook for use once you've
232 defined it."""
291 defined it."""
233
292
234 # FIXME: This function has become a convoluted mess. It needs a
293 # FIXME: This function has become a convoluted mess. It needs a
235 # ground-up rewrite with clean, simple logic.
294 # ground-up rewrite with clean, simple logic.
236
295
237 def make_filename(arg):
296 def make_filename(arg):
238 "Make a filename from the given args"
297 "Make a filename from the given args"
239 try:
298 try:
240 filename = get_py_filename(arg)
299 filename = get_py_filename(arg)
241 except IOError:
300 except IOError:
242 if args.endswith('.py'):
301 if args.endswith('.py'):
243 filename = arg
302 filename = arg
244 else:
303 else:
245 filename = None
304 filename = None
246 return filename
305 return filename
247
306
248 # custom exceptions
307 # custom exceptions
249 class DataIsObject(Exception): pass
308 class DataIsObject(Exception): pass
250
309
251 opts,args = self.parse_options(parameter_s,'prn:')
310 opts,args = self.parse_options(parameter_s,'prn:')
252 # Set a few locals from the options for convenience:
311 # Set a few locals from the options for convenience:
253 opts_p = opts.has_key('p')
312 opts_p = opts.has_key('p')
254 opts_r = opts.has_key('r')
313 opts_r = opts.has_key('r')
255
314
256 # Default line number value
315 # Default line number value
257 lineno = opts.get('n',None)
316 lineno = opts.get('n',None)
258 if lineno is not None:
317 if lineno is not None:
259 try:
318 try:
260 lineno = int(lineno)
319 lineno = int(lineno)
261 except:
320 except:
262 warn("The -n argument must be an integer.")
321 warn("The -n argument must be an integer.")
263 return
322 return
264
323
265 if opts_p:
324 if opts_p:
266 args = '_%s' % last_call[0]
325 args = '_%s' % last_call[0]
267 if not self.shell.user_ns.has_key(args):
326 if not self.shell.user_ns.has_key(args):
268 args = last_call[1]
327 args = last_call[1]
269
328
270 # use last_call to remember the state of the previous call, but don't
329 # use last_call to remember the state of the previous call, but don't
271 # let it be clobbered by successive '-p' calls.
330 # let it be clobbered by successive '-p' calls.
272 try:
331 try:
273 last_call[0] = self.shell.displayhook.prompt_count
332 last_call[0] = self.shell.displayhook.prompt_count
274 if not opts_p:
333 if not opts_p:
275 last_call[1] = parameter_s
334 last_call[1] = parameter_s
276 except:
335 except:
277 pass
336 pass
278
337
279 # by default this is done with temp files, except when the given
338 # by default this is done with temp files, except when the given
280 # arg is a filename
339 # arg is a filename
281 use_temp = 1
340 use_temp = 1
282
341
283 if re.match(r'\d',args):
342 if re.match(r'\d',args):
284 # Mode where user specifies ranges of lines, like in %macro.
343 # Mode where user specifies ranges of lines, like in %macro.
285 # This means that you can't edit files whose names begin with
344 # This means that you can't edit files whose names begin with
286 # numbers this way. Tough.
345 # numbers this way. Tough.
287 ranges = args.split()
346 ranges = args.split()
288 data = ''.join(self.extract_input_slices(ranges,opts_r))
347 data = ''.join(self.extract_input_slices(ranges,opts_r))
289 elif args.endswith('.py'):
348 elif args.endswith('.py'):
290 filename = make_filename(args)
349 filename = make_filename(args)
291 data = ''
350 data = ''
292 use_temp = 0
351 use_temp = 0
293 elif args:
352 elif args:
294 try:
353 try:
295 # Load the parameter given as a variable. If not a string,
354 # Load the parameter given as a variable. If not a string,
296 # process it as an object instead (below)
355 # process it as an object instead (below)
297
356
298 #print '*** args',args,'type',type(args) # dbg
357 #print '*** args',args,'type',type(args) # dbg
299 data = eval(args,self.shell.user_ns)
358 data = eval(args,self.shell.user_ns)
300 if not type(data) in StringTypes:
359 if not type(data) in StringTypes:
301 raise DataIsObject
360 raise DataIsObject
302
361
303 except (NameError,SyntaxError):
362 except (NameError,SyntaxError):
304 # given argument is not a variable, try as a filename
363 # given argument is not a variable, try as a filename
305 filename = make_filename(args)
364 filename = make_filename(args)
306 if filename is None:
365 if filename is None:
307 warn("Argument given (%s) can't be found as a variable "
366 warn("Argument given (%s) can't be found as a variable "
308 "or as a filename." % args)
367 "or as a filename." % args)
309 return
368 return
310
369
311 data = ''
370 data = ''
312 use_temp = 0
371 use_temp = 0
313 except DataIsObject:
372 except DataIsObject:
314
373
315 # macros have a special edit function
374 # macros have a special edit function
316 if isinstance(data,Macro):
375 if isinstance(data,Macro):
317 self._edit_macro(args,data)
376 self._edit_macro(args,data)
318 return
377 return
319
378
320 # For objects, try to edit the file where they are defined
379 # For objects, try to edit the file where they are defined
321 try:
380 try:
322 filename = inspect.getabsfile(data)
381 filename = inspect.getabsfile(data)
323 if 'fakemodule' in filename.lower() and inspect.isclass(data):
382 if 'fakemodule' in filename.lower() and inspect.isclass(data):
324 # class created by %edit? Try to find source
383 # class created by %edit? Try to find source
325 # by looking for method definitions instead, the
384 # by looking for method definitions instead, the
326 # __module__ in those classes is FakeModule.
385 # __module__ in those classes is FakeModule.
327 attrs = [getattr(data, aname) for aname in dir(data)]
386 attrs = [getattr(data, aname) for aname in dir(data)]
328 for attr in attrs:
387 for attr in attrs:
329 if not inspect.ismethod(attr):
388 if not inspect.ismethod(attr):
330 continue
389 continue
331 filename = inspect.getabsfile(attr)
390 filename = inspect.getabsfile(attr)
332 if filename and 'fakemodule' not in filename.lower():
391 if filename and 'fakemodule' not in filename.lower():
333 # change the attribute to be the edit target instead
392 # change the attribute to be the edit target instead
334 data = attr
393 data = attr
335 break
394 break
336
395
337 datafile = 1
396 datafile = 1
338 except TypeError:
397 except TypeError:
339 filename = make_filename(args)
398 filename = make_filename(args)
340 datafile = 1
399 datafile = 1
341 warn('Could not find file where `%s` is defined.\n'
400 warn('Could not find file where `%s` is defined.\n'
342 'Opening a file named `%s`' % (args,filename))
401 'Opening a file named `%s`' % (args,filename))
343 # Now, make sure we can actually read the source (if it was in
402 # Now, make sure we can actually read the source (if it was in
344 # a temp file it's gone by now).
403 # a temp file it's gone by now).
345 if datafile:
404 if datafile:
346 try:
405 try:
347 if lineno is None:
406 if lineno is None:
348 lineno = inspect.getsourcelines(data)[1]
407 lineno = inspect.getsourcelines(data)[1]
349 except IOError:
408 except IOError:
350 filename = make_filename(args)
409 filename = make_filename(args)
351 if filename is None:
410 if filename is None:
352 warn('The file `%s` where `%s` was defined cannot '
411 warn('The file `%s` where `%s` was defined cannot '
353 'be read.' % (filename,data))
412 'be read.' % (filename,data))
354 return
413 return
355 use_temp = 0
414 use_temp = 0
356 else:
415 else:
357 data = ''
416 data = ''
358
417
359 if use_temp:
418 if use_temp:
360 filename = self.shell.mktempfile(data)
419 filename = self.shell.mktempfile(data)
361 print('IPython will make a temporary file named:', filename)
420 print('IPython will make a temporary file named:', filename)
362
421
363 # Make sure we send to the client an absolute path, in case the working
422 # Make sure we send to the client an absolute path, in case the working
364 # directory of client and kernel don't match
423 # directory of client and kernel don't match
365 filename = os.path.abspath(filename)
424 filename = os.path.abspath(filename)
366
425
367 payload = {
426 payload = {
368 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
427 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
369 'filename' : filename,
428 'filename' : filename,
370 'line_number' : lineno
429 'line_number' : lineno
371 }
430 }
372 self.payload_manager.write_payload(payload)
431 self.payload_manager.write_payload(payload)
373
432
374 def magic_gui(self, *args, **kwargs):
433 def magic_gui(self, *args, **kwargs):
375 raise NotImplementedError('GUI support must be enabled in command line options.')
434 raise NotImplementedError('GUI support must be enabled in command line options.')
376
435
377 def magic_pylab(self, *args, **kwargs):
436 def magic_pylab(self, *args, **kwargs):
378 raise NotImplementedError('pylab support must be enabled in commandl in options.')
437 raise NotImplementedError('pylab support must be enabled in commandl in options.')
379
438
380 def auto_rewrite_input(self, cmd):
439 def auto_rewrite_input(self, cmd):
381 """Called to show the auto-rewritten input for autocall and friends.
440 """Called to show the auto-rewritten input for autocall and friends.
382
441
383 FIXME: this payload is currently not correctly processed by the
442 FIXME: this payload is currently not correctly processed by the
384 frontend.
443 frontend.
385 """
444 """
386 new = self.displayhook.prompt1.auto_rewrite() + cmd
445 new = self.displayhook.prompt1.auto_rewrite() + cmd
387 payload = dict(
446 payload = dict(
388 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
447 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
389 transformed_input=new,
448 transformed_input=new,
390 )
449 )
391 self.payload_manager.write_payload(payload)
450 self.payload_manager.write_payload(payload)
392
451
393 def ask_exit(self):
452 def ask_exit(self):
394 """Engage the exit actions."""
453 """Engage the exit actions."""
395 payload = dict(
454 payload = dict(
396 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
455 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
397 exit=True,
456 exit=True,
398 )
457 )
399 self.payload_manager.write_payload(payload)
458 self.payload_manager.write_payload(payload)
400
459
401 def _showtraceback(self, etype, evalue, stb):
460 def _showtraceback(self, etype, evalue, stb):
402
461
403 exc_content = {
462 exc_content = {
404 u'traceback' : stb,
463 u'traceback' : stb,
405 u'ename' : unicode(etype.__name__),
464 u'ename' : unicode(etype.__name__),
406 u'evalue' : unicode(evalue)
465 u'evalue' : unicode(evalue)
407 }
466 }
408
467
409 dh = self.displayhook
468 dh = self.displayhook
410 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
469 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
411 # Send exception info over pub socket for other clients than the caller
470 # Send exception info over pub socket for other clients than the caller
412 # to pick up
471 # to pick up
413 dh.pub_socket.send_json(exc_msg)
472 dh.pub_socket.send_json(exc_msg)
414
473
415 # FIXME - Hack: store exception info in shell object. Right now, the
474 # FIXME - Hack: store exception info in shell object. Right now, the
416 # caller is reading this info after the fact, we need to fix this logic
475 # caller is reading this info after the fact, we need to fix this logic
417 # to remove this hack. Even uglier, we need to store the error status
476 # to remove this hack. Even uglier, we need to store the error status
418 # here, because in the main loop, the logic that sets it is being
477 # here, because in the main loop, the logic that sets it is being
419 # skipped because runlines swallows the exceptions.
478 # skipped because runlines swallows the exceptions.
420 exc_content[u'status'] = u'error'
479 exc_content[u'status'] = u'error'
421 self._reply_content = exc_content
480 self._reply_content = exc_content
422 # /FIXME
481 # /FIXME
423
482
424 return exc_content
483 return exc_content
425
484
426 InteractiveShellABC.register(ZMQInteractiveShell)
485 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now