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