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