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