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