##// END OF EJS Templates
Work again on bug 269966....
Fernando Perez -
Show More
@@ -0,0 +1,38 b''
1 """Minimal script to reproduce our nasty reference counting bug.
2
3 The problem is related to https://bugs.launchpad.net/ipython/+bug/269966
4
5 The original fix for that appeared to work, but JD Hunter found a matplotlib
6 example which, when run twice in a row, would break. The problem were
7 references held by open figures to internals of Tkinter.
8
9 This code reproduces the problem that John saw, without matplotlib. We can
10 thus use it for our test suite.
11 """
12
13 #-----------------------------------------------------------------------------
14 # Module imports
15 #-----------------------------------------------------------------------------
16 import sys
17
18 from IPython import ipapi
19
20 #-----------------------------------------------------------------------------
21 # Globals
22 #-----------------------------------------------------------------------------
23 ip = ipapi.get()
24
25 if not '_refbug_cache' in ip.user_ns:
26 ip.user_ns['_refbug_cache'] = []
27
28
29 aglobal = 'Hello'
30 def f():
31 return aglobal
32
33 cache = ip.user_ns['_refbug_cache']
34 cache.append(f)
35
36 def call_f():
37 for func in cache:
38 print 'lowercased:',func().lower()
@@ -0,0 +1,17 b''
1 """Tests for the FakeModule objects.
2 """
3
4 import nose.tools as nt
5
6 from IPython.FakeModule import FakeModule, init_fakemod_dict
7
8 # Make a fakemod and check a few properties
9 def test_mk_fakemod():
10 fm = FakeModule()
11 yield nt.assert_true,fm
12 yield nt.assert_true,lambda : hasattr(fm,'__file__')
13
14 def test_mk_fakemod_fromdict():
15 """Test making a FakeModule object with initial data"""
16 fm = FakeModule(dict(hello=True))
17 nt.assert_true(fm.hello)
@@ -1,42 +1,66 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Class which mimics a module.
3 Class which mimics a module.
4
4
5 Needed to allow pickle to correctly resolve namespaces during IPython
5 Needed to allow pickle to correctly resolve namespaces during IPython
6 sessions.
6 sessions.
7 """
7 """
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>
10 # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 import types
16 import types
17
17
18 def init_fakemod_dict(fm,adict=None):
19 """Initialize a FakeModule instance __dict__.
20
21 Kept as a standalone function and not a method so the FakeModule API can
22 remain basically empty.
23
24 This should be considered for private IPython use, used in managing
25 namespaces for %run.
26
27 Parameters
28 ----------
29
30 fm : FakeModule instance
31
32 adict : dict, optional
33 """
34
35 dct = {}
36 # It seems pydoc (and perhaps others) needs any module instance to
37 # implement a __nonzero__ method, so we add it if missing:
38 dct.setdefault('__nonzero__',lambda : True)
39 dct.setdefault('__file__',__file__)
40
41 if adict is not None:
42 dct.update(adict)
43
44 # Hard assignment of the object's __dict__. This is nasty but deliberate.
45 fm.__dict__.clear()
46 fm.__dict__.update(dct)
47
48
18 class FakeModule(types.ModuleType):
49 class FakeModule(types.ModuleType):
19 """Simple class with attribute access to fake a module.
50 """Simple class with attribute access to fake a module.
20
51
21 This is not meant to replace a module, but to allow inserting a fake
52 This is not meant to replace a module, but to allow inserting a fake
22 module in sys.modules so that systems which rely on run-time module
53 module in sys.modules so that systems which rely on run-time module
23 importing (like shelve and pickle) work correctly in interactive IPython
54 importing (like shelve and pickle) work correctly in interactive IPython
24 sessions.
55 sessions.
25
56
26 Do NOT use this code for anything other than this IPython private hack."""
57 Do NOT use this code for anything other than this IPython private hack."""
27
58
28 def __init__(self,adict=None):
59 def __init__(self,adict=None):
29
60
30 # tmp to force __dict__ instance creation, else self.__dict__ fails
61 # tmp to force __dict__ instance creation, else self.__dict__ fails
31 self.__iptmp = None
62 self.__iptmp = None
32
33 # It seems pydoc (and perhaps others) needs any module instance to
34 # implement a __nonzero__ method, so we add it if missing:
35 self.__dict__.setdefault('__nonzero__',lambda : True)
36 self.__dict__.setdefault('__file__',__file__)
37
38 # cleanup our temp trick
63 # cleanup our temp trick
39 del self.__iptmp
64 del self.__iptmp
40
65 # Now, initialize the actual data in the instance dict.
41 if adict is not None:
66 init_fakemod_dict(self,adict)
42 self.__dict__.update(adict)
@@ -1,3442 +1,3447 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: 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-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 #****************************************************************************
13 #****************************************************************************
14 # Modules and globals
14 # Modules and globals
15
15
16 # Python standard modules
16 # Python standard modules
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 import inspect
19 import inspect
20 import os
20 import os
21 import pdb
21 import pdb
22 import pydoc
22 import pydoc
23 import sys
23 import sys
24 import re
24 import re
25 import tempfile
25 import tempfile
26 import time
26 import time
27 import cPickle as pickle
27 import cPickle as pickle
28 import textwrap
28 import textwrap
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 pprint, pformat
31 from pprint import pprint, 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 # Homebrewed
44 # Homebrewed
45 import IPython
45 import IPython
46 from IPython import Debugger, OInspect, wildcard
46 from IPython import Debugger, OInspect, wildcard
47 from IPython.FakeModule import FakeModule
47 from IPython.FakeModule import FakeModule
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.PyColorize import Parser
49 from IPython.PyColorize import Parser
50 from IPython.ipstruct import Struct
50 from IPython.ipstruct import Struct
51 from IPython.macro import Macro
51 from IPython.macro import Macro
52 from IPython.genutils import *
52 from IPython.genutils import *
53 from IPython import platutils
53 from IPython import platutils
54 import IPython.generics
54 import IPython.generics
55 import IPython.ipapi
55 import IPython.ipapi
56 from IPython.ipapi import UsageError
56 from IPython.ipapi import UsageError
57 from IPython.testing import decorators as testdec
57 from IPython.testing import decorators as testdec
58
58
59 #***************************************************************************
59 #***************************************************************************
60 # Utility functions
60 # Utility functions
61 def on_off(tag):
61 def on_off(tag):
62 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
62 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
63 return ['OFF','ON'][tag]
63 return ['OFF','ON'][tag]
64
64
65 class Bunch: pass
65 class Bunch: pass
66
66
67 def compress_dhist(dh):
67 def compress_dhist(dh):
68 head, tail = dh[:-10], dh[-10:]
68 head, tail = dh[:-10], dh[-10:]
69
69
70 newhead = []
70 newhead = []
71 done = set()
71 done = set()
72 for h in head:
72 for h in head:
73 if h in done:
73 if h in done:
74 continue
74 continue
75 newhead.append(h)
75 newhead.append(h)
76 done.add(h)
76 done.add(h)
77
77
78 return newhead + tail
78 return newhead + tail
79
79
80
80
81 #***************************************************************************
81 #***************************************************************************
82 # Main class implementing Magic functionality
82 # Main class implementing Magic functionality
83 class Magic:
83 class Magic:
84 """Magic functions for InteractiveShell.
84 """Magic functions for InteractiveShell.
85
85
86 Shell functions which can be reached as %function_name. All magic
86 Shell functions which can be reached as %function_name. All magic
87 functions should accept a string, which they can parse for their own
87 functions should accept a string, which they can parse for their own
88 needs. This can make some functions easier to type, eg `%cd ../`
88 needs. This can make some functions easier to type, eg `%cd ../`
89 vs. `%cd("../")`
89 vs. `%cd("../")`
90
90
91 ALL definitions MUST begin with the prefix magic_. The user won't need it
91 ALL definitions MUST begin with the prefix magic_. The user won't need it
92 at the command line, but it is is needed in the definition. """
92 at the command line, but it is is needed in the definition. """
93
93
94 # class globals
94 # class globals
95 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
95 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
96 'Automagic is ON, % prefix NOT needed for magic functions.']
96 'Automagic is ON, % prefix NOT needed for magic functions.']
97
97
98 #......................................................................
98 #......................................................................
99 # some utility functions
99 # some utility functions
100
100
101 def __init__(self,shell):
101 def __init__(self,shell):
102
102
103 self.options_table = {}
103 self.options_table = {}
104 if profile is None:
104 if profile is None:
105 self.magic_prun = self.profile_missing_notice
105 self.magic_prun = self.profile_missing_notice
106 self.shell = shell
106 self.shell = shell
107
107
108 # namespace for holding state we may need
108 # namespace for holding state we may need
109 self._magic_state = Bunch()
109 self._magic_state = Bunch()
110
110
111 def profile_missing_notice(self, *args, **kwargs):
111 def profile_missing_notice(self, *args, **kwargs):
112 error("""\
112 error("""\
113 The profile module could not be found. It has been removed from the standard
113 The profile module could not be found. It has been removed from the standard
114 python packages because of its non-free license. To use profiling, install the
114 python packages because of its non-free license. To use profiling, install the
115 python-profiler package from non-free.""")
115 python-profiler package from non-free.""")
116
116
117 def default_option(self,fn,optstr):
117 def default_option(self,fn,optstr):
118 """Make an entry in the options_table for fn, with value optstr"""
118 """Make an entry in the options_table for fn, with value optstr"""
119
119
120 if fn not in self.lsmagic():
120 if fn not in self.lsmagic():
121 error("%s is not a magic function" % fn)
121 error("%s is not a magic function" % fn)
122 self.options_table[fn] = optstr
122 self.options_table[fn] = optstr
123
123
124 def lsmagic(self):
124 def lsmagic(self):
125 """Return a list of currently available magic functions.
125 """Return a list of currently available magic functions.
126
126
127 Gives a list of the bare names after mangling (['ls','cd', ...], not
127 Gives a list of the bare names after mangling (['ls','cd', ...], not
128 ['magic_ls','magic_cd',...]"""
128 ['magic_ls','magic_cd',...]"""
129
129
130 # FIXME. This needs a cleanup, in the way the magics list is built.
130 # FIXME. This needs a cleanup, in the way the magics list is built.
131
131
132 # magics in class definition
132 # magics in class definition
133 class_magic = lambda fn: fn.startswith('magic_') and \
133 class_magic = lambda fn: fn.startswith('magic_') and \
134 callable(Magic.__dict__[fn])
134 callable(Magic.__dict__[fn])
135 # in instance namespace (run-time user additions)
135 # in instance namespace (run-time user additions)
136 inst_magic = lambda fn: fn.startswith('magic_') and \
136 inst_magic = lambda fn: fn.startswith('magic_') and \
137 callable(self.__dict__[fn])
137 callable(self.__dict__[fn])
138 # and bound magics by user (so they can access self):
138 # and bound magics by user (so they can access self):
139 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
139 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
140 callable(self.__class__.__dict__[fn])
140 callable(self.__class__.__dict__[fn])
141 magics = filter(class_magic,Magic.__dict__.keys()) + \
141 magics = filter(class_magic,Magic.__dict__.keys()) + \
142 filter(inst_magic,self.__dict__.keys()) + \
142 filter(inst_magic,self.__dict__.keys()) + \
143 filter(inst_bound_magic,self.__class__.__dict__.keys())
143 filter(inst_bound_magic,self.__class__.__dict__.keys())
144 out = []
144 out = []
145 for fn in set(magics):
145 for fn in set(magics):
146 out.append(fn.replace('magic_','',1))
146 out.append(fn.replace('magic_','',1))
147 out.sort()
147 out.sort()
148 return out
148 return out
149
149
150 def extract_input_slices(self,slices,raw=False):
150 def extract_input_slices(self,slices,raw=False):
151 """Return as a string a set of input history slices.
151 """Return as a string a set of input history slices.
152
152
153 Inputs:
153 Inputs:
154
154
155 - slices: the set of slices is given as a list of strings (like
155 - slices: the set of slices is given as a list of strings (like
156 ['1','4:8','9'], since this function is for use by magic functions
156 ['1','4:8','9'], since this function is for use by magic functions
157 which get their arguments as strings.
157 which get their arguments as strings.
158
158
159 Optional inputs:
159 Optional inputs:
160
160
161 - raw(False): by default, the processed input is used. If this is
161 - raw(False): by default, the processed input is used. If this is
162 true, the raw input history is used instead.
162 true, the raw input history is used instead.
163
163
164 Note that slices can be called with two notations:
164 Note that slices can be called with two notations:
165
165
166 N:M -> standard python form, means including items N...(M-1).
166 N:M -> standard python form, means including items N...(M-1).
167
167
168 N-M -> include items N..M (closed endpoint)."""
168 N-M -> include items N..M (closed endpoint)."""
169
169
170 if raw:
170 if raw:
171 hist = self.shell.input_hist_raw
171 hist = self.shell.input_hist_raw
172 else:
172 else:
173 hist = self.shell.input_hist
173 hist = self.shell.input_hist
174
174
175 cmds = []
175 cmds = []
176 for chunk in slices:
176 for chunk in slices:
177 if ':' in chunk:
177 if ':' in chunk:
178 ini,fin = map(int,chunk.split(':'))
178 ini,fin = map(int,chunk.split(':'))
179 elif '-' in chunk:
179 elif '-' in chunk:
180 ini,fin = map(int,chunk.split('-'))
180 ini,fin = map(int,chunk.split('-'))
181 fin += 1
181 fin += 1
182 else:
182 else:
183 ini = int(chunk)
183 ini = int(chunk)
184 fin = ini+1
184 fin = ini+1
185 cmds.append(hist[ini:fin])
185 cmds.append(hist[ini:fin])
186 return cmds
186 return cmds
187
187
188 def _ofind(self, oname, namespaces=None):
188 def _ofind(self, oname, namespaces=None):
189 """Find an object in the available namespaces.
189 """Find an object in the available namespaces.
190
190
191 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
191 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
192
192
193 Has special code to detect magic functions.
193 Has special code to detect magic functions.
194 """
194 """
195
195
196 oname = oname.strip()
196 oname = oname.strip()
197
197
198 alias_ns = None
198 alias_ns = None
199 if namespaces is None:
199 if namespaces is None:
200 # Namespaces to search in:
200 # Namespaces to search in:
201 # Put them in a list. The order is important so that we
201 # Put them in a list. The order is important so that we
202 # find things in the same order that Python finds them.
202 # find things in the same order that Python finds them.
203 namespaces = [ ('Interactive', self.shell.user_ns),
203 namespaces = [ ('Interactive', self.shell.user_ns),
204 ('IPython internal', self.shell.internal_ns),
204 ('IPython internal', self.shell.internal_ns),
205 ('Python builtin', __builtin__.__dict__),
205 ('Python builtin', __builtin__.__dict__),
206 ('Alias', self.shell.alias_table),
206 ('Alias', self.shell.alias_table),
207 ]
207 ]
208 alias_ns = self.shell.alias_table
208 alias_ns = self.shell.alias_table
209
209
210 # initialize results to 'null'
210 # initialize results to 'null'
211 found = 0; obj = None; ospace = None; ds = None;
211 found = 0; obj = None; ospace = None; ds = None;
212 ismagic = 0; isalias = 0; parent = None
212 ismagic = 0; isalias = 0; parent = None
213
213
214 # Look for the given name by splitting it in parts. If the head is
214 # Look for the given name by splitting it in parts. If the head is
215 # found, then we look for all the remaining parts as members, and only
215 # found, then we look for all the remaining parts as members, and only
216 # declare success if we can find them all.
216 # declare success if we can find them all.
217 oname_parts = oname.split('.')
217 oname_parts = oname.split('.')
218 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
218 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
219 for nsname,ns in namespaces:
219 for nsname,ns in namespaces:
220 try:
220 try:
221 obj = ns[oname_head]
221 obj = ns[oname_head]
222 except KeyError:
222 except KeyError:
223 continue
223 continue
224 else:
224 else:
225 #print 'oname_rest:', oname_rest # dbg
225 #print 'oname_rest:', oname_rest # dbg
226 for part in oname_rest:
226 for part in oname_rest:
227 try:
227 try:
228 parent = obj
228 parent = obj
229 obj = getattr(obj,part)
229 obj = getattr(obj,part)
230 except:
230 except:
231 # Blanket except b/c some badly implemented objects
231 # Blanket except b/c some badly implemented objects
232 # allow __getattr__ to raise exceptions other than
232 # allow __getattr__ to raise exceptions other than
233 # AttributeError, which then crashes IPython.
233 # AttributeError, which then crashes IPython.
234 break
234 break
235 else:
235 else:
236 # If we finish the for loop (no break), we got all members
236 # If we finish the for loop (no break), we got all members
237 found = 1
237 found = 1
238 ospace = nsname
238 ospace = nsname
239 if ns == alias_ns:
239 if ns == alias_ns:
240 isalias = 1
240 isalias = 1
241 break # namespace loop
241 break # namespace loop
242
242
243 # Try to see if it's magic
243 # Try to see if it's magic
244 if not found:
244 if not found:
245 if oname.startswith(self.shell.ESC_MAGIC):
245 if oname.startswith(self.shell.ESC_MAGIC):
246 oname = oname[1:]
246 oname = oname[1:]
247 obj = getattr(self,'magic_'+oname,None)
247 obj = getattr(self,'magic_'+oname,None)
248 if obj is not None:
248 if obj is not None:
249 found = 1
249 found = 1
250 ospace = 'IPython internal'
250 ospace = 'IPython internal'
251 ismagic = 1
251 ismagic = 1
252
252
253 # Last try: special-case some literals like '', [], {}, etc:
253 # Last try: special-case some literals like '', [], {}, etc:
254 if not found and oname_head in ["''",'""','[]','{}','()']:
254 if not found and oname_head in ["''",'""','[]','{}','()']:
255 obj = eval(oname_head)
255 obj = eval(oname_head)
256 found = 1
256 found = 1
257 ospace = 'Interactive'
257 ospace = 'Interactive'
258
258
259 return {'found':found, 'obj':obj, 'namespace':ospace,
259 return {'found':found, 'obj':obj, 'namespace':ospace,
260 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
260 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
261
261
262 def arg_err(self,func):
262 def arg_err(self,func):
263 """Print docstring if incorrect arguments were passed"""
263 """Print docstring if incorrect arguments were passed"""
264 print 'Error in arguments:'
264 print 'Error in arguments:'
265 print OInspect.getdoc(func)
265 print OInspect.getdoc(func)
266
266
267 def format_latex(self,strng):
267 def format_latex(self,strng):
268 """Format a string for latex inclusion."""
268 """Format a string for latex inclusion."""
269
269
270 # Characters that need to be escaped for latex:
270 # Characters that need to be escaped for latex:
271 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
271 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
272 # Magic command names as headers:
272 # Magic command names as headers:
273 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
273 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
274 re.MULTILINE)
274 re.MULTILINE)
275 # Magic commands
275 # Magic commands
276 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
276 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
277 re.MULTILINE)
277 re.MULTILINE)
278 # Paragraph continue
278 # Paragraph continue
279 par_re = re.compile(r'\\$',re.MULTILINE)
279 par_re = re.compile(r'\\$',re.MULTILINE)
280
280
281 # The "\n" symbol
281 # The "\n" symbol
282 newline_re = re.compile(r'\\n')
282 newline_re = re.compile(r'\\n')
283
283
284 # Now build the string for output:
284 # Now build the string for output:
285 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
285 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
286 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
286 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
287 strng)
287 strng)
288 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
288 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
289 strng = par_re.sub(r'\\\\',strng)
289 strng = par_re.sub(r'\\\\',strng)
290 strng = escape_re.sub(r'\\\1',strng)
290 strng = escape_re.sub(r'\\\1',strng)
291 strng = newline_re.sub(r'\\textbackslash{}n',strng)
291 strng = newline_re.sub(r'\\textbackslash{}n',strng)
292 return strng
292 return strng
293
293
294 def format_screen(self,strng):
294 def format_screen(self,strng):
295 """Format a string for screen printing.
295 """Format a string for screen printing.
296
296
297 This removes some latex-type format codes."""
297 This removes some latex-type format codes."""
298 # Paragraph continue
298 # Paragraph continue
299 par_re = re.compile(r'\\$',re.MULTILINE)
299 par_re = re.compile(r'\\$',re.MULTILINE)
300 strng = par_re.sub('',strng)
300 strng = par_re.sub('',strng)
301 return strng
301 return strng
302
302
303 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
303 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
304 """Parse options passed to an argument string.
304 """Parse options passed to an argument string.
305
305
306 The interface is similar to that of getopt(), but it returns back a
306 The interface is similar to that of getopt(), but it returns back a
307 Struct with the options as keys and the stripped argument string still
307 Struct with the options as keys and the stripped argument string still
308 as a string.
308 as a string.
309
309
310 arg_str is quoted as a true sys.argv vector by using shlex.split.
310 arg_str is quoted as a true sys.argv vector by using shlex.split.
311 This allows us to easily expand variables, glob files, quote
311 This allows us to easily expand variables, glob files, quote
312 arguments, etc.
312 arguments, etc.
313
313
314 Options:
314 Options:
315 -mode: default 'string'. If given as 'list', the argument string is
315 -mode: default 'string'. If given as 'list', the argument string is
316 returned as a list (split on whitespace) instead of a string.
316 returned as a list (split on whitespace) instead of a string.
317
317
318 -list_all: put all option values in lists. Normally only options
318 -list_all: put all option values in lists. Normally only options
319 appearing more than once are put in a list.
319 appearing more than once are put in a list.
320
320
321 -posix (True): whether to split the input line in POSIX mode or not,
321 -posix (True): whether to split the input line in POSIX mode or not,
322 as per the conventions outlined in the shlex module from the
322 as per the conventions outlined in the shlex module from the
323 standard library."""
323 standard library."""
324
324
325 # inject default options at the beginning of the input line
325 # inject default options at the beginning of the input line
326 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
326 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
327 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
327 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
328
328
329 mode = kw.get('mode','string')
329 mode = kw.get('mode','string')
330 if mode not in ['string','list']:
330 if mode not in ['string','list']:
331 raise ValueError,'incorrect mode given: %s' % mode
331 raise ValueError,'incorrect mode given: %s' % mode
332 # Get options
332 # Get options
333 list_all = kw.get('list_all',0)
333 list_all = kw.get('list_all',0)
334 posix = kw.get('posix',True)
334 posix = kw.get('posix',True)
335
335
336 # Check if we have more than one argument to warrant extra processing:
336 # Check if we have more than one argument to warrant extra processing:
337 odict = {} # Dictionary with options
337 odict = {} # Dictionary with options
338 args = arg_str.split()
338 args = arg_str.split()
339 if len(args) >= 1:
339 if len(args) >= 1:
340 # If the list of inputs only has 0 or 1 thing in it, there's no
340 # If the list of inputs only has 0 or 1 thing in it, there's no
341 # need to look for options
341 # need to look for options
342 argv = arg_split(arg_str,posix)
342 argv = arg_split(arg_str,posix)
343 # Do regular option processing
343 # Do regular option processing
344 try:
344 try:
345 opts,args = getopt(argv,opt_str,*long_opts)
345 opts,args = getopt(argv,opt_str,*long_opts)
346 except GetoptError,e:
346 except GetoptError,e:
347 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
347 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
348 " ".join(long_opts)))
348 " ".join(long_opts)))
349 for o,a in opts:
349 for o,a in opts:
350 if o.startswith('--'):
350 if o.startswith('--'):
351 o = o[2:]
351 o = o[2:]
352 else:
352 else:
353 o = o[1:]
353 o = o[1:]
354 try:
354 try:
355 odict[o].append(a)
355 odict[o].append(a)
356 except AttributeError:
356 except AttributeError:
357 odict[o] = [odict[o],a]
357 odict[o] = [odict[o],a]
358 except KeyError:
358 except KeyError:
359 if list_all:
359 if list_all:
360 odict[o] = [a]
360 odict[o] = [a]
361 else:
361 else:
362 odict[o] = a
362 odict[o] = a
363
363
364 # Prepare opts,args for return
364 # Prepare opts,args for return
365 opts = Struct(odict)
365 opts = Struct(odict)
366 if mode == 'string':
366 if mode == 'string':
367 args = ' '.join(args)
367 args = ' '.join(args)
368
368
369 return opts,args
369 return opts,args
370
370
371 #......................................................................
371 #......................................................................
372 # And now the actual magic functions
372 # And now the actual magic functions
373
373
374 # Functions for IPython shell work (vars,funcs, config, etc)
374 # Functions for IPython shell work (vars,funcs, config, etc)
375 def magic_lsmagic(self, parameter_s = ''):
375 def magic_lsmagic(self, parameter_s = ''):
376 """List currently available magic functions."""
376 """List currently available magic functions."""
377 mesc = self.shell.ESC_MAGIC
377 mesc = self.shell.ESC_MAGIC
378 print 'Available magic functions:\n'+mesc+\
378 print 'Available magic functions:\n'+mesc+\
379 (' '+mesc).join(self.lsmagic())
379 (' '+mesc).join(self.lsmagic())
380 print '\n' + Magic.auto_status[self.shell.rc.automagic]
380 print '\n' + Magic.auto_status[self.shell.rc.automagic]
381 return None
381 return None
382
382
383 def magic_magic(self, parameter_s = ''):
383 def magic_magic(self, parameter_s = ''):
384 """Print information about the magic function system.
384 """Print information about the magic function system.
385
385
386 Supported formats: -latex, -brief, -rest
386 Supported formats: -latex, -brief, -rest
387 """
387 """
388
388
389 mode = ''
389 mode = ''
390 try:
390 try:
391 if parameter_s.split()[0] == '-latex':
391 if parameter_s.split()[0] == '-latex':
392 mode = 'latex'
392 mode = 'latex'
393 if parameter_s.split()[0] == '-brief':
393 if parameter_s.split()[0] == '-brief':
394 mode = 'brief'
394 mode = 'brief'
395 if parameter_s.split()[0] == '-rest':
395 if parameter_s.split()[0] == '-rest':
396 mode = 'rest'
396 mode = 'rest'
397 rest_docs = []
397 rest_docs = []
398 except:
398 except:
399 pass
399 pass
400
400
401 magic_docs = []
401 magic_docs = []
402 for fname in self.lsmagic():
402 for fname in self.lsmagic():
403 mname = 'magic_' + fname
403 mname = 'magic_' + fname
404 for space in (Magic,self,self.__class__):
404 for space in (Magic,self,self.__class__):
405 try:
405 try:
406 fn = space.__dict__[mname]
406 fn = space.__dict__[mname]
407 except KeyError:
407 except KeyError:
408 pass
408 pass
409 else:
409 else:
410 break
410 break
411 if mode == 'brief':
411 if mode == 'brief':
412 # only first line
412 # only first line
413 if fn.__doc__:
413 if fn.__doc__:
414 fndoc = fn.__doc__.split('\n',1)[0]
414 fndoc = fn.__doc__.split('\n',1)[0]
415 else:
415 else:
416 fndoc = 'No documentation'
416 fndoc = 'No documentation'
417 else:
417 else:
418 if fn.__doc__:
418 if fn.__doc__:
419 fndoc = fn.__doc__.rstrip()
419 fndoc = fn.__doc__.rstrip()
420 else:
420 else:
421 fndoc = 'No documentation'
421 fndoc = 'No documentation'
422
422
423
423
424 if mode == 'rest':
424 if mode == 'rest':
425 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
425 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
426 fname,fndoc))
426 fname,fndoc))
427
427
428 else:
428 else:
429 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
429 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
430 fname,fndoc))
430 fname,fndoc))
431
431
432 magic_docs = ''.join(magic_docs)
432 magic_docs = ''.join(magic_docs)
433
433
434 if mode == 'rest':
434 if mode == 'rest':
435 return "".join(rest_docs)
435 return "".join(rest_docs)
436
436
437 if mode == 'latex':
437 if mode == 'latex':
438 print self.format_latex(magic_docs)
438 print self.format_latex(magic_docs)
439 return
439 return
440 else:
440 else:
441 magic_docs = self.format_screen(magic_docs)
441 magic_docs = self.format_screen(magic_docs)
442 if mode == 'brief':
442 if mode == 'brief':
443 return magic_docs
443 return magic_docs
444
444
445 outmsg = """
445 outmsg = """
446 IPython's 'magic' functions
446 IPython's 'magic' functions
447 ===========================
447 ===========================
448
448
449 The magic function system provides a series of functions which allow you to
449 The magic function system provides a series of functions which allow you to
450 control the behavior of IPython itself, plus a lot of system-type
450 control the behavior of IPython itself, plus a lot of system-type
451 features. All these functions are prefixed with a % character, but parameters
451 features. All these functions are prefixed with a % character, but parameters
452 are given without parentheses or quotes.
452 are given without parentheses or quotes.
453
453
454 NOTE: If you have 'automagic' enabled (via the command line option or with the
454 NOTE: If you have 'automagic' enabled (via the command line option or with the
455 %automagic function), you don't need to type in the % explicitly. By default,
455 %automagic function), you don't need to type in the % explicitly. By default,
456 IPython ships with automagic on, so you should only rarely need the % escape.
456 IPython ships with automagic on, so you should only rarely need the % escape.
457
457
458 Example: typing '%cd mydir' (without the quotes) changes you working directory
458 Example: typing '%cd mydir' (without the quotes) changes you working directory
459 to 'mydir', if it exists.
459 to 'mydir', if it exists.
460
460
461 You can define your own magic functions to extend the system. See the supplied
461 You can define your own magic functions to extend the system. See the supplied
462 ipythonrc and example-magic.py files for details (in your ipython
462 ipythonrc and example-magic.py files for details (in your ipython
463 configuration directory, typically $HOME/.ipython/).
463 configuration directory, typically $HOME/.ipython/).
464
464
465 You can also define your own aliased names for magic functions. In your
465 You can also define your own aliased names for magic functions. In your
466 ipythonrc file, placing a line like:
466 ipythonrc file, placing a line like:
467
467
468 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
468 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
469
469
470 will define %pf as a new name for %profile.
470 will define %pf as a new name for %profile.
471
471
472 You can also call magics in code using the ipmagic() function, which IPython
472 You can also call magics in code using the ipmagic() function, which IPython
473 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
473 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
474
474
475 For a list of the available magic functions, use %lsmagic. For a description
475 For a list of the available magic functions, use %lsmagic. For a description
476 of any of them, type %magic_name?, e.g. '%cd?'.
476 of any of them, type %magic_name?, e.g. '%cd?'.
477
477
478 Currently the magic system has the following functions:\n"""
478 Currently the magic system has the following functions:\n"""
479
479
480 mesc = self.shell.ESC_MAGIC
480 mesc = self.shell.ESC_MAGIC
481 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
481 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
482 "\n\n%s%s\n\n%s" % (outmsg,
482 "\n\n%s%s\n\n%s" % (outmsg,
483 magic_docs,mesc,mesc,
483 magic_docs,mesc,mesc,
484 (' '+mesc).join(self.lsmagic()),
484 (' '+mesc).join(self.lsmagic()),
485 Magic.auto_status[self.shell.rc.automagic] ) )
485 Magic.auto_status[self.shell.rc.automagic] ) )
486
486
487 page(outmsg,screen_lines=self.shell.rc.screen_length)
487 page(outmsg,screen_lines=self.shell.rc.screen_length)
488
488
489
489
490 def magic_autoindent(self, parameter_s = ''):
490 def magic_autoindent(self, parameter_s = ''):
491 """Toggle autoindent on/off (if available)."""
491 """Toggle autoindent on/off (if available)."""
492
492
493 self.shell.set_autoindent()
493 self.shell.set_autoindent()
494 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
494 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
495
495
496
496
497 def magic_automagic(self, parameter_s = ''):
497 def magic_automagic(self, parameter_s = ''):
498 """Make magic functions callable without having to type the initial %.
498 """Make magic functions callable without having to type the initial %.
499
499
500 Without argumentsl toggles on/off (when off, you must call it as
500 Without argumentsl toggles on/off (when off, you must call it as
501 %automagic, of course). With arguments it sets the value, and you can
501 %automagic, of course). With arguments it sets the value, and you can
502 use any of (case insensitive):
502 use any of (case insensitive):
503
503
504 - on,1,True: to activate
504 - on,1,True: to activate
505
505
506 - off,0,False: to deactivate.
506 - off,0,False: to deactivate.
507
507
508 Note that magic functions have lowest priority, so if there's a
508 Note that magic functions have lowest priority, so if there's a
509 variable whose name collides with that of a magic fn, automagic won't
509 variable whose name collides with that of a magic fn, automagic won't
510 work for that function (you get the variable instead). However, if you
510 work for that function (you get the variable instead). However, if you
511 delete the variable (del var), the previously shadowed magic function
511 delete the variable (del var), the previously shadowed magic function
512 becomes visible to automagic again."""
512 becomes visible to automagic again."""
513
513
514 rc = self.shell.rc
514 rc = self.shell.rc
515 arg = parameter_s.lower()
515 arg = parameter_s.lower()
516 if parameter_s in ('on','1','true'):
516 if parameter_s in ('on','1','true'):
517 rc.automagic = True
517 rc.automagic = True
518 elif parameter_s in ('off','0','false'):
518 elif parameter_s in ('off','0','false'):
519 rc.automagic = False
519 rc.automagic = False
520 else:
520 else:
521 rc.automagic = not rc.automagic
521 rc.automagic = not rc.automagic
522 print '\n' + Magic.auto_status[rc.automagic]
522 print '\n' + Magic.auto_status[rc.automagic]
523
523
524 @testdec.skip_doctest
524 @testdec.skip_doctest
525 def magic_autocall(self, parameter_s = ''):
525 def magic_autocall(self, parameter_s = ''):
526 """Make functions callable without having to type parentheses.
526 """Make functions callable without having to type parentheses.
527
527
528 Usage:
528 Usage:
529
529
530 %autocall [mode]
530 %autocall [mode]
531
531
532 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
532 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
533 value is toggled on and off (remembering the previous state).
533 value is toggled on and off (remembering the previous state).
534
534
535 In more detail, these values mean:
535 In more detail, these values mean:
536
536
537 0 -> fully disabled
537 0 -> fully disabled
538
538
539 1 -> active, but do not apply if there are no arguments on the line.
539 1 -> active, but do not apply if there are no arguments on the line.
540
540
541 In this mode, you get:
541 In this mode, you get:
542
542
543 In [1]: callable
543 In [1]: callable
544 Out[1]: <built-in function callable>
544 Out[1]: <built-in function callable>
545
545
546 In [2]: callable 'hello'
546 In [2]: callable 'hello'
547 ------> callable('hello')
547 ------> callable('hello')
548 Out[2]: False
548 Out[2]: False
549
549
550 2 -> Active always. Even if no arguments are present, the callable
550 2 -> Active always. Even if no arguments are present, the callable
551 object is called:
551 object is called:
552
552
553 In [2]: float
553 In [2]: float
554 ------> float()
554 ------> float()
555 Out[2]: 0.0
555 Out[2]: 0.0
556
556
557 Note that even with autocall off, you can still use '/' at the start of
557 Note that even with autocall off, you can still use '/' at the start of
558 a line to treat the first argument on the command line as a function
558 a line to treat the first argument on the command line as a function
559 and add parentheses to it:
559 and add parentheses to it:
560
560
561 In [8]: /str 43
561 In [8]: /str 43
562 ------> str(43)
562 ------> str(43)
563 Out[8]: '43'
563 Out[8]: '43'
564
564
565 # all-random (note for auto-testing)
565 # all-random (note for auto-testing)
566 """
566 """
567
567
568 rc = self.shell.rc
568 rc = self.shell.rc
569
569
570 if parameter_s:
570 if parameter_s:
571 arg = int(parameter_s)
571 arg = int(parameter_s)
572 else:
572 else:
573 arg = 'toggle'
573 arg = 'toggle'
574
574
575 if not arg in (0,1,2,'toggle'):
575 if not arg in (0,1,2,'toggle'):
576 error('Valid modes: (0->Off, 1->Smart, 2->Full')
576 error('Valid modes: (0->Off, 1->Smart, 2->Full')
577 return
577 return
578
578
579 if arg in (0,1,2):
579 if arg in (0,1,2):
580 rc.autocall = arg
580 rc.autocall = arg
581 else: # toggle
581 else: # toggle
582 if rc.autocall:
582 if rc.autocall:
583 self._magic_state.autocall_save = rc.autocall
583 self._magic_state.autocall_save = rc.autocall
584 rc.autocall = 0
584 rc.autocall = 0
585 else:
585 else:
586 try:
586 try:
587 rc.autocall = self._magic_state.autocall_save
587 rc.autocall = self._magic_state.autocall_save
588 except AttributeError:
588 except AttributeError:
589 rc.autocall = self._magic_state.autocall_save = 1
589 rc.autocall = self._magic_state.autocall_save = 1
590
590
591 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
591 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
592
592
593 def magic_system_verbose(self, parameter_s = ''):
593 def magic_system_verbose(self, parameter_s = ''):
594 """Set verbose printing of system calls.
594 """Set verbose printing of system calls.
595
595
596 If called without an argument, act as a toggle"""
596 If called without an argument, act as a toggle"""
597
597
598 if parameter_s:
598 if parameter_s:
599 val = bool(eval(parameter_s))
599 val = bool(eval(parameter_s))
600 else:
600 else:
601 val = None
601 val = None
602
602
603 self.shell.rc_set_toggle('system_verbose',val)
603 self.shell.rc_set_toggle('system_verbose',val)
604 print "System verbose printing is:",\
604 print "System verbose printing is:",\
605 ['OFF','ON'][self.shell.rc.system_verbose]
605 ['OFF','ON'][self.shell.rc.system_verbose]
606
606
607
607
608 def magic_page(self, parameter_s=''):
608 def magic_page(self, parameter_s=''):
609 """Pretty print the object and display it through a pager.
609 """Pretty print the object and display it through a pager.
610
610
611 %page [options] OBJECT
611 %page [options] OBJECT
612
612
613 If no object is given, use _ (last output).
613 If no object is given, use _ (last output).
614
614
615 Options:
615 Options:
616
616
617 -r: page str(object), don't pretty-print it."""
617 -r: page str(object), don't pretty-print it."""
618
618
619 # After a function contributed by Olivier Aubert, slightly modified.
619 # After a function contributed by Olivier Aubert, slightly modified.
620
620
621 # Process options/args
621 # Process options/args
622 opts,args = self.parse_options(parameter_s,'r')
622 opts,args = self.parse_options(parameter_s,'r')
623 raw = 'r' in opts
623 raw = 'r' in opts
624
624
625 oname = args and args or '_'
625 oname = args and args or '_'
626 info = self._ofind(oname)
626 info = self._ofind(oname)
627 if info['found']:
627 if info['found']:
628 txt = (raw and str or pformat)( info['obj'] )
628 txt = (raw and str or pformat)( info['obj'] )
629 page(txt)
629 page(txt)
630 else:
630 else:
631 print 'Object `%s` not found' % oname
631 print 'Object `%s` not found' % oname
632
632
633 def magic_profile(self, parameter_s=''):
633 def magic_profile(self, parameter_s=''):
634 """Print your currently active IPyhton profile."""
634 """Print your currently active IPyhton profile."""
635 if self.shell.rc.profile:
635 if self.shell.rc.profile:
636 printpl('Current IPython profile: $self.shell.rc.profile.')
636 printpl('Current IPython profile: $self.shell.rc.profile.')
637 else:
637 else:
638 print 'No profile active.'
638 print 'No profile active.'
639
639
640 def magic_pinfo(self, parameter_s='', namespaces=None):
640 def magic_pinfo(self, parameter_s='', namespaces=None):
641 """Provide detailed information about an object.
641 """Provide detailed information about an object.
642
642
643 '%pinfo object' is just a synonym for object? or ?object."""
643 '%pinfo object' is just a synonym for object? or ?object."""
644
644
645 #print 'pinfo par: <%s>' % parameter_s # dbg
645 #print 'pinfo par: <%s>' % parameter_s # dbg
646
646
647
647
648 # detail_level: 0 -> obj? , 1 -> obj??
648 # detail_level: 0 -> obj? , 1 -> obj??
649 detail_level = 0
649 detail_level = 0
650 # We need to detect if we got called as 'pinfo pinfo foo', which can
650 # We need to detect if we got called as 'pinfo pinfo foo', which can
651 # happen if the user types 'pinfo foo?' at the cmd line.
651 # happen if the user types 'pinfo foo?' at the cmd line.
652 pinfo,qmark1,oname,qmark2 = \
652 pinfo,qmark1,oname,qmark2 = \
653 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
653 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
654 if pinfo or qmark1 or qmark2:
654 if pinfo or qmark1 or qmark2:
655 detail_level = 1
655 detail_level = 1
656 if "*" in oname:
656 if "*" in oname:
657 self.magic_psearch(oname)
657 self.magic_psearch(oname)
658 else:
658 else:
659 self._inspect('pinfo', oname, detail_level=detail_level,
659 self._inspect('pinfo', oname, detail_level=detail_level,
660 namespaces=namespaces)
660 namespaces=namespaces)
661
661
662 def magic_pdef(self, parameter_s='', namespaces=None):
662 def magic_pdef(self, parameter_s='', namespaces=None):
663 """Print the definition header for any callable object.
663 """Print the definition header for any callable object.
664
664
665 If the object is a class, print the constructor information."""
665 If the object is a class, print the constructor information."""
666 self._inspect('pdef',parameter_s, namespaces)
666 self._inspect('pdef',parameter_s, namespaces)
667
667
668 def magic_pdoc(self, parameter_s='', namespaces=None):
668 def magic_pdoc(self, parameter_s='', namespaces=None):
669 """Print the docstring for an object.
669 """Print the docstring for an object.
670
670
671 If the given object is a class, it will print both the class and the
671 If the given object is a class, it will print both the class and the
672 constructor docstrings."""
672 constructor docstrings."""
673 self._inspect('pdoc',parameter_s, namespaces)
673 self._inspect('pdoc',parameter_s, namespaces)
674
674
675 def magic_psource(self, parameter_s='', namespaces=None):
675 def magic_psource(self, parameter_s='', namespaces=None):
676 """Print (or run through pager) the source code for an object."""
676 """Print (or run through pager) the source code for an object."""
677 self._inspect('psource',parameter_s, namespaces)
677 self._inspect('psource',parameter_s, namespaces)
678
678
679 def magic_pfile(self, parameter_s=''):
679 def magic_pfile(self, parameter_s=''):
680 """Print (or run through pager) the file where an object is defined.
680 """Print (or run through pager) the file where an object is defined.
681
681
682 The file opens at the line where the object definition begins. IPython
682 The file opens at the line where the object definition begins. IPython
683 will honor the environment variable PAGER if set, and otherwise will
683 will honor the environment variable PAGER if set, and otherwise will
684 do its best to print the file in a convenient form.
684 do its best to print the file in a convenient form.
685
685
686 If the given argument is not an object currently defined, IPython will
686 If the given argument is not an object currently defined, IPython will
687 try to interpret it as a filename (automatically adding a .py extension
687 try to interpret it as a filename (automatically adding a .py extension
688 if needed). You can thus use %pfile as a syntax highlighting code
688 if needed). You can thus use %pfile as a syntax highlighting code
689 viewer."""
689 viewer."""
690
690
691 # first interpret argument as an object name
691 # first interpret argument as an object name
692 out = self._inspect('pfile',parameter_s)
692 out = self._inspect('pfile',parameter_s)
693 # if not, try the input as a filename
693 # if not, try the input as a filename
694 if out == 'not found':
694 if out == 'not found':
695 try:
695 try:
696 filename = get_py_filename(parameter_s)
696 filename = get_py_filename(parameter_s)
697 except IOError,msg:
697 except IOError,msg:
698 print msg
698 print msg
699 return
699 return
700 page(self.shell.inspector.format(file(filename).read()))
700 page(self.shell.inspector.format(file(filename).read()))
701
701
702 def _inspect(self,meth,oname,namespaces=None,**kw):
702 def _inspect(self,meth,oname,namespaces=None,**kw):
703 """Generic interface to the inspector system.
703 """Generic interface to the inspector system.
704
704
705 This function is meant to be called by pdef, pdoc & friends."""
705 This function is meant to be called by pdef, pdoc & friends."""
706
706
707 #oname = oname.strip()
707 #oname = oname.strip()
708 #print '1- oname: <%r>' % oname # dbg
708 #print '1- oname: <%r>' % oname # dbg
709 try:
709 try:
710 oname = oname.strip().encode('ascii')
710 oname = oname.strip().encode('ascii')
711 #print '2- oname: <%r>' % oname # dbg
711 #print '2- oname: <%r>' % oname # dbg
712 except UnicodeEncodeError:
712 except UnicodeEncodeError:
713 print 'Python identifiers can only contain ascii characters.'
713 print 'Python identifiers can only contain ascii characters.'
714 return 'not found'
714 return 'not found'
715
715
716 info = Struct(self._ofind(oname, namespaces))
716 info = Struct(self._ofind(oname, namespaces))
717
717
718 if info.found:
718 if info.found:
719 try:
719 try:
720 IPython.generics.inspect_object(info.obj)
720 IPython.generics.inspect_object(info.obj)
721 return
721 return
722 except IPython.ipapi.TryNext:
722 except IPython.ipapi.TryNext:
723 pass
723 pass
724 # Get the docstring of the class property if it exists.
724 # Get the docstring of the class property if it exists.
725 path = oname.split('.')
725 path = oname.split('.')
726 root = '.'.join(path[:-1])
726 root = '.'.join(path[:-1])
727 if info.parent is not None:
727 if info.parent is not None:
728 try:
728 try:
729 target = getattr(info.parent, '__class__')
729 target = getattr(info.parent, '__class__')
730 # The object belongs to a class instance.
730 # The object belongs to a class instance.
731 try:
731 try:
732 target = getattr(target, path[-1])
732 target = getattr(target, path[-1])
733 # The class defines the object.
733 # The class defines the object.
734 if isinstance(target, property):
734 if isinstance(target, property):
735 oname = root + '.__class__.' + path[-1]
735 oname = root + '.__class__.' + path[-1]
736 info = Struct(self._ofind(oname))
736 info = Struct(self._ofind(oname))
737 except AttributeError: pass
737 except AttributeError: pass
738 except AttributeError: pass
738 except AttributeError: pass
739
739
740 pmethod = getattr(self.shell.inspector,meth)
740 pmethod = getattr(self.shell.inspector,meth)
741 formatter = info.ismagic and self.format_screen or None
741 formatter = info.ismagic and self.format_screen or None
742 if meth == 'pdoc':
742 if meth == 'pdoc':
743 pmethod(info.obj,oname,formatter)
743 pmethod(info.obj,oname,formatter)
744 elif meth == 'pinfo':
744 elif meth == 'pinfo':
745 pmethod(info.obj,oname,formatter,info,**kw)
745 pmethod(info.obj,oname,formatter,info,**kw)
746 else:
746 else:
747 pmethod(info.obj,oname)
747 pmethod(info.obj,oname)
748 else:
748 else:
749 print 'Object `%s` not found.' % oname
749 print 'Object `%s` not found.' % oname
750 return 'not found' # so callers can take other action
750 return 'not found' # so callers can take other action
751
751
752 def magic_psearch(self, parameter_s=''):
752 def magic_psearch(self, parameter_s=''):
753 """Search for object in namespaces by wildcard.
753 """Search for object in namespaces by wildcard.
754
754
755 %psearch [options] PATTERN [OBJECT TYPE]
755 %psearch [options] PATTERN [OBJECT TYPE]
756
756
757 Note: ? can be used as a synonym for %psearch, at the beginning or at
757 Note: ? can be used as a synonym for %psearch, at the beginning or at
758 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
758 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
759 rest of the command line must be unchanged (options come first), so
759 rest of the command line must be unchanged (options come first), so
760 for example the following forms are equivalent
760 for example the following forms are equivalent
761
761
762 %psearch -i a* function
762 %psearch -i a* function
763 -i a* function?
763 -i a* function?
764 ?-i a* function
764 ?-i a* function
765
765
766 Arguments:
766 Arguments:
767
767
768 PATTERN
768 PATTERN
769
769
770 where PATTERN is a string containing * as a wildcard similar to its
770 where PATTERN is a string containing * as a wildcard similar to its
771 use in a shell. The pattern is matched in all namespaces on the
771 use in a shell. The pattern is matched in all namespaces on the
772 search path. By default objects starting with a single _ are not
772 search path. By default objects starting with a single _ are not
773 matched, many IPython generated objects have a single
773 matched, many IPython generated objects have a single
774 underscore. The default is case insensitive matching. Matching is
774 underscore. The default is case insensitive matching. Matching is
775 also done on the attributes of objects and not only on the objects
775 also done on the attributes of objects and not only on the objects
776 in a module.
776 in a module.
777
777
778 [OBJECT TYPE]
778 [OBJECT TYPE]
779
779
780 Is the name of a python type from the types module. The name is
780 Is the name of a python type from the types module. The name is
781 given in lowercase without the ending type, ex. StringType is
781 given in lowercase without the ending type, ex. StringType is
782 written string. By adding a type here only objects matching the
782 written string. By adding a type here only objects matching the
783 given type are matched. Using all here makes the pattern match all
783 given type are matched. Using all here makes the pattern match all
784 types (this is the default).
784 types (this is the default).
785
785
786 Options:
786 Options:
787
787
788 -a: makes the pattern match even objects whose names start with a
788 -a: makes the pattern match even objects whose names start with a
789 single underscore. These names are normally ommitted from the
789 single underscore. These names are normally ommitted from the
790 search.
790 search.
791
791
792 -i/-c: make the pattern case insensitive/sensitive. If neither of
792 -i/-c: make the pattern case insensitive/sensitive. If neither of
793 these options is given, the default is read from your ipythonrc
793 these options is given, the default is read from your ipythonrc
794 file. The option name which sets this value is
794 file. The option name which sets this value is
795 'wildcards_case_sensitive'. If this option is not specified in your
795 'wildcards_case_sensitive'. If this option is not specified in your
796 ipythonrc file, IPython's internal default is to do a case sensitive
796 ipythonrc file, IPython's internal default is to do a case sensitive
797 search.
797 search.
798
798
799 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
799 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
800 specifiy can be searched in any of the following namespaces:
800 specifiy can be searched in any of the following namespaces:
801 'builtin', 'user', 'user_global','internal', 'alias', where
801 'builtin', 'user', 'user_global','internal', 'alias', where
802 'builtin' and 'user' are the search defaults. Note that you should
802 'builtin' and 'user' are the search defaults. Note that you should
803 not use quotes when specifying namespaces.
803 not use quotes when specifying namespaces.
804
804
805 'Builtin' contains the python module builtin, 'user' contains all
805 'Builtin' contains the python module builtin, 'user' contains all
806 user data, 'alias' only contain the shell aliases and no python
806 user data, 'alias' only contain the shell aliases and no python
807 objects, 'internal' contains objects used by IPython. The
807 objects, 'internal' contains objects used by IPython. The
808 'user_global' namespace is only used by embedded IPython instances,
808 'user_global' namespace is only used by embedded IPython instances,
809 and it contains module-level globals. You can add namespaces to the
809 and it contains module-level globals. You can add namespaces to the
810 search with -s or exclude them with -e (these options can be given
810 search with -s or exclude them with -e (these options can be given
811 more than once).
811 more than once).
812
812
813 Examples:
813 Examples:
814
814
815 %psearch a* -> objects beginning with an a
815 %psearch a* -> objects beginning with an a
816 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
816 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
817 %psearch a* function -> all functions beginning with an a
817 %psearch a* function -> all functions beginning with an a
818 %psearch re.e* -> objects beginning with an e in module re
818 %psearch re.e* -> objects beginning with an e in module re
819 %psearch r*.e* -> objects that start with e in modules starting in r
819 %psearch r*.e* -> objects that start with e in modules starting in r
820 %psearch r*.* string -> all strings in modules beginning with r
820 %psearch r*.* string -> all strings in modules beginning with r
821
821
822 Case sensitve search:
822 Case sensitve search:
823
823
824 %psearch -c a* list all object beginning with lower case a
824 %psearch -c a* list all object beginning with lower case a
825
825
826 Show objects beginning with a single _:
826 Show objects beginning with a single _:
827
827
828 %psearch -a _* list objects beginning with a single underscore"""
828 %psearch -a _* list objects beginning with a single underscore"""
829 try:
829 try:
830 parameter_s = parameter_s.encode('ascii')
830 parameter_s = parameter_s.encode('ascii')
831 except UnicodeEncodeError:
831 except UnicodeEncodeError:
832 print 'Python identifiers can only contain ascii characters.'
832 print 'Python identifiers can only contain ascii characters.'
833 return
833 return
834
834
835 # default namespaces to be searched
835 # default namespaces to be searched
836 def_search = ['user','builtin']
836 def_search = ['user','builtin']
837
837
838 # Process options/args
838 # Process options/args
839 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
839 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
840 opt = opts.get
840 opt = opts.get
841 shell = self.shell
841 shell = self.shell
842 psearch = shell.inspector.psearch
842 psearch = shell.inspector.psearch
843
843
844 # select case options
844 # select case options
845 if opts.has_key('i'):
845 if opts.has_key('i'):
846 ignore_case = True
846 ignore_case = True
847 elif opts.has_key('c'):
847 elif opts.has_key('c'):
848 ignore_case = False
848 ignore_case = False
849 else:
849 else:
850 ignore_case = not shell.rc.wildcards_case_sensitive
850 ignore_case = not shell.rc.wildcards_case_sensitive
851
851
852 # Build list of namespaces to search from user options
852 # Build list of namespaces to search from user options
853 def_search.extend(opt('s',[]))
853 def_search.extend(opt('s',[]))
854 ns_exclude = ns_exclude=opt('e',[])
854 ns_exclude = ns_exclude=opt('e',[])
855 ns_search = [nm for nm in def_search if nm not in ns_exclude]
855 ns_search = [nm for nm in def_search if nm not in ns_exclude]
856
856
857 # Call the actual search
857 # Call the actual search
858 try:
858 try:
859 psearch(args,shell.ns_table,ns_search,
859 psearch(args,shell.ns_table,ns_search,
860 show_all=opt('a'),ignore_case=ignore_case)
860 show_all=opt('a'),ignore_case=ignore_case)
861 except:
861 except:
862 shell.showtraceback()
862 shell.showtraceback()
863
863
864 def magic_who_ls(self, parameter_s=''):
864 def magic_who_ls(self, parameter_s=''):
865 """Return a sorted list of all interactive variables.
865 """Return a sorted list of all interactive variables.
866
866
867 If arguments are given, only variables of types matching these
867 If arguments are given, only variables of types matching these
868 arguments are returned."""
868 arguments are returned."""
869
869
870 user_ns = self.shell.user_ns
870 user_ns = self.shell.user_ns
871 internal_ns = self.shell.internal_ns
871 internal_ns = self.shell.internal_ns
872 user_config_ns = self.shell.user_config_ns
872 user_config_ns = self.shell.user_config_ns
873 out = []
873 out = []
874 typelist = parameter_s.split()
874 typelist = parameter_s.split()
875
875
876 for i in user_ns:
876 for i in user_ns:
877 if not (i.startswith('_') or i.startswith('_i')) \
877 if not (i.startswith('_') or i.startswith('_i')) \
878 and not (i in internal_ns or i in user_config_ns):
878 and not (i in internal_ns or i in user_config_ns):
879 if typelist:
879 if typelist:
880 if type(user_ns[i]).__name__ in typelist:
880 if type(user_ns[i]).__name__ in typelist:
881 out.append(i)
881 out.append(i)
882 else:
882 else:
883 out.append(i)
883 out.append(i)
884 out.sort()
884 out.sort()
885 return out
885 return out
886
886
887 def magic_who(self, parameter_s=''):
887 def magic_who(self, parameter_s=''):
888 """Print all interactive variables, with some minimal formatting.
888 """Print all interactive variables, with some minimal formatting.
889
889
890 If any arguments are given, only variables whose type matches one of
890 If any arguments are given, only variables whose type matches one of
891 these are printed. For example:
891 these are printed. For example:
892
892
893 %who function str
893 %who function str
894
894
895 will only list functions and strings, excluding all other types of
895 will only list functions and strings, excluding all other types of
896 variables. To find the proper type names, simply use type(var) at a
896 variables. To find the proper type names, simply use type(var) at a
897 command line to see how python prints type names. For example:
897 command line to see how python prints type names. For example:
898
898
899 In [1]: type('hello')\\
899 In [1]: type('hello')\\
900 Out[1]: <type 'str'>
900 Out[1]: <type 'str'>
901
901
902 indicates that the type name for strings is 'str'.
902 indicates that the type name for strings is 'str'.
903
903
904 %who always excludes executed names loaded through your configuration
904 %who always excludes executed names loaded through your configuration
905 file and things which are internal to IPython.
905 file and things which are internal to IPython.
906
906
907 This is deliberate, as typically you may load many modules and the
907 This is deliberate, as typically you may load many modules and the
908 purpose of %who is to show you only what you've manually defined."""
908 purpose of %who is to show you only what you've manually defined."""
909
909
910 varlist = self.magic_who_ls(parameter_s)
910 varlist = self.magic_who_ls(parameter_s)
911 if not varlist:
911 if not varlist:
912 if parameter_s:
912 if parameter_s:
913 print 'No variables match your requested type.'
913 print 'No variables match your requested type.'
914 else:
914 else:
915 print 'Interactive namespace is empty.'
915 print 'Interactive namespace is empty.'
916 return
916 return
917
917
918 # if we have variables, move on...
918 # if we have variables, move on...
919 count = 0
919 count = 0
920 for i in varlist:
920 for i in varlist:
921 print i+'\t',
921 print i+'\t',
922 count += 1
922 count += 1
923 if count > 8:
923 if count > 8:
924 count = 0
924 count = 0
925 print
925 print
926 print
926 print
927
927
928 def magic_whos(self, parameter_s=''):
928 def magic_whos(self, parameter_s=''):
929 """Like %who, but gives some extra information about each variable.
929 """Like %who, but gives some extra information about each variable.
930
930
931 The same type filtering of %who can be applied here.
931 The same type filtering of %who can be applied here.
932
932
933 For all variables, the type is printed. Additionally it prints:
933 For all variables, the type is printed. Additionally it prints:
934
934
935 - For {},[],(): their length.
935 - For {},[],(): their length.
936
936
937 - For numpy and Numeric arrays, a summary with shape, number of
937 - For numpy and Numeric arrays, a summary with shape, number of
938 elements, typecode and size in memory.
938 elements, typecode and size in memory.
939
939
940 - Everything else: a string representation, snipping their middle if
940 - Everything else: a string representation, snipping their middle if
941 too long."""
941 too long."""
942
942
943 varnames = self.magic_who_ls(parameter_s)
943 varnames = self.magic_who_ls(parameter_s)
944 if not varnames:
944 if not varnames:
945 if parameter_s:
945 if parameter_s:
946 print 'No variables match your requested type.'
946 print 'No variables match your requested type.'
947 else:
947 else:
948 print 'Interactive namespace is empty.'
948 print 'Interactive namespace is empty.'
949 return
949 return
950
950
951 # if we have variables, move on...
951 # if we have variables, move on...
952
952
953 # for these types, show len() instead of data:
953 # for these types, show len() instead of data:
954 seq_types = [types.DictType,types.ListType,types.TupleType]
954 seq_types = [types.DictType,types.ListType,types.TupleType]
955
955
956 # for numpy/Numeric arrays, display summary info
956 # for numpy/Numeric arrays, display summary info
957 try:
957 try:
958 import numpy
958 import numpy
959 except ImportError:
959 except ImportError:
960 ndarray_type = None
960 ndarray_type = None
961 else:
961 else:
962 ndarray_type = numpy.ndarray.__name__
962 ndarray_type = numpy.ndarray.__name__
963 try:
963 try:
964 import Numeric
964 import Numeric
965 except ImportError:
965 except ImportError:
966 array_type = None
966 array_type = None
967 else:
967 else:
968 array_type = Numeric.ArrayType.__name__
968 array_type = Numeric.ArrayType.__name__
969
969
970 # Find all variable names and types so we can figure out column sizes
970 # Find all variable names and types so we can figure out column sizes
971 def get_vars(i):
971 def get_vars(i):
972 return self.shell.user_ns[i]
972 return self.shell.user_ns[i]
973
973
974 # some types are well known and can be shorter
974 # some types are well known and can be shorter
975 abbrevs = {'IPython.macro.Macro' : 'Macro'}
975 abbrevs = {'IPython.macro.Macro' : 'Macro'}
976 def type_name(v):
976 def type_name(v):
977 tn = type(v).__name__
977 tn = type(v).__name__
978 return abbrevs.get(tn,tn)
978 return abbrevs.get(tn,tn)
979
979
980 varlist = map(get_vars,varnames)
980 varlist = map(get_vars,varnames)
981
981
982 typelist = []
982 typelist = []
983 for vv in varlist:
983 for vv in varlist:
984 tt = type_name(vv)
984 tt = type_name(vv)
985
985
986 if tt=='instance':
986 if tt=='instance':
987 typelist.append( abbrevs.get(str(vv.__class__),
987 typelist.append( abbrevs.get(str(vv.__class__),
988 str(vv.__class__)))
988 str(vv.__class__)))
989 else:
989 else:
990 typelist.append(tt)
990 typelist.append(tt)
991
991
992 # column labels and # of spaces as separator
992 # column labels and # of spaces as separator
993 varlabel = 'Variable'
993 varlabel = 'Variable'
994 typelabel = 'Type'
994 typelabel = 'Type'
995 datalabel = 'Data/Info'
995 datalabel = 'Data/Info'
996 colsep = 3
996 colsep = 3
997 # variable format strings
997 # variable format strings
998 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
998 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
999 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
999 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1000 aformat = "%s: %s elems, type `%s`, %s bytes"
1000 aformat = "%s: %s elems, type `%s`, %s bytes"
1001 # find the size of the columns to format the output nicely
1001 # find the size of the columns to format the output nicely
1002 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1002 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1003 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1003 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1004 # table header
1004 # table header
1005 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1005 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1006 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1006 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1007 # and the table itself
1007 # and the table itself
1008 kb = 1024
1008 kb = 1024
1009 Mb = 1048576 # kb**2
1009 Mb = 1048576 # kb**2
1010 for vname,var,vtype in zip(varnames,varlist,typelist):
1010 for vname,var,vtype in zip(varnames,varlist,typelist):
1011 print itpl(vformat),
1011 print itpl(vformat),
1012 if vtype in seq_types:
1012 if vtype in seq_types:
1013 print len(var)
1013 print len(var)
1014 elif vtype in [array_type,ndarray_type]:
1014 elif vtype in [array_type,ndarray_type]:
1015 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1015 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1016 if vtype==ndarray_type:
1016 if vtype==ndarray_type:
1017 # numpy
1017 # numpy
1018 vsize = var.size
1018 vsize = var.size
1019 vbytes = vsize*var.itemsize
1019 vbytes = vsize*var.itemsize
1020 vdtype = var.dtype
1020 vdtype = var.dtype
1021 else:
1021 else:
1022 # Numeric
1022 # Numeric
1023 vsize = Numeric.size(var)
1023 vsize = Numeric.size(var)
1024 vbytes = vsize*var.itemsize()
1024 vbytes = vsize*var.itemsize()
1025 vdtype = var.typecode()
1025 vdtype = var.typecode()
1026
1026
1027 if vbytes < 100000:
1027 if vbytes < 100000:
1028 print aformat % (vshape,vsize,vdtype,vbytes)
1028 print aformat % (vshape,vsize,vdtype,vbytes)
1029 else:
1029 else:
1030 print aformat % (vshape,vsize,vdtype,vbytes),
1030 print aformat % (vshape,vsize,vdtype,vbytes),
1031 if vbytes < Mb:
1031 if vbytes < Mb:
1032 print '(%s kb)' % (vbytes/kb,)
1032 print '(%s kb)' % (vbytes/kb,)
1033 else:
1033 else:
1034 print '(%s Mb)' % (vbytes/Mb,)
1034 print '(%s Mb)' % (vbytes/Mb,)
1035 else:
1035 else:
1036 try:
1036 try:
1037 vstr = str(var)
1037 vstr = str(var)
1038 except UnicodeEncodeError:
1038 except UnicodeEncodeError:
1039 vstr = unicode(var).encode(sys.getdefaultencoding(),
1039 vstr = unicode(var).encode(sys.getdefaultencoding(),
1040 'backslashreplace')
1040 'backslashreplace')
1041 vstr = vstr.replace('\n','\\n')
1041 vstr = vstr.replace('\n','\\n')
1042 if len(vstr) < 50:
1042 if len(vstr) < 50:
1043 print vstr
1043 print vstr
1044 else:
1044 else:
1045 printpl(vfmt_short)
1045 printpl(vfmt_short)
1046
1046
1047 def magic_reset(self, parameter_s=''):
1047 def magic_reset(self, parameter_s=''):
1048 """Resets the namespace by removing all names defined by the user.
1048 """Resets the namespace by removing all names defined by the user.
1049
1049
1050 Input/Output history are left around in case you need them.
1050 Input/Output history are left around in case you need them.
1051
1051
1052 Parameters
1052 Parameters
1053 ----------
1053 ----------
1054 -y : force reset without asking for confirmation.
1054 -y : force reset without asking for confirmation.
1055
1055
1056 Examples
1056 Examples
1057 --------
1057 --------
1058 In [6]: a = 1
1058 In [6]: a = 1
1059
1059
1060 In [7]: a
1060 In [7]: a
1061 Out[7]: 1
1061 Out[7]: 1
1062
1062
1063 In [8]: 'a' in _ip.user_ns
1063 In [8]: 'a' in _ip.user_ns
1064 Out[8]: True
1064 Out[8]: True
1065
1065
1066 In [9]: %reset -f
1066 In [9]: %reset -f
1067
1067
1068 In [10]: 'a' in _ip.user_ns
1068 In [10]: 'a' in _ip.user_ns
1069 Out[10]: False
1069 Out[10]: False
1070 """
1070 """
1071
1071
1072 if parameter_s == '-f':
1072 if parameter_s == '-f':
1073 ans = True
1073 ans = True
1074 else:
1074 else:
1075 ans = self.shell.ask_yes_no(
1075 ans = self.shell.ask_yes_no(
1076 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1076 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1077 if not ans:
1077 if not ans:
1078 print 'Nothing done.'
1078 print 'Nothing done.'
1079 return
1079 return
1080 user_ns = self.shell.user_ns
1080 user_ns = self.shell.user_ns
1081 for i in self.magic_who_ls():
1081 for i in self.magic_who_ls():
1082 del(user_ns[i])
1082 del(user_ns[i])
1083
1083
1084 # Also flush the private list of module references kept for script
1084 # Also flush the private list of module references kept for script
1085 # execution protection
1085 # execution protection
1086 self.shell.clear_main_mod_cache()
1086 self.shell.clear_main_mod_cache()
1087
1087
1088 def magic_logstart(self,parameter_s=''):
1088 def magic_logstart(self,parameter_s=''):
1089 """Start logging anywhere in a session.
1089 """Start logging anywhere in a session.
1090
1090
1091 %logstart [-o|-r|-t] [log_name [log_mode]]
1091 %logstart [-o|-r|-t] [log_name [log_mode]]
1092
1092
1093 If no name is given, it defaults to a file named 'ipython_log.py' in your
1093 If no name is given, it defaults to a file named 'ipython_log.py' in your
1094 current directory, in 'rotate' mode (see below).
1094 current directory, in 'rotate' mode (see below).
1095
1095
1096 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1096 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1097 history up to that point and then continues logging.
1097 history up to that point and then continues logging.
1098
1098
1099 %logstart takes a second optional parameter: logging mode. This can be one
1099 %logstart takes a second optional parameter: logging mode. This can be one
1100 of (note that the modes are given unquoted):\\
1100 of (note that the modes are given unquoted):\\
1101 append: well, that says it.\\
1101 append: well, that says it.\\
1102 backup: rename (if exists) to name~ and start name.\\
1102 backup: rename (if exists) to name~ and start name.\\
1103 global: single logfile in your home dir, appended to.\\
1103 global: single logfile in your home dir, appended to.\\
1104 over : overwrite existing log.\\
1104 over : overwrite existing log.\\
1105 rotate: create rotating logs name.1~, name.2~, etc.
1105 rotate: create rotating logs name.1~, name.2~, etc.
1106
1106
1107 Options:
1107 Options:
1108
1108
1109 -o: log also IPython's output. In this mode, all commands which
1109 -o: log also IPython's output. In this mode, all commands which
1110 generate an Out[NN] prompt are recorded to the logfile, right after
1110 generate an Out[NN] prompt are recorded to the logfile, right after
1111 their corresponding input line. The output lines are always
1111 their corresponding input line. The output lines are always
1112 prepended with a '#[Out]# ' marker, so that the log remains valid
1112 prepended with a '#[Out]# ' marker, so that the log remains valid
1113 Python code.
1113 Python code.
1114
1114
1115 Since this marker is always the same, filtering only the output from
1115 Since this marker is always the same, filtering only the output from
1116 a log is very easy, using for example a simple awk call:
1116 a log is very easy, using for example a simple awk call:
1117
1117
1118 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1118 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1119
1119
1120 -r: log 'raw' input. Normally, IPython's logs contain the processed
1120 -r: log 'raw' input. Normally, IPython's logs contain the processed
1121 input, so that user lines are logged in their final form, converted
1121 input, so that user lines are logged in their final form, converted
1122 into valid Python. For example, %Exit is logged as
1122 into valid Python. For example, %Exit is logged as
1123 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1123 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1124 exactly as typed, with no transformations applied.
1124 exactly as typed, with no transformations applied.
1125
1125
1126 -t: put timestamps before each input line logged (these are put in
1126 -t: put timestamps before each input line logged (these are put in
1127 comments)."""
1127 comments)."""
1128
1128
1129 opts,par = self.parse_options(parameter_s,'ort')
1129 opts,par = self.parse_options(parameter_s,'ort')
1130 log_output = 'o' in opts
1130 log_output = 'o' in opts
1131 log_raw_input = 'r' in opts
1131 log_raw_input = 'r' in opts
1132 timestamp = 't' in opts
1132 timestamp = 't' in opts
1133
1133
1134 rc = self.shell.rc
1134 rc = self.shell.rc
1135 logger = self.shell.logger
1135 logger = self.shell.logger
1136
1136
1137 # if no args are given, the defaults set in the logger constructor by
1137 # if no args are given, the defaults set in the logger constructor by
1138 # ipytohn remain valid
1138 # ipytohn remain valid
1139 if par:
1139 if par:
1140 try:
1140 try:
1141 logfname,logmode = par.split()
1141 logfname,logmode = par.split()
1142 except:
1142 except:
1143 logfname = par
1143 logfname = par
1144 logmode = 'backup'
1144 logmode = 'backup'
1145 else:
1145 else:
1146 logfname = logger.logfname
1146 logfname = logger.logfname
1147 logmode = logger.logmode
1147 logmode = logger.logmode
1148 # put logfname into rc struct as if it had been called on the command
1148 # put logfname into rc struct as if it had been called on the command
1149 # line, so it ends up saved in the log header Save it in case we need
1149 # line, so it ends up saved in the log header Save it in case we need
1150 # to restore it...
1150 # to restore it...
1151 old_logfile = rc.opts.get('logfile','')
1151 old_logfile = rc.opts.get('logfile','')
1152 if logfname:
1152 if logfname:
1153 logfname = os.path.expanduser(logfname)
1153 logfname = os.path.expanduser(logfname)
1154 rc.opts.logfile = logfname
1154 rc.opts.logfile = logfname
1155 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1155 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1156 try:
1156 try:
1157 started = logger.logstart(logfname,loghead,logmode,
1157 started = logger.logstart(logfname,loghead,logmode,
1158 log_output,timestamp,log_raw_input)
1158 log_output,timestamp,log_raw_input)
1159 except:
1159 except:
1160 rc.opts.logfile = old_logfile
1160 rc.opts.logfile = old_logfile
1161 warn("Couldn't start log: %s" % sys.exc_info()[1])
1161 warn("Couldn't start log: %s" % sys.exc_info()[1])
1162 else:
1162 else:
1163 # log input history up to this point, optionally interleaving
1163 # log input history up to this point, optionally interleaving
1164 # output if requested
1164 # output if requested
1165
1165
1166 if timestamp:
1166 if timestamp:
1167 # disable timestamping for the previous history, since we've
1167 # disable timestamping for the previous history, since we've
1168 # lost those already (no time machine here).
1168 # lost those already (no time machine here).
1169 logger.timestamp = False
1169 logger.timestamp = False
1170
1170
1171 if log_raw_input:
1171 if log_raw_input:
1172 input_hist = self.shell.input_hist_raw
1172 input_hist = self.shell.input_hist_raw
1173 else:
1173 else:
1174 input_hist = self.shell.input_hist
1174 input_hist = self.shell.input_hist
1175
1175
1176 if log_output:
1176 if log_output:
1177 log_write = logger.log_write
1177 log_write = logger.log_write
1178 output_hist = self.shell.output_hist
1178 output_hist = self.shell.output_hist
1179 for n in range(1,len(input_hist)-1):
1179 for n in range(1,len(input_hist)-1):
1180 log_write(input_hist[n].rstrip())
1180 log_write(input_hist[n].rstrip())
1181 if n in output_hist:
1181 if n in output_hist:
1182 log_write(repr(output_hist[n]),'output')
1182 log_write(repr(output_hist[n]),'output')
1183 else:
1183 else:
1184 logger.log_write(input_hist[1:])
1184 logger.log_write(input_hist[1:])
1185 if timestamp:
1185 if timestamp:
1186 # re-enable timestamping
1186 # re-enable timestamping
1187 logger.timestamp = True
1187 logger.timestamp = True
1188
1188
1189 print ('Activating auto-logging. '
1189 print ('Activating auto-logging. '
1190 'Current session state plus future input saved.')
1190 'Current session state plus future input saved.')
1191 logger.logstate()
1191 logger.logstate()
1192
1192
1193 def magic_logstop(self,parameter_s=''):
1193 def magic_logstop(self,parameter_s=''):
1194 """Fully stop logging and close log file.
1194 """Fully stop logging and close log file.
1195
1195
1196 In order to start logging again, a new %logstart call needs to be made,
1196 In order to start logging again, a new %logstart call needs to be made,
1197 possibly (though not necessarily) with a new filename, mode and other
1197 possibly (though not necessarily) with a new filename, mode and other
1198 options."""
1198 options."""
1199 self.logger.logstop()
1199 self.logger.logstop()
1200
1200
1201 def magic_logoff(self,parameter_s=''):
1201 def magic_logoff(self,parameter_s=''):
1202 """Temporarily stop logging.
1202 """Temporarily stop logging.
1203
1203
1204 You must have previously started logging."""
1204 You must have previously started logging."""
1205 self.shell.logger.switch_log(0)
1205 self.shell.logger.switch_log(0)
1206
1206
1207 def magic_logon(self,parameter_s=''):
1207 def magic_logon(self,parameter_s=''):
1208 """Restart logging.
1208 """Restart logging.
1209
1209
1210 This function is for restarting logging which you've temporarily
1210 This function is for restarting logging which you've temporarily
1211 stopped with %logoff. For starting logging for the first time, you
1211 stopped with %logoff. For starting logging for the first time, you
1212 must use the %logstart function, which allows you to specify an
1212 must use the %logstart function, which allows you to specify an
1213 optional log filename."""
1213 optional log filename."""
1214
1214
1215 self.shell.logger.switch_log(1)
1215 self.shell.logger.switch_log(1)
1216
1216
1217 def magic_logstate(self,parameter_s=''):
1217 def magic_logstate(self,parameter_s=''):
1218 """Print the status of the logging system."""
1218 """Print the status of the logging system."""
1219
1219
1220 self.shell.logger.logstate()
1220 self.shell.logger.logstate()
1221
1221
1222 def magic_pdb(self, parameter_s=''):
1222 def magic_pdb(self, parameter_s=''):
1223 """Control the automatic calling of the pdb interactive debugger.
1223 """Control the automatic calling of the pdb interactive debugger.
1224
1224
1225 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1225 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1226 argument it works as a toggle.
1226 argument it works as a toggle.
1227
1227
1228 When an exception is triggered, IPython can optionally call the
1228 When an exception is triggered, IPython can optionally call the
1229 interactive pdb debugger after the traceback printout. %pdb toggles
1229 interactive pdb debugger after the traceback printout. %pdb toggles
1230 this feature on and off.
1230 this feature on and off.
1231
1231
1232 The initial state of this feature is set in your ipythonrc
1232 The initial state of this feature is set in your ipythonrc
1233 configuration file (the variable is called 'pdb').
1233 configuration file (the variable is called 'pdb').
1234
1234
1235 If you want to just activate the debugger AFTER an exception has fired,
1235 If you want to just activate the debugger AFTER an exception has fired,
1236 without having to type '%pdb on' and rerunning your code, you can use
1236 without having to type '%pdb on' and rerunning your code, you can use
1237 the %debug magic."""
1237 the %debug magic."""
1238
1238
1239 par = parameter_s.strip().lower()
1239 par = parameter_s.strip().lower()
1240
1240
1241 if par:
1241 if par:
1242 try:
1242 try:
1243 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1243 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1244 except KeyError:
1244 except KeyError:
1245 print ('Incorrect argument. Use on/1, off/0, '
1245 print ('Incorrect argument. Use on/1, off/0, '
1246 'or nothing for a toggle.')
1246 'or nothing for a toggle.')
1247 return
1247 return
1248 else:
1248 else:
1249 # toggle
1249 # toggle
1250 new_pdb = not self.shell.call_pdb
1250 new_pdb = not self.shell.call_pdb
1251
1251
1252 # set on the shell
1252 # set on the shell
1253 self.shell.call_pdb = new_pdb
1253 self.shell.call_pdb = new_pdb
1254 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1254 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1255
1255
1256 def magic_debug(self, parameter_s=''):
1256 def magic_debug(self, parameter_s=''):
1257 """Activate the interactive debugger in post-mortem mode.
1257 """Activate the interactive debugger in post-mortem mode.
1258
1258
1259 If an exception has just occurred, this lets you inspect its stack
1259 If an exception has just occurred, this lets you inspect its stack
1260 frames interactively. Note that this will always work only on the last
1260 frames interactively. Note that this will always work only on the last
1261 traceback that occurred, so you must call this quickly after an
1261 traceback that occurred, so you must call this quickly after an
1262 exception that you wish to inspect has fired, because if another one
1262 exception that you wish to inspect has fired, because if another one
1263 occurs, it clobbers the previous one.
1263 occurs, it clobbers the previous one.
1264
1264
1265 If you want IPython to automatically do this on every exception, see
1265 If you want IPython to automatically do this on every exception, see
1266 the %pdb magic for more details.
1266 the %pdb magic for more details.
1267 """
1267 """
1268
1268
1269 self.shell.debugger(force=True)
1269 self.shell.debugger(force=True)
1270
1270
1271 @testdec.skip_doctest
1271 @testdec.skip_doctest
1272 def magic_prun(self, parameter_s ='',user_mode=1,
1272 def magic_prun(self, parameter_s ='',user_mode=1,
1273 opts=None,arg_lst=None,prog_ns=None):
1273 opts=None,arg_lst=None,prog_ns=None):
1274
1274
1275 """Run a statement through the python code profiler.
1275 """Run a statement through the python code profiler.
1276
1276
1277 Usage:
1277 Usage:
1278 %prun [options] statement
1278 %prun [options] statement
1279
1279
1280 The given statement (which doesn't require quote marks) is run via the
1280 The given statement (which doesn't require quote marks) is run via the
1281 python profiler in a manner similar to the profile.run() function.
1281 python profiler in a manner similar to the profile.run() function.
1282 Namespaces are internally managed to work correctly; profile.run
1282 Namespaces are internally managed to work correctly; profile.run
1283 cannot be used in IPython because it makes certain assumptions about
1283 cannot be used in IPython because it makes certain assumptions about
1284 namespaces which do not hold under IPython.
1284 namespaces which do not hold under IPython.
1285
1285
1286 Options:
1286 Options:
1287
1287
1288 -l <limit>: you can place restrictions on what or how much of the
1288 -l <limit>: you can place restrictions on what or how much of the
1289 profile gets printed. The limit value can be:
1289 profile gets printed. The limit value can be:
1290
1290
1291 * A string: only information for function names containing this string
1291 * A string: only information for function names containing this string
1292 is printed.
1292 is printed.
1293
1293
1294 * An integer: only these many lines are printed.
1294 * An integer: only these many lines are printed.
1295
1295
1296 * A float (between 0 and 1): this fraction of the report is printed
1296 * A float (between 0 and 1): this fraction of the report is printed
1297 (for example, use a limit of 0.4 to see the topmost 40% only).
1297 (for example, use a limit of 0.4 to see the topmost 40% only).
1298
1298
1299 You can combine several limits with repeated use of the option. For
1299 You can combine several limits with repeated use of the option. For
1300 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1300 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1301 information about class constructors.
1301 information about class constructors.
1302
1302
1303 -r: return the pstats.Stats object generated by the profiling. This
1303 -r: return the pstats.Stats object generated by the profiling. This
1304 object has all the information about the profile in it, and you can
1304 object has all the information about the profile in it, and you can
1305 later use it for further analysis or in other functions.
1305 later use it for further analysis or in other functions.
1306
1306
1307 -s <key>: sort profile by given key. You can provide more than one key
1307 -s <key>: sort profile by given key. You can provide more than one key
1308 by using the option several times: '-s key1 -s key2 -s key3...'. The
1308 by using the option several times: '-s key1 -s key2 -s key3...'. The
1309 default sorting key is 'time'.
1309 default sorting key is 'time'.
1310
1310
1311 The following is copied verbatim from the profile documentation
1311 The following is copied verbatim from the profile documentation
1312 referenced below:
1312 referenced below:
1313
1313
1314 When more than one key is provided, additional keys are used as
1314 When more than one key is provided, additional keys are used as
1315 secondary criteria when the there is equality in all keys selected
1315 secondary criteria when the there is equality in all keys selected
1316 before them.
1316 before them.
1317
1317
1318 Abbreviations can be used for any key names, as long as the
1318 Abbreviations can be used for any key names, as long as the
1319 abbreviation is unambiguous. The following are the keys currently
1319 abbreviation is unambiguous. The following are the keys currently
1320 defined:
1320 defined:
1321
1321
1322 Valid Arg Meaning
1322 Valid Arg Meaning
1323 "calls" call count
1323 "calls" call count
1324 "cumulative" cumulative time
1324 "cumulative" cumulative time
1325 "file" file name
1325 "file" file name
1326 "module" file name
1326 "module" file name
1327 "pcalls" primitive call count
1327 "pcalls" primitive call count
1328 "line" line number
1328 "line" line number
1329 "name" function name
1329 "name" function name
1330 "nfl" name/file/line
1330 "nfl" name/file/line
1331 "stdname" standard name
1331 "stdname" standard name
1332 "time" internal time
1332 "time" internal time
1333
1333
1334 Note that all sorts on statistics are in descending order (placing
1334 Note that all sorts on statistics are in descending order (placing
1335 most time consuming items first), where as name, file, and line number
1335 most time consuming items first), where as name, file, and line number
1336 searches are in ascending order (i.e., alphabetical). The subtle
1336 searches are in ascending order (i.e., alphabetical). The subtle
1337 distinction between "nfl" and "stdname" is that the standard name is a
1337 distinction between "nfl" and "stdname" is that the standard name is a
1338 sort of the name as printed, which means that the embedded line
1338 sort of the name as printed, which means that the embedded line
1339 numbers get compared in an odd way. For example, lines 3, 20, and 40
1339 numbers get compared in an odd way. For example, lines 3, 20, and 40
1340 would (if the file names were the same) appear in the string order
1340 would (if the file names were the same) appear in the string order
1341 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1341 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1342 line numbers. In fact, sort_stats("nfl") is the same as
1342 line numbers. In fact, sort_stats("nfl") is the same as
1343 sort_stats("name", "file", "line").
1343 sort_stats("name", "file", "line").
1344
1344
1345 -T <filename>: save profile results as shown on screen to a text
1345 -T <filename>: save profile results as shown on screen to a text
1346 file. The profile is still shown on screen.
1346 file. The profile is still shown on screen.
1347
1347
1348 -D <filename>: save (via dump_stats) profile statistics to given
1348 -D <filename>: save (via dump_stats) profile statistics to given
1349 filename. This data is in a format understod by the pstats module, and
1349 filename. This data is in a format understod by the pstats module, and
1350 is generated by a call to the dump_stats() method of profile
1350 is generated by a call to the dump_stats() method of profile
1351 objects. The profile is still shown on screen.
1351 objects. The profile is still shown on screen.
1352
1352
1353 If you want to run complete programs under the profiler's control, use
1353 If you want to run complete programs under the profiler's control, use
1354 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1354 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1355 contains profiler specific options as described here.
1355 contains profiler specific options as described here.
1356
1356
1357 You can read the complete documentation for the profile module with::
1357 You can read the complete documentation for the profile module with::
1358
1358
1359 In [1]: import profile; profile.help()
1359 In [1]: import profile; profile.help()
1360 """
1360 """
1361
1361
1362 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1362 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1363 # protect user quote marks
1363 # protect user quote marks
1364 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1364 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1365
1365
1366 if user_mode: # regular user call
1366 if user_mode: # regular user call
1367 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1367 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1368 list_all=1)
1368 list_all=1)
1369 namespace = self.shell.user_ns
1369 namespace = self.shell.user_ns
1370 else: # called to run a program by %run -p
1370 else: # called to run a program by %run -p
1371 try:
1371 try:
1372 filename = get_py_filename(arg_lst[0])
1372 filename = get_py_filename(arg_lst[0])
1373 except IOError,msg:
1373 except IOError,msg:
1374 error(msg)
1374 error(msg)
1375 return
1375 return
1376
1376
1377 arg_str = 'execfile(filename,prog_ns)'
1377 arg_str = 'execfile(filename,prog_ns)'
1378 namespace = locals()
1378 namespace = locals()
1379
1379
1380 opts.merge(opts_def)
1380 opts.merge(opts_def)
1381
1381
1382 prof = profile.Profile()
1382 prof = profile.Profile()
1383 try:
1383 try:
1384 prof = prof.runctx(arg_str,namespace,namespace)
1384 prof = prof.runctx(arg_str,namespace,namespace)
1385 sys_exit = ''
1385 sys_exit = ''
1386 except SystemExit:
1386 except SystemExit:
1387 sys_exit = """*** SystemExit exception caught in code being profiled."""
1387 sys_exit = """*** SystemExit exception caught in code being profiled."""
1388
1388
1389 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1389 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1390
1390
1391 lims = opts.l
1391 lims = opts.l
1392 if lims:
1392 if lims:
1393 lims = [] # rebuild lims with ints/floats/strings
1393 lims = [] # rebuild lims with ints/floats/strings
1394 for lim in opts.l:
1394 for lim in opts.l:
1395 try:
1395 try:
1396 lims.append(int(lim))
1396 lims.append(int(lim))
1397 except ValueError:
1397 except ValueError:
1398 try:
1398 try:
1399 lims.append(float(lim))
1399 lims.append(float(lim))
1400 except ValueError:
1400 except ValueError:
1401 lims.append(lim)
1401 lims.append(lim)
1402
1402
1403 # Trap output.
1403 # Trap output.
1404 stdout_trap = StringIO()
1404 stdout_trap = StringIO()
1405
1405
1406 if hasattr(stats,'stream'):
1406 if hasattr(stats,'stream'):
1407 # In newer versions of python, the stats object has a 'stream'
1407 # In newer versions of python, the stats object has a 'stream'
1408 # attribute to write into.
1408 # attribute to write into.
1409 stats.stream = stdout_trap
1409 stats.stream = stdout_trap
1410 stats.print_stats(*lims)
1410 stats.print_stats(*lims)
1411 else:
1411 else:
1412 # For older versions, we manually redirect stdout during printing
1412 # For older versions, we manually redirect stdout during printing
1413 sys_stdout = sys.stdout
1413 sys_stdout = sys.stdout
1414 try:
1414 try:
1415 sys.stdout = stdout_trap
1415 sys.stdout = stdout_trap
1416 stats.print_stats(*lims)
1416 stats.print_stats(*lims)
1417 finally:
1417 finally:
1418 sys.stdout = sys_stdout
1418 sys.stdout = sys_stdout
1419
1419
1420 output = stdout_trap.getvalue()
1420 output = stdout_trap.getvalue()
1421 output = output.rstrip()
1421 output = output.rstrip()
1422
1422
1423 page(output,screen_lines=self.shell.rc.screen_length)
1423 page(output,screen_lines=self.shell.rc.screen_length)
1424 print sys_exit,
1424 print sys_exit,
1425
1425
1426 dump_file = opts.D[0]
1426 dump_file = opts.D[0]
1427 text_file = opts.T[0]
1427 text_file = opts.T[0]
1428 if dump_file:
1428 if dump_file:
1429 prof.dump_stats(dump_file)
1429 prof.dump_stats(dump_file)
1430 print '\n*** Profile stats marshalled to file',\
1430 print '\n*** Profile stats marshalled to file',\
1431 `dump_file`+'.',sys_exit
1431 `dump_file`+'.',sys_exit
1432 if text_file:
1432 if text_file:
1433 pfile = file(text_file,'w')
1433 pfile = file(text_file,'w')
1434 pfile.write(output)
1434 pfile.write(output)
1435 pfile.close()
1435 pfile.close()
1436 print '\n*** Profile printout saved to text file',\
1436 print '\n*** Profile printout saved to text file',\
1437 `text_file`+'.',sys_exit
1437 `text_file`+'.',sys_exit
1438
1438
1439 if opts.has_key('r'):
1439 if opts.has_key('r'):
1440 return stats
1440 return stats
1441 else:
1441 else:
1442 return None
1442 return None
1443
1443
1444 @testdec.skip_doctest
1444 @testdec.skip_doctest
1445 def magic_run(self, parameter_s ='',runner=None,
1445 def magic_run(self, parameter_s ='',runner=None,
1446 file_finder=get_py_filename):
1446 file_finder=get_py_filename):
1447 """Run the named file inside IPython as a program.
1447 """Run the named file inside IPython as a program.
1448
1448
1449 Usage:\\
1449 Usage:\\
1450 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1450 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1451
1451
1452 Parameters after the filename are passed as command-line arguments to
1452 Parameters after the filename are passed as command-line arguments to
1453 the program (put in sys.argv). Then, control returns to IPython's
1453 the program (put in sys.argv). Then, control returns to IPython's
1454 prompt.
1454 prompt.
1455
1455
1456 This is similar to running at a system prompt:\\
1456 This is similar to running at a system prompt:\\
1457 $ python file args\\
1457 $ python file args\\
1458 but with the advantage of giving you IPython's tracebacks, and of
1458 but with the advantage of giving you IPython's tracebacks, and of
1459 loading all variables into your interactive namespace for further use
1459 loading all variables into your interactive namespace for further use
1460 (unless -p is used, see below).
1460 (unless -p is used, see below).
1461
1461
1462 The file is executed in a namespace initially consisting only of
1462 The file is executed in a namespace initially consisting only of
1463 __name__=='__main__' and sys.argv constructed as indicated. It thus
1463 __name__=='__main__' and sys.argv constructed as indicated. It thus
1464 sees its environment as if it were being run as a stand-alone program
1464 sees its environment as if it were being run as a stand-alone program
1465 (except for sharing global objects such as previously imported
1465 (except for sharing global objects such as previously imported
1466 modules). But after execution, the IPython interactive namespace gets
1466 modules). But after execution, the IPython interactive namespace gets
1467 updated with all variables defined in the program (except for __name__
1467 updated with all variables defined in the program (except for __name__
1468 and sys.argv). This allows for very convenient loading of code for
1468 and sys.argv). This allows for very convenient loading of code for
1469 interactive work, while giving each program a 'clean sheet' to run in.
1469 interactive work, while giving each program a 'clean sheet' to run in.
1470
1470
1471 Options:
1471 Options:
1472
1472
1473 -n: __name__ is NOT set to '__main__', but to the running file's name
1473 -n: __name__ is NOT set to '__main__', but to the running file's name
1474 without extension (as python does under import). This allows running
1474 without extension (as python does under import). This allows running
1475 scripts and reloading the definitions in them without calling code
1475 scripts and reloading the definitions in them without calling code
1476 protected by an ' if __name__ == "__main__" ' clause.
1476 protected by an ' if __name__ == "__main__" ' clause.
1477
1477
1478 -i: run the file in IPython's namespace instead of an empty one. This
1478 -i: run the file in IPython's namespace instead of an empty one. This
1479 is useful if you are experimenting with code written in a text editor
1479 is useful if you are experimenting with code written in a text editor
1480 which depends on variables defined interactively.
1480 which depends on variables defined interactively.
1481
1481
1482 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1482 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1483 being run. This is particularly useful if IPython is being used to
1483 being run. This is particularly useful if IPython is being used to
1484 run unittests, which always exit with a sys.exit() call. In such
1484 run unittests, which always exit with a sys.exit() call. In such
1485 cases you are interested in the output of the test results, not in
1485 cases you are interested in the output of the test results, not in
1486 seeing a traceback of the unittest module.
1486 seeing a traceback of the unittest module.
1487
1487
1488 -t: print timing information at the end of the run. IPython will give
1488 -t: print timing information at the end of the run. IPython will give
1489 you an estimated CPU time consumption for your script, which under
1489 you an estimated CPU time consumption for your script, which under
1490 Unix uses the resource module to avoid the wraparound problems of
1490 Unix uses the resource module to avoid the wraparound problems of
1491 time.clock(). Under Unix, an estimate of time spent on system tasks
1491 time.clock(). Under Unix, an estimate of time spent on system tasks
1492 is also given (for Windows platforms this is reported as 0.0).
1492 is also given (for Windows platforms this is reported as 0.0).
1493
1493
1494 If -t is given, an additional -N<N> option can be given, where <N>
1494 If -t is given, an additional -N<N> option can be given, where <N>
1495 must be an integer indicating how many times you want the script to
1495 must be an integer indicating how many times you want the script to
1496 run. The final timing report will include total and per run results.
1496 run. The final timing report will include total and per run results.
1497
1497
1498 For example (testing the script uniq_stable.py):
1498 For example (testing the script uniq_stable.py):
1499
1499
1500 In [1]: run -t uniq_stable
1500 In [1]: run -t uniq_stable
1501
1501
1502 IPython CPU timings (estimated):\\
1502 IPython CPU timings (estimated):\\
1503 User : 0.19597 s.\\
1503 User : 0.19597 s.\\
1504 System: 0.0 s.\\
1504 System: 0.0 s.\\
1505
1505
1506 In [2]: run -t -N5 uniq_stable
1506 In [2]: run -t -N5 uniq_stable
1507
1507
1508 IPython CPU timings (estimated):\\
1508 IPython CPU timings (estimated):\\
1509 Total runs performed: 5\\
1509 Total runs performed: 5\\
1510 Times : Total Per run\\
1510 Times : Total Per run\\
1511 User : 0.910862 s, 0.1821724 s.\\
1511 User : 0.910862 s, 0.1821724 s.\\
1512 System: 0.0 s, 0.0 s.
1512 System: 0.0 s, 0.0 s.
1513
1513
1514 -d: run your program under the control of pdb, the Python debugger.
1514 -d: run your program under the control of pdb, the Python debugger.
1515 This allows you to execute your program step by step, watch variables,
1515 This allows you to execute your program step by step, watch variables,
1516 etc. Internally, what IPython does is similar to calling:
1516 etc. Internally, what IPython does is similar to calling:
1517
1517
1518 pdb.run('execfile("YOURFILENAME")')
1518 pdb.run('execfile("YOURFILENAME")')
1519
1519
1520 with a breakpoint set on line 1 of your file. You can change the line
1520 with a breakpoint set on line 1 of your file. You can change the line
1521 number for this automatic breakpoint to be <N> by using the -bN option
1521 number for this automatic breakpoint to be <N> by using the -bN option
1522 (where N must be an integer). For example:
1522 (where N must be an integer). For example:
1523
1523
1524 %run -d -b40 myscript
1524 %run -d -b40 myscript
1525
1525
1526 will set the first breakpoint at line 40 in myscript.py. Note that
1526 will set the first breakpoint at line 40 in myscript.py. Note that
1527 the first breakpoint must be set on a line which actually does
1527 the first breakpoint must be set on a line which actually does
1528 something (not a comment or docstring) for it to stop execution.
1528 something (not a comment or docstring) for it to stop execution.
1529
1529
1530 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1530 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1531 first enter 'c' (without qoutes) to start execution up to the first
1531 first enter 'c' (without qoutes) to start execution up to the first
1532 breakpoint.
1532 breakpoint.
1533
1533
1534 Entering 'help' gives information about the use of the debugger. You
1534 Entering 'help' gives information about the use of the debugger. You
1535 can easily see pdb's full documentation with "import pdb;pdb.help()"
1535 can easily see pdb's full documentation with "import pdb;pdb.help()"
1536 at a prompt.
1536 at a prompt.
1537
1537
1538 -p: run program under the control of the Python profiler module (which
1538 -p: run program under the control of the Python profiler module (which
1539 prints a detailed report of execution times, function calls, etc).
1539 prints a detailed report of execution times, function calls, etc).
1540
1540
1541 You can pass other options after -p which affect the behavior of the
1541 You can pass other options after -p which affect the behavior of the
1542 profiler itself. See the docs for %prun for details.
1542 profiler itself. See the docs for %prun for details.
1543
1543
1544 In this mode, the program's variables do NOT propagate back to the
1544 In this mode, the program's variables do NOT propagate back to the
1545 IPython interactive namespace (because they remain in the namespace
1545 IPython interactive namespace (because they remain in the namespace
1546 where the profiler executes them).
1546 where the profiler executes them).
1547
1547
1548 Internally this triggers a call to %prun, see its documentation for
1548 Internally this triggers a call to %prun, see its documentation for
1549 details on the options available specifically for profiling.
1549 details on the options available specifically for profiling.
1550
1550
1551 There is one special usage for which the text above doesn't apply:
1551 There is one special usage for which the text above doesn't apply:
1552 if the filename ends with .ipy, the file is run as ipython script,
1552 if the filename ends with .ipy, the file is run as ipython script,
1553 just as if the commands were written on IPython prompt.
1553 just as if the commands were written on IPython prompt.
1554 """
1554 """
1555
1555
1556 # get arguments and set sys.argv for program to be run.
1556 # get arguments and set sys.argv for program to be run.
1557 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1557 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1558 mode='list',list_all=1)
1558 mode='list',list_all=1)
1559
1559
1560 try:
1560 try:
1561 filename = file_finder(arg_lst[0])
1561 filename = file_finder(arg_lst[0])
1562 except IndexError:
1562 except IndexError:
1563 warn('you must provide at least a filename.')
1563 warn('you must provide at least a filename.')
1564 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1564 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1565 return
1565 return
1566 except IOError,msg:
1566 except IOError,msg:
1567 error(msg)
1567 error(msg)
1568 return
1568 return
1569
1569
1570 if filename.lower().endswith('.ipy'):
1570 if filename.lower().endswith('.ipy'):
1571 self.api.runlines(open(filename).read())
1571 self.api.runlines(open(filename).read())
1572 return
1572 return
1573
1573
1574 # Control the response to exit() calls made by the script being run
1574 # Control the response to exit() calls made by the script being run
1575 exit_ignore = opts.has_key('e')
1575 exit_ignore = opts.has_key('e')
1576
1576
1577 # Make sure that the running script gets a proper sys.argv as if it
1577 # Make sure that the running script gets a proper sys.argv as if it
1578 # were run from a system shell.
1578 # were run from a system shell.
1579 save_argv = sys.argv # save it for later restoring
1579 save_argv = sys.argv # save it for later restoring
1580 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1580 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1581
1581
1582 if opts.has_key('i'):
1582 if opts.has_key('i'):
1583 # Run in user's interactive namespace
1583 # Run in user's interactive namespace
1584 prog_ns = self.shell.user_ns
1584 prog_ns = self.shell.user_ns
1585 __name__save = self.shell.user_ns['__name__']
1585 __name__save = self.shell.user_ns['__name__']
1586 prog_ns['__name__'] = '__main__'
1586 prog_ns['__name__'] = '__main__'
1587 main_mod = FakeModule(prog_ns)
1587
1588 ##main_mod = FakeModule(prog_ns)
1589 main_mod = self.shell.new_main_mod(prog_ns)
1590
1588 else:
1591 else:
1589 # Run in a fresh, empty namespace
1592 # Run in a fresh, empty namespace
1590 if opts.has_key('n'):
1593 if opts.has_key('n'):
1591 name = os.path.splitext(os.path.basename(filename))[0]
1594 name = os.path.splitext(os.path.basename(filename))[0]
1592 else:
1595 else:
1593 name = '__main__'
1596 name = '__main__'
1594 main_mod = FakeModule()
1597
1598 main_mod = self.shell.new_main_mod()
1599
1595 prog_ns = main_mod.__dict__
1600 prog_ns = main_mod.__dict__
1596 prog_ns['__name__'] = name
1601 prog_ns['__name__'] = name
1597
1602
1598 # The shell MUST hold a reference to main_mod so after %run exits,
1599 # the python deletion mechanism doesn't zero it out (leaving
1600 # dangling references). However, we should drop old versions of
1601 # main_mod. There is now a proper API to manage this caching in
1602 # the main shell object, we use that.
1603 self.shell.cache_main_mod(main_mod)
1604
1603
1605 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1604 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1606 # set the __file__ global in the script's namespace
1605 # set the __file__ global in the script's namespace
1607 prog_ns['__file__'] = filename
1606 prog_ns['__file__'] = filename
1608
1607
1609 # pickle fix. See iplib for an explanation. But we need to make sure
1608 # pickle fix. See iplib for an explanation. But we need to make sure
1610 # that, if we overwrite __main__, we replace it at the end
1609 # that, if we overwrite __main__, we replace it at the end
1611 main_mod_name = prog_ns['__name__']
1610 main_mod_name = prog_ns['__name__']
1612
1611
1613 if main_mod_name == '__main__':
1612 if main_mod_name == '__main__':
1614 restore_main = sys.modules['__main__']
1613 restore_main = sys.modules['__main__']
1615 else:
1614 else:
1616 restore_main = False
1615 restore_main = False
1617
1616
1618 # This needs to be undone at the end to prevent holding references to
1617 # This needs to be undone at the end to prevent holding references to
1619 # every single object ever created.
1618 # every single object ever created.
1620 sys.modules[main_mod_name] = main_mod
1619 sys.modules[main_mod_name] = main_mod
1621
1620
1622 stats = None
1621 stats = None
1623 try:
1622 try:
1624 self.shell.savehist()
1623 self.shell.savehist()
1625
1624
1626 if opts.has_key('p'):
1625 if opts.has_key('p'):
1627 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1626 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1628 else:
1627 else:
1629 if opts.has_key('d'):
1628 if opts.has_key('d'):
1630 deb = Debugger.Pdb(self.shell.rc.colors)
1629 deb = Debugger.Pdb(self.shell.rc.colors)
1631 # reset Breakpoint state, which is moronically kept
1630 # reset Breakpoint state, which is moronically kept
1632 # in a class
1631 # in a class
1633 bdb.Breakpoint.next = 1
1632 bdb.Breakpoint.next = 1
1634 bdb.Breakpoint.bplist = {}
1633 bdb.Breakpoint.bplist = {}
1635 bdb.Breakpoint.bpbynumber = [None]
1634 bdb.Breakpoint.bpbynumber = [None]
1636 # Set an initial breakpoint to stop execution
1635 # Set an initial breakpoint to stop execution
1637 maxtries = 10
1636 maxtries = 10
1638 bp = int(opts.get('b',[1])[0])
1637 bp = int(opts.get('b',[1])[0])
1639 checkline = deb.checkline(filename,bp)
1638 checkline = deb.checkline(filename,bp)
1640 if not checkline:
1639 if not checkline:
1641 for bp in range(bp+1,bp+maxtries+1):
1640 for bp in range(bp+1,bp+maxtries+1):
1642 if deb.checkline(filename,bp):
1641 if deb.checkline(filename,bp):
1643 break
1642 break
1644 else:
1643 else:
1645 msg = ("\nI failed to find a valid line to set "
1644 msg = ("\nI failed to find a valid line to set "
1646 "a breakpoint\n"
1645 "a breakpoint\n"
1647 "after trying up to line: %s.\n"
1646 "after trying up to line: %s.\n"
1648 "Please set a valid breakpoint manually "
1647 "Please set a valid breakpoint manually "
1649 "with the -b option." % bp)
1648 "with the -b option." % bp)
1650 error(msg)
1649 error(msg)
1651 return
1650 return
1652 # if we find a good linenumber, set the breakpoint
1651 # if we find a good linenumber, set the breakpoint
1653 deb.do_break('%s:%s' % (filename,bp))
1652 deb.do_break('%s:%s' % (filename,bp))
1654 # Start file run
1653 # Start file run
1655 print "NOTE: Enter 'c' at the",
1654 print "NOTE: Enter 'c' at the",
1656 print "%s prompt to start your script." % deb.prompt
1655 print "%s prompt to start your script." % deb.prompt
1657 try:
1656 try:
1658 deb.run('execfile("%s")' % filename,prog_ns)
1657 deb.run('execfile("%s")' % filename,prog_ns)
1659
1658
1660 except:
1659 except:
1661 etype, value, tb = sys.exc_info()
1660 etype, value, tb = sys.exc_info()
1662 # Skip three frames in the traceback: the %run one,
1661 # Skip three frames in the traceback: the %run one,
1663 # one inside bdb.py, and the command-line typed by the
1662 # one inside bdb.py, and the command-line typed by the
1664 # user (run by exec in pdb itself).
1663 # user (run by exec in pdb itself).
1665 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1664 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1666 else:
1665 else:
1667 if runner is None:
1666 if runner is None:
1668 runner = self.shell.safe_execfile
1667 runner = self.shell.safe_execfile
1669 if opts.has_key('t'):
1668 if opts.has_key('t'):
1670 # timed execution
1669 # timed execution
1671 try:
1670 try:
1672 nruns = int(opts['N'][0])
1671 nruns = int(opts['N'][0])
1673 if nruns < 1:
1672 if nruns < 1:
1674 error('Number of runs must be >=1')
1673 error('Number of runs must be >=1')
1675 return
1674 return
1676 except (KeyError):
1675 except (KeyError):
1677 nruns = 1
1676 nruns = 1
1678 if nruns == 1:
1677 if nruns == 1:
1679 t0 = clock2()
1678 t0 = clock2()
1680 runner(filename,prog_ns,prog_ns,
1679 runner(filename,prog_ns,prog_ns,
1681 exit_ignore=exit_ignore)
1680 exit_ignore=exit_ignore)
1682 t1 = clock2()
1681 t1 = clock2()
1683 t_usr = t1[0]-t0[0]
1682 t_usr = t1[0]-t0[0]
1684 t_sys = t1[1]-t1[1]
1683 t_sys = t1[1]-t1[1]
1685 print "\nIPython CPU timings (estimated):"
1684 print "\nIPython CPU timings (estimated):"
1686 print " User : %10s s." % t_usr
1685 print " User : %10s s." % t_usr
1687 print " System: %10s s." % t_sys
1686 print " System: %10s s." % t_sys
1688 else:
1687 else:
1689 runs = range(nruns)
1688 runs = range(nruns)
1690 t0 = clock2()
1689 t0 = clock2()
1691 for nr in runs:
1690 for nr in runs:
1692 runner(filename,prog_ns,prog_ns,
1691 runner(filename,prog_ns,prog_ns,
1693 exit_ignore=exit_ignore)
1692 exit_ignore=exit_ignore)
1694 t1 = clock2()
1693 t1 = clock2()
1695 t_usr = t1[0]-t0[0]
1694 t_usr = t1[0]-t0[0]
1696 t_sys = t1[1]-t1[1]
1695 t_sys = t1[1]-t1[1]
1697 print "\nIPython CPU timings (estimated):"
1696 print "\nIPython CPU timings (estimated):"
1698 print "Total runs performed:",nruns
1697 print "Total runs performed:",nruns
1699 print " Times : %10s %10s" % ('Total','Per run')
1698 print " Times : %10s %10s" % ('Total','Per run')
1700 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1699 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1701 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1700 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1702
1701
1703 else:
1702 else:
1704 # regular execution
1703 # regular execution
1705 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1704 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1705
1706 if opts.has_key('i'):
1706 if opts.has_key('i'):
1707 self.shell.user_ns['__name__'] = __name__save
1707 self.shell.user_ns['__name__'] = __name__save
1708 else:
1708 else:
1709 # The shell MUST hold a reference to prog_ns so after %run
1710 # exits, the python deletion mechanism doesn't zero it out
1711 # (leaving dangling references).
1712 self.shell.cache_main_mod(prog_ns,filename)
1709 # update IPython interactive namespace
1713 # update IPython interactive namespace
1710 del prog_ns['__name__']
1714 del prog_ns['__name__']
1711 self.shell.user_ns.update(prog_ns)
1715 self.shell.user_ns.update(prog_ns)
1712 finally:
1716 finally:
1713 # Ensure key global structures are restored
1717 # Ensure key global structures are restored
1714 sys.argv = save_argv
1718 sys.argv = save_argv
1715 if restore_main:
1719 if restore_main:
1716 sys.modules['__main__'] = restore_main
1720 sys.modules['__main__'] = restore_main
1717 else:
1721 else:
1718 # Remove from sys.modules the reference to main_mod we'd
1722 # Remove from sys.modules the reference to main_mod we'd
1719 # added. Otherwise it will trap references to objects
1723 # added. Otherwise it will trap references to objects
1720 # contained therein.
1724 # contained therein.
1721 del sys.modules[main_mod_name]
1725 del sys.modules[main_mod_name]
1726
1722 self.shell.reloadhist()
1727 self.shell.reloadhist()
1723
1728
1724 return stats
1729 return stats
1725
1730
1726 def magic_runlog(self, parameter_s =''):
1731 def magic_runlog(self, parameter_s =''):
1727 """Run files as logs.
1732 """Run files as logs.
1728
1733
1729 Usage:\\
1734 Usage:\\
1730 %runlog file1 file2 ...
1735 %runlog file1 file2 ...
1731
1736
1732 Run the named files (treating them as log files) in sequence inside
1737 Run the named files (treating them as log files) in sequence inside
1733 the interpreter, and return to the prompt. This is much slower than
1738 the interpreter, and return to the prompt. This is much slower than
1734 %run because each line is executed in a try/except block, but it
1739 %run because each line is executed in a try/except block, but it
1735 allows running files with syntax errors in them.
1740 allows running files with syntax errors in them.
1736
1741
1737 Normally IPython will guess when a file is one of its own logfiles, so
1742 Normally IPython will guess when a file is one of its own logfiles, so
1738 you can typically use %run even for logs. This shorthand allows you to
1743 you can typically use %run even for logs. This shorthand allows you to
1739 force any file to be treated as a log file."""
1744 force any file to be treated as a log file."""
1740
1745
1741 for f in parameter_s.split():
1746 for f in parameter_s.split():
1742 self.shell.safe_execfile(f,self.shell.user_ns,
1747 self.shell.safe_execfile(f,self.shell.user_ns,
1743 self.shell.user_ns,islog=1)
1748 self.shell.user_ns,islog=1)
1744
1749
1745 @testdec.skip_doctest
1750 @testdec.skip_doctest
1746 def magic_timeit(self, parameter_s =''):
1751 def magic_timeit(self, parameter_s =''):
1747 """Time execution of a Python statement or expression
1752 """Time execution of a Python statement or expression
1748
1753
1749 Usage:\\
1754 Usage:\\
1750 %timeit [-n<N> -r<R> [-t|-c]] statement
1755 %timeit [-n<N> -r<R> [-t|-c]] statement
1751
1756
1752 Time execution of a Python statement or expression using the timeit
1757 Time execution of a Python statement or expression using the timeit
1753 module.
1758 module.
1754
1759
1755 Options:
1760 Options:
1756 -n<N>: execute the given statement <N> times in a loop. If this value
1761 -n<N>: execute the given statement <N> times in a loop. If this value
1757 is not given, a fitting value is chosen.
1762 is not given, a fitting value is chosen.
1758
1763
1759 -r<R>: repeat the loop iteration <R> times and take the best result.
1764 -r<R>: repeat the loop iteration <R> times and take the best result.
1760 Default: 3
1765 Default: 3
1761
1766
1762 -t: use time.time to measure the time, which is the default on Unix.
1767 -t: use time.time to measure the time, which is the default on Unix.
1763 This function measures wall time.
1768 This function measures wall time.
1764
1769
1765 -c: use time.clock to measure the time, which is the default on
1770 -c: use time.clock to measure the time, which is the default on
1766 Windows and measures wall time. On Unix, resource.getrusage is used
1771 Windows and measures wall time. On Unix, resource.getrusage is used
1767 instead and returns the CPU user time.
1772 instead and returns the CPU user time.
1768
1773
1769 -p<P>: use a precision of <P> digits to display the timing result.
1774 -p<P>: use a precision of <P> digits to display the timing result.
1770 Default: 3
1775 Default: 3
1771
1776
1772
1777
1773 Examples:
1778 Examples:
1774
1779
1775 In [1]: %timeit pass
1780 In [1]: %timeit pass
1776 10000000 loops, best of 3: 53.3 ns per loop
1781 10000000 loops, best of 3: 53.3 ns per loop
1777
1782
1778 In [2]: u = None
1783 In [2]: u = None
1779
1784
1780 In [3]: %timeit u is None
1785 In [3]: %timeit u is None
1781 10000000 loops, best of 3: 184 ns per loop
1786 10000000 loops, best of 3: 184 ns per loop
1782
1787
1783 In [4]: %timeit -r 4 u == None
1788 In [4]: %timeit -r 4 u == None
1784 1000000 loops, best of 4: 242 ns per loop
1789 1000000 loops, best of 4: 242 ns per loop
1785
1790
1786 In [5]: import time
1791 In [5]: import time
1787
1792
1788 In [6]: %timeit -n1 time.sleep(2)
1793 In [6]: %timeit -n1 time.sleep(2)
1789 1 loops, best of 3: 2 s per loop
1794 1 loops, best of 3: 2 s per loop
1790
1795
1791
1796
1792 The times reported by %timeit will be slightly higher than those
1797 The times reported by %timeit will be slightly higher than those
1793 reported by the timeit.py script when variables are accessed. This is
1798 reported by the timeit.py script when variables are accessed. This is
1794 due to the fact that %timeit executes the statement in the namespace
1799 due to the fact that %timeit executes the statement in the namespace
1795 of the shell, compared with timeit.py, which uses a single setup
1800 of the shell, compared with timeit.py, which uses a single setup
1796 statement to import function or create variables. Generally, the bias
1801 statement to import function or create variables. Generally, the bias
1797 does not matter as long as results from timeit.py are not mixed with
1802 does not matter as long as results from timeit.py are not mixed with
1798 those from %timeit."""
1803 those from %timeit."""
1799
1804
1800 import timeit
1805 import timeit
1801 import math
1806 import math
1802
1807
1803 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1808 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1804 # certain terminals. Until we figure out a robust way of
1809 # certain terminals. Until we figure out a robust way of
1805 # auto-detecting if the terminal can deal with it, use plain 'us' for
1810 # auto-detecting if the terminal can deal with it, use plain 'us' for
1806 # microseconds. Note: using
1811 # microseconds. Note: using
1807 #
1812 #
1808 # s = u'\xb5'
1813 # s = u'\xb5'
1809 # s.encode(sys.getdefaultencoding())
1814 # s.encode(sys.getdefaultencoding())
1810 #
1815 #
1811 # is not sufficient, as I've seen terminals where that fails but
1816 # is not sufficient, as I've seen terminals where that fails but
1812 # print s
1817 # print s
1813 #
1818 #
1814 # succeeds
1819 # succeeds
1815 #
1820 #
1816 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1821 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1817
1822
1818 #units = [u"s", u"ms",u'\xb5',"ns"]
1823 #units = [u"s", u"ms",u'\xb5',"ns"]
1819 units = [u"s", u"ms",u'us',"ns"]
1824 units = [u"s", u"ms",u'us',"ns"]
1820
1825
1821 scaling = [1, 1e3, 1e6, 1e9]
1826 scaling = [1, 1e3, 1e6, 1e9]
1822
1827
1823 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1828 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1824 posix=False)
1829 posix=False)
1825 if stmt == "":
1830 if stmt == "":
1826 return
1831 return
1827 timefunc = timeit.default_timer
1832 timefunc = timeit.default_timer
1828 number = int(getattr(opts, "n", 0))
1833 number = int(getattr(opts, "n", 0))
1829 repeat = int(getattr(opts, "r", timeit.default_repeat))
1834 repeat = int(getattr(opts, "r", timeit.default_repeat))
1830 precision = int(getattr(opts, "p", 3))
1835 precision = int(getattr(opts, "p", 3))
1831 if hasattr(opts, "t"):
1836 if hasattr(opts, "t"):
1832 timefunc = time.time
1837 timefunc = time.time
1833 if hasattr(opts, "c"):
1838 if hasattr(opts, "c"):
1834 timefunc = clock
1839 timefunc = clock
1835
1840
1836 timer = timeit.Timer(timer=timefunc)
1841 timer = timeit.Timer(timer=timefunc)
1837 # this code has tight coupling to the inner workings of timeit.Timer,
1842 # this code has tight coupling to the inner workings of timeit.Timer,
1838 # but is there a better way to achieve that the code stmt has access
1843 # but is there a better way to achieve that the code stmt has access
1839 # to the shell namespace?
1844 # to the shell namespace?
1840
1845
1841 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1846 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1842 'setup': "pass"}
1847 'setup': "pass"}
1843 # Track compilation time so it can be reported if too long
1848 # Track compilation time so it can be reported if too long
1844 # Minimum time above which compilation time will be reported
1849 # Minimum time above which compilation time will be reported
1845 tc_min = 0.1
1850 tc_min = 0.1
1846
1851
1847 t0 = clock()
1852 t0 = clock()
1848 code = compile(src, "<magic-timeit>", "exec")
1853 code = compile(src, "<magic-timeit>", "exec")
1849 tc = clock()-t0
1854 tc = clock()-t0
1850
1855
1851 ns = {}
1856 ns = {}
1852 exec code in self.shell.user_ns, ns
1857 exec code in self.shell.user_ns, ns
1853 timer.inner = ns["inner"]
1858 timer.inner = ns["inner"]
1854
1859
1855 if number == 0:
1860 if number == 0:
1856 # determine number so that 0.2 <= total time < 2.0
1861 # determine number so that 0.2 <= total time < 2.0
1857 number = 1
1862 number = 1
1858 for i in range(1, 10):
1863 for i in range(1, 10):
1859 number *= 10
1864 number *= 10
1860 if timer.timeit(number) >= 0.2:
1865 if timer.timeit(number) >= 0.2:
1861 break
1866 break
1862
1867
1863 best = min(timer.repeat(repeat, number)) / number
1868 best = min(timer.repeat(repeat, number)) / number
1864
1869
1865 if best > 0.0:
1870 if best > 0.0:
1866 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1871 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1867 else:
1872 else:
1868 order = 3
1873 order = 3
1869 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1874 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1870 precision,
1875 precision,
1871 best * scaling[order],
1876 best * scaling[order],
1872 units[order])
1877 units[order])
1873 if tc > tc_min:
1878 if tc > tc_min:
1874 print "Compiler time: %.2f s" % tc
1879 print "Compiler time: %.2f s" % tc
1875
1880
1876 @testdec.skip_doctest
1881 @testdec.skip_doctest
1877 def magic_time(self,parameter_s = ''):
1882 def magic_time(self,parameter_s = ''):
1878 """Time execution of a Python statement or expression.
1883 """Time execution of a Python statement or expression.
1879
1884
1880 The CPU and wall clock times are printed, and the value of the
1885 The CPU and wall clock times are printed, and the value of the
1881 expression (if any) is returned. Note that under Win32, system time
1886 expression (if any) is returned. Note that under Win32, system time
1882 is always reported as 0, since it can not be measured.
1887 is always reported as 0, since it can not be measured.
1883
1888
1884 This function provides very basic timing functionality. In Python
1889 This function provides very basic timing functionality. In Python
1885 2.3, the timeit module offers more control and sophistication, so this
1890 2.3, the timeit module offers more control and sophistication, so this
1886 could be rewritten to use it (patches welcome).
1891 could be rewritten to use it (patches welcome).
1887
1892
1888 Some examples:
1893 Some examples:
1889
1894
1890 In [1]: time 2**128
1895 In [1]: time 2**128
1891 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1896 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1892 Wall time: 0.00
1897 Wall time: 0.00
1893 Out[1]: 340282366920938463463374607431768211456L
1898 Out[1]: 340282366920938463463374607431768211456L
1894
1899
1895 In [2]: n = 1000000
1900 In [2]: n = 1000000
1896
1901
1897 In [3]: time sum(range(n))
1902 In [3]: time sum(range(n))
1898 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1903 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1899 Wall time: 1.37
1904 Wall time: 1.37
1900 Out[3]: 499999500000L
1905 Out[3]: 499999500000L
1901
1906
1902 In [4]: time print 'hello world'
1907 In [4]: time print 'hello world'
1903 hello world
1908 hello world
1904 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1909 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1905 Wall time: 0.00
1910 Wall time: 0.00
1906
1911
1907 Note that the time needed by Python to compile the given expression
1912 Note that the time needed by Python to compile the given expression
1908 will be reported if it is more than 0.1s. In this example, the
1913 will be reported if it is more than 0.1s. In this example, the
1909 actual exponentiation is done by Python at compilation time, so while
1914 actual exponentiation is done by Python at compilation time, so while
1910 the expression can take a noticeable amount of time to compute, that
1915 the expression can take a noticeable amount of time to compute, that
1911 time is purely due to the compilation:
1916 time is purely due to the compilation:
1912
1917
1913 In [5]: time 3**9999;
1918 In [5]: time 3**9999;
1914 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1919 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1915 Wall time: 0.00 s
1920 Wall time: 0.00 s
1916
1921
1917 In [6]: time 3**999999;
1922 In [6]: time 3**999999;
1918 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1923 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1919 Wall time: 0.00 s
1924 Wall time: 0.00 s
1920 Compiler : 0.78 s
1925 Compiler : 0.78 s
1921 """
1926 """
1922
1927
1923 # fail immediately if the given expression can't be compiled
1928 # fail immediately if the given expression can't be compiled
1924
1929
1925 expr = self.shell.prefilter(parameter_s,False)
1930 expr = self.shell.prefilter(parameter_s,False)
1926
1931
1927 # Minimum time above which compilation time will be reported
1932 # Minimum time above which compilation time will be reported
1928 tc_min = 0.1
1933 tc_min = 0.1
1929
1934
1930 try:
1935 try:
1931 mode = 'eval'
1936 mode = 'eval'
1932 t0 = clock()
1937 t0 = clock()
1933 code = compile(expr,'<timed eval>',mode)
1938 code = compile(expr,'<timed eval>',mode)
1934 tc = clock()-t0
1939 tc = clock()-t0
1935 except SyntaxError:
1940 except SyntaxError:
1936 mode = 'exec'
1941 mode = 'exec'
1937 t0 = clock()
1942 t0 = clock()
1938 code = compile(expr,'<timed exec>',mode)
1943 code = compile(expr,'<timed exec>',mode)
1939 tc = clock()-t0
1944 tc = clock()-t0
1940 # skew measurement as little as possible
1945 # skew measurement as little as possible
1941 glob = self.shell.user_ns
1946 glob = self.shell.user_ns
1942 clk = clock2
1947 clk = clock2
1943 wtime = time.time
1948 wtime = time.time
1944 # time execution
1949 # time execution
1945 wall_st = wtime()
1950 wall_st = wtime()
1946 if mode=='eval':
1951 if mode=='eval':
1947 st = clk()
1952 st = clk()
1948 out = eval(code,glob)
1953 out = eval(code,glob)
1949 end = clk()
1954 end = clk()
1950 else:
1955 else:
1951 st = clk()
1956 st = clk()
1952 exec code in glob
1957 exec code in glob
1953 end = clk()
1958 end = clk()
1954 out = None
1959 out = None
1955 wall_end = wtime()
1960 wall_end = wtime()
1956 # Compute actual times and report
1961 # Compute actual times and report
1957 wall_time = wall_end-wall_st
1962 wall_time = wall_end-wall_st
1958 cpu_user = end[0]-st[0]
1963 cpu_user = end[0]-st[0]
1959 cpu_sys = end[1]-st[1]
1964 cpu_sys = end[1]-st[1]
1960 cpu_tot = cpu_user+cpu_sys
1965 cpu_tot = cpu_user+cpu_sys
1961 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1966 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1962 (cpu_user,cpu_sys,cpu_tot)
1967 (cpu_user,cpu_sys,cpu_tot)
1963 print "Wall time: %.2f s" % wall_time
1968 print "Wall time: %.2f s" % wall_time
1964 if tc > tc_min:
1969 if tc > tc_min:
1965 print "Compiler : %.2f s" % tc
1970 print "Compiler : %.2f s" % tc
1966 return out
1971 return out
1967
1972
1968 @testdec.skip_doctest
1973 @testdec.skip_doctest
1969 def magic_macro(self,parameter_s = ''):
1974 def magic_macro(self,parameter_s = ''):
1970 """Define a set of input lines as a macro for future re-execution.
1975 """Define a set of input lines as a macro for future re-execution.
1971
1976
1972 Usage:\\
1977 Usage:\\
1973 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1978 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1974
1979
1975 Options:
1980 Options:
1976
1981
1977 -r: use 'raw' input. By default, the 'processed' history is used,
1982 -r: use 'raw' input. By default, the 'processed' history is used,
1978 so that magics are loaded in their transformed version to valid
1983 so that magics are loaded in their transformed version to valid
1979 Python. If this option is given, the raw input as typed as the
1984 Python. If this option is given, the raw input as typed as the
1980 command line is used instead.
1985 command line is used instead.
1981
1986
1982 This will define a global variable called `name` which is a string
1987 This will define a global variable called `name` which is a string
1983 made of joining the slices and lines you specify (n1,n2,... numbers
1988 made of joining the slices and lines you specify (n1,n2,... numbers
1984 above) from your input history into a single string. This variable
1989 above) from your input history into a single string. This variable
1985 acts like an automatic function which re-executes those lines as if
1990 acts like an automatic function which re-executes those lines as if
1986 you had typed them. You just type 'name' at the prompt and the code
1991 you had typed them. You just type 'name' at the prompt and the code
1987 executes.
1992 executes.
1988
1993
1989 The notation for indicating number ranges is: n1-n2 means 'use line
1994 The notation for indicating number ranges is: n1-n2 means 'use line
1990 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1995 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1991 using the lines numbered 5,6 and 7.
1996 using the lines numbered 5,6 and 7.
1992
1997
1993 Note: as a 'hidden' feature, you can also use traditional python slice
1998 Note: as a 'hidden' feature, you can also use traditional python slice
1994 notation, where N:M means numbers N through M-1.
1999 notation, where N:M means numbers N through M-1.
1995
2000
1996 For example, if your history contains (%hist prints it):
2001 For example, if your history contains (%hist prints it):
1997
2002
1998 44: x=1
2003 44: x=1
1999 45: y=3
2004 45: y=3
2000 46: z=x+y
2005 46: z=x+y
2001 47: print x
2006 47: print x
2002 48: a=5
2007 48: a=5
2003 49: print 'x',x,'y',y
2008 49: print 'x',x,'y',y
2004
2009
2005 you can create a macro with lines 44 through 47 (included) and line 49
2010 you can create a macro with lines 44 through 47 (included) and line 49
2006 called my_macro with:
2011 called my_macro with:
2007
2012
2008 In [55]: %macro my_macro 44-47 49
2013 In [55]: %macro my_macro 44-47 49
2009
2014
2010 Now, typing `my_macro` (without quotes) will re-execute all this code
2015 Now, typing `my_macro` (without quotes) will re-execute all this code
2011 in one pass.
2016 in one pass.
2012
2017
2013 You don't need to give the line-numbers in order, and any given line
2018 You don't need to give the line-numbers in order, and any given line
2014 number can appear multiple times. You can assemble macros with any
2019 number can appear multiple times. You can assemble macros with any
2015 lines from your input history in any order.
2020 lines from your input history in any order.
2016
2021
2017 The macro is a simple object which holds its value in an attribute,
2022 The macro is a simple object which holds its value in an attribute,
2018 but IPython's display system checks for macros and executes them as
2023 but IPython's display system checks for macros and executes them as
2019 code instead of printing them when you type their name.
2024 code instead of printing them when you type their name.
2020
2025
2021 You can view a macro's contents by explicitly printing it with:
2026 You can view a macro's contents by explicitly printing it with:
2022
2027
2023 'print macro_name'.
2028 'print macro_name'.
2024
2029
2025 For one-off cases which DON'T contain magic function calls in them you
2030 For one-off cases which DON'T contain magic function calls in them you
2026 can obtain similar results by explicitly executing slices from your
2031 can obtain similar results by explicitly executing slices from your
2027 input history with:
2032 input history with:
2028
2033
2029 In [60]: exec In[44:48]+In[49]"""
2034 In [60]: exec In[44:48]+In[49]"""
2030
2035
2031 opts,args = self.parse_options(parameter_s,'r',mode='list')
2036 opts,args = self.parse_options(parameter_s,'r',mode='list')
2032 if not args:
2037 if not args:
2033 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2038 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2034 macs.sort()
2039 macs.sort()
2035 return macs
2040 return macs
2036 if len(args) == 1:
2041 if len(args) == 1:
2037 raise UsageError(
2042 raise UsageError(
2038 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2043 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2039 name,ranges = args[0], args[1:]
2044 name,ranges = args[0], args[1:]
2040
2045
2041 #print 'rng',ranges # dbg
2046 #print 'rng',ranges # dbg
2042 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2047 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2043 macro = Macro(lines)
2048 macro = Macro(lines)
2044 self.shell.user_ns.update({name:macro})
2049 self.shell.user_ns.update({name:macro})
2045 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2050 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2046 print 'Macro contents:'
2051 print 'Macro contents:'
2047 print macro,
2052 print macro,
2048
2053
2049 def magic_save(self,parameter_s = ''):
2054 def magic_save(self,parameter_s = ''):
2050 """Save a set of lines to a given filename.
2055 """Save a set of lines to a given filename.
2051
2056
2052 Usage:\\
2057 Usage:\\
2053 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2058 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2054
2059
2055 Options:
2060 Options:
2056
2061
2057 -r: use 'raw' input. By default, the 'processed' history is used,
2062 -r: use 'raw' input. By default, the 'processed' history is used,
2058 so that magics are loaded in their transformed version to valid
2063 so that magics are loaded in their transformed version to valid
2059 Python. If this option is given, the raw input as typed as the
2064 Python. If this option is given, the raw input as typed as the
2060 command line is used instead.
2065 command line is used instead.
2061
2066
2062 This function uses the same syntax as %macro for line extraction, but
2067 This function uses the same syntax as %macro for line extraction, but
2063 instead of creating a macro it saves the resulting string to the
2068 instead of creating a macro it saves the resulting string to the
2064 filename you specify.
2069 filename you specify.
2065
2070
2066 It adds a '.py' extension to the file if you don't do so yourself, and
2071 It adds a '.py' extension to the file if you don't do so yourself, and
2067 it asks for confirmation before overwriting existing files."""
2072 it asks for confirmation before overwriting existing files."""
2068
2073
2069 opts,args = self.parse_options(parameter_s,'r',mode='list')
2074 opts,args = self.parse_options(parameter_s,'r',mode='list')
2070 fname,ranges = args[0], args[1:]
2075 fname,ranges = args[0], args[1:]
2071 if not fname.endswith('.py'):
2076 if not fname.endswith('.py'):
2072 fname += '.py'
2077 fname += '.py'
2073 if os.path.isfile(fname):
2078 if os.path.isfile(fname):
2074 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2079 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2075 if ans.lower() not in ['y','yes']:
2080 if ans.lower() not in ['y','yes']:
2076 print 'Operation cancelled.'
2081 print 'Operation cancelled.'
2077 return
2082 return
2078 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2083 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2079 f = file(fname,'w')
2084 f = file(fname,'w')
2080 f.write(cmds)
2085 f.write(cmds)
2081 f.close()
2086 f.close()
2082 print 'The following commands were written to file `%s`:' % fname
2087 print 'The following commands were written to file `%s`:' % fname
2083 print cmds
2088 print cmds
2084
2089
2085 def _edit_macro(self,mname,macro):
2090 def _edit_macro(self,mname,macro):
2086 """open an editor with the macro data in a file"""
2091 """open an editor with the macro data in a file"""
2087 filename = self.shell.mktempfile(macro.value)
2092 filename = self.shell.mktempfile(macro.value)
2088 self.shell.hooks.editor(filename)
2093 self.shell.hooks.editor(filename)
2089
2094
2090 # and make a new macro object, to replace the old one
2095 # and make a new macro object, to replace the old one
2091 mfile = open(filename)
2096 mfile = open(filename)
2092 mvalue = mfile.read()
2097 mvalue = mfile.read()
2093 mfile.close()
2098 mfile.close()
2094 self.shell.user_ns[mname] = Macro(mvalue)
2099 self.shell.user_ns[mname] = Macro(mvalue)
2095
2100
2096 def magic_ed(self,parameter_s=''):
2101 def magic_ed(self,parameter_s=''):
2097 """Alias to %edit."""
2102 """Alias to %edit."""
2098 return self.magic_edit(parameter_s)
2103 return self.magic_edit(parameter_s)
2099
2104
2100 @testdec.skip_doctest
2105 @testdec.skip_doctest
2101 def magic_edit(self,parameter_s='',last_call=['','']):
2106 def magic_edit(self,parameter_s='',last_call=['','']):
2102 """Bring up an editor and execute the resulting code.
2107 """Bring up an editor and execute the resulting code.
2103
2108
2104 Usage:
2109 Usage:
2105 %edit [options] [args]
2110 %edit [options] [args]
2106
2111
2107 %edit runs IPython's editor hook. The default version of this hook is
2112 %edit runs IPython's editor hook. The default version of this hook is
2108 set to call the __IPYTHON__.rc.editor command. This is read from your
2113 set to call the __IPYTHON__.rc.editor command. This is read from your
2109 environment variable $EDITOR. If this isn't found, it will default to
2114 environment variable $EDITOR. If this isn't found, it will default to
2110 vi under Linux/Unix and to notepad under Windows. See the end of this
2115 vi under Linux/Unix and to notepad under Windows. See the end of this
2111 docstring for how to change the editor hook.
2116 docstring for how to change the editor hook.
2112
2117
2113 You can also set the value of this editor via the command line option
2118 You can also set the value of this editor via the command line option
2114 '-editor' or in your ipythonrc file. This is useful if you wish to use
2119 '-editor' or in your ipythonrc file. This is useful if you wish to use
2115 specifically for IPython an editor different from your typical default
2120 specifically for IPython an editor different from your typical default
2116 (and for Windows users who typically don't set environment variables).
2121 (and for Windows users who typically don't set environment variables).
2117
2122
2118 This command allows you to conveniently edit multi-line code right in
2123 This command allows you to conveniently edit multi-line code right in
2119 your IPython session.
2124 your IPython session.
2120
2125
2121 If called without arguments, %edit opens up an empty editor with a
2126 If called without arguments, %edit opens up an empty editor with a
2122 temporary file and will execute the contents of this file when you
2127 temporary file and will execute the contents of this file when you
2123 close it (don't forget to save it!).
2128 close it (don't forget to save it!).
2124
2129
2125
2130
2126 Options:
2131 Options:
2127
2132
2128 -n <number>: open the editor at a specified line number. By default,
2133 -n <number>: open the editor at a specified line number. By default,
2129 the IPython editor hook uses the unix syntax 'editor +N filename', but
2134 the IPython editor hook uses the unix syntax 'editor +N filename', but
2130 you can configure this by providing your own modified hook if your
2135 you can configure this by providing your own modified hook if your
2131 favorite editor supports line-number specifications with a different
2136 favorite editor supports line-number specifications with a different
2132 syntax.
2137 syntax.
2133
2138
2134 -p: this will call the editor with the same data as the previous time
2139 -p: this will call the editor with the same data as the previous time
2135 it was used, regardless of how long ago (in your current session) it
2140 it was used, regardless of how long ago (in your current session) it
2136 was.
2141 was.
2137
2142
2138 -r: use 'raw' input. This option only applies to input taken from the
2143 -r: use 'raw' input. This option only applies to input taken from the
2139 user's history. By default, the 'processed' history is used, so that
2144 user's history. By default, the 'processed' history is used, so that
2140 magics are loaded in their transformed version to valid Python. If
2145 magics are loaded in their transformed version to valid Python. If
2141 this option is given, the raw input as typed as the command line is
2146 this option is given, the raw input as typed as the command line is
2142 used instead. When you exit the editor, it will be executed by
2147 used instead. When you exit the editor, it will be executed by
2143 IPython's own processor.
2148 IPython's own processor.
2144
2149
2145 -x: do not execute the edited code immediately upon exit. This is
2150 -x: do not execute the edited code immediately upon exit. This is
2146 mainly useful if you are editing programs which need to be called with
2151 mainly useful if you are editing programs which need to be called with
2147 command line arguments, which you can then do using %run.
2152 command line arguments, which you can then do using %run.
2148
2153
2149
2154
2150 Arguments:
2155 Arguments:
2151
2156
2152 If arguments are given, the following possibilites exist:
2157 If arguments are given, the following possibilites exist:
2153
2158
2154 - The arguments are numbers or pairs of colon-separated numbers (like
2159 - The arguments are numbers or pairs of colon-separated numbers (like
2155 1 4:8 9). These are interpreted as lines of previous input to be
2160 1 4:8 9). These are interpreted as lines of previous input to be
2156 loaded into the editor. The syntax is the same of the %macro command.
2161 loaded into the editor. The syntax is the same of the %macro command.
2157
2162
2158 - If the argument doesn't start with a number, it is evaluated as a
2163 - If the argument doesn't start with a number, it is evaluated as a
2159 variable and its contents loaded into the editor. You can thus edit
2164 variable and its contents loaded into the editor. You can thus edit
2160 any string which contains python code (including the result of
2165 any string which contains python code (including the result of
2161 previous edits).
2166 previous edits).
2162
2167
2163 - If the argument is the name of an object (other than a string),
2168 - If the argument is the name of an object (other than a string),
2164 IPython will try to locate the file where it was defined and open the
2169 IPython will try to locate the file where it was defined and open the
2165 editor at the point where it is defined. You can use `%edit function`
2170 editor at the point where it is defined. You can use `%edit function`
2166 to load an editor exactly at the point where 'function' is defined,
2171 to load an editor exactly at the point where 'function' is defined,
2167 edit it and have the file be executed automatically.
2172 edit it and have the file be executed automatically.
2168
2173
2169 If the object is a macro (see %macro for details), this opens up your
2174 If the object is a macro (see %macro for details), this opens up your
2170 specified editor with a temporary file containing the macro's data.
2175 specified editor with a temporary file containing the macro's data.
2171 Upon exit, the macro is reloaded with the contents of the file.
2176 Upon exit, the macro is reloaded with the contents of the file.
2172
2177
2173 Note: opening at an exact line is only supported under Unix, and some
2178 Note: opening at an exact line is only supported under Unix, and some
2174 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2179 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2175 '+NUMBER' parameter necessary for this feature. Good editors like
2180 '+NUMBER' parameter necessary for this feature. Good editors like
2176 (X)Emacs, vi, jed, pico and joe all do.
2181 (X)Emacs, vi, jed, pico and joe all do.
2177
2182
2178 - If the argument is not found as a variable, IPython will look for a
2183 - If the argument is not found as a variable, IPython will look for a
2179 file with that name (adding .py if necessary) and load it into the
2184 file with that name (adding .py if necessary) and load it into the
2180 editor. It will execute its contents with execfile() when you exit,
2185 editor. It will execute its contents with execfile() when you exit,
2181 loading any code in the file into your interactive namespace.
2186 loading any code in the file into your interactive namespace.
2182
2187
2183 After executing your code, %edit will return as output the code you
2188 After executing your code, %edit will return as output the code you
2184 typed in the editor (except when it was an existing file). This way
2189 typed in the editor (except when it was an existing file). This way
2185 you can reload the code in further invocations of %edit as a variable,
2190 you can reload the code in further invocations of %edit as a variable,
2186 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2191 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2187 the output.
2192 the output.
2188
2193
2189 Note that %edit is also available through the alias %ed.
2194 Note that %edit is also available through the alias %ed.
2190
2195
2191 This is an example of creating a simple function inside the editor and
2196 This is an example of creating a simple function inside the editor and
2192 then modifying it. First, start up the editor:
2197 then modifying it. First, start up the editor:
2193
2198
2194 In [1]: ed
2199 In [1]: ed
2195 Editing... done. Executing edited code...
2200 Editing... done. Executing edited code...
2196 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2201 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2197
2202
2198 We can then call the function foo():
2203 We can then call the function foo():
2199
2204
2200 In [2]: foo()
2205 In [2]: foo()
2201 foo() was defined in an editing session
2206 foo() was defined in an editing session
2202
2207
2203 Now we edit foo. IPython automatically loads the editor with the
2208 Now we edit foo. IPython automatically loads the editor with the
2204 (temporary) file where foo() was previously defined:
2209 (temporary) file where foo() was previously defined:
2205
2210
2206 In [3]: ed foo
2211 In [3]: ed foo
2207 Editing... done. Executing edited code...
2212 Editing... done. Executing edited code...
2208
2213
2209 And if we call foo() again we get the modified version:
2214 And if we call foo() again we get the modified version:
2210
2215
2211 In [4]: foo()
2216 In [4]: foo()
2212 foo() has now been changed!
2217 foo() has now been changed!
2213
2218
2214 Here is an example of how to edit a code snippet successive
2219 Here is an example of how to edit a code snippet successive
2215 times. First we call the editor:
2220 times. First we call the editor:
2216
2221
2217 In [5]: ed
2222 In [5]: ed
2218 Editing... done. Executing edited code...
2223 Editing... done. Executing edited code...
2219 hello
2224 hello
2220 Out[5]: "print 'hello'n"
2225 Out[5]: "print 'hello'n"
2221
2226
2222 Now we call it again with the previous output (stored in _):
2227 Now we call it again with the previous output (stored in _):
2223
2228
2224 In [6]: ed _
2229 In [6]: ed _
2225 Editing... done. Executing edited code...
2230 Editing... done. Executing edited code...
2226 hello world
2231 hello world
2227 Out[6]: "print 'hello world'n"
2232 Out[6]: "print 'hello world'n"
2228
2233
2229 Now we call it with the output #8 (stored in _8, also as Out[8]):
2234 Now we call it with the output #8 (stored in _8, also as Out[8]):
2230
2235
2231 In [7]: ed _8
2236 In [7]: ed _8
2232 Editing... done. Executing edited code...
2237 Editing... done. Executing edited code...
2233 hello again
2238 hello again
2234 Out[7]: "print 'hello again'n"
2239 Out[7]: "print 'hello again'n"
2235
2240
2236
2241
2237 Changing the default editor hook:
2242 Changing the default editor hook:
2238
2243
2239 If you wish to write your own editor hook, you can put it in a
2244 If you wish to write your own editor hook, you can put it in a
2240 configuration file which you load at startup time. The default hook
2245 configuration file which you load at startup time. The default hook
2241 is defined in the IPython.hooks module, and you can use that as a
2246 is defined in the IPython.hooks module, and you can use that as a
2242 starting example for further modifications. That file also has
2247 starting example for further modifications. That file also has
2243 general instructions on how to set a new hook for use once you've
2248 general instructions on how to set a new hook for use once you've
2244 defined it."""
2249 defined it."""
2245
2250
2246 # FIXME: This function has become a convoluted mess. It needs a
2251 # FIXME: This function has become a convoluted mess. It needs a
2247 # ground-up rewrite with clean, simple logic.
2252 # ground-up rewrite with clean, simple logic.
2248
2253
2249 def make_filename(arg):
2254 def make_filename(arg):
2250 "Make a filename from the given args"
2255 "Make a filename from the given args"
2251 try:
2256 try:
2252 filename = get_py_filename(arg)
2257 filename = get_py_filename(arg)
2253 except IOError:
2258 except IOError:
2254 if args.endswith('.py'):
2259 if args.endswith('.py'):
2255 filename = arg
2260 filename = arg
2256 else:
2261 else:
2257 filename = None
2262 filename = None
2258 return filename
2263 return filename
2259
2264
2260 # custom exceptions
2265 # custom exceptions
2261 class DataIsObject(Exception): pass
2266 class DataIsObject(Exception): pass
2262
2267
2263 opts,args = self.parse_options(parameter_s,'prxn:')
2268 opts,args = self.parse_options(parameter_s,'prxn:')
2264 # Set a few locals from the options for convenience:
2269 # Set a few locals from the options for convenience:
2265 opts_p = opts.has_key('p')
2270 opts_p = opts.has_key('p')
2266 opts_r = opts.has_key('r')
2271 opts_r = opts.has_key('r')
2267
2272
2268 # Default line number value
2273 # Default line number value
2269 lineno = opts.get('n',None)
2274 lineno = opts.get('n',None)
2270
2275
2271 if opts_p:
2276 if opts_p:
2272 args = '_%s' % last_call[0]
2277 args = '_%s' % last_call[0]
2273 if not self.shell.user_ns.has_key(args):
2278 if not self.shell.user_ns.has_key(args):
2274 args = last_call[1]
2279 args = last_call[1]
2275
2280
2276 # use last_call to remember the state of the previous call, but don't
2281 # use last_call to remember the state of the previous call, but don't
2277 # let it be clobbered by successive '-p' calls.
2282 # let it be clobbered by successive '-p' calls.
2278 try:
2283 try:
2279 last_call[0] = self.shell.outputcache.prompt_count
2284 last_call[0] = self.shell.outputcache.prompt_count
2280 if not opts_p:
2285 if not opts_p:
2281 last_call[1] = parameter_s
2286 last_call[1] = parameter_s
2282 except:
2287 except:
2283 pass
2288 pass
2284
2289
2285 # by default this is done with temp files, except when the given
2290 # by default this is done with temp files, except when the given
2286 # arg is a filename
2291 # arg is a filename
2287 use_temp = 1
2292 use_temp = 1
2288
2293
2289 if re.match(r'\d',args):
2294 if re.match(r'\d',args):
2290 # Mode where user specifies ranges of lines, like in %macro.
2295 # Mode where user specifies ranges of lines, like in %macro.
2291 # This means that you can't edit files whose names begin with
2296 # This means that you can't edit files whose names begin with
2292 # numbers this way. Tough.
2297 # numbers this way. Tough.
2293 ranges = args.split()
2298 ranges = args.split()
2294 data = ''.join(self.extract_input_slices(ranges,opts_r))
2299 data = ''.join(self.extract_input_slices(ranges,opts_r))
2295 elif args.endswith('.py'):
2300 elif args.endswith('.py'):
2296 filename = make_filename(args)
2301 filename = make_filename(args)
2297 data = ''
2302 data = ''
2298 use_temp = 0
2303 use_temp = 0
2299 elif args:
2304 elif args:
2300 try:
2305 try:
2301 # Load the parameter given as a variable. If not a string,
2306 # Load the parameter given as a variable. If not a string,
2302 # process it as an object instead (below)
2307 # process it as an object instead (below)
2303
2308
2304 #print '*** args',args,'type',type(args) # dbg
2309 #print '*** args',args,'type',type(args) # dbg
2305 data = eval(args,self.shell.user_ns)
2310 data = eval(args,self.shell.user_ns)
2306 if not type(data) in StringTypes:
2311 if not type(data) in StringTypes:
2307 raise DataIsObject
2312 raise DataIsObject
2308
2313
2309 except (NameError,SyntaxError):
2314 except (NameError,SyntaxError):
2310 # given argument is not a variable, try as a filename
2315 # given argument is not a variable, try as a filename
2311 filename = make_filename(args)
2316 filename = make_filename(args)
2312 if filename is None:
2317 if filename is None:
2313 warn("Argument given (%s) can't be found as a variable "
2318 warn("Argument given (%s) can't be found as a variable "
2314 "or as a filename." % args)
2319 "or as a filename." % args)
2315 return
2320 return
2316
2321
2317 data = ''
2322 data = ''
2318 use_temp = 0
2323 use_temp = 0
2319 except DataIsObject:
2324 except DataIsObject:
2320
2325
2321 # macros have a special edit function
2326 # macros have a special edit function
2322 if isinstance(data,Macro):
2327 if isinstance(data,Macro):
2323 self._edit_macro(args,data)
2328 self._edit_macro(args,data)
2324 return
2329 return
2325
2330
2326 # For objects, try to edit the file where they are defined
2331 # For objects, try to edit the file where they are defined
2327 try:
2332 try:
2328 filename = inspect.getabsfile(data)
2333 filename = inspect.getabsfile(data)
2329 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2334 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2330 # class created by %edit? Try to find source
2335 # class created by %edit? Try to find source
2331 # by looking for method definitions instead, the
2336 # by looking for method definitions instead, the
2332 # __module__ in those classes is FakeModule.
2337 # __module__ in those classes is FakeModule.
2333 attrs = [getattr(data, aname) for aname in dir(data)]
2338 attrs = [getattr(data, aname) for aname in dir(data)]
2334 for attr in attrs:
2339 for attr in attrs:
2335 if not inspect.ismethod(attr):
2340 if not inspect.ismethod(attr):
2336 continue
2341 continue
2337 filename = inspect.getabsfile(attr)
2342 filename = inspect.getabsfile(attr)
2338 if filename and 'fakemodule' not in filename.lower():
2343 if filename and 'fakemodule' not in filename.lower():
2339 # change the attribute to be the edit target instead
2344 # change the attribute to be the edit target instead
2340 data = attr
2345 data = attr
2341 break
2346 break
2342
2347
2343 datafile = 1
2348 datafile = 1
2344 except TypeError:
2349 except TypeError:
2345 filename = make_filename(args)
2350 filename = make_filename(args)
2346 datafile = 1
2351 datafile = 1
2347 warn('Could not find file where `%s` is defined.\n'
2352 warn('Could not find file where `%s` is defined.\n'
2348 'Opening a file named `%s`' % (args,filename))
2353 'Opening a file named `%s`' % (args,filename))
2349 # Now, make sure we can actually read the source (if it was in
2354 # Now, make sure we can actually read the source (if it was in
2350 # a temp file it's gone by now).
2355 # a temp file it's gone by now).
2351 if datafile:
2356 if datafile:
2352 try:
2357 try:
2353 if lineno is None:
2358 if lineno is None:
2354 lineno = inspect.getsourcelines(data)[1]
2359 lineno = inspect.getsourcelines(data)[1]
2355 except IOError:
2360 except IOError:
2356 filename = make_filename(args)
2361 filename = make_filename(args)
2357 if filename is None:
2362 if filename is None:
2358 warn('The file `%s` where `%s` was defined cannot '
2363 warn('The file `%s` where `%s` was defined cannot '
2359 'be read.' % (filename,data))
2364 'be read.' % (filename,data))
2360 return
2365 return
2361 use_temp = 0
2366 use_temp = 0
2362 else:
2367 else:
2363 data = ''
2368 data = ''
2364
2369
2365 if use_temp:
2370 if use_temp:
2366 filename = self.shell.mktempfile(data)
2371 filename = self.shell.mktempfile(data)
2367 print 'IPython will make a temporary file named:',filename
2372 print 'IPython will make a temporary file named:',filename
2368
2373
2369 # do actual editing here
2374 # do actual editing here
2370 print 'Editing...',
2375 print 'Editing...',
2371 sys.stdout.flush()
2376 sys.stdout.flush()
2372 try:
2377 try:
2373 self.shell.hooks.editor(filename,lineno)
2378 self.shell.hooks.editor(filename,lineno)
2374 except IPython.ipapi.TryNext:
2379 except IPython.ipapi.TryNext:
2375 warn('Could not open editor')
2380 warn('Could not open editor')
2376 return
2381 return
2377
2382
2378 # XXX TODO: should this be generalized for all string vars?
2383 # XXX TODO: should this be generalized for all string vars?
2379 # For now, this is special-cased to blocks created by cpaste
2384 # For now, this is special-cased to blocks created by cpaste
2380 if args.strip() == 'pasted_block':
2385 if args.strip() == 'pasted_block':
2381 self.shell.user_ns['pasted_block'] = file_read(filename)
2386 self.shell.user_ns['pasted_block'] = file_read(filename)
2382
2387
2383 if opts.has_key('x'): # -x prevents actual execution
2388 if opts.has_key('x'): # -x prevents actual execution
2384 print
2389 print
2385 else:
2390 else:
2386 print 'done. Executing edited code...'
2391 print 'done. Executing edited code...'
2387 if opts_r:
2392 if opts_r:
2388 self.shell.runlines(file_read(filename))
2393 self.shell.runlines(file_read(filename))
2389 else:
2394 else:
2390 self.shell.safe_execfile(filename,self.shell.user_ns,
2395 self.shell.safe_execfile(filename,self.shell.user_ns,
2391 self.shell.user_ns)
2396 self.shell.user_ns)
2392
2397
2393
2398
2394 if use_temp:
2399 if use_temp:
2395 try:
2400 try:
2396 return open(filename).read()
2401 return open(filename).read()
2397 except IOError,msg:
2402 except IOError,msg:
2398 if msg.filename == filename:
2403 if msg.filename == filename:
2399 warn('File not found. Did you forget to save?')
2404 warn('File not found. Did you forget to save?')
2400 return
2405 return
2401 else:
2406 else:
2402 self.shell.showtraceback()
2407 self.shell.showtraceback()
2403
2408
2404 def magic_xmode(self,parameter_s = ''):
2409 def magic_xmode(self,parameter_s = ''):
2405 """Switch modes for the exception handlers.
2410 """Switch modes for the exception handlers.
2406
2411
2407 Valid modes: Plain, Context and Verbose.
2412 Valid modes: Plain, Context and Verbose.
2408
2413
2409 If called without arguments, acts as a toggle."""
2414 If called without arguments, acts as a toggle."""
2410
2415
2411 def xmode_switch_err(name):
2416 def xmode_switch_err(name):
2412 warn('Error changing %s exception modes.\n%s' %
2417 warn('Error changing %s exception modes.\n%s' %
2413 (name,sys.exc_info()[1]))
2418 (name,sys.exc_info()[1]))
2414
2419
2415 shell = self.shell
2420 shell = self.shell
2416 new_mode = parameter_s.strip().capitalize()
2421 new_mode = parameter_s.strip().capitalize()
2417 try:
2422 try:
2418 shell.InteractiveTB.set_mode(mode=new_mode)
2423 shell.InteractiveTB.set_mode(mode=new_mode)
2419 print 'Exception reporting mode:',shell.InteractiveTB.mode
2424 print 'Exception reporting mode:',shell.InteractiveTB.mode
2420 except:
2425 except:
2421 xmode_switch_err('user')
2426 xmode_switch_err('user')
2422
2427
2423 # threaded shells use a special handler in sys.excepthook
2428 # threaded shells use a special handler in sys.excepthook
2424 if shell.isthreaded:
2429 if shell.isthreaded:
2425 try:
2430 try:
2426 shell.sys_excepthook.set_mode(mode=new_mode)
2431 shell.sys_excepthook.set_mode(mode=new_mode)
2427 except:
2432 except:
2428 xmode_switch_err('threaded')
2433 xmode_switch_err('threaded')
2429
2434
2430 def magic_colors(self,parameter_s = ''):
2435 def magic_colors(self,parameter_s = ''):
2431 """Switch color scheme for prompts, info system and exception handlers.
2436 """Switch color scheme for prompts, info system and exception handlers.
2432
2437
2433 Currently implemented schemes: NoColor, Linux, LightBG.
2438 Currently implemented schemes: NoColor, Linux, LightBG.
2434
2439
2435 Color scheme names are not case-sensitive."""
2440 Color scheme names are not case-sensitive."""
2436
2441
2437 def color_switch_err(name):
2442 def color_switch_err(name):
2438 warn('Error changing %s color schemes.\n%s' %
2443 warn('Error changing %s color schemes.\n%s' %
2439 (name,sys.exc_info()[1]))
2444 (name,sys.exc_info()[1]))
2440
2445
2441
2446
2442 new_scheme = parameter_s.strip()
2447 new_scheme = parameter_s.strip()
2443 if not new_scheme:
2448 if not new_scheme:
2444 raise UsageError(
2449 raise UsageError(
2445 "%colors: you must specify a color scheme. See '%colors?'")
2450 "%colors: you must specify a color scheme. See '%colors?'")
2446 return
2451 return
2447 # local shortcut
2452 # local shortcut
2448 shell = self.shell
2453 shell = self.shell
2449
2454
2450 import IPython.rlineimpl as readline
2455 import IPython.rlineimpl as readline
2451
2456
2452 if not readline.have_readline and sys.platform == "win32":
2457 if not readline.have_readline and sys.platform == "win32":
2453 msg = """\
2458 msg = """\
2454 Proper color support under MS Windows requires the pyreadline library.
2459 Proper color support under MS Windows requires the pyreadline library.
2455 You can find it at:
2460 You can find it at:
2456 http://ipython.scipy.org/moin/PyReadline/Intro
2461 http://ipython.scipy.org/moin/PyReadline/Intro
2457 Gary's readline needs the ctypes module, from:
2462 Gary's readline needs the ctypes module, from:
2458 http://starship.python.net/crew/theller/ctypes
2463 http://starship.python.net/crew/theller/ctypes
2459 (Note that ctypes is already part of Python versions 2.5 and newer).
2464 (Note that ctypes is already part of Python versions 2.5 and newer).
2460
2465
2461 Defaulting color scheme to 'NoColor'"""
2466 Defaulting color scheme to 'NoColor'"""
2462 new_scheme = 'NoColor'
2467 new_scheme = 'NoColor'
2463 warn(msg)
2468 warn(msg)
2464
2469
2465 # readline option is 0
2470 # readline option is 0
2466 if not shell.has_readline:
2471 if not shell.has_readline:
2467 new_scheme = 'NoColor'
2472 new_scheme = 'NoColor'
2468
2473
2469 # Set prompt colors
2474 # Set prompt colors
2470 try:
2475 try:
2471 shell.outputcache.set_colors(new_scheme)
2476 shell.outputcache.set_colors(new_scheme)
2472 except:
2477 except:
2473 color_switch_err('prompt')
2478 color_switch_err('prompt')
2474 else:
2479 else:
2475 shell.rc.colors = \
2480 shell.rc.colors = \
2476 shell.outputcache.color_table.active_scheme_name
2481 shell.outputcache.color_table.active_scheme_name
2477 # Set exception colors
2482 # Set exception colors
2478 try:
2483 try:
2479 shell.InteractiveTB.set_colors(scheme = new_scheme)
2484 shell.InteractiveTB.set_colors(scheme = new_scheme)
2480 shell.SyntaxTB.set_colors(scheme = new_scheme)
2485 shell.SyntaxTB.set_colors(scheme = new_scheme)
2481 except:
2486 except:
2482 color_switch_err('exception')
2487 color_switch_err('exception')
2483
2488
2484 # threaded shells use a verbose traceback in sys.excepthook
2489 # threaded shells use a verbose traceback in sys.excepthook
2485 if shell.isthreaded:
2490 if shell.isthreaded:
2486 try:
2491 try:
2487 shell.sys_excepthook.set_colors(scheme=new_scheme)
2492 shell.sys_excepthook.set_colors(scheme=new_scheme)
2488 except:
2493 except:
2489 color_switch_err('system exception handler')
2494 color_switch_err('system exception handler')
2490
2495
2491 # Set info (for 'object?') colors
2496 # Set info (for 'object?') colors
2492 if shell.rc.color_info:
2497 if shell.rc.color_info:
2493 try:
2498 try:
2494 shell.inspector.set_active_scheme(new_scheme)
2499 shell.inspector.set_active_scheme(new_scheme)
2495 except:
2500 except:
2496 color_switch_err('object inspector')
2501 color_switch_err('object inspector')
2497 else:
2502 else:
2498 shell.inspector.set_active_scheme('NoColor')
2503 shell.inspector.set_active_scheme('NoColor')
2499
2504
2500 def magic_color_info(self,parameter_s = ''):
2505 def magic_color_info(self,parameter_s = ''):
2501 """Toggle color_info.
2506 """Toggle color_info.
2502
2507
2503 The color_info configuration parameter controls whether colors are
2508 The color_info configuration parameter controls whether colors are
2504 used for displaying object details (by things like %psource, %pfile or
2509 used for displaying object details (by things like %psource, %pfile or
2505 the '?' system). This function toggles this value with each call.
2510 the '?' system). This function toggles this value with each call.
2506
2511
2507 Note that unless you have a fairly recent pager (less works better
2512 Note that unless you have a fairly recent pager (less works better
2508 than more) in your system, using colored object information displays
2513 than more) in your system, using colored object information displays
2509 will not work properly. Test it and see."""
2514 will not work properly. Test it and see."""
2510
2515
2511 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2516 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2512 self.magic_colors(self.shell.rc.colors)
2517 self.magic_colors(self.shell.rc.colors)
2513 print 'Object introspection functions have now coloring:',
2518 print 'Object introspection functions have now coloring:',
2514 print ['OFF','ON'][self.shell.rc.color_info]
2519 print ['OFF','ON'][self.shell.rc.color_info]
2515
2520
2516 def magic_Pprint(self, parameter_s=''):
2521 def magic_Pprint(self, parameter_s=''):
2517 """Toggle pretty printing on/off."""
2522 """Toggle pretty printing on/off."""
2518
2523
2519 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2524 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2520 print 'Pretty printing has been turned', \
2525 print 'Pretty printing has been turned', \
2521 ['OFF','ON'][self.shell.rc.pprint]
2526 ['OFF','ON'][self.shell.rc.pprint]
2522
2527
2523 def magic_exit(self, parameter_s=''):
2528 def magic_exit(self, parameter_s=''):
2524 """Exit IPython, confirming if configured to do so.
2529 """Exit IPython, confirming if configured to do so.
2525
2530
2526 You can configure whether IPython asks for confirmation upon exit by
2531 You can configure whether IPython asks for confirmation upon exit by
2527 setting the confirm_exit flag in the ipythonrc file."""
2532 setting the confirm_exit flag in the ipythonrc file."""
2528
2533
2529 self.shell.exit()
2534 self.shell.exit()
2530
2535
2531 def magic_quit(self, parameter_s=''):
2536 def magic_quit(self, parameter_s=''):
2532 """Exit IPython, confirming if configured to do so (like %exit)"""
2537 """Exit IPython, confirming if configured to do so (like %exit)"""
2533
2538
2534 self.shell.exit()
2539 self.shell.exit()
2535
2540
2536 def magic_Exit(self, parameter_s=''):
2541 def magic_Exit(self, parameter_s=''):
2537 """Exit IPython without confirmation."""
2542 """Exit IPython without confirmation."""
2538
2543
2539 self.shell.ask_exit()
2544 self.shell.ask_exit()
2540
2545
2541 #......................................................................
2546 #......................................................................
2542 # Functions to implement unix shell-type things
2547 # Functions to implement unix shell-type things
2543
2548
2544 @testdec.skip_doctest
2549 @testdec.skip_doctest
2545 def magic_alias(self, parameter_s = ''):
2550 def magic_alias(self, parameter_s = ''):
2546 """Define an alias for a system command.
2551 """Define an alias for a system command.
2547
2552
2548 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2553 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2549
2554
2550 Then, typing 'alias_name params' will execute the system command 'cmd
2555 Then, typing 'alias_name params' will execute the system command 'cmd
2551 params' (from your underlying operating system).
2556 params' (from your underlying operating system).
2552
2557
2553 Aliases have lower precedence than magic functions and Python normal
2558 Aliases have lower precedence than magic functions and Python normal
2554 variables, so if 'foo' is both a Python variable and an alias, the
2559 variables, so if 'foo' is both a Python variable and an alias, the
2555 alias can not be executed until 'del foo' removes the Python variable.
2560 alias can not be executed until 'del foo' removes the Python variable.
2556
2561
2557 You can use the %l specifier in an alias definition to represent the
2562 You can use the %l specifier in an alias definition to represent the
2558 whole line when the alias is called. For example:
2563 whole line when the alias is called. For example:
2559
2564
2560 In [2]: alias all echo "Input in brackets: <%l>"
2565 In [2]: alias all echo "Input in brackets: <%l>"
2561 In [3]: all hello world
2566 In [3]: all hello world
2562 Input in brackets: <hello world>
2567 Input in brackets: <hello world>
2563
2568
2564 You can also define aliases with parameters using %s specifiers (one
2569 You can also define aliases with parameters using %s specifiers (one
2565 per parameter):
2570 per parameter):
2566
2571
2567 In [1]: alias parts echo first %s second %s
2572 In [1]: alias parts echo first %s second %s
2568 In [2]: %parts A B
2573 In [2]: %parts A B
2569 first A second B
2574 first A second B
2570 In [3]: %parts A
2575 In [3]: %parts A
2571 Incorrect number of arguments: 2 expected.
2576 Incorrect number of arguments: 2 expected.
2572 parts is an alias to: 'echo first %s second %s'
2577 parts is an alias to: 'echo first %s second %s'
2573
2578
2574 Note that %l and %s are mutually exclusive. You can only use one or
2579 Note that %l and %s are mutually exclusive. You can only use one or
2575 the other in your aliases.
2580 the other in your aliases.
2576
2581
2577 Aliases expand Python variables just like system calls using ! or !!
2582 Aliases expand Python variables just like system calls using ! or !!
2578 do: all expressions prefixed with '$' get expanded. For details of
2583 do: all expressions prefixed with '$' get expanded. For details of
2579 the semantic rules, see PEP-215:
2584 the semantic rules, see PEP-215:
2580 http://www.python.org/peps/pep-0215.html. This is the library used by
2585 http://www.python.org/peps/pep-0215.html. This is the library used by
2581 IPython for variable expansion. If you want to access a true shell
2586 IPython for variable expansion. If you want to access a true shell
2582 variable, an extra $ is necessary to prevent its expansion by IPython:
2587 variable, an extra $ is necessary to prevent its expansion by IPython:
2583
2588
2584 In [6]: alias show echo
2589 In [6]: alias show echo
2585 In [7]: PATH='A Python string'
2590 In [7]: PATH='A Python string'
2586 In [8]: show $PATH
2591 In [8]: show $PATH
2587 A Python string
2592 A Python string
2588 In [9]: show $$PATH
2593 In [9]: show $$PATH
2589 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2594 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2590
2595
2591 You can use the alias facility to acess all of $PATH. See the %rehash
2596 You can use the alias facility to acess all of $PATH. See the %rehash
2592 and %rehashx functions, which automatically create aliases for the
2597 and %rehashx functions, which automatically create aliases for the
2593 contents of your $PATH.
2598 contents of your $PATH.
2594
2599
2595 If called with no parameters, %alias prints the current alias table."""
2600 If called with no parameters, %alias prints the current alias table."""
2596
2601
2597 par = parameter_s.strip()
2602 par = parameter_s.strip()
2598 if not par:
2603 if not par:
2599 stored = self.db.get('stored_aliases', {} )
2604 stored = self.db.get('stored_aliases', {} )
2600 atab = self.shell.alias_table
2605 atab = self.shell.alias_table
2601 aliases = atab.keys()
2606 aliases = atab.keys()
2602 aliases.sort()
2607 aliases.sort()
2603 res = []
2608 res = []
2604 showlast = []
2609 showlast = []
2605 for alias in aliases:
2610 for alias in aliases:
2606 special = False
2611 special = False
2607 try:
2612 try:
2608 tgt = atab[alias][1]
2613 tgt = atab[alias][1]
2609 except (TypeError, AttributeError):
2614 except (TypeError, AttributeError):
2610 # unsubscriptable? probably a callable
2615 # unsubscriptable? probably a callable
2611 tgt = atab[alias]
2616 tgt = atab[alias]
2612 special = True
2617 special = True
2613 # 'interesting' aliases
2618 # 'interesting' aliases
2614 if (alias in stored or
2619 if (alias in stored or
2615 special or
2620 special or
2616 alias.lower() != os.path.splitext(tgt)[0].lower() or
2621 alias.lower() != os.path.splitext(tgt)[0].lower() or
2617 ' ' in tgt):
2622 ' ' in tgt):
2618 showlast.append((alias, tgt))
2623 showlast.append((alias, tgt))
2619 else:
2624 else:
2620 res.append((alias, tgt ))
2625 res.append((alias, tgt ))
2621
2626
2622 # show most interesting aliases last
2627 # show most interesting aliases last
2623 res.extend(showlast)
2628 res.extend(showlast)
2624 print "Total number of aliases:",len(aliases)
2629 print "Total number of aliases:",len(aliases)
2625 return res
2630 return res
2626 try:
2631 try:
2627 alias,cmd = par.split(None,1)
2632 alias,cmd = par.split(None,1)
2628 except:
2633 except:
2629 print OInspect.getdoc(self.magic_alias)
2634 print OInspect.getdoc(self.magic_alias)
2630 else:
2635 else:
2631 nargs = cmd.count('%s')
2636 nargs = cmd.count('%s')
2632 if nargs>0 and cmd.find('%l')>=0:
2637 if nargs>0 and cmd.find('%l')>=0:
2633 error('The %s and %l specifiers are mutually exclusive '
2638 error('The %s and %l specifiers are mutually exclusive '
2634 'in alias definitions.')
2639 'in alias definitions.')
2635 else: # all looks OK
2640 else: # all looks OK
2636 self.shell.alias_table[alias] = (nargs,cmd)
2641 self.shell.alias_table[alias] = (nargs,cmd)
2637 self.shell.alias_table_validate(verbose=0)
2642 self.shell.alias_table_validate(verbose=0)
2638 # end magic_alias
2643 # end magic_alias
2639
2644
2640 def magic_unalias(self, parameter_s = ''):
2645 def magic_unalias(self, parameter_s = ''):
2641 """Remove an alias"""
2646 """Remove an alias"""
2642
2647
2643 aname = parameter_s.strip()
2648 aname = parameter_s.strip()
2644 if aname in self.shell.alias_table:
2649 if aname in self.shell.alias_table:
2645 del self.shell.alias_table[aname]
2650 del self.shell.alias_table[aname]
2646 stored = self.db.get('stored_aliases', {} )
2651 stored = self.db.get('stored_aliases', {} )
2647 if aname in stored:
2652 if aname in stored:
2648 print "Removing %stored alias",aname
2653 print "Removing %stored alias",aname
2649 del stored[aname]
2654 del stored[aname]
2650 self.db['stored_aliases'] = stored
2655 self.db['stored_aliases'] = stored
2651
2656
2652
2657
2653 def magic_rehashx(self, parameter_s = ''):
2658 def magic_rehashx(self, parameter_s = ''):
2654 """Update the alias table with all executable files in $PATH.
2659 """Update the alias table with all executable files in $PATH.
2655
2660
2656 This version explicitly checks that every entry in $PATH is a file
2661 This version explicitly checks that every entry in $PATH is a file
2657 with execute access (os.X_OK), so it is much slower than %rehash.
2662 with execute access (os.X_OK), so it is much slower than %rehash.
2658
2663
2659 Under Windows, it checks executability as a match agains a
2664 Under Windows, it checks executability as a match agains a
2660 '|'-separated string of extensions, stored in the IPython config
2665 '|'-separated string of extensions, stored in the IPython config
2661 variable win_exec_ext. This defaults to 'exe|com|bat'.
2666 variable win_exec_ext. This defaults to 'exe|com|bat'.
2662
2667
2663 This function also resets the root module cache of module completer,
2668 This function also resets the root module cache of module completer,
2664 used on slow filesystems.
2669 used on slow filesystems.
2665 """
2670 """
2666
2671
2667
2672
2668 ip = self.api
2673 ip = self.api
2669
2674
2670 # for the benefit of module completer in ipy_completers.py
2675 # for the benefit of module completer in ipy_completers.py
2671 del ip.db['rootmodules']
2676 del ip.db['rootmodules']
2672
2677
2673 path = [os.path.abspath(os.path.expanduser(p)) for p in
2678 path = [os.path.abspath(os.path.expanduser(p)) for p in
2674 os.environ.get('PATH','').split(os.pathsep)]
2679 os.environ.get('PATH','').split(os.pathsep)]
2675 path = filter(os.path.isdir,path)
2680 path = filter(os.path.isdir,path)
2676
2681
2677 alias_table = self.shell.alias_table
2682 alias_table = self.shell.alias_table
2678 syscmdlist = []
2683 syscmdlist = []
2679 if os.name == 'posix':
2684 if os.name == 'posix':
2680 isexec = lambda fname:os.path.isfile(fname) and \
2685 isexec = lambda fname:os.path.isfile(fname) and \
2681 os.access(fname,os.X_OK)
2686 os.access(fname,os.X_OK)
2682 else:
2687 else:
2683
2688
2684 try:
2689 try:
2685 winext = os.environ['pathext'].replace(';','|').replace('.','')
2690 winext = os.environ['pathext'].replace(';','|').replace('.','')
2686 except KeyError:
2691 except KeyError:
2687 winext = 'exe|com|bat|py'
2692 winext = 'exe|com|bat|py'
2688 if 'py' not in winext:
2693 if 'py' not in winext:
2689 winext += '|py'
2694 winext += '|py'
2690 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2695 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2691 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2696 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2692 savedir = os.getcwd()
2697 savedir = os.getcwd()
2693 try:
2698 try:
2694 # write the whole loop for posix/Windows so we don't have an if in
2699 # write the whole loop for posix/Windows so we don't have an if in
2695 # the innermost part
2700 # the innermost part
2696 if os.name == 'posix':
2701 if os.name == 'posix':
2697 for pdir in path:
2702 for pdir in path:
2698 os.chdir(pdir)
2703 os.chdir(pdir)
2699 for ff in os.listdir(pdir):
2704 for ff in os.listdir(pdir):
2700 if isexec(ff) and ff not in self.shell.no_alias:
2705 if isexec(ff) and ff not in self.shell.no_alias:
2701 # each entry in the alias table must be (N,name),
2706 # each entry in the alias table must be (N,name),
2702 # where N is the number of positional arguments of the
2707 # where N is the number of positional arguments of the
2703 # alias.
2708 # alias.
2704 # Dots will be removed from alias names, since ipython
2709 # Dots will be removed from alias names, since ipython
2705 # assumes names with dots to be python code
2710 # assumes names with dots to be python code
2706 alias_table[ff.replace('.','')] = (0,ff)
2711 alias_table[ff.replace('.','')] = (0,ff)
2707 syscmdlist.append(ff)
2712 syscmdlist.append(ff)
2708 else:
2713 else:
2709 for pdir in path:
2714 for pdir in path:
2710 os.chdir(pdir)
2715 os.chdir(pdir)
2711 for ff in os.listdir(pdir):
2716 for ff in os.listdir(pdir):
2712 base, ext = os.path.splitext(ff)
2717 base, ext = os.path.splitext(ff)
2713 if isexec(ff) and base.lower() not in self.shell.no_alias:
2718 if isexec(ff) and base.lower() not in self.shell.no_alias:
2714 if ext.lower() == '.exe':
2719 if ext.lower() == '.exe':
2715 ff = base
2720 ff = base
2716 alias_table[base.lower().replace('.','')] = (0,ff)
2721 alias_table[base.lower().replace('.','')] = (0,ff)
2717 syscmdlist.append(ff)
2722 syscmdlist.append(ff)
2718 # Make sure the alias table doesn't contain keywords or builtins
2723 # Make sure the alias table doesn't contain keywords or builtins
2719 self.shell.alias_table_validate()
2724 self.shell.alias_table_validate()
2720 # Call again init_auto_alias() so we get 'rm -i' and other
2725 # Call again init_auto_alias() so we get 'rm -i' and other
2721 # modified aliases since %rehashx will probably clobber them
2726 # modified aliases since %rehashx will probably clobber them
2722
2727
2723 # no, we don't want them. if %rehashx clobbers them, good,
2728 # no, we don't want them. if %rehashx clobbers them, good,
2724 # we'll probably get better versions
2729 # we'll probably get better versions
2725 # self.shell.init_auto_alias()
2730 # self.shell.init_auto_alias()
2726 db = ip.db
2731 db = ip.db
2727 db['syscmdlist'] = syscmdlist
2732 db['syscmdlist'] = syscmdlist
2728 finally:
2733 finally:
2729 os.chdir(savedir)
2734 os.chdir(savedir)
2730
2735
2731 def magic_pwd(self, parameter_s = ''):
2736 def magic_pwd(self, parameter_s = ''):
2732 """Return the current working directory path."""
2737 """Return the current working directory path."""
2733 return os.getcwd()
2738 return os.getcwd()
2734
2739
2735 def magic_cd(self, parameter_s=''):
2740 def magic_cd(self, parameter_s=''):
2736 """Change the current working directory.
2741 """Change the current working directory.
2737
2742
2738 This command automatically maintains an internal list of directories
2743 This command automatically maintains an internal list of directories
2739 you visit during your IPython session, in the variable _dh. The
2744 you visit during your IPython session, in the variable _dh. The
2740 command %dhist shows this history nicely formatted. You can also
2745 command %dhist shows this history nicely formatted. You can also
2741 do 'cd -<tab>' to see directory history conveniently.
2746 do 'cd -<tab>' to see directory history conveniently.
2742
2747
2743 Usage:
2748 Usage:
2744
2749
2745 cd 'dir': changes to directory 'dir'.
2750 cd 'dir': changes to directory 'dir'.
2746
2751
2747 cd -: changes to the last visited directory.
2752 cd -: changes to the last visited directory.
2748
2753
2749 cd -<n>: changes to the n-th directory in the directory history.
2754 cd -<n>: changes to the n-th directory in the directory history.
2750
2755
2751 cd --foo: change to directory that matches 'foo' in history
2756 cd --foo: change to directory that matches 'foo' in history
2752
2757
2753 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2758 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2754 (note: cd <bookmark_name> is enough if there is no
2759 (note: cd <bookmark_name> is enough if there is no
2755 directory <bookmark_name>, but a bookmark with the name exists.)
2760 directory <bookmark_name>, but a bookmark with the name exists.)
2756 'cd -b <tab>' allows you to tab-complete bookmark names.
2761 'cd -b <tab>' allows you to tab-complete bookmark names.
2757
2762
2758 Options:
2763 Options:
2759
2764
2760 -q: quiet. Do not print the working directory after the cd command is
2765 -q: quiet. Do not print the working directory after the cd command is
2761 executed. By default IPython's cd command does print this directory,
2766 executed. By default IPython's cd command does print this directory,
2762 since the default prompts do not display path information.
2767 since the default prompts do not display path information.
2763
2768
2764 Note that !cd doesn't work for this purpose because the shell where
2769 Note that !cd doesn't work for this purpose because the shell where
2765 !command runs is immediately discarded after executing 'command'."""
2770 !command runs is immediately discarded after executing 'command'."""
2766
2771
2767 parameter_s = parameter_s.strip()
2772 parameter_s = parameter_s.strip()
2768 #bkms = self.shell.persist.get("bookmarks",{})
2773 #bkms = self.shell.persist.get("bookmarks",{})
2769
2774
2770 oldcwd = os.getcwd()
2775 oldcwd = os.getcwd()
2771 numcd = re.match(r'(-)(\d+)$',parameter_s)
2776 numcd = re.match(r'(-)(\d+)$',parameter_s)
2772 # jump in directory history by number
2777 # jump in directory history by number
2773 if numcd:
2778 if numcd:
2774 nn = int(numcd.group(2))
2779 nn = int(numcd.group(2))
2775 try:
2780 try:
2776 ps = self.shell.user_ns['_dh'][nn]
2781 ps = self.shell.user_ns['_dh'][nn]
2777 except IndexError:
2782 except IndexError:
2778 print 'The requested directory does not exist in history.'
2783 print 'The requested directory does not exist in history.'
2779 return
2784 return
2780 else:
2785 else:
2781 opts = {}
2786 opts = {}
2782 elif parameter_s.startswith('--'):
2787 elif parameter_s.startswith('--'):
2783 ps = None
2788 ps = None
2784 fallback = None
2789 fallback = None
2785 pat = parameter_s[2:]
2790 pat = parameter_s[2:]
2786 dh = self.shell.user_ns['_dh']
2791 dh = self.shell.user_ns['_dh']
2787 # first search only by basename (last component)
2792 # first search only by basename (last component)
2788 for ent in reversed(dh):
2793 for ent in reversed(dh):
2789 if pat in os.path.basename(ent) and os.path.isdir(ent):
2794 if pat in os.path.basename(ent) and os.path.isdir(ent):
2790 ps = ent
2795 ps = ent
2791 break
2796 break
2792
2797
2793 if fallback is None and pat in ent and os.path.isdir(ent):
2798 if fallback is None and pat in ent and os.path.isdir(ent):
2794 fallback = ent
2799 fallback = ent
2795
2800
2796 # if we have no last part match, pick the first full path match
2801 # if we have no last part match, pick the first full path match
2797 if ps is None:
2802 if ps is None:
2798 ps = fallback
2803 ps = fallback
2799
2804
2800 if ps is None:
2805 if ps is None:
2801 print "No matching entry in directory history"
2806 print "No matching entry in directory history"
2802 return
2807 return
2803 else:
2808 else:
2804 opts = {}
2809 opts = {}
2805
2810
2806
2811
2807 else:
2812 else:
2808 #turn all non-space-escaping backslashes to slashes,
2813 #turn all non-space-escaping backslashes to slashes,
2809 # for c:\windows\directory\names\
2814 # for c:\windows\directory\names\
2810 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2815 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2811 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2816 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2812 # jump to previous
2817 # jump to previous
2813 if ps == '-':
2818 if ps == '-':
2814 try:
2819 try:
2815 ps = self.shell.user_ns['_dh'][-2]
2820 ps = self.shell.user_ns['_dh'][-2]
2816 except IndexError:
2821 except IndexError:
2817 raise UsageError('%cd -: No previous directory to change to.')
2822 raise UsageError('%cd -: No previous directory to change to.')
2818 # jump to bookmark if needed
2823 # jump to bookmark if needed
2819 else:
2824 else:
2820 if not os.path.isdir(ps) or opts.has_key('b'):
2825 if not os.path.isdir(ps) or opts.has_key('b'):
2821 bkms = self.db.get('bookmarks', {})
2826 bkms = self.db.get('bookmarks', {})
2822
2827
2823 if bkms.has_key(ps):
2828 if bkms.has_key(ps):
2824 target = bkms[ps]
2829 target = bkms[ps]
2825 print '(bookmark:%s) -> %s' % (ps,target)
2830 print '(bookmark:%s) -> %s' % (ps,target)
2826 ps = target
2831 ps = target
2827 else:
2832 else:
2828 if opts.has_key('b'):
2833 if opts.has_key('b'):
2829 raise UsageError("Bookmark '%s' not found. "
2834 raise UsageError("Bookmark '%s' not found. "
2830 "Use '%%bookmark -l' to see your bookmarks." % ps)
2835 "Use '%%bookmark -l' to see your bookmarks." % ps)
2831
2836
2832 # at this point ps should point to the target dir
2837 # at this point ps should point to the target dir
2833 if ps:
2838 if ps:
2834 try:
2839 try:
2835 os.chdir(os.path.expanduser(ps))
2840 os.chdir(os.path.expanduser(ps))
2836 if self.shell.rc.term_title:
2841 if self.shell.rc.term_title:
2837 #print 'set term title:',self.shell.rc.term_title # dbg
2842 #print 'set term title:',self.shell.rc.term_title # dbg
2838 platutils.set_term_title('IPy ' + abbrev_cwd())
2843 platutils.set_term_title('IPy ' + abbrev_cwd())
2839 except OSError:
2844 except OSError:
2840 print sys.exc_info()[1]
2845 print sys.exc_info()[1]
2841 else:
2846 else:
2842 cwd = os.getcwd()
2847 cwd = os.getcwd()
2843 dhist = self.shell.user_ns['_dh']
2848 dhist = self.shell.user_ns['_dh']
2844 if oldcwd != cwd:
2849 if oldcwd != cwd:
2845 dhist.append(cwd)
2850 dhist.append(cwd)
2846 self.db['dhist'] = compress_dhist(dhist)[-100:]
2851 self.db['dhist'] = compress_dhist(dhist)[-100:]
2847
2852
2848 else:
2853 else:
2849 os.chdir(self.shell.home_dir)
2854 os.chdir(self.shell.home_dir)
2850 if self.shell.rc.term_title:
2855 if self.shell.rc.term_title:
2851 platutils.set_term_title("IPy ~")
2856 platutils.set_term_title("IPy ~")
2852 cwd = os.getcwd()
2857 cwd = os.getcwd()
2853 dhist = self.shell.user_ns['_dh']
2858 dhist = self.shell.user_ns['_dh']
2854
2859
2855 if oldcwd != cwd:
2860 if oldcwd != cwd:
2856 dhist.append(cwd)
2861 dhist.append(cwd)
2857 self.db['dhist'] = compress_dhist(dhist)[-100:]
2862 self.db['dhist'] = compress_dhist(dhist)[-100:]
2858 if not 'q' in opts and self.shell.user_ns['_dh']:
2863 if not 'q' in opts and self.shell.user_ns['_dh']:
2859 print self.shell.user_ns['_dh'][-1]
2864 print self.shell.user_ns['_dh'][-1]
2860
2865
2861
2866
2862 def magic_env(self, parameter_s=''):
2867 def magic_env(self, parameter_s=''):
2863 """List environment variables."""
2868 """List environment variables."""
2864
2869
2865 return os.environ.data
2870 return os.environ.data
2866
2871
2867 def magic_pushd(self, parameter_s=''):
2872 def magic_pushd(self, parameter_s=''):
2868 """Place the current dir on stack and change directory.
2873 """Place the current dir on stack and change directory.
2869
2874
2870 Usage:\\
2875 Usage:\\
2871 %pushd ['dirname']
2876 %pushd ['dirname']
2872 """
2877 """
2873
2878
2874 dir_s = self.shell.dir_stack
2879 dir_s = self.shell.dir_stack
2875 tgt = os.path.expanduser(parameter_s)
2880 tgt = os.path.expanduser(parameter_s)
2876 cwd = os.getcwd().replace(self.home_dir,'~')
2881 cwd = os.getcwd().replace(self.home_dir,'~')
2877 if tgt:
2882 if tgt:
2878 self.magic_cd(parameter_s)
2883 self.magic_cd(parameter_s)
2879 dir_s.insert(0,cwd)
2884 dir_s.insert(0,cwd)
2880 return self.magic_dirs()
2885 return self.magic_dirs()
2881
2886
2882 def magic_popd(self, parameter_s=''):
2887 def magic_popd(self, parameter_s=''):
2883 """Change to directory popped off the top of the stack.
2888 """Change to directory popped off the top of the stack.
2884 """
2889 """
2885 if not self.shell.dir_stack:
2890 if not self.shell.dir_stack:
2886 raise UsageError("%popd on empty stack")
2891 raise UsageError("%popd on empty stack")
2887 top = self.shell.dir_stack.pop(0)
2892 top = self.shell.dir_stack.pop(0)
2888 self.magic_cd(top)
2893 self.magic_cd(top)
2889 print "popd ->",top
2894 print "popd ->",top
2890
2895
2891 def magic_dirs(self, parameter_s=''):
2896 def magic_dirs(self, parameter_s=''):
2892 """Return the current directory stack."""
2897 """Return the current directory stack."""
2893
2898
2894 return self.shell.dir_stack
2899 return self.shell.dir_stack
2895
2900
2896 def magic_dhist(self, parameter_s=''):
2901 def magic_dhist(self, parameter_s=''):
2897 """Print your history of visited directories.
2902 """Print your history of visited directories.
2898
2903
2899 %dhist -> print full history\\
2904 %dhist -> print full history\\
2900 %dhist n -> print last n entries only\\
2905 %dhist n -> print last n entries only\\
2901 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2906 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2902
2907
2903 This history is automatically maintained by the %cd command, and
2908 This history is automatically maintained by the %cd command, and
2904 always available as the global list variable _dh. You can use %cd -<n>
2909 always available as the global list variable _dh. You can use %cd -<n>
2905 to go to directory number <n>.
2910 to go to directory number <n>.
2906
2911
2907 Note that most of time, you should view directory history by entering
2912 Note that most of time, you should view directory history by entering
2908 cd -<TAB>.
2913 cd -<TAB>.
2909
2914
2910 """
2915 """
2911
2916
2912 dh = self.shell.user_ns['_dh']
2917 dh = self.shell.user_ns['_dh']
2913 if parameter_s:
2918 if parameter_s:
2914 try:
2919 try:
2915 args = map(int,parameter_s.split())
2920 args = map(int,parameter_s.split())
2916 except:
2921 except:
2917 self.arg_err(Magic.magic_dhist)
2922 self.arg_err(Magic.magic_dhist)
2918 return
2923 return
2919 if len(args) == 1:
2924 if len(args) == 1:
2920 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2925 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2921 elif len(args) == 2:
2926 elif len(args) == 2:
2922 ini,fin = args
2927 ini,fin = args
2923 else:
2928 else:
2924 self.arg_err(Magic.magic_dhist)
2929 self.arg_err(Magic.magic_dhist)
2925 return
2930 return
2926 else:
2931 else:
2927 ini,fin = 0,len(dh)
2932 ini,fin = 0,len(dh)
2928 nlprint(dh,
2933 nlprint(dh,
2929 header = 'Directory history (kept in _dh)',
2934 header = 'Directory history (kept in _dh)',
2930 start=ini,stop=fin)
2935 start=ini,stop=fin)
2931
2936
2932 @testdec.skip_doctest
2937 @testdec.skip_doctest
2933 def magic_sc(self, parameter_s=''):
2938 def magic_sc(self, parameter_s=''):
2934 """Shell capture - execute a shell command and capture its output.
2939 """Shell capture - execute a shell command and capture its output.
2935
2940
2936 DEPRECATED. Suboptimal, retained for backwards compatibility.
2941 DEPRECATED. Suboptimal, retained for backwards compatibility.
2937
2942
2938 You should use the form 'var = !command' instead. Example:
2943 You should use the form 'var = !command' instead. Example:
2939
2944
2940 "%sc -l myfiles = ls ~" should now be written as
2945 "%sc -l myfiles = ls ~" should now be written as
2941
2946
2942 "myfiles = !ls ~"
2947 "myfiles = !ls ~"
2943
2948
2944 myfiles.s, myfiles.l and myfiles.n still apply as documented
2949 myfiles.s, myfiles.l and myfiles.n still apply as documented
2945 below.
2950 below.
2946
2951
2947 --
2952 --
2948 %sc [options] varname=command
2953 %sc [options] varname=command
2949
2954
2950 IPython will run the given command using commands.getoutput(), and
2955 IPython will run the given command using commands.getoutput(), and
2951 will then update the user's interactive namespace with a variable
2956 will then update the user's interactive namespace with a variable
2952 called varname, containing the value of the call. Your command can
2957 called varname, containing the value of the call. Your command can
2953 contain shell wildcards, pipes, etc.
2958 contain shell wildcards, pipes, etc.
2954
2959
2955 The '=' sign in the syntax is mandatory, and the variable name you
2960 The '=' sign in the syntax is mandatory, and the variable name you
2956 supply must follow Python's standard conventions for valid names.
2961 supply must follow Python's standard conventions for valid names.
2957
2962
2958 (A special format without variable name exists for internal use)
2963 (A special format without variable name exists for internal use)
2959
2964
2960 Options:
2965 Options:
2961
2966
2962 -l: list output. Split the output on newlines into a list before
2967 -l: list output. Split the output on newlines into a list before
2963 assigning it to the given variable. By default the output is stored
2968 assigning it to the given variable. By default the output is stored
2964 as a single string.
2969 as a single string.
2965
2970
2966 -v: verbose. Print the contents of the variable.
2971 -v: verbose. Print the contents of the variable.
2967
2972
2968 In most cases you should not need to split as a list, because the
2973 In most cases you should not need to split as a list, because the
2969 returned value is a special type of string which can automatically
2974 returned value is a special type of string which can automatically
2970 provide its contents either as a list (split on newlines) or as a
2975 provide its contents either as a list (split on newlines) or as a
2971 space-separated string. These are convenient, respectively, either
2976 space-separated string. These are convenient, respectively, either
2972 for sequential processing or to be passed to a shell command.
2977 for sequential processing or to be passed to a shell command.
2973
2978
2974 For example:
2979 For example:
2975
2980
2976 # all-random
2981 # all-random
2977
2982
2978 # Capture into variable a
2983 # Capture into variable a
2979 In [1]: sc a=ls *py
2984 In [1]: sc a=ls *py
2980
2985
2981 # a is a string with embedded newlines
2986 # a is a string with embedded newlines
2982 In [2]: a
2987 In [2]: a
2983 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2988 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2984
2989
2985 # which can be seen as a list:
2990 # which can be seen as a list:
2986 In [3]: a.l
2991 In [3]: a.l
2987 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2992 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2988
2993
2989 # or as a whitespace-separated string:
2994 # or as a whitespace-separated string:
2990 In [4]: a.s
2995 In [4]: a.s
2991 Out[4]: 'setup.py win32_manual_post_install.py'
2996 Out[4]: 'setup.py win32_manual_post_install.py'
2992
2997
2993 # a.s is useful to pass as a single command line:
2998 # a.s is useful to pass as a single command line:
2994 In [5]: !wc -l $a.s
2999 In [5]: !wc -l $a.s
2995 146 setup.py
3000 146 setup.py
2996 130 win32_manual_post_install.py
3001 130 win32_manual_post_install.py
2997 276 total
3002 276 total
2998
3003
2999 # while the list form is useful to loop over:
3004 # while the list form is useful to loop over:
3000 In [6]: for f in a.l:
3005 In [6]: for f in a.l:
3001 ...: !wc -l $f
3006 ...: !wc -l $f
3002 ...:
3007 ...:
3003 146 setup.py
3008 146 setup.py
3004 130 win32_manual_post_install.py
3009 130 win32_manual_post_install.py
3005
3010
3006 Similiarly, the lists returned by the -l option are also special, in
3011 Similiarly, the lists returned by the -l option are also special, in
3007 the sense that you can equally invoke the .s attribute on them to
3012 the sense that you can equally invoke the .s attribute on them to
3008 automatically get a whitespace-separated string from their contents:
3013 automatically get a whitespace-separated string from their contents:
3009
3014
3010 In [7]: sc -l b=ls *py
3015 In [7]: sc -l b=ls *py
3011
3016
3012 In [8]: b
3017 In [8]: b
3013 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3018 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3014
3019
3015 In [9]: b.s
3020 In [9]: b.s
3016 Out[9]: 'setup.py win32_manual_post_install.py'
3021 Out[9]: 'setup.py win32_manual_post_install.py'
3017
3022
3018 In summary, both the lists and strings used for ouptut capture have
3023 In summary, both the lists and strings used for ouptut capture have
3019 the following special attributes:
3024 the following special attributes:
3020
3025
3021 .l (or .list) : value as list.
3026 .l (or .list) : value as list.
3022 .n (or .nlstr): value as newline-separated string.
3027 .n (or .nlstr): value as newline-separated string.
3023 .s (or .spstr): value as space-separated string.
3028 .s (or .spstr): value as space-separated string.
3024 """
3029 """
3025
3030
3026 opts,args = self.parse_options(parameter_s,'lv')
3031 opts,args = self.parse_options(parameter_s,'lv')
3027 # Try to get a variable name and command to run
3032 # Try to get a variable name and command to run
3028 try:
3033 try:
3029 # the variable name must be obtained from the parse_options
3034 # the variable name must be obtained from the parse_options
3030 # output, which uses shlex.split to strip options out.
3035 # output, which uses shlex.split to strip options out.
3031 var,_ = args.split('=',1)
3036 var,_ = args.split('=',1)
3032 var = var.strip()
3037 var = var.strip()
3033 # But the the command has to be extracted from the original input
3038 # But the the command has to be extracted from the original input
3034 # parameter_s, not on what parse_options returns, to avoid the
3039 # parameter_s, not on what parse_options returns, to avoid the
3035 # quote stripping which shlex.split performs on it.
3040 # quote stripping which shlex.split performs on it.
3036 _,cmd = parameter_s.split('=',1)
3041 _,cmd = parameter_s.split('=',1)
3037 except ValueError:
3042 except ValueError:
3038 var,cmd = '',''
3043 var,cmd = '',''
3039 # If all looks ok, proceed
3044 # If all looks ok, proceed
3040 out,err = self.shell.getoutputerror(cmd)
3045 out,err = self.shell.getoutputerror(cmd)
3041 if err:
3046 if err:
3042 print >> Term.cerr,err
3047 print >> Term.cerr,err
3043 if opts.has_key('l'):
3048 if opts.has_key('l'):
3044 out = SList(out.split('\n'))
3049 out = SList(out.split('\n'))
3045 else:
3050 else:
3046 out = LSString(out)
3051 out = LSString(out)
3047 if opts.has_key('v'):
3052 if opts.has_key('v'):
3048 print '%s ==\n%s' % (var,pformat(out))
3053 print '%s ==\n%s' % (var,pformat(out))
3049 if var:
3054 if var:
3050 self.shell.user_ns.update({var:out})
3055 self.shell.user_ns.update({var:out})
3051 else:
3056 else:
3052 return out
3057 return out
3053
3058
3054 def magic_sx(self, parameter_s=''):
3059 def magic_sx(self, parameter_s=''):
3055 """Shell execute - run a shell command and capture its output.
3060 """Shell execute - run a shell command and capture its output.
3056
3061
3057 %sx command
3062 %sx command
3058
3063
3059 IPython will run the given command using commands.getoutput(), and
3064 IPython will run the given command using commands.getoutput(), and
3060 return the result formatted as a list (split on '\\n'). Since the
3065 return the result formatted as a list (split on '\\n'). Since the
3061 output is _returned_, it will be stored in ipython's regular output
3066 output is _returned_, it will be stored in ipython's regular output
3062 cache Out[N] and in the '_N' automatic variables.
3067 cache Out[N] and in the '_N' automatic variables.
3063
3068
3064 Notes:
3069 Notes:
3065
3070
3066 1) If an input line begins with '!!', then %sx is automatically
3071 1) If an input line begins with '!!', then %sx is automatically
3067 invoked. That is, while:
3072 invoked. That is, while:
3068 !ls
3073 !ls
3069 causes ipython to simply issue system('ls'), typing
3074 causes ipython to simply issue system('ls'), typing
3070 !!ls
3075 !!ls
3071 is a shorthand equivalent to:
3076 is a shorthand equivalent to:
3072 %sx ls
3077 %sx ls
3073
3078
3074 2) %sx differs from %sc in that %sx automatically splits into a list,
3079 2) %sx differs from %sc in that %sx automatically splits into a list,
3075 like '%sc -l'. The reason for this is to make it as easy as possible
3080 like '%sc -l'. The reason for this is to make it as easy as possible
3076 to process line-oriented shell output via further python commands.
3081 to process line-oriented shell output via further python commands.
3077 %sc is meant to provide much finer control, but requires more
3082 %sc is meant to provide much finer control, but requires more
3078 typing.
3083 typing.
3079
3084
3080 3) Just like %sc -l, this is a list with special attributes:
3085 3) Just like %sc -l, this is a list with special attributes:
3081
3086
3082 .l (or .list) : value as list.
3087 .l (or .list) : value as list.
3083 .n (or .nlstr): value as newline-separated string.
3088 .n (or .nlstr): value as newline-separated string.
3084 .s (or .spstr): value as whitespace-separated string.
3089 .s (or .spstr): value as whitespace-separated string.
3085
3090
3086 This is very useful when trying to use such lists as arguments to
3091 This is very useful when trying to use such lists as arguments to
3087 system commands."""
3092 system commands."""
3088
3093
3089 if parameter_s:
3094 if parameter_s:
3090 out,err = self.shell.getoutputerror(parameter_s)
3095 out,err = self.shell.getoutputerror(parameter_s)
3091 if err:
3096 if err:
3092 print >> Term.cerr,err
3097 print >> Term.cerr,err
3093 return SList(out.split('\n'))
3098 return SList(out.split('\n'))
3094
3099
3095 def magic_bg(self, parameter_s=''):
3100 def magic_bg(self, parameter_s=''):
3096 """Run a job in the background, in a separate thread.
3101 """Run a job in the background, in a separate thread.
3097
3102
3098 For example,
3103 For example,
3099
3104
3100 %bg myfunc(x,y,z=1)
3105 %bg myfunc(x,y,z=1)
3101
3106
3102 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3107 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3103 execution starts, a message will be printed indicating the job
3108 execution starts, a message will be printed indicating the job
3104 number. If your job number is 5, you can use
3109 number. If your job number is 5, you can use
3105
3110
3106 myvar = jobs.result(5) or myvar = jobs[5].result
3111 myvar = jobs.result(5) or myvar = jobs[5].result
3107
3112
3108 to assign this result to variable 'myvar'.
3113 to assign this result to variable 'myvar'.
3109
3114
3110 IPython has a job manager, accessible via the 'jobs' object. You can
3115 IPython has a job manager, accessible via the 'jobs' object. You can
3111 type jobs? to get more information about it, and use jobs.<TAB> to see
3116 type jobs? to get more information about it, and use jobs.<TAB> to see
3112 its attributes. All attributes not starting with an underscore are
3117 its attributes. All attributes not starting with an underscore are
3113 meant for public use.
3118 meant for public use.
3114
3119
3115 In particular, look at the jobs.new() method, which is used to create
3120 In particular, look at the jobs.new() method, which is used to create
3116 new jobs. This magic %bg function is just a convenience wrapper
3121 new jobs. This magic %bg function is just a convenience wrapper
3117 around jobs.new(), for expression-based jobs. If you want to create a
3122 around jobs.new(), for expression-based jobs. If you want to create a
3118 new job with an explicit function object and arguments, you must call
3123 new job with an explicit function object and arguments, you must call
3119 jobs.new() directly.
3124 jobs.new() directly.
3120
3125
3121 The jobs.new docstring also describes in detail several important
3126 The jobs.new docstring also describes in detail several important
3122 caveats associated with a thread-based model for background job
3127 caveats associated with a thread-based model for background job
3123 execution. Type jobs.new? for details.
3128 execution. Type jobs.new? for details.
3124
3129
3125 You can check the status of all jobs with jobs.status().
3130 You can check the status of all jobs with jobs.status().
3126
3131
3127 The jobs variable is set by IPython into the Python builtin namespace.
3132 The jobs variable is set by IPython into the Python builtin namespace.
3128 If you ever declare a variable named 'jobs', you will shadow this
3133 If you ever declare a variable named 'jobs', you will shadow this
3129 name. You can either delete your global jobs variable to regain
3134 name. You can either delete your global jobs variable to regain
3130 access to the job manager, or make a new name and assign it manually
3135 access to the job manager, or make a new name and assign it manually
3131 to the manager (stored in IPython's namespace). For example, to
3136 to the manager (stored in IPython's namespace). For example, to
3132 assign the job manager to the Jobs name, use:
3137 assign the job manager to the Jobs name, use:
3133
3138
3134 Jobs = __builtins__.jobs"""
3139 Jobs = __builtins__.jobs"""
3135
3140
3136 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3141 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3137
3142
3138 def magic_r(self, parameter_s=''):
3143 def magic_r(self, parameter_s=''):
3139 """Repeat previous input.
3144 """Repeat previous input.
3140
3145
3141 Note: Consider using the more powerfull %rep instead!
3146 Note: Consider using the more powerfull %rep instead!
3142
3147
3143 If given an argument, repeats the previous command which starts with
3148 If given an argument, repeats the previous command which starts with
3144 the same string, otherwise it just repeats the previous input.
3149 the same string, otherwise it just repeats the previous input.
3145
3150
3146 Shell escaped commands (with ! as first character) are not recognized
3151 Shell escaped commands (with ! as first character) are not recognized
3147 by this system, only pure python code and magic commands.
3152 by this system, only pure python code and magic commands.
3148 """
3153 """
3149
3154
3150 start = parameter_s.strip()
3155 start = parameter_s.strip()
3151 esc_magic = self.shell.ESC_MAGIC
3156 esc_magic = self.shell.ESC_MAGIC
3152 # Identify magic commands even if automagic is on (which means
3157 # Identify magic commands even if automagic is on (which means
3153 # the in-memory version is different from that typed by the user).
3158 # the in-memory version is different from that typed by the user).
3154 if self.shell.rc.automagic:
3159 if self.shell.rc.automagic:
3155 start_magic = esc_magic+start
3160 start_magic = esc_magic+start
3156 else:
3161 else:
3157 start_magic = start
3162 start_magic = start
3158 # Look through the input history in reverse
3163 # Look through the input history in reverse
3159 for n in range(len(self.shell.input_hist)-2,0,-1):
3164 for n in range(len(self.shell.input_hist)-2,0,-1):
3160 input = self.shell.input_hist[n]
3165 input = self.shell.input_hist[n]
3161 # skip plain 'r' lines so we don't recurse to infinity
3166 # skip plain 'r' lines so we don't recurse to infinity
3162 if input != '_ip.magic("r")\n' and \
3167 if input != '_ip.magic("r")\n' and \
3163 (input.startswith(start) or input.startswith(start_magic)):
3168 (input.startswith(start) or input.startswith(start_magic)):
3164 #print 'match',`input` # dbg
3169 #print 'match',`input` # dbg
3165 print 'Executing:',input,
3170 print 'Executing:',input,
3166 self.shell.runlines(input)
3171 self.shell.runlines(input)
3167 return
3172 return
3168 print 'No previous input matching `%s` found.' % start
3173 print 'No previous input matching `%s` found.' % start
3169
3174
3170
3175
3171 def magic_bookmark(self, parameter_s=''):
3176 def magic_bookmark(self, parameter_s=''):
3172 """Manage IPython's bookmark system.
3177 """Manage IPython's bookmark system.
3173
3178
3174 %bookmark <name> - set bookmark to current dir
3179 %bookmark <name> - set bookmark to current dir
3175 %bookmark <name> <dir> - set bookmark to <dir>
3180 %bookmark <name> <dir> - set bookmark to <dir>
3176 %bookmark -l - list all bookmarks
3181 %bookmark -l - list all bookmarks
3177 %bookmark -d <name> - remove bookmark
3182 %bookmark -d <name> - remove bookmark
3178 %bookmark -r - remove all bookmarks
3183 %bookmark -r - remove all bookmarks
3179
3184
3180 You can later on access a bookmarked folder with:
3185 You can later on access a bookmarked folder with:
3181 %cd -b <name>
3186 %cd -b <name>
3182 or simply '%cd <name>' if there is no directory called <name> AND
3187 or simply '%cd <name>' if there is no directory called <name> AND
3183 there is such a bookmark defined.
3188 there is such a bookmark defined.
3184
3189
3185 Your bookmarks persist through IPython sessions, but they are
3190 Your bookmarks persist through IPython sessions, but they are
3186 associated with each profile."""
3191 associated with each profile."""
3187
3192
3188 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3193 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3189 if len(args) > 2:
3194 if len(args) > 2:
3190 raise UsageError("%bookmark: too many arguments")
3195 raise UsageError("%bookmark: too many arguments")
3191
3196
3192 bkms = self.db.get('bookmarks',{})
3197 bkms = self.db.get('bookmarks',{})
3193
3198
3194 if opts.has_key('d'):
3199 if opts.has_key('d'):
3195 try:
3200 try:
3196 todel = args[0]
3201 todel = args[0]
3197 except IndexError:
3202 except IndexError:
3198 raise UsageError(
3203 raise UsageError(
3199 "%bookmark -d: must provide a bookmark to delete")
3204 "%bookmark -d: must provide a bookmark to delete")
3200 else:
3205 else:
3201 try:
3206 try:
3202 del bkms[todel]
3207 del bkms[todel]
3203 except KeyError:
3208 except KeyError:
3204 raise UsageError(
3209 raise UsageError(
3205 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3210 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3206
3211
3207 elif opts.has_key('r'):
3212 elif opts.has_key('r'):
3208 bkms = {}
3213 bkms = {}
3209 elif opts.has_key('l'):
3214 elif opts.has_key('l'):
3210 bks = bkms.keys()
3215 bks = bkms.keys()
3211 bks.sort()
3216 bks.sort()
3212 if bks:
3217 if bks:
3213 size = max(map(len,bks))
3218 size = max(map(len,bks))
3214 else:
3219 else:
3215 size = 0
3220 size = 0
3216 fmt = '%-'+str(size)+'s -> %s'
3221 fmt = '%-'+str(size)+'s -> %s'
3217 print 'Current bookmarks:'
3222 print 'Current bookmarks:'
3218 for bk in bks:
3223 for bk in bks:
3219 print fmt % (bk,bkms[bk])
3224 print fmt % (bk,bkms[bk])
3220 else:
3225 else:
3221 if not args:
3226 if not args:
3222 raise UsageError("%bookmark: You must specify the bookmark name")
3227 raise UsageError("%bookmark: You must specify the bookmark name")
3223 elif len(args)==1:
3228 elif len(args)==1:
3224 bkms[args[0]] = os.getcwd()
3229 bkms[args[0]] = os.getcwd()
3225 elif len(args)==2:
3230 elif len(args)==2:
3226 bkms[args[0]] = args[1]
3231 bkms[args[0]] = args[1]
3227 self.db['bookmarks'] = bkms
3232 self.db['bookmarks'] = bkms
3228
3233
3229 def magic_pycat(self, parameter_s=''):
3234 def magic_pycat(self, parameter_s=''):
3230 """Show a syntax-highlighted file through a pager.
3235 """Show a syntax-highlighted file through a pager.
3231
3236
3232 This magic is similar to the cat utility, but it will assume the file
3237 This magic is similar to the cat utility, but it will assume the file
3233 to be Python source and will show it with syntax highlighting. """
3238 to be Python source and will show it with syntax highlighting. """
3234
3239
3235 try:
3240 try:
3236 filename = get_py_filename(parameter_s)
3241 filename = get_py_filename(parameter_s)
3237 cont = file_read(filename)
3242 cont = file_read(filename)
3238 except IOError:
3243 except IOError:
3239 try:
3244 try:
3240 cont = eval(parameter_s,self.user_ns)
3245 cont = eval(parameter_s,self.user_ns)
3241 except NameError:
3246 except NameError:
3242 cont = None
3247 cont = None
3243 if cont is None:
3248 if cont is None:
3244 print "Error: no such file or variable"
3249 print "Error: no such file or variable"
3245 return
3250 return
3246
3251
3247 page(self.shell.pycolorize(cont),
3252 page(self.shell.pycolorize(cont),
3248 screen_lines=self.shell.rc.screen_length)
3253 screen_lines=self.shell.rc.screen_length)
3249
3254
3250 def magic_cpaste(self, parameter_s=''):
3255 def magic_cpaste(self, parameter_s=''):
3251 """Allows you to paste & execute a pre-formatted code block from clipboard.
3256 """Allows you to paste & execute a pre-formatted code block from clipboard.
3252
3257
3253 You must terminate the block with '--' (two minus-signs) alone on the
3258 You must terminate the block with '--' (two minus-signs) alone on the
3254 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3259 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3255 is the new sentinel for this operation)
3260 is the new sentinel for this operation)
3256
3261
3257 The block is dedented prior to execution to enable execution of method
3262 The block is dedented prior to execution to enable execution of method
3258 definitions. '>' and '+' characters at the beginning of a line are
3263 definitions. '>' and '+' characters at the beginning of a line are
3259 ignored, to allow pasting directly from e-mails, diff files and
3264 ignored, to allow pasting directly from e-mails, diff files and
3260 doctests (the '...' continuation prompt is also stripped). The
3265 doctests (the '...' continuation prompt is also stripped). The
3261 executed block is also assigned to variable named 'pasted_block' for
3266 executed block is also assigned to variable named 'pasted_block' for
3262 later editing with '%edit pasted_block'.
3267 later editing with '%edit pasted_block'.
3263
3268
3264 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3269 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3265 This assigns the pasted block to variable 'foo' as string, without
3270 This assigns the pasted block to variable 'foo' as string, without
3266 dedenting or executing it (preceding >>> and + is still stripped)
3271 dedenting or executing it (preceding >>> and + is still stripped)
3267
3272
3268 '%cpaste -r' re-executes the block previously entered by cpaste.
3273 '%cpaste -r' re-executes the block previously entered by cpaste.
3269
3274
3270 Do not be alarmed by garbled output on Windows (it's a readline bug).
3275 Do not be alarmed by garbled output on Windows (it's a readline bug).
3271 Just press enter and type -- (and press enter again) and the block
3276 Just press enter and type -- (and press enter again) and the block
3272 will be what was just pasted.
3277 will be what was just pasted.
3273
3278
3274 IPython statements (magics, shell escapes) are not supported (yet).
3279 IPython statements (magics, shell escapes) are not supported (yet).
3275 """
3280 """
3276 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3281 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3277 par = args.strip()
3282 par = args.strip()
3278 if opts.has_key('r'):
3283 if opts.has_key('r'):
3279 b = self.user_ns.get('pasted_block', None)
3284 b = self.user_ns.get('pasted_block', None)
3280 if b is None:
3285 if b is None:
3281 raise UsageError('No previous pasted block available')
3286 raise UsageError('No previous pasted block available')
3282 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3287 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3283 exec b in self.user_ns
3288 exec b in self.user_ns
3284 return
3289 return
3285
3290
3286 sentinel = opts.get('s','--')
3291 sentinel = opts.get('s','--')
3287
3292
3288 # Regular expressions that declare text we strip from the input:
3293 # Regular expressions that declare text we strip from the input:
3289 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3294 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3290 r'^\s*(\s?>)+', # Python input prompt
3295 r'^\s*(\s?>)+', # Python input prompt
3291 r'^\s*\.{3,}', # Continuation prompts
3296 r'^\s*\.{3,}', # Continuation prompts
3292 r'^\++',
3297 r'^\++',
3293 ]
3298 ]
3294
3299
3295 strip_from_start = map(re.compile,strip_re)
3300 strip_from_start = map(re.compile,strip_re)
3296
3301
3297 from IPython import iplib
3302 from IPython import iplib
3298 lines = []
3303 lines = []
3299 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3304 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3300 while 1:
3305 while 1:
3301 l = iplib.raw_input_original(':')
3306 l = iplib.raw_input_original(':')
3302 if l ==sentinel:
3307 if l ==sentinel:
3303 break
3308 break
3304
3309
3305 for pat in strip_from_start:
3310 for pat in strip_from_start:
3306 l = pat.sub('',l)
3311 l = pat.sub('',l)
3307 lines.append(l)
3312 lines.append(l)
3308
3313
3309 block = "\n".join(lines) + '\n'
3314 block = "\n".join(lines) + '\n'
3310 #print "block:\n",block
3315 #print "block:\n",block
3311 if not par:
3316 if not par:
3312 b = textwrap.dedent(block)
3317 b = textwrap.dedent(block)
3313 self.user_ns['pasted_block'] = b
3318 self.user_ns['pasted_block'] = b
3314 exec b in self.user_ns
3319 exec b in self.user_ns
3315 else:
3320 else:
3316 self.user_ns[par] = SList(block.splitlines())
3321 self.user_ns[par] = SList(block.splitlines())
3317 print "Block assigned to '%s'" % par
3322 print "Block assigned to '%s'" % par
3318
3323
3319 def magic_quickref(self,arg):
3324 def magic_quickref(self,arg):
3320 """ Show a quick reference sheet """
3325 """ Show a quick reference sheet """
3321 import IPython.usage
3326 import IPython.usage
3322 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3327 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3323
3328
3324 page(qr)
3329 page(qr)
3325
3330
3326 def magic_upgrade(self,arg):
3331 def magic_upgrade(self,arg):
3327 """ Upgrade your IPython installation
3332 """ Upgrade your IPython installation
3328
3333
3329 This will copy the config files that don't yet exist in your
3334 This will copy the config files that don't yet exist in your
3330 ipython dir from the system config dir. Use this after upgrading
3335 ipython dir from the system config dir. Use this after upgrading
3331 IPython if you don't wish to delete your .ipython dir.
3336 IPython if you don't wish to delete your .ipython dir.
3332
3337
3333 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3338 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3334 new users)
3339 new users)
3335
3340
3336 """
3341 """
3337 ip = self.getapi()
3342 ip = self.getapi()
3338 ipinstallation = path(IPython.__file__).dirname()
3343 ipinstallation = path(IPython.__file__).dirname()
3339 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3344 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3340 src_config = ipinstallation / 'UserConfig'
3345 src_config = ipinstallation / 'UserConfig'
3341 userdir = path(ip.options.ipythondir)
3346 userdir = path(ip.options.ipythondir)
3342 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3347 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3343 print ">",cmd
3348 print ">",cmd
3344 shell(cmd)
3349 shell(cmd)
3345 if arg == '-nolegacy':
3350 if arg == '-nolegacy':
3346 legacy = userdir.files('ipythonrc*')
3351 legacy = userdir.files('ipythonrc*')
3347 print "Nuking legacy files:",legacy
3352 print "Nuking legacy files:",legacy
3348
3353
3349 [p.remove() for p in legacy]
3354 [p.remove() for p in legacy]
3350 suffix = (sys.platform == 'win32' and '.ini' or '')
3355 suffix = (sys.platform == 'win32' and '.ini' or '')
3351 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3356 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3352
3357
3353
3358
3354 def magic_doctest_mode(self,parameter_s=''):
3359 def magic_doctest_mode(self,parameter_s=''):
3355 """Toggle doctest mode on and off.
3360 """Toggle doctest mode on and off.
3356
3361
3357 This mode allows you to toggle the prompt behavior between normal
3362 This mode allows you to toggle the prompt behavior between normal
3358 IPython prompts and ones that are as similar to the default IPython
3363 IPython prompts and ones that are as similar to the default IPython
3359 interpreter as possible.
3364 interpreter as possible.
3360
3365
3361 It also supports the pasting of code snippets that have leading '>>>'
3366 It also supports the pasting of code snippets that have leading '>>>'
3362 and '...' prompts in them. This means that you can paste doctests from
3367 and '...' prompts in them. This means that you can paste doctests from
3363 files or docstrings (even if they have leading whitespace), and the
3368 files or docstrings (even if they have leading whitespace), and the
3364 code will execute correctly. You can then use '%history -tn' to see
3369 code will execute correctly. You can then use '%history -tn' to see
3365 the translated history without line numbers; this will give you the
3370 the translated history without line numbers; this will give you the
3366 input after removal of all the leading prompts and whitespace, which
3371 input after removal of all the leading prompts and whitespace, which
3367 can be pasted back into an editor.
3372 can be pasted back into an editor.
3368
3373
3369 With these features, you can switch into this mode easily whenever you
3374 With these features, you can switch into this mode easily whenever you
3370 need to do testing and changes to doctests, without having to leave
3375 need to do testing and changes to doctests, without having to leave
3371 your existing IPython session.
3376 your existing IPython session.
3372 """
3377 """
3373
3378
3374 # XXX - Fix this to have cleaner activate/deactivate calls.
3379 # XXX - Fix this to have cleaner activate/deactivate calls.
3375 from IPython.Extensions import InterpreterPasteInput as ipaste
3380 from IPython.Extensions import InterpreterPasteInput as ipaste
3376 from IPython.ipstruct import Struct
3381 from IPython.ipstruct import Struct
3377
3382
3378 # Shorthands
3383 # Shorthands
3379 shell = self.shell
3384 shell = self.shell
3380 oc = shell.outputcache
3385 oc = shell.outputcache
3381 rc = shell.rc
3386 rc = shell.rc
3382 meta = shell.meta
3387 meta = shell.meta
3383 # dstore is a data store kept in the instance metadata bag to track any
3388 # dstore is a data store kept in the instance metadata bag to track any
3384 # changes we make, so we can undo them later.
3389 # changes we make, so we can undo them later.
3385 dstore = meta.setdefault('doctest_mode',Struct())
3390 dstore = meta.setdefault('doctest_mode',Struct())
3386 save_dstore = dstore.setdefault
3391 save_dstore = dstore.setdefault
3387
3392
3388 # save a few values we'll need to recover later
3393 # save a few values we'll need to recover later
3389 mode = save_dstore('mode',False)
3394 mode = save_dstore('mode',False)
3390 save_dstore('rc_pprint',rc.pprint)
3395 save_dstore('rc_pprint',rc.pprint)
3391 save_dstore('xmode',shell.InteractiveTB.mode)
3396 save_dstore('xmode',shell.InteractiveTB.mode)
3392 save_dstore('rc_separate_out',rc.separate_out)
3397 save_dstore('rc_separate_out',rc.separate_out)
3393 save_dstore('rc_separate_out2',rc.separate_out2)
3398 save_dstore('rc_separate_out2',rc.separate_out2)
3394 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3399 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3395 save_dstore('rc_separate_in',rc.separate_in)
3400 save_dstore('rc_separate_in',rc.separate_in)
3396
3401
3397 if mode == False:
3402 if mode == False:
3398 # turn on
3403 # turn on
3399 ipaste.activate_prefilter()
3404 ipaste.activate_prefilter()
3400
3405
3401 oc.prompt1.p_template = '>>> '
3406 oc.prompt1.p_template = '>>> '
3402 oc.prompt2.p_template = '... '
3407 oc.prompt2.p_template = '... '
3403 oc.prompt_out.p_template = ''
3408 oc.prompt_out.p_template = ''
3404
3409
3405 # Prompt separators like plain python
3410 # Prompt separators like plain python
3406 oc.input_sep = oc.prompt1.sep = ''
3411 oc.input_sep = oc.prompt1.sep = ''
3407 oc.output_sep = ''
3412 oc.output_sep = ''
3408 oc.output_sep2 = ''
3413 oc.output_sep2 = ''
3409
3414
3410 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3415 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3411 oc.prompt_out.pad_left = False
3416 oc.prompt_out.pad_left = False
3412
3417
3413 rc.pprint = False
3418 rc.pprint = False
3414
3419
3415 shell.magic_xmode('Plain')
3420 shell.magic_xmode('Plain')
3416
3421
3417 else:
3422 else:
3418 # turn off
3423 # turn off
3419 ipaste.deactivate_prefilter()
3424 ipaste.deactivate_prefilter()
3420
3425
3421 oc.prompt1.p_template = rc.prompt_in1
3426 oc.prompt1.p_template = rc.prompt_in1
3422 oc.prompt2.p_template = rc.prompt_in2
3427 oc.prompt2.p_template = rc.prompt_in2
3423 oc.prompt_out.p_template = rc.prompt_out
3428 oc.prompt_out.p_template = rc.prompt_out
3424
3429
3425 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3430 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3426
3431
3427 oc.output_sep = dstore.rc_separate_out
3432 oc.output_sep = dstore.rc_separate_out
3428 oc.output_sep2 = dstore.rc_separate_out2
3433 oc.output_sep2 = dstore.rc_separate_out2
3429
3434
3430 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3435 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3431 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3436 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3432
3437
3433 rc.pprint = dstore.rc_pprint
3438 rc.pprint = dstore.rc_pprint
3434
3439
3435 shell.magic_xmode(dstore.xmode)
3440 shell.magic_xmode(dstore.xmode)
3436
3441
3437 # Store new mode and inform
3442 # Store new mode and inform
3438 dstore.mode = bool(1-int(mode))
3443 dstore.mode = bool(1-int(mode))
3439 print 'Doctest mode is:',
3444 print 'Doctest mode is:',
3440 print ['OFF','ON'][dstore.mode]
3445 print ['OFF','ON'][dstore.mode]
3441
3446
3442 # end Magic
3447 # end Magic
@@ -1,2839 +1,2865 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.4 or newer.
5 Requires Python 2.4 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # 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
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #
16 #
17 # Note: this code originally subclassed code.InteractiveConsole from the
17 # Note: this code originally subclassed code.InteractiveConsole from the
18 # Python standard library. Over time, all of that class has been copied
18 # Python standard library. Over time, all of that class has been copied
19 # verbatim here for modifications which could not be accomplished by
19 # verbatim here for modifications which could not be accomplished by
20 # subclassing. At this point, there are no dependencies at all on the code
20 # subclassing. At this point, there are no dependencies at all on the code
21 # module anymore (it is not even imported). The Python License (sec. 2)
21 # module anymore (it is not even imported). The Python License (sec. 2)
22 # allows for this, but it's always nice to acknowledge credit where credit is
22 # allows for this, but it's always nice to acknowledge credit where credit is
23 # due.
23 # due.
24 #*****************************************************************************
24 #*****************************************************************************
25
25
26 #****************************************************************************
26 #****************************************************************************
27 # Modules and globals
27 # Modules and globals
28
28
29 # Python standard modules
29 # Python standard modules
30 import __main__
30 import __main__
31 import __builtin__
31 import __builtin__
32 import StringIO
32 import StringIO
33 import bdb
33 import bdb
34 import cPickle as pickle
34 import cPickle as pickle
35 import codeop
35 import codeop
36 import exceptions
36 import exceptions
37 import glob
37 import glob
38 import inspect
38 import inspect
39 import keyword
39 import keyword
40 import new
40 import new
41 import os
41 import os
42 import pydoc
42 import pydoc
43 import re
43 import re
44 import shutil
44 import shutil
45 import string
45 import string
46 import sys
46 import sys
47 import tempfile
47 import tempfile
48 import traceback
48 import traceback
49 import types
49 import types
50 from pprint import pprint, pformat
50 from pprint import pprint, pformat
51
51
52 # IPython's own modules
52 # IPython's own modules
53 #import IPython
53 #import IPython
54 from IPython import Debugger,OInspect,PyColorize,ultraTB
54 from IPython import Debugger,OInspect,PyColorize,ultraTB
55 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
55 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
56 from IPython.Extensions import pickleshare
56 from IPython.Extensions import pickleshare
57 from IPython.FakeModule import FakeModule
57 from IPython.FakeModule import FakeModule, init_fakemod_dict
58 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
58 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
59 from IPython.Logger import Logger
59 from IPython.Logger import Logger
60 from IPython.Magic import Magic
60 from IPython.Magic import Magic
61 from IPython.Prompts import CachedOutput
61 from IPython.Prompts import CachedOutput
62 from IPython.ipstruct import Struct
62 from IPython.ipstruct import Struct
63 from IPython.background_jobs import BackgroundJobManager
63 from IPython.background_jobs import BackgroundJobManager
64 from IPython.usage import cmd_line_usage,interactive_usage
64 from IPython.usage import cmd_line_usage,interactive_usage
65 from IPython.genutils import *
65 from IPython.genutils import *
66 from IPython.strdispatch import StrDispatch
66 from IPython.strdispatch import StrDispatch
67 import IPython.ipapi
67 import IPython.ipapi
68 import IPython.history
68 import IPython.history
69 import IPython.prefilter as prefilter
69 import IPython.prefilter as prefilter
70 import IPython.shadowns
70 import IPython.shadowns
71 # Globals
71 # Globals
72
72
73 # store the builtin raw_input globally, and use this always, in case user code
73 # store the builtin raw_input globally, and use this always, in case user code
74 # overwrites it (like wx.py.PyShell does)
74 # overwrites it (like wx.py.PyShell does)
75 raw_input_original = raw_input
75 raw_input_original = raw_input
76
76
77 # compiled regexps for autoindent management
77 # compiled regexps for autoindent management
78 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
79
79
80
80
81 #****************************************************************************
81 #****************************************************************************
82 # Some utility function definitions
82 # Some utility function definitions
83
83
84 ini_spaces_re = re.compile(r'^(\s+)')
84 ini_spaces_re = re.compile(r'^(\s+)')
85
85
86 def num_ini_spaces(strng):
86 def num_ini_spaces(strng):
87 """Return the number of initial spaces in a string"""
87 """Return the number of initial spaces in a string"""
88
88
89 ini_spaces = ini_spaces_re.match(strng)
89 ini_spaces = ini_spaces_re.match(strng)
90 if ini_spaces:
90 if ini_spaces:
91 return ini_spaces.end()
91 return ini_spaces.end()
92 else:
92 else:
93 return 0
93 return 0
94
94
95 def softspace(file, newvalue):
95 def softspace(file, newvalue):
96 """Copied from code.py, to remove the dependency"""
96 """Copied from code.py, to remove the dependency"""
97
97
98 oldvalue = 0
98 oldvalue = 0
99 try:
99 try:
100 oldvalue = file.softspace
100 oldvalue = file.softspace
101 except AttributeError:
101 except AttributeError:
102 pass
102 pass
103 try:
103 try:
104 file.softspace = newvalue
104 file.softspace = newvalue
105 except (AttributeError, TypeError):
105 except (AttributeError, TypeError):
106 # "attribute-less object" or "read-only attributes"
106 # "attribute-less object" or "read-only attributes"
107 pass
107 pass
108 return oldvalue
108 return oldvalue
109
109
110
110
111 def user_setup(ipythondir,rc_suffix,mode='install',interactive=True):
111 def user_setup(ipythondir,rc_suffix,mode='install',interactive=True):
112 """Install or upgrade the user configuration directory.
112 """Install or upgrade the user configuration directory.
113
113
114 Can be called when running for the first time or to upgrade the user's
114 Can be called when running for the first time or to upgrade the user's
115 .ipython/ directory.
115 .ipython/ directory.
116
116
117 Parameters
117 Parameters
118 ----------
118 ----------
119 ipythondir : path
119 ipythondir : path
120 The directory to be used for installation/upgrade. In 'install' mode,
120 The directory to be used for installation/upgrade. In 'install' mode,
121 if this path already exists, the function exits immediately.
121 if this path already exists, the function exits immediately.
122
122
123 rc_suffix : str
123 rc_suffix : str
124 Extension for the config files. On *nix platforms it is typically the
124 Extension for the config files. On *nix platforms it is typically the
125 empty string, while Windows normally uses '.ini'.
125 empty string, while Windows normally uses '.ini'.
126
126
127 mode : str, optional
127 mode : str, optional
128 Valid modes are 'install' and 'upgrade'.
128 Valid modes are 'install' and 'upgrade'.
129
129
130 interactive : bool, optional
130 interactive : bool, optional
131 If False, do not wait for user input on any errors. Normally after
131 If False, do not wait for user input on any errors. Normally after
132 printing its status information, this function waits for the user to
132 printing its status information, this function waits for the user to
133 hit Return before proceeding. This is because the default use case is
133 hit Return before proceeding. This is because the default use case is
134 when first installing the IPython configuration, so we want the user to
134 when first installing the IPython configuration, so we want the user to
135 acknowledge the initial message, which contains some useful
135 acknowledge the initial message, which contains some useful
136 information.
136 information.
137 """
137 """
138
138
139 # For automatic use, deactivate all i/o
139 # For automatic use, deactivate all i/o
140 if interactive:
140 if interactive:
141 def wait():
141 def wait():
142 try:
142 try:
143 raw_input("Please press <RETURN> to start IPython.")
143 raw_input("Please press <RETURN> to start IPython.")
144 except EOFError:
144 except EOFError:
145 print >> Term.cout
145 print >> Term.cout
146 print '*'*70
146 print '*'*70
147
147
148 def printf(s):
148 def printf(s):
149 print s
149 print s
150 else:
150 else:
151 wait = lambda : None
151 wait = lambda : None
152 printf = lambda s : None
152 printf = lambda s : None
153
153
154 # Install mode should be re-entrant: if the install dir already exists,
154 # Install mode should be re-entrant: if the install dir already exists,
155 # bail out cleanly
155 # bail out cleanly
156 if mode == 'install' and os.path.isdir(ipythondir):
156 if mode == 'install' and os.path.isdir(ipythondir):
157 return
157 return
158
158
159 cwd = os.getcwd() # remember where we started
159 cwd = os.getcwd() # remember where we started
160 glb = glob.glob
160 glb = glob.glob
161
161
162 printf('*'*70)
162 printf('*'*70)
163 if mode == 'install':
163 if mode == 'install':
164 printf(
164 printf(
165 """Welcome to IPython. I will try to create a personal configuration directory
165 """Welcome to IPython. I will try to create a personal configuration directory
166 where you can customize many aspects of IPython's functionality in:\n""")
166 where you can customize many aspects of IPython's functionality in:\n""")
167 else:
167 else:
168 printf('I am going to upgrade your configuration in:')
168 printf('I am going to upgrade your configuration in:')
169
169
170 printf(ipythondir)
170 printf(ipythondir)
171
171
172 rcdirend = os.path.join('IPython','UserConfig')
172 rcdirend = os.path.join('IPython','UserConfig')
173 cfg = lambda d: os.path.join(d,rcdirend)
173 cfg = lambda d: os.path.join(d,rcdirend)
174 try:
174 try:
175 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
175 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
176 printf("Initializing from configuration: %s" % rcdir)
176 printf("Initializing from configuration: %s" % rcdir)
177 except IndexError:
177 except IndexError:
178 warning = """
178 warning = """
179 Installation error. IPython's directory was not found.
179 Installation error. IPython's directory was not found.
180
180
181 Check the following:
181 Check the following:
182
182
183 The ipython/IPython directory should be in a directory belonging to your
183 The ipython/IPython directory should be in a directory belonging to your
184 PYTHONPATH environment variable (that is, it should be in a directory
184 PYTHONPATH environment variable (that is, it should be in a directory
185 belonging to sys.path). You can copy it explicitly there or just link to it.
185 belonging to sys.path). You can copy it explicitly there or just link to it.
186
186
187 IPython will create a minimal default configuration for you.
187 IPython will create a minimal default configuration for you.
188
188
189 """
189 """
190 warn(warning)
190 warn(warning)
191 wait()
191 wait()
192
192
193 if sys.platform =='win32':
193 if sys.platform =='win32':
194 inif = 'ipythonrc.ini'
194 inif = 'ipythonrc.ini'
195 else:
195 else:
196 inif = 'ipythonrc'
196 inif = 'ipythonrc'
197 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
197 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
198 inif : '# intentionally left blank' }
198 inif : '# intentionally left blank' }
199 os.makedirs(ipythondir, mode = 0777)
199 os.makedirs(ipythondir, mode = 0777)
200 for f, cont in minimal_setup.items():
200 for f, cont in minimal_setup.items():
201 # In 2.5, this can be more cleanly done using 'with'
201 # In 2.5, this can be more cleanly done using 'with'
202 fobj = file(ipythondir + '/' + f,'w')
202 fobj = file(ipythondir + '/' + f,'w')
203 fobj.write(cont)
203 fobj.write(cont)
204 fobj.close()
204 fobj.close()
205
205
206 return
206 return
207
207
208 if mode == 'install':
208 if mode == 'install':
209 try:
209 try:
210 shutil.copytree(rcdir,ipythondir)
210 shutil.copytree(rcdir,ipythondir)
211 os.chdir(ipythondir)
211 os.chdir(ipythondir)
212 rc_files = glb("ipythonrc*")
212 rc_files = glb("ipythonrc*")
213 for rc_file in rc_files:
213 for rc_file in rc_files:
214 os.rename(rc_file,rc_file+rc_suffix)
214 os.rename(rc_file,rc_file+rc_suffix)
215 except:
215 except:
216 warning = """
216 warning = """
217
217
218 There was a problem with the installation:
218 There was a problem with the installation:
219 %s
219 %s
220 Try to correct it or contact the developers if you think it's a bug.
220 Try to correct it or contact the developers if you think it's a bug.
221 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
221 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
222 warn(warning)
222 warn(warning)
223 wait()
223 wait()
224 return
224 return
225
225
226 elif mode == 'upgrade':
226 elif mode == 'upgrade':
227 try:
227 try:
228 os.chdir(ipythondir)
228 os.chdir(ipythondir)
229 except:
229 except:
230 printf("""
230 printf("""
231 Can not upgrade: changing to directory %s failed. Details:
231 Can not upgrade: changing to directory %s failed. Details:
232 %s
232 %s
233 """ % (ipythondir,sys.exc_info()[1]) )
233 """ % (ipythondir,sys.exc_info()[1]) )
234 wait()
234 wait()
235 return
235 return
236 else:
236 else:
237 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
237 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
238 for new_full_path in sources:
238 for new_full_path in sources:
239 new_filename = os.path.basename(new_full_path)
239 new_filename = os.path.basename(new_full_path)
240 if new_filename.startswith('ipythonrc'):
240 if new_filename.startswith('ipythonrc'):
241 new_filename = new_filename + rc_suffix
241 new_filename = new_filename + rc_suffix
242 # The config directory should only contain files, skip any
242 # The config directory should only contain files, skip any
243 # directories which may be there (like CVS)
243 # directories which may be there (like CVS)
244 if os.path.isdir(new_full_path):
244 if os.path.isdir(new_full_path):
245 continue
245 continue
246 if os.path.exists(new_filename):
246 if os.path.exists(new_filename):
247 old_file = new_filename+'.old'
247 old_file = new_filename+'.old'
248 if os.path.exists(old_file):
248 if os.path.exists(old_file):
249 os.remove(old_file)
249 os.remove(old_file)
250 os.rename(new_filename,old_file)
250 os.rename(new_filename,old_file)
251 shutil.copy(new_full_path,new_filename)
251 shutil.copy(new_full_path,new_filename)
252 else:
252 else:
253 raise ValueError('unrecognized mode for install: %r' % mode)
253 raise ValueError('unrecognized mode for install: %r' % mode)
254
254
255 # Fix line-endings to those native to each platform in the config
255 # Fix line-endings to those native to each platform in the config
256 # directory.
256 # directory.
257 try:
257 try:
258 os.chdir(ipythondir)
258 os.chdir(ipythondir)
259 except:
259 except:
260 printf("""
260 printf("""
261 Problem: changing to directory %s failed.
261 Problem: changing to directory %s failed.
262 Details:
262 Details:
263 %s
263 %s
264
264
265 Some configuration files may have incorrect line endings. This should not
265 Some configuration files may have incorrect line endings. This should not
266 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) )
266 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) )
267 wait()
267 wait()
268 else:
268 else:
269 for fname in glb('ipythonrc*'):
269 for fname in glb('ipythonrc*'):
270 try:
270 try:
271 native_line_ends(fname,backup=0)
271 native_line_ends(fname,backup=0)
272 except IOError:
272 except IOError:
273 pass
273 pass
274
274
275 if mode == 'install':
275 if mode == 'install':
276 printf("""
276 printf("""
277 Successful installation!
277 Successful installation!
278
278
279 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
279 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
280 IPython manual (there are both HTML and PDF versions supplied with the
280 IPython manual (there are both HTML and PDF versions supplied with the
281 distribution) to make sure that your system environment is properly configured
281 distribution) to make sure that your system environment is properly configured
282 to take advantage of IPython's features.
282 to take advantage of IPython's features.
283
283
284 Important note: the configuration system has changed! The old system is
284 Important note: the configuration system has changed! The old system is
285 still in place, but its setting may be partly overridden by the settings in
285 still in place, but its setting may be partly overridden by the settings in
286 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
286 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
287 if some of the new settings bother you.
287 if some of the new settings bother you.
288
288
289 """)
289 """)
290 else:
290 else:
291 printf("""
291 printf("""
292 Successful upgrade!
292 Successful upgrade!
293
293
294 All files in your directory:
294 All files in your directory:
295 %(ipythondir)s
295 %(ipythondir)s
296 which would have been overwritten by the upgrade were backed up with a .old
296 which would have been overwritten by the upgrade were backed up with a .old
297 extension. If you had made particular customizations in those files you may
297 extension. If you had made particular customizations in those files you may
298 want to merge them back into the new files.""" % locals() )
298 want to merge them back into the new files.""" % locals() )
299 wait()
299 wait()
300 os.chdir(cwd)
300 os.chdir(cwd)
301
301
302 #****************************************************************************
302 #****************************************************************************
303 # Local use exceptions
303 # Local use exceptions
304 class SpaceInInput(exceptions.Exception): pass
304 class SpaceInInput(exceptions.Exception): pass
305
305
306
306
307 #****************************************************************************
307 #****************************************************************************
308 # Local use classes
308 # Local use classes
309 class Bunch: pass
309 class Bunch: pass
310
310
311 class Undefined: pass
311 class Undefined: pass
312
312
313 class Quitter(object):
313 class Quitter(object):
314 """Simple class to handle exit, similar to Python 2.5's.
314 """Simple class to handle exit, similar to Python 2.5's.
315
315
316 It handles exiting in an ipython-safe manner, which the one in Python 2.5
316 It handles exiting in an ipython-safe manner, which the one in Python 2.5
317 doesn't do (obviously, since it doesn't know about ipython)."""
317 doesn't do (obviously, since it doesn't know about ipython)."""
318
318
319 def __init__(self,shell,name):
319 def __init__(self,shell,name):
320 self.shell = shell
320 self.shell = shell
321 self.name = name
321 self.name = name
322
322
323 def __repr__(self):
323 def __repr__(self):
324 return 'Type %s() to exit.' % self.name
324 return 'Type %s() to exit.' % self.name
325 __str__ = __repr__
325 __str__ = __repr__
326
326
327 def __call__(self):
327 def __call__(self):
328 self.shell.exit()
328 self.shell.exit()
329
329
330 class InputList(list):
330 class InputList(list):
331 """Class to store user input.
331 """Class to store user input.
332
332
333 It's basically a list, but slices return a string instead of a list, thus
333 It's basically a list, but slices return a string instead of a list, thus
334 allowing things like (assuming 'In' is an instance):
334 allowing things like (assuming 'In' is an instance):
335
335
336 exec In[4:7]
336 exec In[4:7]
337
337
338 or
338 or
339
339
340 exec In[5:9] + In[14] + In[21:25]"""
340 exec In[5:9] + In[14] + In[21:25]"""
341
341
342 def __getslice__(self,i,j):
342 def __getslice__(self,i,j):
343 return ''.join(list.__getslice__(self,i,j))
343 return ''.join(list.__getslice__(self,i,j))
344
344
345 class SyntaxTB(ultraTB.ListTB):
345 class SyntaxTB(ultraTB.ListTB):
346 """Extension which holds some state: the last exception value"""
346 """Extension which holds some state: the last exception value"""
347
347
348 def __init__(self,color_scheme = 'NoColor'):
348 def __init__(self,color_scheme = 'NoColor'):
349 ultraTB.ListTB.__init__(self,color_scheme)
349 ultraTB.ListTB.__init__(self,color_scheme)
350 self.last_syntax_error = None
350 self.last_syntax_error = None
351
351
352 def __call__(self, etype, value, elist):
352 def __call__(self, etype, value, elist):
353 self.last_syntax_error = value
353 self.last_syntax_error = value
354 ultraTB.ListTB.__call__(self,etype,value,elist)
354 ultraTB.ListTB.__call__(self,etype,value,elist)
355
355
356 def clear_err_state(self):
356 def clear_err_state(self):
357 """Return the current error state and clear it"""
357 """Return the current error state and clear it"""
358 e = self.last_syntax_error
358 e = self.last_syntax_error
359 self.last_syntax_error = None
359 self.last_syntax_error = None
360 return e
360 return e
361
361
362 #****************************************************************************
362 #****************************************************************************
363 # Main IPython class
363 # Main IPython class
364
364
365 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
365 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
366 # until a full rewrite is made. I've cleaned all cross-class uses of
366 # until a full rewrite is made. I've cleaned all cross-class uses of
367 # attributes and methods, but too much user code out there relies on the
367 # attributes and methods, but too much user code out there relies on the
368 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
368 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
369 #
369 #
370 # But at least now, all the pieces have been separated and we could, in
370 # But at least now, all the pieces have been separated and we could, in
371 # principle, stop using the mixin. This will ease the transition to the
371 # principle, stop using the mixin. This will ease the transition to the
372 # chainsaw branch.
372 # chainsaw branch.
373
373
374 # For reference, the following is the list of 'self.foo' uses in the Magic
374 # For reference, the following is the list of 'self.foo' uses in the Magic
375 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
375 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
376 # class, to prevent clashes.
376 # class, to prevent clashes.
377
377
378 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
378 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
379 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
379 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
380 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
380 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
381 # 'self.value']
381 # 'self.value']
382
382
383 class InteractiveShell(object,Magic):
383 class InteractiveShell(object,Magic):
384 """An enhanced console for Python."""
384 """An enhanced console for Python."""
385
385
386 # class attribute to indicate whether the class supports threads or not.
386 # class attribute to indicate whether the class supports threads or not.
387 # Subclasses with thread support should override this as needed.
387 # Subclasses with thread support should override this as needed.
388 isthreaded = False
388 isthreaded = False
389
389
390 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
390 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
391 user_ns=None,user_global_ns=None,banner2='',
391 user_ns=None,user_global_ns=None,banner2='',
392 custom_exceptions=((),None),embedded=False):
392 custom_exceptions=((),None),embedded=False):
393
393
394 # log system
394 # log system
395 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
395 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
396
396
397 # Job manager (for jobs run as background threads)
397 # Job manager (for jobs run as background threads)
398 self.jobs = BackgroundJobManager()
398 self.jobs = BackgroundJobManager()
399
399
400 # Store the actual shell's name
400 # Store the actual shell's name
401 self.name = name
401 self.name = name
402 self.more = False
402 self.more = False
403
403
404 # We need to know whether the instance is meant for embedding, since
404 # We need to know whether the instance is meant for embedding, since
405 # global/local namespaces need to be handled differently in that case
405 # global/local namespaces need to be handled differently in that case
406 self.embedded = embedded
406 self.embedded = embedded
407 if embedded:
407 if embedded:
408 # Control variable so users can, from within the embedded instance,
408 # Control variable so users can, from within the embedded instance,
409 # permanently deactivate it.
409 # permanently deactivate it.
410 self.embedded_active = True
410 self.embedded_active = True
411
411
412 # command compiler
412 # command compiler
413 self.compile = codeop.CommandCompiler()
413 self.compile = codeop.CommandCompiler()
414
414
415 # User input buffer
415 # User input buffer
416 self.buffer = []
416 self.buffer = []
417
417
418 # Default name given in compilation of code
418 # Default name given in compilation of code
419 self.filename = '<ipython console>'
419 self.filename = '<ipython console>'
420
420
421 # Install our own quitter instead of the builtins. For python2.3-2.4,
421 # Install our own quitter instead of the builtins. For python2.3-2.4,
422 # this brings in behavior like 2.5, and for 2.5 it's identical.
422 # this brings in behavior like 2.5, and for 2.5 it's identical.
423 __builtin__.exit = Quitter(self,'exit')
423 __builtin__.exit = Quitter(self,'exit')
424 __builtin__.quit = Quitter(self,'quit')
424 __builtin__.quit = Quitter(self,'quit')
425
425
426 # Make an empty namespace, which extension writers can rely on both
426 # Make an empty namespace, which extension writers can rely on both
427 # existing and NEVER being used by ipython itself. This gives them a
427 # existing and NEVER being used by ipython itself. This gives them a
428 # convenient location for storing additional information and state
428 # convenient location for storing additional information and state
429 # their extensions may require, without fear of collisions with other
429 # their extensions may require, without fear of collisions with other
430 # ipython names that may develop later.
430 # ipython names that may develop later.
431 self.meta = Struct()
431 self.meta = Struct()
432
432
433 # Create the namespace where the user will operate. user_ns is
433 # Create the namespace where the user will operate. user_ns is
434 # normally the only one used, and it is passed to the exec calls as
434 # normally the only one used, and it is passed to the exec calls as
435 # the locals argument. But we do carry a user_global_ns namespace
435 # the locals argument. But we do carry a user_global_ns namespace
436 # given as the exec 'globals' argument, This is useful in embedding
436 # given as the exec 'globals' argument, This is useful in embedding
437 # situations where the ipython shell opens in a context where the
437 # situations where the ipython shell opens in a context where the
438 # distinction between locals and globals is meaningful. For
438 # distinction between locals and globals is meaningful. For
439 # non-embedded contexts, it is just the same object as the user_ns dict.
439 # non-embedded contexts, it is just the same object as the user_ns dict.
440
440
441 # FIXME. For some strange reason, __builtins__ is showing up at user
441 # FIXME. For some strange reason, __builtins__ is showing up at user
442 # level as a dict instead of a module. This is a manual fix, but I
442 # level as a dict instead of a module. This is a manual fix, but I
443 # should really track down where the problem is coming from. Alex
443 # should really track down where the problem is coming from. Alex
444 # Schmolck reported this problem first.
444 # Schmolck reported this problem first.
445
445
446 # A useful post by Alex Martelli on this topic:
446 # A useful post by Alex Martelli on this topic:
447 # Re: inconsistent value from __builtins__
447 # Re: inconsistent value from __builtins__
448 # Von: Alex Martelli <aleaxit@yahoo.com>
448 # Von: Alex Martelli <aleaxit@yahoo.com>
449 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
449 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
450 # Gruppen: comp.lang.python
450 # Gruppen: comp.lang.python
451
451
452 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
452 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
453 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
453 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
454 # > <type 'dict'>
454 # > <type 'dict'>
455 # > >>> print type(__builtins__)
455 # > >>> print type(__builtins__)
456 # > <type 'module'>
456 # > <type 'module'>
457 # > Is this difference in return value intentional?
457 # > Is this difference in return value intentional?
458
458
459 # Well, it's documented that '__builtins__' can be either a dictionary
459 # Well, it's documented that '__builtins__' can be either a dictionary
460 # or a module, and it's been that way for a long time. Whether it's
460 # or a module, and it's been that way for a long time. Whether it's
461 # intentional (or sensible), I don't know. In any case, the idea is
461 # intentional (or sensible), I don't know. In any case, the idea is
462 # that if you need to access the built-in namespace directly, you
462 # that if you need to access the built-in namespace directly, you
463 # should start with "import __builtin__" (note, no 's') which will
463 # should start with "import __builtin__" (note, no 's') which will
464 # definitely give you a module. Yeah, it's somewhat confusing:-(.
464 # definitely give you a module. Yeah, it's somewhat confusing:-(.
465
465
466 # These routines return properly built dicts as needed by the rest of
466 # These routines return properly built dicts as needed by the rest of
467 # the code, and can also be used by extension writers to generate
467 # the code, and can also be used by extension writers to generate
468 # properly initialized namespaces.
468 # properly initialized namespaces.
469 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
469 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
470 user_global_ns)
470 user_global_ns)
471
471
472 # Assign namespaces
472 # Assign namespaces
473 # This is the namespace where all normal user variables live
473 # This is the namespace where all normal user variables live
474 self.user_ns = user_ns
474 self.user_ns = user_ns
475 self.user_global_ns = user_global_ns
475 self.user_global_ns = user_global_ns
476
476
477 # An auxiliary namespace that checks what parts of the user_ns were
477 # An auxiliary namespace that checks what parts of the user_ns were
478 # loaded at startup, so we can list later only variables defined in
478 # loaded at startup, so we can list later only variables defined in
479 # actual interactive use. Since it is always a subset of user_ns, it
479 # actual interactive use. Since it is always a subset of user_ns, it
480 # doesn't need to be seaparately tracked in the ns_table
480 # doesn't need to be seaparately tracked in the ns_table
481 self.user_config_ns = {}
481 self.user_config_ns = {}
482
482
483 # A namespace to keep track of internal data structures to prevent
483 # A namespace to keep track of internal data structures to prevent
484 # them from cluttering user-visible stuff. Will be updated later
484 # them from cluttering user-visible stuff. Will be updated later
485 self.internal_ns = {}
485 self.internal_ns = {}
486
486
487 # Namespace of system aliases. Each entry in the alias
487 # Namespace of system aliases. Each entry in the alias
488 # table must be a 2-tuple of the form (N,name), where N is the number
488 # table must be a 2-tuple of the form (N,name), where N is the number
489 # of positional arguments of the alias.
489 # of positional arguments of the alias.
490 self.alias_table = {}
490 self.alias_table = {}
491
491
492 # Now that FakeModule produces a real module, we've run into a nasty
492 # Now that FakeModule produces a real module, we've run into a nasty
493 # problem: after script execution (via %run), the module where the user
493 # problem: after script execution (via %run), the module where the user
494 # code ran is deleted. Now that this object is a true module (needed
494 # code ran is deleted. Now that this object is a true module (needed
495 # so docetst and other tools work correctly), the Python module
495 # so docetst and other tools work correctly), the Python module
496 # teardown mechanism runs over it, and sets to None every variable
496 # teardown mechanism runs over it, and sets to None every variable
497 # present in that module. Top-level references to objects from the
497 # present in that module. Top-level references to objects from the
498 # script survive, because the user_ns is updated with them. However,
498 # script survive, because the user_ns is updated with them. However,
499 # calling functions defined in the script that use other things from
499 # calling functions defined in the script that use other things from
500 # the script will fail, because the function's closure had references
500 # the script will fail, because the function's closure had references
501 # to the original objects, which are now all None. So we must protect
501 # to the original objects, which are now all None. So we must protect
502 # these modules from deletion by keeping a cache. To avoid keeping
502 # these modules from deletion by keeping a cache.
503 # stale modules around (we only need the one from the last run), we use
503 #
504 # a dict keyed with the full path to the script, so only the last
504 # To avoid keeping stale modules around (we only need the one from the
505 # version of the module is held in the cache. The %reset command will
505 # last run), we use a dict keyed with the full path to the script, so
506 # flush this cache. See the cache_main_mod() and clear_main_mod_cache()
506 # only the last version of the module is held in the cache. Note,
507 # methods for details on use.
507 # however, that we must cache the module *namespace contents* (their
508 self._user_main_modules = {}
508 # __dict__). Because if we try to cache the actual modules, old ones
509 # (uncached) could be destroyed while still holding references (such as
510 # those held by GUI objects that tend to be long-lived)>
511 #
512 # The %reset command will flush this cache. See the cache_main_mod()
513 # and clear_main_mod_cache() methods for details on use.
514
515 # This is the cache used for 'main' namespaces
516 self._main_ns_cache = {}
517 # And this is the single instance of FakeModule whose __dict__ we keep
518 # copying and clearing for reuse on each %run
519 self._user_main_module = FakeModule()
509
520
510 # A table holding all the namespaces IPython deals with, so that
521 # A table holding all the namespaces IPython deals with, so that
511 # introspection facilities can search easily.
522 # introspection facilities can search easily.
512 self.ns_table = {'user':user_ns,
523 self.ns_table = {'user':user_ns,
513 'user_global':user_global_ns,
524 'user_global':user_global_ns,
514 'alias':self.alias_table,
525 'alias':self.alias_table,
515 'internal':self.internal_ns,
526 'internal':self.internal_ns,
516 'builtin':__builtin__.__dict__
527 'builtin':__builtin__.__dict__
517 }
528 }
518
529
519 # Similarly, track all namespaces where references can be held and that
530 # Similarly, track all namespaces where references can be held and that
520 # we can safely clear (so it can NOT include builtin). This one can be
531 # we can safely clear (so it can NOT include builtin). This one can be
521 # a simple list.
532 # a simple list.
522 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
533 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
523 self.alias_table, self.internal_ns,
534 self.alias_table, self.internal_ns,
524 self._user_main_modules ]
535 self._main_ns_cache ]
525
536
526 # We need to insert into sys.modules something that looks like a
537 # We need to insert into sys.modules something that looks like a
527 # module but which accesses the IPython namespace, for shelve and
538 # module but which accesses the IPython namespace, for shelve and
528 # pickle to work interactively. Normally they rely on getting
539 # pickle to work interactively. Normally they rely on getting
529 # everything out of __main__, but for embedding purposes each IPython
540 # everything out of __main__, but for embedding purposes each IPython
530 # instance has its own private namespace, so we can't go shoving
541 # instance has its own private namespace, so we can't go shoving
531 # everything into __main__.
542 # everything into __main__.
532
543
533 # note, however, that we should only do this for non-embedded
544 # note, however, that we should only do this for non-embedded
534 # ipythons, which really mimic the __main__.__dict__ with their own
545 # ipythons, which really mimic the __main__.__dict__ with their own
535 # namespace. Embedded instances, on the other hand, should not do
546 # namespace. Embedded instances, on the other hand, should not do
536 # this because they need to manage the user local/global namespaces
547 # this because they need to manage the user local/global namespaces
537 # only, but they live within a 'normal' __main__ (meaning, they
548 # only, but they live within a 'normal' __main__ (meaning, they
538 # shouldn't overtake the execution environment of the script they're
549 # shouldn't overtake the execution environment of the script they're
539 # embedded in).
550 # embedded in).
540
551
541 if not embedded:
552 if not embedded:
542 try:
553 try:
543 main_name = self.user_ns['__name__']
554 main_name = self.user_ns['__name__']
544 except KeyError:
555 except KeyError:
545 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
556 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
546 else:
557 else:
547 #print "pickle hack in place" # dbg
558 #print "pickle hack in place" # dbg
548 #print 'main_name:',main_name # dbg
559 #print 'main_name:',main_name # dbg
549 sys.modules[main_name] = FakeModule(self.user_ns)
560 sys.modules[main_name] = FakeModule(self.user_ns)
550
561
551 # List of input with multi-line handling.
562 # List of input with multi-line handling.
552 self.input_hist = InputList()
563 self.input_hist = InputList()
553 # This one will hold the 'raw' input history, without any
564 # This one will hold the 'raw' input history, without any
554 # pre-processing. This will allow users to retrieve the input just as
565 # pre-processing. This will allow users to retrieve the input just as
555 # it was exactly typed in by the user, with %hist -r.
566 # it was exactly typed in by the user, with %hist -r.
556 self.input_hist_raw = InputList()
567 self.input_hist_raw = InputList()
557
568
558 # list of visited directories
569 # list of visited directories
559 try:
570 try:
560 self.dir_hist = [os.getcwd()]
571 self.dir_hist = [os.getcwd()]
561 except OSError:
572 except OSError:
562 self.dir_hist = []
573 self.dir_hist = []
563
574
564 # dict of output history
575 # dict of output history
565 self.output_hist = {}
576 self.output_hist = {}
566
577
567 # Get system encoding at startup time. Certain terminals (like Emacs
578 # Get system encoding at startup time. Certain terminals (like Emacs
568 # under Win32 have it set to None, and we need to have a known valid
579 # under Win32 have it set to None, and we need to have a known valid
569 # encoding to use in the raw_input() method
580 # encoding to use in the raw_input() method
570 try:
581 try:
571 self.stdin_encoding = sys.stdin.encoding or 'ascii'
582 self.stdin_encoding = sys.stdin.encoding or 'ascii'
572 except AttributeError:
583 except AttributeError:
573 self.stdin_encoding = 'ascii'
584 self.stdin_encoding = 'ascii'
574
585
575 # dict of things NOT to alias (keywords, builtins and some magics)
586 # dict of things NOT to alias (keywords, builtins and some magics)
576 no_alias = {}
587 no_alias = {}
577 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
588 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
578 for key in keyword.kwlist + no_alias_magics:
589 for key in keyword.kwlist + no_alias_magics:
579 no_alias[key] = 1
590 no_alias[key] = 1
580 no_alias.update(__builtin__.__dict__)
591 no_alias.update(__builtin__.__dict__)
581 self.no_alias = no_alias
592 self.no_alias = no_alias
582
593
583 # Object variable to store code object waiting execution. This is
594 # Object variable to store code object waiting execution. This is
584 # used mainly by the multithreaded shells, but it can come in handy in
595 # used mainly by the multithreaded shells, but it can come in handy in
585 # other situations. No need to use a Queue here, since it's a single
596 # other situations. No need to use a Queue here, since it's a single
586 # item which gets cleared once run.
597 # item which gets cleared once run.
587 self.code_to_run = None
598 self.code_to_run = None
588
599
589 # escapes for automatic behavior on the command line
600 # escapes for automatic behavior on the command line
590 self.ESC_SHELL = '!'
601 self.ESC_SHELL = '!'
591 self.ESC_SH_CAP = '!!'
602 self.ESC_SH_CAP = '!!'
592 self.ESC_HELP = '?'
603 self.ESC_HELP = '?'
593 self.ESC_MAGIC = '%'
604 self.ESC_MAGIC = '%'
594 self.ESC_QUOTE = ','
605 self.ESC_QUOTE = ','
595 self.ESC_QUOTE2 = ';'
606 self.ESC_QUOTE2 = ';'
596 self.ESC_PAREN = '/'
607 self.ESC_PAREN = '/'
597
608
598 # And their associated handlers
609 # And their associated handlers
599 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
610 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
600 self.ESC_QUOTE : self.handle_auto,
611 self.ESC_QUOTE : self.handle_auto,
601 self.ESC_QUOTE2 : self.handle_auto,
612 self.ESC_QUOTE2 : self.handle_auto,
602 self.ESC_MAGIC : self.handle_magic,
613 self.ESC_MAGIC : self.handle_magic,
603 self.ESC_HELP : self.handle_help,
614 self.ESC_HELP : self.handle_help,
604 self.ESC_SHELL : self.handle_shell_escape,
615 self.ESC_SHELL : self.handle_shell_escape,
605 self.ESC_SH_CAP : self.handle_shell_escape,
616 self.ESC_SH_CAP : self.handle_shell_escape,
606 }
617 }
607
618
608 # class initializations
619 # class initializations
609 Magic.__init__(self,self)
620 Magic.__init__(self,self)
610
621
611 # Python source parser/formatter for syntax highlighting
622 # Python source parser/formatter for syntax highlighting
612 pyformat = PyColorize.Parser().format
623 pyformat = PyColorize.Parser().format
613 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
624 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
614
625
615 # hooks holds pointers used for user-side customizations
626 # hooks holds pointers used for user-side customizations
616 self.hooks = Struct()
627 self.hooks = Struct()
617
628
618 self.strdispatchers = {}
629 self.strdispatchers = {}
619
630
620 # Set all default hooks, defined in the IPython.hooks module.
631 # Set all default hooks, defined in the IPython.hooks module.
621 hooks = IPython.hooks
632 hooks = IPython.hooks
622 for hook_name in hooks.__all__:
633 for hook_name in hooks.__all__:
623 # default hooks have priority 100, i.e. low; user hooks should have
634 # default hooks have priority 100, i.e. low; user hooks should have
624 # 0-100 priority
635 # 0-100 priority
625 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
636 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
626 #print "bound hook",hook_name
637 #print "bound hook",hook_name
627
638
628 # Flag to mark unconditional exit
639 # Flag to mark unconditional exit
629 self.exit_now = False
640 self.exit_now = False
630
641
631 self.usage_min = """\
642 self.usage_min = """\
632 An enhanced console for Python.
643 An enhanced console for Python.
633 Some of its features are:
644 Some of its features are:
634 - Readline support if the readline library is present.
645 - Readline support if the readline library is present.
635 - Tab completion in the local namespace.
646 - Tab completion in the local namespace.
636 - Logging of input, see command-line options.
647 - Logging of input, see command-line options.
637 - System shell escape via ! , eg !ls.
648 - System shell escape via ! , eg !ls.
638 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
649 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
639 - Keeps track of locally defined variables via %who, %whos.
650 - Keeps track of locally defined variables via %who, %whos.
640 - Show object information with a ? eg ?x or x? (use ?? for more info).
651 - Show object information with a ? eg ?x or x? (use ?? for more info).
641 """
652 """
642 if usage: self.usage = usage
653 if usage: self.usage = usage
643 else: self.usage = self.usage_min
654 else: self.usage = self.usage_min
644
655
645 # Storage
656 # Storage
646 self.rc = rc # This will hold all configuration information
657 self.rc = rc # This will hold all configuration information
647 self.pager = 'less'
658 self.pager = 'less'
648 # temporary files used for various purposes. Deleted at exit.
659 # temporary files used for various purposes. Deleted at exit.
649 self.tempfiles = []
660 self.tempfiles = []
650
661
651 # Keep track of readline usage (later set by init_readline)
662 # Keep track of readline usage (later set by init_readline)
652 self.has_readline = False
663 self.has_readline = False
653
664
654 # template for logfile headers. It gets resolved at runtime by the
665 # template for logfile headers. It gets resolved at runtime by the
655 # logstart method.
666 # logstart method.
656 self.loghead_tpl = \
667 self.loghead_tpl = \
657 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
668 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
658 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
669 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
659 #log# opts = %s
670 #log# opts = %s
660 #log# args = %s
671 #log# args = %s
661 #log# It is safe to make manual edits below here.
672 #log# It is safe to make manual edits below here.
662 #log#-----------------------------------------------------------------------
673 #log#-----------------------------------------------------------------------
663 """
674 """
664 # for pushd/popd management
675 # for pushd/popd management
665 try:
676 try:
666 self.home_dir = get_home_dir()
677 self.home_dir = get_home_dir()
667 except HomeDirError,msg:
678 except HomeDirError,msg:
668 fatal(msg)
679 fatal(msg)
669
680
670 self.dir_stack = []
681 self.dir_stack = []
671
682
672 # Functions to call the underlying shell.
683 # Functions to call the underlying shell.
673
684
674 # The first is similar to os.system, but it doesn't return a value,
685 # The first is similar to os.system, but it doesn't return a value,
675 # and it allows interpolation of variables in the user's namespace.
686 # and it allows interpolation of variables in the user's namespace.
676 self.system = lambda cmd: \
687 self.system = lambda cmd: \
677 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
688 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
678
689
679 # These are for getoutput and getoutputerror:
690 # These are for getoutput and getoutputerror:
680 self.getoutput = lambda cmd: \
691 self.getoutput = lambda cmd: \
681 getoutput(self.var_expand(cmd,depth=2),
692 getoutput(self.var_expand(cmd,depth=2),
682 header=self.rc.system_header,
693 header=self.rc.system_header,
683 verbose=self.rc.system_verbose)
694 verbose=self.rc.system_verbose)
684
695
685 self.getoutputerror = lambda cmd: \
696 self.getoutputerror = lambda cmd: \
686 getoutputerror(self.var_expand(cmd,depth=2),
697 getoutputerror(self.var_expand(cmd,depth=2),
687 header=self.rc.system_header,
698 header=self.rc.system_header,
688 verbose=self.rc.system_verbose)
699 verbose=self.rc.system_verbose)
689
700
690
701
691 # keep track of where we started running (mainly for crash post-mortem)
702 # keep track of where we started running (mainly for crash post-mortem)
692 self.starting_dir = os.getcwd()
703 self.starting_dir = os.getcwd()
693
704
694 # Various switches which can be set
705 # Various switches which can be set
695 self.CACHELENGTH = 5000 # this is cheap, it's just text
706 self.CACHELENGTH = 5000 # this is cheap, it's just text
696 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
707 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
697 self.banner2 = banner2
708 self.banner2 = banner2
698
709
699 # TraceBack handlers:
710 # TraceBack handlers:
700
711
701 # Syntax error handler.
712 # Syntax error handler.
702 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
713 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
703
714
704 # The interactive one is initialized with an offset, meaning we always
715 # The interactive one is initialized with an offset, meaning we always
705 # want to remove the topmost item in the traceback, which is our own
716 # want to remove the topmost item in the traceback, which is our own
706 # internal code. Valid modes: ['Plain','Context','Verbose']
717 # internal code. Valid modes: ['Plain','Context','Verbose']
707 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
718 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
708 color_scheme='NoColor',
719 color_scheme='NoColor',
709 tb_offset = 1)
720 tb_offset = 1)
710
721
711 # IPython itself shouldn't crash. This will produce a detailed
722 # IPython itself shouldn't crash. This will produce a detailed
712 # post-mortem if it does. But we only install the crash handler for
723 # post-mortem if it does. But we only install the crash handler for
713 # non-threaded shells, the threaded ones use a normal verbose reporter
724 # non-threaded shells, the threaded ones use a normal verbose reporter
714 # and lose the crash handler. This is because exceptions in the main
725 # and lose the crash handler. This is because exceptions in the main
715 # thread (such as in GUI code) propagate directly to sys.excepthook,
726 # thread (such as in GUI code) propagate directly to sys.excepthook,
716 # and there's no point in printing crash dumps for every user exception.
727 # and there's no point in printing crash dumps for every user exception.
717 if self.isthreaded:
728 if self.isthreaded:
718 ipCrashHandler = ultraTB.FormattedTB()
729 ipCrashHandler = ultraTB.FormattedTB()
719 else:
730 else:
720 from IPython import CrashHandler
731 from IPython import CrashHandler
721 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
732 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
722 self.set_crash_handler(ipCrashHandler)
733 self.set_crash_handler(ipCrashHandler)
723
734
724 # and add any custom exception handlers the user may have specified
735 # and add any custom exception handlers the user may have specified
725 self.set_custom_exc(*custom_exceptions)
736 self.set_custom_exc(*custom_exceptions)
726
737
727 # indentation management
738 # indentation management
728 self.autoindent = False
739 self.autoindent = False
729 self.indent_current_nsp = 0
740 self.indent_current_nsp = 0
730
741
731 # Make some aliases automatically
742 # Make some aliases automatically
732 # Prepare list of shell aliases to auto-define
743 # Prepare list of shell aliases to auto-define
733 if os.name == 'posix':
744 if os.name == 'posix':
734 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
745 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
735 'mv mv -i','rm rm -i','cp cp -i',
746 'mv mv -i','rm rm -i','cp cp -i',
736 'cat cat','less less','clear clear',
747 'cat cat','less less','clear clear',
737 # a better ls
748 # a better ls
738 'ls ls -F',
749 'ls ls -F',
739 # long ls
750 # long ls
740 'll ls -lF')
751 'll ls -lF')
741 # Extra ls aliases with color, which need special treatment on BSD
752 # Extra ls aliases with color, which need special treatment on BSD
742 # variants
753 # variants
743 ls_extra = ( # color ls
754 ls_extra = ( # color ls
744 'lc ls -F -o --color',
755 'lc ls -F -o --color',
745 # ls normal files only
756 # ls normal files only
746 'lf ls -F -o --color %l | grep ^-',
757 'lf ls -F -o --color %l | grep ^-',
747 # ls symbolic links
758 # ls symbolic links
748 'lk ls -F -o --color %l | grep ^l',
759 'lk ls -F -o --color %l | grep ^l',
749 # directories or links to directories,
760 # directories or links to directories,
750 'ldir ls -F -o --color %l | grep /$',
761 'ldir ls -F -o --color %l | grep /$',
751 # things which are executable
762 # things which are executable
752 'lx ls -F -o --color %l | grep ^-..x',
763 'lx ls -F -o --color %l | grep ^-..x',
753 )
764 )
754 # The BSDs don't ship GNU ls, so they don't understand the
765 # The BSDs don't ship GNU ls, so they don't understand the
755 # --color switch out of the box
766 # --color switch out of the box
756 if 'bsd' in sys.platform:
767 if 'bsd' in sys.platform:
757 ls_extra = ( # ls normal files only
768 ls_extra = ( # ls normal files only
758 'lf ls -lF | grep ^-',
769 'lf ls -lF | grep ^-',
759 # ls symbolic links
770 # ls symbolic links
760 'lk ls -lF | grep ^l',
771 'lk ls -lF | grep ^l',
761 # directories or links to directories,
772 # directories or links to directories,
762 'ldir ls -lF | grep /$',
773 'ldir ls -lF | grep /$',
763 # things which are executable
774 # things which are executable
764 'lx ls -lF | grep ^-..x',
775 'lx ls -lF | grep ^-..x',
765 )
776 )
766 auto_alias = auto_alias + ls_extra
777 auto_alias = auto_alias + ls_extra
767 elif os.name in ['nt','dos']:
778 elif os.name in ['nt','dos']:
768 auto_alias = ('ls dir /on',
779 auto_alias = ('ls dir /on',
769 'ddir dir /ad /on', 'ldir dir /ad /on',
780 'ddir dir /ad /on', 'ldir dir /ad /on',
770 'mkdir mkdir','rmdir rmdir','echo echo',
781 'mkdir mkdir','rmdir rmdir','echo echo',
771 'ren ren','cls cls','copy copy')
782 'ren ren','cls cls','copy copy')
772 else:
783 else:
773 auto_alias = ()
784 auto_alias = ()
774 self.auto_alias = [s.split(None,1) for s in auto_alias]
785 self.auto_alias = [s.split(None,1) for s in auto_alias]
775
786
776 # Produce a public API instance
787 # Produce a public API instance
777 self.api = IPython.ipapi.IPApi(self)
788 self.api = IPython.ipapi.IPApi(self)
778
789
779 # Initialize all user-visible namespaces
790 # Initialize all user-visible namespaces
780 self.init_namespaces()
791 self.init_namespaces()
781
792
782 # Call the actual (public) initializer
793 # Call the actual (public) initializer
783 self.init_auto_alias()
794 self.init_auto_alias()
784
795
785 # track which builtins we add, so we can clean up later
796 # track which builtins we add, so we can clean up later
786 self.builtins_added = {}
797 self.builtins_added = {}
787 # This method will add the necessary builtins for operation, but
798 # This method will add the necessary builtins for operation, but
788 # tracking what it did via the builtins_added dict.
799 # tracking what it did via the builtins_added dict.
789
800
790 #TODO: remove this, redundant
801 #TODO: remove this, redundant
791 self.add_builtins()
802 self.add_builtins()
792 # end __init__
803 # end __init__
793
804
794 def var_expand(self,cmd,depth=0):
805 def var_expand(self,cmd,depth=0):
795 """Expand python variables in a string.
806 """Expand python variables in a string.
796
807
797 The depth argument indicates how many frames above the caller should
808 The depth argument indicates how many frames above the caller should
798 be walked to look for the local namespace where to expand variables.
809 be walked to look for the local namespace where to expand variables.
799
810
800 The global namespace for expansion is always the user's interactive
811 The global namespace for expansion is always the user's interactive
801 namespace.
812 namespace.
802 """
813 """
803
814
804 return str(ItplNS(cmd,
815 return str(ItplNS(cmd,
805 self.user_ns, # globals
816 self.user_ns, # globals
806 # Skip our own frame in searching for locals:
817 # Skip our own frame in searching for locals:
807 sys._getframe(depth+1).f_locals # locals
818 sys._getframe(depth+1).f_locals # locals
808 ))
819 ))
809
820
810 def pre_config_initialization(self):
821 def pre_config_initialization(self):
811 """Pre-configuration init method
822 """Pre-configuration init method
812
823
813 This is called before the configuration files are processed to
824 This is called before the configuration files are processed to
814 prepare the services the config files might need.
825 prepare the services the config files might need.
815
826
816 self.rc already has reasonable default values at this point.
827 self.rc already has reasonable default values at this point.
817 """
828 """
818 rc = self.rc
829 rc = self.rc
819 try:
830 try:
820 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
831 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
821 except exceptions.UnicodeDecodeError:
832 except exceptions.UnicodeDecodeError:
822 print "Your ipythondir can't be decoded to unicode!"
833 print "Your ipythondir can't be decoded to unicode!"
823 print "Please set HOME environment variable to something that"
834 print "Please set HOME environment variable to something that"
824 print r"only has ASCII characters, e.g. c:\home"
835 print r"only has ASCII characters, e.g. c:\home"
825 print "Now it is",rc.ipythondir
836 print "Now it is",rc.ipythondir
826 sys.exit()
837 sys.exit()
827 self.shadowhist = IPython.history.ShadowHist(self.db)
838 self.shadowhist = IPython.history.ShadowHist(self.db)
828
839
829 def post_config_initialization(self):
840 def post_config_initialization(self):
830 """Post configuration init method
841 """Post configuration init method
831
842
832 This is called after the configuration files have been processed to
843 This is called after the configuration files have been processed to
833 'finalize' the initialization."""
844 'finalize' the initialization."""
834
845
835 rc = self.rc
846 rc = self.rc
836
847
837 # Object inspector
848 # Object inspector
838 self.inspector = OInspect.Inspector(OInspect.InspectColors,
849 self.inspector = OInspect.Inspector(OInspect.InspectColors,
839 PyColorize.ANSICodeColors,
850 PyColorize.ANSICodeColors,
840 'NoColor',
851 'NoColor',
841 rc.object_info_string_level)
852 rc.object_info_string_level)
842
853
843 self.rl_next_input = None
854 self.rl_next_input = None
844 self.rl_do_indent = False
855 self.rl_do_indent = False
845 # Load readline proper
856 # Load readline proper
846 if rc.readline:
857 if rc.readline:
847 self.init_readline()
858 self.init_readline()
848
859
849 # local shortcut, this is used a LOT
860 # local shortcut, this is used a LOT
850 self.log = self.logger.log
861 self.log = self.logger.log
851
862
852 # Initialize cache, set in/out prompts and printing system
863 # Initialize cache, set in/out prompts and printing system
853 self.outputcache = CachedOutput(self,
864 self.outputcache = CachedOutput(self,
854 rc.cache_size,
865 rc.cache_size,
855 rc.pprint,
866 rc.pprint,
856 input_sep = rc.separate_in,
867 input_sep = rc.separate_in,
857 output_sep = rc.separate_out,
868 output_sep = rc.separate_out,
858 output_sep2 = rc.separate_out2,
869 output_sep2 = rc.separate_out2,
859 ps1 = rc.prompt_in1,
870 ps1 = rc.prompt_in1,
860 ps2 = rc.prompt_in2,
871 ps2 = rc.prompt_in2,
861 ps_out = rc.prompt_out,
872 ps_out = rc.prompt_out,
862 pad_left = rc.prompts_pad_left)
873 pad_left = rc.prompts_pad_left)
863
874
864 # user may have over-ridden the default print hook:
875 # user may have over-ridden the default print hook:
865 try:
876 try:
866 self.outputcache.__class__.display = self.hooks.display
877 self.outputcache.__class__.display = self.hooks.display
867 except AttributeError:
878 except AttributeError:
868 pass
879 pass
869
880
870 # I don't like assigning globally to sys, because it means when
881 # I don't like assigning globally to sys, because it means when
871 # embedding instances, each embedded instance overrides the previous
882 # embedding instances, each embedded instance overrides the previous
872 # choice. But sys.displayhook seems to be called internally by exec,
883 # choice. But sys.displayhook seems to be called internally by exec,
873 # so I don't see a way around it. We first save the original and then
884 # so I don't see a way around it. We first save the original and then
874 # overwrite it.
885 # overwrite it.
875 self.sys_displayhook = sys.displayhook
886 self.sys_displayhook = sys.displayhook
876 sys.displayhook = self.outputcache
887 sys.displayhook = self.outputcache
877
888
878 # Do a proper resetting of doctest, including the necessary displayhook
889 # Do a proper resetting of doctest, including the necessary displayhook
879 # monkeypatching
890 # monkeypatching
880 try:
891 try:
881 doctest_reload()
892 doctest_reload()
882 except ImportError:
893 except ImportError:
883 warn("doctest module does not exist.")
894 warn("doctest module does not exist.")
884
895
885 # Set user colors (don't do it in the constructor above so that it
896 # Set user colors (don't do it in the constructor above so that it
886 # doesn't crash if colors option is invalid)
897 # doesn't crash if colors option is invalid)
887 self.magic_colors(rc.colors)
898 self.magic_colors(rc.colors)
888
899
889 # Set calling of pdb on exceptions
900 # Set calling of pdb on exceptions
890 self.call_pdb = rc.pdb
901 self.call_pdb = rc.pdb
891
902
892 # Load user aliases
903 # Load user aliases
893 for alias in rc.alias:
904 for alias in rc.alias:
894 self.magic_alias(alias)
905 self.magic_alias(alias)
895
906
896 self.hooks.late_startup_hook()
907 self.hooks.late_startup_hook()
897
908
898 for cmd in self.rc.autoexec:
909 for cmd in self.rc.autoexec:
899 #print "autoexec>",cmd #dbg
910 #print "autoexec>",cmd #dbg
900 self.api.runlines(cmd)
911 self.api.runlines(cmd)
901
912
902 batchrun = False
913 batchrun = False
903 for batchfile in [path(arg) for arg in self.rc.args
914 for batchfile in [path(arg) for arg in self.rc.args
904 if arg.lower().endswith('.ipy')]:
915 if arg.lower().endswith('.ipy')]:
905 if not batchfile.isfile():
916 if not batchfile.isfile():
906 print "No such batch file:", batchfile
917 print "No such batch file:", batchfile
907 continue
918 continue
908 self.api.runlines(batchfile.text())
919 self.api.runlines(batchfile.text())
909 batchrun = True
920 batchrun = True
910 # without -i option, exit after running the batch file
921 # without -i option, exit after running the batch file
911 if batchrun and not self.rc.interact:
922 if batchrun and not self.rc.interact:
912 self.ask_exit()
923 self.ask_exit()
913
924
914 def init_namespaces(self):
925 def init_namespaces(self):
915 """Initialize all user-visible namespaces to their minimum defaults.
926 """Initialize all user-visible namespaces to their minimum defaults.
916
927
917 Certain history lists are also initialized here, as they effectively
928 Certain history lists are also initialized here, as they effectively
918 act as user namespaces.
929 act as user namespaces.
919
930
920 Note
931 Note
921 ----
932 ----
922 All data structures here are only filled in, they are NOT reset by this
933 All data structures here are only filled in, they are NOT reset by this
923 method. If they were not empty before, data will simply be added to
934 method. If they were not empty before, data will simply be added to
924 therm.
935 therm.
925 """
936 """
926 # The user namespace MUST have a pointer to the shell itself.
937 # The user namespace MUST have a pointer to the shell itself.
927 self.user_ns[self.name] = self
938 self.user_ns[self.name] = self
928
939
929 # Store the public api instance
940 # Store the public api instance
930 self.user_ns['_ip'] = self.api
941 self.user_ns['_ip'] = self.api
931
942
932 # make global variables for user access to the histories
943 # make global variables for user access to the histories
933 self.user_ns['_ih'] = self.input_hist
944 self.user_ns['_ih'] = self.input_hist
934 self.user_ns['_oh'] = self.output_hist
945 self.user_ns['_oh'] = self.output_hist
935 self.user_ns['_dh'] = self.dir_hist
946 self.user_ns['_dh'] = self.dir_hist
936
947
937 # user aliases to input and output histories
948 # user aliases to input and output histories
938 self.user_ns['In'] = self.input_hist
949 self.user_ns['In'] = self.input_hist
939 self.user_ns['Out'] = self.output_hist
950 self.user_ns['Out'] = self.output_hist
940
951
941 self.user_ns['_sh'] = IPython.shadowns
952 self.user_ns['_sh'] = IPython.shadowns
942
953
943 # Fill the history zero entry, user counter starts at 1
954 # Fill the history zero entry, user counter starts at 1
944 self.input_hist.append('\n')
955 self.input_hist.append('\n')
945 self.input_hist_raw.append('\n')
956 self.input_hist_raw.append('\n')
946
957
947 def add_builtins(self):
958 def add_builtins(self):
948 """Store ipython references into the builtin namespace.
959 """Store ipython references into the builtin namespace.
949
960
950 Some parts of ipython operate via builtins injected here, which hold a
961 Some parts of ipython operate via builtins injected here, which hold a
951 reference to IPython itself."""
962 reference to IPython itself."""
952
963
953 # TODO: deprecate all of these, they are unsafe
964 # TODO: deprecate all of these, they are unsafe
954 builtins_new = dict(__IPYTHON__ = self,
965 builtins_new = dict(__IPYTHON__ = self,
955 ip_set_hook = self.set_hook,
966 ip_set_hook = self.set_hook,
956 jobs = self.jobs,
967 jobs = self.jobs,
957 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
968 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
958 ipalias = wrap_deprecated(self.ipalias),
969 ipalias = wrap_deprecated(self.ipalias),
959 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
970 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
960 #_ip = self.api
971 #_ip = self.api
961 )
972 )
962 for biname,bival in builtins_new.items():
973 for biname,bival in builtins_new.items():
963 try:
974 try:
964 # store the orignal value so we can restore it
975 # store the orignal value so we can restore it
965 self.builtins_added[biname] = __builtin__.__dict__[biname]
976 self.builtins_added[biname] = __builtin__.__dict__[biname]
966 except KeyError:
977 except KeyError:
967 # or mark that it wasn't defined, and we'll just delete it at
978 # or mark that it wasn't defined, and we'll just delete it at
968 # cleanup
979 # cleanup
969 self.builtins_added[biname] = Undefined
980 self.builtins_added[biname] = Undefined
970 __builtin__.__dict__[biname] = bival
981 __builtin__.__dict__[biname] = bival
971
982
972 # Keep in the builtins a flag for when IPython is active. We set it
983 # Keep in the builtins a flag for when IPython is active. We set it
973 # with setdefault so that multiple nested IPythons don't clobber one
984 # with setdefault so that multiple nested IPythons don't clobber one
974 # another. Each will increase its value by one upon being activated,
985 # another. Each will increase its value by one upon being activated,
975 # which also gives us a way to determine the nesting level.
986 # which also gives us a way to determine the nesting level.
976 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
987 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
977
988
978 def clean_builtins(self):
989 def clean_builtins(self):
979 """Remove any builtins which might have been added by add_builtins, or
990 """Remove any builtins which might have been added by add_builtins, or
980 restore overwritten ones to their previous values."""
991 restore overwritten ones to their previous values."""
981 for biname,bival in self.builtins_added.items():
992 for biname,bival in self.builtins_added.items():
982 if bival is Undefined:
993 if bival is Undefined:
983 del __builtin__.__dict__[biname]
994 del __builtin__.__dict__[biname]
984 else:
995 else:
985 __builtin__.__dict__[biname] = bival
996 __builtin__.__dict__[biname] = bival
986 self.builtins_added.clear()
997 self.builtins_added.clear()
987
998
988 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
999 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
989 """set_hook(name,hook) -> sets an internal IPython hook.
1000 """set_hook(name,hook) -> sets an internal IPython hook.
990
1001
991 IPython exposes some of its internal API as user-modifiable hooks. By
1002 IPython exposes some of its internal API as user-modifiable hooks. By
992 adding your function to one of these hooks, you can modify IPython's
1003 adding your function to one of these hooks, you can modify IPython's
993 behavior to call at runtime your own routines."""
1004 behavior to call at runtime your own routines."""
994
1005
995 # At some point in the future, this should validate the hook before it
1006 # At some point in the future, this should validate the hook before it
996 # accepts it. Probably at least check that the hook takes the number
1007 # accepts it. Probably at least check that the hook takes the number
997 # of args it's supposed to.
1008 # of args it's supposed to.
998
1009
999 f = new.instancemethod(hook,self,self.__class__)
1010 f = new.instancemethod(hook,self,self.__class__)
1000
1011
1001 # check if the hook is for strdispatcher first
1012 # check if the hook is for strdispatcher first
1002 if str_key is not None:
1013 if str_key is not None:
1003 sdp = self.strdispatchers.get(name, StrDispatch())
1014 sdp = self.strdispatchers.get(name, StrDispatch())
1004 sdp.add_s(str_key, f, priority )
1015 sdp.add_s(str_key, f, priority )
1005 self.strdispatchers[name] = sdp
1016 self.strdispatchers[name] = sdp
1006 return
1017 return
1007 if re_key is not None:
1018 if re_key is not None:
1008 sdp = self.strdispatchers.get(name, StrDispatch())
1019 sdp = self.strdispatchers.get(name, StrDispatch())
1009 sdp.add_re(re.compile(re_key), f, priority )
1020 sdp.add_re(re.compile(re_key), f, priority )
1010 self.strdispatchers[name] = sdp
1021 self.strdispatchers[name] = sdp
1011 return
1022 return
1012
1023
1013 dp = getattr(self.hooks, name, None)
1024 dp = getattr(self.hooks, name, None)
1014 if name not in IPython.hooks.__all__:
1025 if name not in IPython.hooks.__all__:
1015 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
1026 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
1016 if not dp:
1027 if not dp:
1017 dp = IPython.hooks.CommandChainDispatcher()
1028 dp = IPython.hooks.CommandChainDispatcher()
1018
1029
1019 try:
1030 try:
1020 dp.add(f,priority)
1031 dp.add(f,priority)
1021 except AttributeError:
1032 except AttributeError:
1022 # it was not commandchain, plain old func - replace
1033 # it was not commandchain, plain old func - replace
1023 dp = f
1034 dp = f
1024
1035
1025 setattr(self.hooks,name, dp)
1036 setattr(self.hooks,name, dp)
1026
1037
1027
1038
1028 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
1039 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
1029
1040
1030 def set_crash_handler(self,crashHandler):
1041 def set_crash_handler(self,crashHandler):
1031 """Set the IPython crash handler.
1042 """Set the IPython crash handler.
1032
1043
1033 This must be a callable with a signature suitable for use as
1044 This must be a callable with a signature suitable for use as
1034 sys.excepthook."""
1045 sys.excepthook."""
1035
1046
1036 # Install the given crash handler as the Python exception hook
1047 # Install the given crash handler as the Python exception hook
1037 sys.excepthook = crashHandler
1048 sys.excepthook = crashHandler
1038
1049
1039 # The instance will store a pointer to this, so that runtime code
1050 # The instance will store a pointer to this, so that runtime code
1040 # (such as magics) can access it. This is because during the
1051 # (such as magics) can access it. This is because during the
1041 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1052 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1042 # frameworks).
1053 # frameworks).
1043 self.sys_excepthook = sys.excepthook
1054 self.sys_excepthook = sys.excepthook
1044
1055
1045
1056
1046 def set_custom_exc(self,exc_tuple,handler):
1057 def set_custom_exc(self,exc_tuple,handler):
1047 """set_custom_exc(exc_tuple,handler)
1058 """set_custom_exc(exc_tuple,handler)
1048
1059
1049 Set a custom exception handler, which will be called if any of the
1060 Set a custom exception handler, which will be called if any of the
1050 exceptions in exc_tuple occur in the mainloop (specifically, in the
1061 exceptions in exc_tuple occur in the mainloop (specifically, in the
1051 runcode() method.
1062 runcode() method.
1052
1063
1053 Inputs:
1064 Inputs:
1054
1065
1055 - exc_tuple: a *tuple* of valid exceptions to call the defined
1066 - exc_tuple: a *tuple* of valid exceptions to call the defined
1056 handler for. It is very important that you use a tuple, and NOT A
1067 handler for. It is very important that you use a tuple, and NOT A
1057 LIST here, because of the way Python's except statement works. If
1068 LIST here, because of the way Python's except statement works. If
1058 you only want to trap a single exception, use a singleton tuple:
1069 you only want to trap a single exception, use a singleton tuple:
1059
1070
1060 exc_tuple == (MyCustomException,)
1071 exc_tuple == (MyCustomException,)
1061
1072
1062 - handler: this must be defined as a function with the following
1073 - handler: this must be defined as a function with the following
1063 basic interface: def my_handler(self,etype,value,tb).
1074 basic interface: def my_handler(self,etype,value,tb).
1064
1075
1065 This will be made into an instance method (via new.instancemethod)
1076 This will be made into an instance method (via new.instancemethod)
1066 of IPython itself, and it will be called if any of the exceptions
1077 of IPython itself, and it will be called if any of the exceptions
1067 listed in the exc_tuple are caught. If the handler is None, an
1078 listed in the exc_tuple are caught. If the handler is None, an
1068 internal basic one is used, which just prints basic info.
1079 internal basic one is used, which just prints basic info.
1069
1080
1070 WARNING: by putting in your own exception handler into IPython's main
1081 WARNING: by putting in your own exception handler into IPython's main
1071 execution loop, you run a very good chance of nasty crashes. This
1082 execution loop, you run a very good chance of nasty crashes. This
1072 facility should only be used if you really know what you are doing."""
1083 facility should only be used if you really know what you are doing."""
1073
1084
1074 assert type(exc_tuple)==type(()) , \
1085 assert type(exc_tuple)==type(()) , \
1075 "The custom exceptions must be given AS A TUPLE."
1086 "The custom exceptions must be given AS A TUPLE."
1076
1087
1077 def dummy_handler(self,etype,value,tb):
1088 def dummy_handler(self,etype,value,tb):
1078 print '*** Simple custom exception handler ***'
1089 print '*** Simple custom exception handler ***'
1079 print 'Exception type :',etype
1090 print 'Exception type :',etype
1080 print 'Exception value:',value
1091 print 'Exception value:',value
1081 print 'Traceback :',tb
1092 print 'Traceback :',tb
1082 print 'Source code :','\n'.join(self.buffer)
1093 print 'Source code :','\n'.join(self.buffer)
1083
1094
1084 if handler is None: handler = dummy_handler
1095 if handler is None: handler = dummy_handler
1085
1096
1086 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1097 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1087 self.custom_exceptions = exc_tuple
1098 self.custom_exceptions = exc_tuple
1088
1099
1089 def set_custom_completer(self,completer,pos=0):
1100 def set_custom_completer(self,completer,pos=0):
1090 """set_custom_completer(completer,pos=0)
1101 """set_custom_completer(completer,pos=0)
1091
1102
1092 Adds a new custom completer function.
1103 Adds a new custom completer function.
1093
1104
1094 The position argument (defaults to 0) is the index in the completers
1105 The position argument (defaults to 0) is the index in the completers
1095 list where you want the completer to be inserted."""
1106 list where you want the completer to be inserted."""
1096
1107
1097 newcomp = new.instancemethod(completer,self.Completer,
1108 newcomp = new.instancemethod(completer,self.Completer,
1098 self.Completer.__class__)
1109 self.Completer.__class__)
1099 self.Completer.matchers.insert(pos,newcomp)
1110 self.Completer.matchers.insert(pos,newcomp)
1100
1111
1101 def set_completer(self):
1112 def set_completer(self):
1102 """reset readline's completer to be our own."""
1113 """reset readline's completer to be our own."""
1103 self.readline.set_completer(self.Completer.complete)
1114 self.readline.set_completer(self.Completer.complete)
1104
1115
1105 def _get_call_pdb(self):
1116 def _get_call_pdb(self):
1106 return self._call_pdb
1117 return self._call_pdb
1107
1118
1108 def _set_call_pdb(self,val):
1119 def _set_call_pdb(self,val):
1109
1120
1110 if val not in (0,1,False,True):
1121 if val not in (0,1,False,True):
1111 raise ValueError,'new call_pdb value must be boolean'
1122 raise ValueError,'new call_pdb value must be boolean'
1112
1123
1113 # store value in instance
1124 # store value in instance
1114 self._call_pdb = val
1125 self._call_pdb = val
1115
1126
1116 # notify the actual exception handlers
1127 # notify the actual exception handlers
1117 self.InteractiveTB.call_pdb = val
1128 self.InteractiveTB.call_pdb = val
1118 if self.isthreaded:
1129 if self.isthreaded:
1119 try:
1130 try:
1120 self.sys_excepthook.call_pdb = val
1131 self.sys_excepthook.call_pdb = val
1121 except:
1132 except:
1122 warn('Failed to activate pdb for threaded exception handler')
1133 warn('Failed to activate pdb for threaded exception handler')
1123
1134
1124 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1135 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1125 'Control auto-activation of pdb at exceptions')
1136 'Control auto-activation of pdb at exceptions')
1126
1137
1127 # These special functions get installed in the builtin namespace, to
1138 # These special functions get installed in the builtin namespace, to
1128 # provide programmatic (pure python) access to magics, aliases and system
1139 # provide programmatic (pure python) access to magics, aliases and system
1129 # calls. This is important for logging, user scripting, and more.
1140 # calls. This is important for logging, user scripting, and more.
1130
1141
1131 # We are basically exposing, via normal python functions, the three
1142 # We are basically exposing, via normal python functions, the three
1132 # mechanisms in which ipython offers special call modes (magics for
1143 # mechanisms in which ipython offers special call modes (magics for
1133 # internal control, aliases for direct system access via pre-selected
1144 # internal control, aliases for direct system access via pre-selected
1134 # names, and !cmd for calling arbitrary system commands).
1145 # names, and !cmd for calling arbitrary system commands).
1135
1146
1136 def ipmagic(self,arg_s):
1147 def ipmagic(self,arg_s):
1137 """Call a magic function by name.
1148 """Call a magic function by name.
1138
1149
1139 Input: a string containing the name of the magic function to call and any
1150 Input: a string containing the name of the magic function to call and any
1140 additional arguments to be passed to the magic.
1151 additional arguments to be passed to the magic.
1141
1152
1142 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1153 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1143 prompt:
1154 prompt:
1144
1155
1145 In[1]: %name -opt foo bar
1156 In[1]: %name -opt foo bar
1146
1157
1147 To call a magic without arguments, simply use ipmagic('name').
1158 To call a magic without arguments, simply use ipmagic('name').
1148
1159
1149 This provides a proper Python function to call IPython's magics in any
1160 This provides a proper Python function to call IPython's magics in any
1150 valid Python code you can type at the interpreter, including loops and
1161 valid Python code you can type at the interpreter, including loops and
1151 compound statements. It is added by IPython to the Python builtin
1162 compound statements. It is added by IPython to the Python builtin
1152 namespace upon initialization."""
1163 namespace upon initialization."""
1153
1164
1154 args = arg_s.split(' ',1)
1165 args = arg_s.split(' ',1)
1155 magic_name = args[0]
1166 magic_name = args[0]
1156 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1167 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1157
1168
1158 try:
1169 try:
1159 magic_args = args[1]
1170 magic_args = args[1]
1160 except IndexError:
1171 except IndexError:
1161 magic_args = ''
1172 magic_args = ''
1162 fn = getattr(self,'magic_'+magic_name,None)
1173 fn = getattr(self,'magic_'+magic_name,None)
1163 if fn is None:
1174 if fn is None:
1164 error("Magic function `%s` not found." % magic_name)
1175 error("Magic function `%s` not found." % magic_name)
1165 else:
1176 else:
1166 magic_args = self.var_expand(magic_args,1)
1177 magic_args = self.var_expand(magic_args,1)
1167 return fn(magic_args)
1178 return fn(magic_args)
1168
1179
1169 def ipalias(self,arg_s):
1180 def ipalias(self,arg_s):
1170 """Call an alias by name.
1181 """Call an alias by name.
1171
1182
1172 Input: a string containing the name of the alias to call and any
1183 Input: a string containing the name of the alias to call and any
1173 additional arguments to be passed to the magic.
1184 additional arguments to be passed to the magic.
1174
1185
1175 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1186 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1176 prompt:
1187 prompt:
1177
1188
1178 In[1]: name -opt foo bar
1189 In[1]: name -opt foo bar
1179
1190
1180 To call an alias without arguments, simply use ipalias('name').
1191 To call an alias without arguments, simply use ipalias('name').
1181
1192
1182 This provides a proper Python function to call IPython's aliases in any
1193 This provides a proper Python function to call IPython's aliases in any
1183 valid Python code you can type at the interpreter, including loops and
1194 valid Python code you can type at the interpreter, including loops and
1184 compound statements. It is added by IPython to the Python builtin
1195 compound statements. It is added by IPython to the Python builtin
1185 namespace upon initialization."""
1196 namespace upon initialization."""
1186
1197
1187 args = arg_s.split(' ',1)
1198 args = arg_s.split(' ',1)
1188 alias_name = args[0]
1199 alias_name = args[0]
1189 try:
1200 try:
1190 alias_args = args[1]
1201 alias_args = args[1]
1191 except IndexError:
1202 except IndexError:
1192 alias_args = ''
1203 alias_args = ''
1193 if alias_name in self.alias_table:
1204 if alias_name in self.alias_table:
1194 self.call_alias(alias_name,alias_args)
1205 self.call_alias(alias_name,alias_args)
1195 else:
1206 else:
1196 error("Alias `%s` not found." % alias_name)
1207 error("Alias `%s` not found." % alias_name)
1197
1208
1198 def ipsystem(self,arg_s):
1209 def ipsystem(self,arg_s):
1199 """Make a system call, using IPython."""
1210 """Make a system call, using IPython."""
1200
1211
1201 self.system(arg_s)
1212 self.system(arg_s)
1202
1213
1203 def complete(self,text):
1214 def complete(self,text):
1204 """Return a sorted list of all possible completions on text.
1215 """Return a sorted list of all possible completions on text.
1205
1216
1206 Inputs:
1217 Inputs:
1207
1218
1208 - text: a string of text to be completed on.
1219 - text: a string of text to be completed on.
1209
1220
1210 This is a wrapper around the completion mechanism, similar to what
1221 This is a wrapper around the completion mechanism, similar to what
1211 readline does at the command line when the TAB key is hit. By
1222 readline does at the command line when the TAB key is hit. By
1212 exposing it as a method, it can be used by other non-readline
1223 exposing it as a method, it can be used by other non-readline
1213 environments (such as GUIs) for text completion.
1224 environments (such as GUIs) for text completion.
1214
1225
1215 Simple usage example:
1226 Simple usage example:
1216
1227
1217 In [7]: x = 'hello'
1228 In [7]: x = 'hello'
1218
1229
1219 In [8]: x
1230 In [8]: x
1220 Out[8]: 'hello'
1231 Out[8]: 'hello'
1221
1232
1222 In [9]: print x
1233 In [9]: print x
1223 hello
1234 hello
1224
1235
1225 In [10]: _ip.IP.complete('x.l')
1236 In [10]: _ip.IP.complete('x.l')
1226 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1237 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1227 """
1238 """
1228
1239
1229 complete = self.Completer.complete
1240 complete = self.Completer.complete
1230 state = 0
1241 state = 0
1231 # use a dict so we get unique keys, since ipyhton's multiple
1242 # use a dict so we get unique keys, since ipyhton's multiple
1232 # completers can return duplicates. When we make 2.4 a requirement,
1243 # completers can return duplicates. When we make 2.4 a requirement,
1233 # start using sets instead, which are faster.
1244 # start using sets instead, which are faster.
1234 comps = {}
1245 comps = {}
1235 while True:
1246 while True:
1236 newcomp = complete(text,state,line_buffer=text)
1247 newcomp = complete(text,state,line_buffer=text)
1237 if newcomp is None:
1248 if newcomp is None:
1238 break
1249 break
1239 comps[newcomp] = 1
1250 comps[newcomp] = 1
1240 state += 1
1251 state += 1
1241 outcomps = comps.keys()
1252 outcomps = comps.keys()
1242 outcomps.sort()
1253 outcomps.sort()
1243 #print "T:",text,"OC:",outcomps # dbg
1254 #print "T:",text,"OC:",outcomps # dbg
1244 #print "vars:",self.user_ns.keys()
1255 #print "vars:",self.user_ns.keys()
1245 return outcomps
1256 return outcomps
1246
1257
1247 def set_completer_frame(self, frame=None):
1258 def set_completer_frame(self, frame=None):
1248 if frame:
1259 if frame:
1249 self.Completer.namespace = frame.f_locals
1260 self.Completer.namespace = frame.f_locals
1250 self.Completer.global_namespace = frame.f_globals
1261 self.Completer.global_namespace = frame.f_globals
1251 else:
1262 else:
1252 self.Completer.namespace = self.user_ns
1263 self.Completer.namespace = self.user_ns
1253 self.Completer.global_namespace = self.user_global_ns
1264 self.Completer.global_namespace = self.user_global_ns
1254
1265
1255 def init_auto_alias(self):
1266 def init_auto_alias(self):
1256 """Define some aliases automatically.
1267 """Define some aliases automatically.
1257
1268
1258 These are ALL parameter-less aliases"""
1269 These are ALL parameter-less aliases"""
1259
1270
1260 for alias,cmd in self.auto_alias:
1271 for alias,cmd in self.auto_alias:
1261 self.getapi().defalias(alias,cmd)
1272 self.getapi().defalias(alias,cmd)
1262
1273
1263
1274
1264 def alias_table_validate(self,verbose=0):
1275 def alias_table_validate(self,verbose=0):
1265 """Update information about the alias table.
1276 """Update information about the alias table.
1266
1277
1267 In particular, make sure no Python keywords/builtins are in it."""
1278 In particular, make sure no Python keywords/builtins are in it."""
1268
1279
1269 no_alias = self.no_alias
1280 no_alias = self.no_alias
1270 for k in self.alias_table.keys():
1281 for k in self.alias_table.keys():
1271 if k in no_alias:
1282 if k in no_alias:
1272 del self.alias_table[k]
1283 del self.alias_table[k]
1273 if verbose:
1284 if verbose:
1274 print ("Deleting alias <%s>, it's a Python "
1285 print ("Deleting alias <%s>, it's a Python "
1275 "keyword or builtin." % k)
1286 "keyword or builtin." % k)
1276
1287
1277 def set_autoindent(self,value=None):
1288 def set_autoindent(self,value=None):
1278 """Set the autoindent flag, checking for readline support.
1289 """Set the autoindent flag, checking for readline support.
1279
1290
1280 If called with no arguments, it acts as a toggle."""
1291 If called with no arguments, it acts as a toggle."""
1281
1292
1282 if not self.has_readline:
1293 if not self.has_readline:
1283 if os.name == 'posix':
1294 if os.name == 'posix':
1284 warn("The auto-indent feature requires the readline library")
1295 warn("The auto-indent feature requires the readline library")
1285 self.autoindent = 0
1296 self.autoindent = 0
1286 return
1297 return
1287 if value is None:
1298 if value is None:
1288 self.autoindent = not self.autoindent
1299 self.autoindent = not self.autoindent
1289 else:
1300 else:
1290 self.autoindent = value
1301 self.autoindent = value
1291
1302
1292 def rc_set_toggle(self,rc_field,value=None):
1303 def rc_set_toggle(self,rc_field,value=None):
1293 """Set or toggle a field in IPython's rc config. structure.
1304 """Set or toggle a field in IPython's rc config. structure.
1294
1305
1295 If called with no arguments, it acts as a toggle.
1306 If called with no arguments, it acts as a toggle.
1296
1307
1297 If called with a non-existent field, the resulting AttributeError
1308 If called with a non-existent field, the resulting AttributeError
1298 exception will propagate out."""
1309 exception will propagate out."""
1299
1310
1300 rc_val = getattr(self.rc,rc_field)
1311 rc_val = getattr(self.rc,rc_field)
1301 if value is None:
1312 if value is None:
1302 value = not rc_val
1313 value = not rc_val
1303 setattr(self.rc,rc_field,value)
1314 setattr(self.rc,rc_field,value)
1304
1315
1305 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1316 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1306 """Install the user configuration directory.
1317 """Install the user configuration directory.
1307
1318
1308 Note
1319 Note
1309 ----
1320 ----
1310 DEPRECATED: use the top-level user_setup() function instead.
1321 DEPRECATED: use the top-level user_setup() function instead.
1311 """
1322 """
1312 return user_setup(ipythondir,rc_suffix,mode)
1323 return user_setup(ipythondir,rc_suffix,mode)
1313
1324
1314 def atexit_operations(self):
1325 def atexit_operations(self):
1315 """This will be executed at the time of exit.
1326 """This will be executed at the time of exit.
1316
1327
1317 Saving of persistent data should be performed here. """
1328 Saving of persistent data should be performed here. """
1318
1329
1319 #print '*** IPython exit cleanup ***' # dbg
1330 #print '*** IPython exit cleanup ***' # dbg
1320 # input history
1331 # input history
1321 self.savehist()
1332 self.savehist()
1322
1333
1323 # Cleanup all tempfiles left around
1334 # Cleanup all tempfiles left around
1324 for tfile in self.tempfiles:
1335 for tfile in self.tempfiles:
1325 try:
1336 try:
1326 os.unlink(tfile)
1337 os.unlink(tfile)
1327 except OSError:
1338 except OSError:
1328 pass
1339 pass
1329
1340
1330 # Clear all user namespaces to release all references cleanly.
1341 # Clear all user namespaces to release all references cleanly.
1331 self.reset()
1342 self.reset()
1332
1343
1333 # Run user hooks
1344 # Run user hooks
1334 self.hooks.shutdown_hook()
1345 self.hooks.shutdown_hook()
1335
1346
1336 def reset(self):
1347 def reset(self):
1337 """Clear all internal namespaces.
1348 """Clear all internal namespaces.
1338
1349
1339 Note that this is much more aggressive than %reset, since it clears
1350 Note that this is much more aggressive than %reset, since it clears
1340 fully all namespaces, as well as all input/output lists.
1351 fully all namespaces, as well as all input/output lists.
1341 """
1352 """
1342 for ns in self.ns_refs_table:
1353 for ns in self.ns_refs_table:
1343 ns.clear()
1354 ns.clear()
1344
1355
1345 # Clear input and output histories
1356 # Clear input and output histories
1346 self.input_hist[:] = []
1357 self.input_hist[:] = []
1347 self.input_hist_raw[:] = []
1358 self.input_hist_raw[:] = []
1348 self.output_hist.clear()
1359 self.output_hist.clear()
1349 # Restore the user namespaces to minimal usability
1360 # Restore the user namespaces to minimal usability
1350 self.init_namespaces()
1361 self.init_namespaces()
1351
1362
1352 def savehist(self):
1363 def savehist(self):
1353 """Save input history to a file (via readline library)."""
1364 """Save input history to a file (via readline library)."""
1354
1365
1355 if not self.has_readline:
1366 if not self.has_readline:
1356 return
1367 return
1357
1368
1358 try:
1369 try:
1359 self.readline.write_history_file(self.histfile)
1370 self.readline.write_history_file(self.histfile)
1360 except:
1371 except:
1361 print 'Unable to save IPython command history to file: ' + \
1372 print 'Unable to save IPython command history to file: ' + \
1362 `self.histfile`
1373 `self.histfile`
1363
1374
1364 def reloadhist(self):
1375 def reloadhist(self):
1365 """Reload the input history from disk file."""
1376 """Reload the input history from disk file."""
1366
1377
1367 if self.has_readline:
1378 if self.has_readline:
1368 try:
1379 try:
1369 self.readline.clear_history()
1380 self.readline.clear_history()
1370 self.readline.read_history_file(self.shell.histfile)
1381 self.readline.read_history_file(self.shell.histfile)
1371 except AttributeError:
1382 except AttributeError:
1372 pass
1383 pass
1373
1384
1374
1385
1375 def history_saving_wrapper(self, func):
1386 def history_saving_wrapper(self, func):
1376 """ Wrap func for readline history saving
1387 """ Wrap func for readline history saving
1377
1388
1378 Convert func into callable that saves & restores
1389 Convert func into callable that saves & restores
1379 history around the call """
1390 history around the call """
1380
1391
1381 if not self.has_readline:
1392 if not self.has_readline:
1382 return func
1393 return func
1383
1394
1384 def wrapper():
1395 def wrapper():
1385 self.savehist()
1396 self.savehist()
1386 try:
1397 try:
1387 func()
1398 func()
1388 finally:
1399 finally:
1389 readline.read_history_file(self.histfile)
1400 readline.read_history_file(self.histfile)
1390 return wrapper
1401 return wrapper
1391
1402
1392 def pre_readline(self):
1403 def pre_readline(self):
1393 """readline hook to be used at the start of each line.
1404 """readline hook to be used at the start of each line.
1394
1405
1395 Currently it handles auto-indent only."""
1406 Currently it handles auto-indent only."""
1396
1407
1397 #debugx('self.indent_current_nsp','pre_readline:')
1408 #debugx('self.indent_current_nsp','pre_readline:')
1398
1409
1399 if self.rl_do_indent:
1410 if self.rl_do_indent:
1400 self.readline.insert_text(self.indent_current_str())
1411 self.readline.insert_text(self.indent_current_str())
1401 if self.rl_next_input is not None:
1412 if self.rl_next_input is not None:
1402 self.readline.insert_text(self.rl_next_input)
1413 self.readline.insert_text(self.rl_next_input)
1403 self.rl_next_input = None
1414 self.rl_next_input = None
1404
1415
1405 def init_readline(self):
1416 def init_readline(self):
1406 """Command history completion/saving/reloading."""
1417 """Command history completion/saving/reloading."""
1407
1418
1408
1419
1409 import IPython.rlineimpl as readline
1420 import IPython.rlineimpl as readline
1410
1421
1411 if not readline.have_readline:
1422 if not readline.have_readline:
1412 self.has_readline = 0
1423 self.has_readline = 0
1413 self.readline = None
1424 self.readline = None
1414 # no point in bugging windows users with this every time:
1425 # no point in bugging windows users with this every time:
1415 warn('Readline services not available on this platform.')
1426 warn('Readline services not available on this platform.')
1416 else:
1427 else:
1417 sys.modules['readline'] = readline
1428 sys.modules['readline'] = readline
1418 import atexit
1429 import atexit
1419 from IPython.completer import IPCompleter
1430 from IPython.completer import IPCompleter
1420 self.Completer = IPCompleter(self,
1431 self.Completer = IPCompleter(self,
1421 self.user_ns,
1432 self.user_ns,
1422 self.user_global_ns,
1433 self.user_global_ns,
1423 self.rc.readline_omit__names,
1434 self.rc.readline_omit__names,
1424 self.alias_table)
1435 self.alias_table)
1425 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1436 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1426 self.strdispatchers['complete_command'] = sdisp
1437 self.strdispatchers['complete_command'] = sdisp
1427 self.Completer.custom_completers = sdisp
1438 self.Completer.custom_completers = sdisp
1428 # Platform-specific configuration
1439 # Platform-specific configuration
1429 if os.name == 'nt':
1440 if os.name == 'nt':
1430 self.readline_startup_hook = readline.set_pre_input_hook
1441 self.readline_startup_hook = readline.set_pre_input_hook
1431 else:
1442 else:
1432 self.readline_startup_hook = readline.set_startup_hook
1443 self.readline_startup_hook = readline.set_startup_hook
1433
1444
1434 # Load user's initrc file (readline config)
1445 # Load user's initrc file (readline config)
1435 # Or if libedit is used, load editrc.
1446 # Or if libedit is used, load editrc.
1436 inputrc_name = os.environ.get('INPUTRC')
1447 inputrc_name = os.environ.get('INPUTRC')
1437 if inputrc_name is None:
1448 if inputrc_name is None:
1438 home_dir = get_home_dir()
1449 home_dir = get_home_dir()
1439 if home_dir is not None:
1450 if home_dir is not None:
1440 inputrc_name = '.inputrc'
1451 inputrc_name = '.inputrc'
1441 if readline.uses_libedit:
1452 if readline.uses_libedit:
1442 inputrc_name = '.editrc'
1453 inputrc_name = '.editrc'
1443 inputrc_name = os.path.join(home_dir, inputrc_name)
1454 inputrc_name = os.path.join(home_dir, inputrc_name)
1444 if os.path.isfile(inputrc_name):
1455 if os.path.isfile(inputrc_name):
1445 try:
1456 try:
1446 readline.read_init_file(inputrc_name)
1457 readline.read_init_file(inputrc_name)
1447 except:
1458 except:
1448 warn('Problems reading readline initialization file <%s>'
1459 warn('Problems reading readline initialization file <%s>'
1449 % inputrc_name)
1460 % inputrc_name)
1450
1461
1451 self.has_readline = 1
1462 self.has_readline = 1
1452 self.readline = readline
1463 self.readline = readline
1453 # save this in sys so embedded copies can restore it properly
1464 # save this in sys so embedded copies can restore it properly
1454 sys.ipcompleter = self.Completer.complete
1465 sys.ipcompleter = self.Completer.complete
1455 self.set_completer()
1466 self.set_completer()
1456
1467
1457 # Configure readline according to user's prefs
1468 # Configure readline according to user's prefs
1458 # This is only done if GNU readline is being used. If libedit
1469 # This is only done if GNU readline is being used. If libedit
1459 # is being used (as on Leopard) the readline config is
1470 # is being used (as on Leopard) the readline config is
1460 # not run as the syntax for libedit is different.
1471 # not run as the syntax for libedit is different.
1461 if not readline.uses_libedit:
1472 if not readline.uses_libedit:
1462 for rlcommand in self.rc.readline_parse_and_bind:
1473 for rlcommand in self.rc.readline_parse_and_bind:
1463 #print "loading rl:",rlcommand # dbg
1474 #print "loading rl:",rlcommand # dbg
1464 readline.parse_and_bind(rlcommand)
1475 readline.parse_and_bind(rlcommand)
1465
1476
1466 # remove some chars from the delimiters list
1477 # remove some chars from the delimiters list
1467 delims = readline.get_completer_delims()
1478 delims = readline.get_completer_delims()
1468 delims = delims.translate(string._idmap,
1479 delims = delims.translate(string._idmap,
1469 self.rc.readline_remove_delims)
1480 self.rc.readline_remove_delims)
1470 readline.set_completer_delims(delims)
1481 readline.set_completer_delims(delims)
1471 # otherwise we end up with a monster history after a while:
1482 # otherwise we end up with a monster history after a while:
1472 readline.set_history_length(1000)
1483 readline.set_history_length(1000)
1473 try:
1484 try:
1474 #print '*** Reading readline history' # dbg
1485 #print '*** Reading readline history' # dbg
1475 readline.read_history_file(self.histfile)
1486 readline.read_history_file(self.histfile)
1476 except IOError:
1487 except IOError:
1477 pass # It doesn't exist yet.
1488 pass # It doesn't exist yet.
1478
1489
1479 atexit.register(self.atexit_operations)
1490 atexit.register(self.atexit_operations)
1480 del atexit
1491 del atexit
1481
1492
1482 # Configure auto-indent for all platforms
1493 # Configure auto-indent for all platforms
1483 self.set_autoindent(self.rc.autoindent)
1494 self.set_autoindent(self.rc.autoindent)
1484
1495
1485 def ask_yes_no(self,prompt,default=True):
1496 def ask_yes_no(self,prompt,default=True):
1486 if self.rc.quiet:
1497 if self.rc.quiet:
1487 return True
1498 return True
1488 return ask_yes_no(prompt,default)
1499 return ask_yes_no(prompt,default)
1489
1500
1490 def cache_main_mod(self,mod,fname=None):
1501 def new_main_mod(self,ns=None):
1491 """Cache a main module.
1502 """Return a new 'main' module object for user code execution.
1503 """
1504 main_mod = self._user_main_module
1505 init_fakemod_dict(main_mod,ns)
1506 return main_mod
1507
1508 def cache_main_mod(self,ns,fname):
1509 """Cache a main module's namespace.
1492
1510
1493 When scripts are executed via %run, we must keep a reference to their
1511 When scripts are executed via %run, we must keep a reference to the
1494 __main__ module (a FakeModule instance) around so that Python doesn't
1512 namespace of their __main__ module (a FakeModule instance) around so
1495 clear it, rendering objects defined therein useless.
1513 that Python doesn't clear it, rendering objects defined therein
1514 useless.
1496
1515
1497 This method keeps said reference in a private dict, keyed by the
1516 This method keeps said reference in a private dict, keyed by the
1498 absolute path of the module object (which corresponds to the script
1517 absolute path of the module object (which corresponds to the script
1499 path). This way, for multiple executions of the same script we only
1518 path). This way, for multiple executions of the same script we only
1500 keep one copy of __main__ (the last one), thus preventing memory leaks
1519 keep one copy of the namespace (the last one), thus preventing memory
1501 from old references while allowing the objects from the last execution
1520 leaks from old references while allowing the objects from the last
1502 to be accessible.
1521 execution to be accessible.
1522
1523 Note: we can not allow the actual FakeModule instances to be deleted,
1524 because of how Python tears down modules (it hard-sets all their
1525 references to None without regard for reference counts). This method
1526 must therefore make a *copy* of the given namespace, to allow the
1527 original module's __dict__ to be cleared and reused.
1528
1503
1529
1504 Parameters
1530 Parameters
1505 ----------
1531 ----------
1506 mod : a module object
1532 ns : a namespace (a dict, typically)
1533
1534 fname : str
1535 Filename associated with the namespace.
1507
1536
1508 Examples
1537 Examples
1509 --------
1538 --------
1510
1539
1511 In [10]: import IPython
1540 In [10]: import IPython
1512
1541
1513 In [11]: _ip.IP.cache_main_mod(IPython)
1542 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1514
1543
1515 In [12]: IPython.__file__ in _ip.IP._user_main_modules
1544 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1516 Out[12]: True
1545 Out[12]: True
1517 """
1546 """
1518 if fname is None:
1547 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1519 fname = mod.__file__
1520 #print >> sys.stderr, 'CFNAME :', os.path.abspath(fname) # dbg
1521 self._user_main_modules[os.path.abspath(fname)] = mod
1522
1548
1523 def clear_main_mod_cache(self):
1549 def clear_main_mod_cache(self):
1524 """Clear the cache of main modules.
1550 """Clear the cache of main modules.
1525
1551
1526 Mainly for use by utilities like %reset.
1552 Mainly for use by utilities like %reset.
1527
1553
1528 Examples
1554 Examples
1529 --------
1555 --------
1530
1556
1531 In [15]: import IPython
1557 In [15]: import IPython
1532
1558
1533 In [16]: _ip.IP.cache_main_mod(IPython)
1559 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1534
1560
1535 In [17]: len(_ip.IP._user_main_modules) > 0
1561 In [17]: len(_ip.IP._main_ns_cache) > 0
1536 Out[17]: True
1562 Out[17]: True
1537
1563
1538 In [18]: _ip.IP.clear_main_mod_cache()
1564 In [18]: _ip.IP.clear_main_mod_cache()
1539
1565
1540 In [19]: len(_ip.IP._user_main_modules) == 0
1566 In [19]: len(_ip.IP._main_ns_cache) == 0
1541 Out[19]: True
1567 Out[19]: True
1542 """
1568 """
1543 self._user_main_modules.clear()
1569 self._main_ns_cache.clear()
1544
1570
1545 def _should_recompile(self,e):
1571 def _should_recompile(self,e):
1546 """Utility routine for edit_syntax_error"""
1572 """Utility routine for edit_syntax_error"""
1547
1573
1548 if e.filename in ('<ipython console>','<input>','<string>',
1574 if e.filename in ('<ipython console>','<input>','<string>',
1549 '<console>','<BackgroundJob compilation>',
1575 '<console>','<BackgroundJob compilation>',
1550 None):
1576 None):
1551
1577
1552 return False
1578 return False
1553 try:
1579 try:
1554 if (self.rc.autoedit_syntax and
1580 if (self.rc.autoedit_syntax and
1555 not self.ask_yes_no('Return to editor to correct syntax error? '
1581 not self.ask_yes_no('Return to editor to correct syntax error? '
1556 '[Y/n] ','y')):
1582 '[Y/n] ','y')):
1557 return False
1583 return False
1558 except EOFError:
1584 except EOFError:
1559 return False
1585 return False
1560
1586
1561 def int0(x):
1587 def int0(x):
1562 try:
1588 try:
1563 return int(x)
1589 return int(x)
1564 except TypeError:
1590 except TypeError:
1565 return 0
1591 return 0
1566 # always pass integer line and offset values to editor hook
1592 # always pass integer line and offset values to editor hook
1567 try:
1593 try:
1568 self.hooks.fix_error_editor(e.filename,
1594 self.hooks.fix_error_editor(e.filename,
1569 int0(e.lineno),int0(e.offset),e.msg)
1595 int0(e.lineno),int0(e.offset),e.msg)
1570 except IPython.ipapi.TryNext:
1596 except IPython.ipapi.TryNext:
1571 warn('Could not open editor')
1597 warn('Could not open editor')
1572 return False
1598 return False
1573 return True
1599 return True
1574
1600
1575 def edit_syntax_error(self):
1601 def edit_syntax_error(self):
1576 """The bottom half of the syntax error handler called in the main loop.
1602 """The bottom half of the syntax error handler called in the main loop.
1577
1603
1578 Loop until syntax error is fixed or user cancels.
1604 Loop until syntax error is fixed or user cancels.
1579 """
1605 """
1580
1606
1581 while self.SyntaxTB.last_syntax_error:
1607 while self.SyntaxTB.last_syntax_error:
1582 # copy and clear last_syntax_error
1608 # copy and clear last_syntax_error
1583 err = self.SyntaxTB.clear_err_state()
1609 err = self.SyntaxTB.clear_err_state()
1584 if not self._should_recompile(err):
1610 if not self._should_recompile(err):
1585 return
1611 return
1586 try:
1612 try:
1587 # may set last_syntax_error again if a SyntaxError is raised
1613 # may set last_syntax_error again if a SyntaxError is raised
1588 self.safe_execfile(err.filename,self.user_ns)
1614 self.safe_execfile(err.filename,self.user_ns)
1589 except:
1615 except:
1590 self.showtraceback()
1616 self.showtraceback()
1591 else:
1617 else:
1592 try:
1618 try:
1593 f = file(err.filename)
1619 f = file(err.filename)
1594 try:
1620 try:
1595 sys.displayhook(f.read())
1621 sys.displayhook(f.read())
1596 finally:
1622 finally:
1597 f.close()
1623 f.close()
1598 except:
1624 except:
1599 self.showtraceback()
1625 self.showtraceback()
1600
1626
1601 def showsyntaxerror(self, filename=None):
1627 def showsyntaxerror(self, filename=None):
1602 """Display the syntax error that just occurred.
1628 """Display the syntax error that just occurred.
1603
1629
1604 This doesn't display a stack trace because there isn't one.
1630 This doesn't display a stack trace because there isn't one.
1605
1631
1606 If a filename is given, it is stuffed in the exception instead
1632 If a filename is given, it is stuffed in the exception instead
1607 of what was there before (because Python's parser always uses
1633 of what was there before (because Python's parser always uses
1608 "<string>" when reading from a string).
1634 "<string>" when reading from a string).
1609 """
1635 """
1610 etype, value, last_traceback = sys.exc_info()
1636 etype, value, last_traceback = sys.exc_info()
1611
1637
1612 # See note about these variables in showtraceback() below
1638 # See note about these variables in showtraceback() below
1613 sys.last_type = etype
1639 sys.last_type = etype
1614 sys.last_value = value
1640 sys.last_value = value
1615 sys.last_traceback = last_traceback
1641 sys.last_traceback = last_traceback
1616
1642
1617 if filename and etype is SyntaxError:
1643 if filename and etype is SyntaxError:
1618 # Work hard to stuff the correct filename in the exception
1644 # Work hard to stuff the correct filename in the exception
1619 try:
1645 try:
1620 msg, (dummy_filename, lineno, offset, line) = value
1646 msg, (dummy_filename, lineno, offset, line) = value
1621 except:
1647 except:
1622 # Not the format we expect; leave it alone
1648 # Not the format we expect; leave it alone
1623 pass
1649 pass
1624 else:
1650 else:
1625 # Stuff in the right filename
1651 # Stuff in the right filename
1626 try:
1652 try:
1627 # Assume SyntaxError is a class exception
1653 # Assume SyntaxError is a class exception
1628 value = SyntaxError(msg, (filename, lineno, offset, line))
1654 value = SyntaxError(msg, (filename, lineno, offset, line))
1629 except:
1655 except:
1630 # If that failed, assume SyntaxError is a string
1656 # If that failed, assume SyntaxError is a string
1631 value = msg, (filename, lineno, offset, line)
1657 value = msg, (filename, lineno, offset, line)
1632 self.SyntaxTB(etype,value,[])
1658 self.SyntaxTB(etype,value,[])
1633
1659
1634 def debugger(self,force=False):
1660 def debugger(self,force=False):
1635 """Call the pydb/pdb debugger.
1661 """Call the pydb/pdb debugger.
1636
1662
1637 Keywords:
1663 Keywords:
1638
1664
1639 - force(False): by default, this routine checks the instance call_pdb
1665 - force(False): by default, this routine checks the instance call_pdb
1640 flag and does not actually invoke the debugger if the flag is false.
1666 flag and does not actually invoke the debugger if the flag is false.
1641 The 'force' option forces the debugger to activate even if the flag
1667 The 'force' option forces the debugger to activate even if the flag
1642 is false.
1668 is false.
1643 """
1669 """
1644
1670
1645 if not (force or self.call_pdb):
1671 if not (force or self.call_pdb):
1646 return
1672 return
1647
1673
1648 if not hasattr(sys,'last_traceback'):
1674 if not hasattr(sys,'last_traceback'):
1649 error('No traceback has been produced, nothing to debug.')
1675 error('No traceback has been produced, nothing to debug.')
1650 return
1676 return
1651
1677
1652 # use pydb if available
1678 # use pydb if available
1653 if Debugger.has_pydb:
1679 if Debugger.has_pydb:
1654 from pydb import pm
1680 from pydb import pm
1655 else:
1681 else:
1656 # fallback to our internal debugger
1682 # fallback to our internal debugger
1657 pm = lambda : self.InteractiveTB.debugger(force=True)
1683 pm = lambda : self.InteractiveTB.debugger(force=True)
1658 self.history_saving_wrapper(pm)()
1684 self.history_saving_wrapper(pm)()
1659
1685
1660 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1686 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1661 """Display the exception that just occurred.
1687 """Display the exception that just occurred.
1662
1688
1663 If nothing is known about the exception, this is the method which
1689 If nothing is known about the exception, this is the method which
1664 should be used throughout the code for presenting user tracebacks,
1690 should be used throughout the code for presenting user tracebacks,
1665 rather than directly invoking the InteractiveTB object.
1691 rather than directly invoking the InteractiveTB object.
1666
1692
1667 A specific showsyntaxerror() also exists, but this method can take
1693 A specific showsyntaxerror() also exists, but this method can take
1668 care of calling it if needed, so unless you are explicitly catching a
1694 care of calling it if needed, so unless you are explicitly catching a
1669 SyntaxError exception, don't try to analyze the stack manually and
1695 SyntaxError exception, don't try to analyze the stack manually and
1670 simply call this method."""
1696 simply call this method."""
1671
1697
1672
1698
1673 # Though this won't be called by syntax errors in the input line,
1699 # Though this won't be called by syntax errors in the input line,
1674 # there may be SyntaxError cases whith imported code.
1700 # there may be SyntaxError cases whith imported code.
1675
1701
1676 try:
1702 try:
1677 if exc_tuple is None:
1703 if exc_tuple is None:
1678 etype, value, tb = sys.exc_info()
1704 etype, value, tb = sys.exc_info()
1679 else:
1705 else:
1680 etype, value, tb = exc_tuple
1706 etype, value, tb = exc_tuple
1681
1707
1682 if etype is SyntaxError:
1708 if etype is SyntaxError:
1683 self.showsyntaxerror(filename)
1709 self.showsyntaxerror(filename)
1684 elif etype is IPython.ipapi.UsageError:
1710 elif etype is IPython.ipapi.UsageError:
1685 print "UsageError:", value
1711 print "UsageError:", value
1686 else:
1712 else:
1687 # WARNING: these variables are somewhat deprecated and not
1713 # WARNING: these variables are somewhat deprecated and not
1688 # necessarily safe to use in a threaded environment, but tools
1714 # necessarily safe to use in a threaded environment, but tools
1689 # like pdb depend on their existence, so let's set them. If we
1715 # like pdb depend on their existence, so let's set them. If we
1690 # find problems in the field, we'll need to revisit their use.
1716 # find problems in the field, we'll need to revisit their use.
1691 sys.last_type = etype
1717 sys.last_type = etype
1692 sys.last_value = value
1718 sys.last_value = value
1693 sys.last_traceback = tb
1719 sys.last_traceback = tb
1694
1720
1695 if etype in self.custom_exceptions:
1721 if etype in self.custom_exceptions:
1696 self.CustomTB(etype,value,tb)
1722 self.CustomTB(etype,value,tb)
1697 else:
1723 else:
1698 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1724 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1699 if self.InteractiveTB.call_pdb and self.has_readline:
1725 if self.InteractiveTB.call_pdb and self.has_readline:
1700 # pdb mucks up readline, fix it back
1726 # pdb mucks up readline, fix it back
1701 self.set_completer()
1727 self.set_completer()
1702 except KeyboardInterrupt:
1728 except KeyboardInterrupt:
1703 self.write("\nKeyboardInterrupt\n")
1729 self.write("\nKeyboardInterrupt\n")
1704
1730
1705 def mainloop(self,banner=None):
1731 def mainloop(self,banner=None):
1706 """Creates the local namespace and starts the mainloop.
1732 """Creates the local namespace and starts the mainloop.
1707
1733
1708 If an optional banner argument is given, it will override the
1734 If an optional banner argument is given, it will override the
1709 internally created default banner."""
1735 internally created default banner."""
1710
1736
1711 if self.rc.c: # Emulate Python's -c option
1737 if self.rc.c: # Emulate Python's -c option
1712 self.exec_init_cmd()
1738 self.exec_init_cmd()
1713 if banner is None:
1739 if banner is None:
1714 if not self.rc.banner:
1740 if not self.rc.banner:
1715 banner = ''
1741 banner = ''
1716 # banner is string? Use it directly!
1742 # banner is string? Use it directly!
1717 elif isinstance(self.rc.banner,basestring):
1743 elif isinstance(self.rc.banner,basestring):
1718 banner = self.rc.banner
1744 banner = self.rc.banner
1719 else:
1745 else:
1720 banner = self.BANNER+self.banner2
1746 banner = self.BANNER+self.banner2
1721
1747
1722 # if you run stuff with -c <cmd>, raw hist is not updated
1748 # if you run stuff with -c <cmd>, raw hist is not updated
1723 # ensure that it's in sync
1749 # ensure that it's in sync
1724 if len(self.input_hist) != len (self.input_hist_raw):
1750 if len(self.input_hist) != len (self.input_hist_raw):
1725 self.input_hist_raw = InputList(self.input_hist)
1751 self.input_hist_raw = InputList(self.input_hist)
1726
1752
1727 while 1:
1753 while 1:
1728 try:
1754 try:
1729 self.interact(banner)
1755 self.interact(banner)
1730 #self.interact_with_readline()
1756 #self.interact_with_readline()
1731
1757
1732 # XXX for testing of a readline-decoupled repl loop, call
1758 # XXX for testing of a readline-decoupled repl loop, call
1733 # interact_with_readline above
1759 # interact_with_readline above
1734
1760
1735 break
1761 break
1736 except KeyboardInterrupt:
1762 except KeyboardInterrupt:
1737 # this should not be necessary, but KeyboardInterrupt
1763 # this should not be necessary, but KeyboardInterrupt
1738 # handling seems rather unpredictable...
1764 # handling seems rather unpredictable...
1739 self.write("\nKeyboardInterrupt in interact()\n")
1765 self.write("\nKeyboardInterrupt in interact()\n")
1740
1766
1741 def exec_init_cmd(self):
1767 def exec_init_cmd(self):
1742 """Execute a command given at the command line.
1768 """Execute a command given at the command line.
1743
1769
1744 This emulates Python's -c option."""
1770 This emulates Python's -c option."""
1745
1771
1746 #sys.argv = ['-c']
1772 #sys.argv = ['-c']
1747 self.push(self.prefilter(self.rc.c, False))
1773 self.push(self.prefilter(self.rc.c, False))
1748 if not self.rc.interact:
1774 if not self.rc.interact:
1749 self.ask_exit()
1775 self.ask_exit()
1750
1776
1751 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1777 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1752 """Embeds IPython into a running python program.
1778 """Embeds IPython into a running python program.
1753
1779
1754 Input:
1780 Input:
1755
1781
1756 - header: An optional header message can be specified.
1782 - header: An optional header message can be specified.
1757
1783
1758 - local_ns, global_ns: working namespaces. If given as None, the
1784 - local_ns, global_ns: working namespaces. If given as None, the
1759 IPython-initialized one is updated with __main__.__dict__, so that
1785 IPython-initialized one is updated with __main__.__dict__, so that
1760 program variables become visible but user-specific configuration
1786 program variables become visible but user-specific configuration
1761 remains possible.
1787 remains possible.
1762
1788
1763 - stack_depth: specifies how many levels in the stack to go to
1789 - stack_depth: specifies how many levels in the stack to go to
1764 looking for namespaces (when local_ns and global_ns are None). This
1790 looking for namespaces (when local_ns and global_ns are None). This
1765 allows an intermediate caller to make sure that this function gets
1791 allows an intermediate caller to make sure that this function gets
1766 the namespace from the intended level in the stack. By default (0)
1792 the namespace from the intended level in the stack. By default (0)
1767 it will get its locals and globals from the immediate caller.
1793 it will get its locals and globals from the immediate caller.
1768
1794
1769 Warning: it's possible to use this in a program which is being run by
1795 Warning: it's possible to use this in a program which is being run by
1770 IPython itself (via %run), but some funny things will happen (a few
1796 IPython itself (via %run), but some funny things will happen (a few
1771 globals get overwritten). In the future this will be cleaned up, as
1797 globals get overwritten). In the future this will be cleaned up, as
1772 there is no fundamental reason why it can't work perfectly."""
1798 there is no fundamental reason why it can't work perfectly."""
1773
1799
1774 # Get locals and globals from caller
1800 # Get locals and globals from caller
1775 if local_ns is None or global_ns is None:
1801 if local_ns is None or global_ns is None:
1776 call_frame = sys._getframe(stack_depth).f_back
1802 call_frame = sys._getframe(stack_depth).f_back
1777
1803
1778 if local_ns is None:
1804 if local_ns is None:
1779 local_ns = call_frame.f_locals
1805 local_ns = call_frame.f_locals
1780 if global_ns is None:
1806 if global_ns is None:
1781 global_ns = call_frame.f_globals
1807 global_ns = call_frame.f_globals
1782
1808
1783 # Update namespaces and fire up interpreter
1809 # Update namespaces and fire up interpreter
1784
1810
1785 # The global one is easy, we can just throw it in
1811 # The global one is easy, we can just throw it in
1786 self.user_global_ns = global_ns
1812 self.user_global_ns = global_ns
1787
1813
1788 # but the user/local one is tricky: ipython needs it to store internal
1814 # but the user/local one is tricky: ipython needs it to store internal
1789 # data, but we also need the locals. We'll copy locals in the user
1815 # data, but we also need the locals. We'll copy locals in the user
1790 # one, but will track what got copied so we can delete them at exit.
1816 # one, but will track what got copied so we can delete them at exit.
1791 # This is so that a later embedded call doesn't see locals from a
1817 # This is so that a later embedded call doesn't see locals from a
1792 # previous call (which most likely existed in a separate scope).
1818 # previous call (which most likely existed in a separate scope).
1793 local_varnames = local_ns.keys()
1819 local_varnames = local_ns.keys()
1794 self.user_ns.update(local_ns)
1820 self.user_ns.update(local_ns)
1795 #self.user_ns['local_ns'] = local_ns # dbg
1821 #self.user_ns['local_ns'] = local_ns # dbg
1796
1822
1797 # Patch for global embedding to make sure that things don't overwrite
1823 # Patch for global embedding to make sure that things don't overwrite
1798 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1824 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1799 # FIXME. Test this a bit more carefully (the if.. is new)
1825 # FIXME. Test this a bit more carefully (the if.. is new)
1800 if local_ns is None and global_ns is None:
1826 if local_ns is None and global_ns is None:
1801 self.user_global_ns.update(__main__.__dict__)
1827 self.user_global_ns.update(__main__.__dict__)
1802
1828
1803 # make sure the tab-completer has the correct frame information, so it
1829 # make sure the tab-completer has the correct frame information, so it
1804 # actually completes using the frame's locals/globals
1830 # actually completes using the frame's locals/globals
1805 self.set_completer_frame()
1831 self.set_completer_frame()
1806
1832
1807 # before activating the interactive mode, we need to make sure that
1833 # before activating the interactive mode, we need to make sure that
1808 # all names in the builtin namespace needed by ipython point to
1834 # all names in the builtin namespace needed by ipython point to
1809 # ourselves, and not to other instances.
1835 # ourselves, and not to other instances.
1810 self.add_builtins()
1836 self.add_builtins()
1811
1837
1812 self.interact(header)
1838 self.interact(header)
1813
1839
1814 # now, purge out the user namespace from anything we might have added
1840 # now, purge out the user namespace from anything we might have added
1815 # from the caller's local namespace
1841 # from the caller's local namespace
1816 delvar = self.user_ns.pop
1842 delvar = self.user_ns.pop
1817 for var in local_varnames:
1843 for var in local_varnames:
1818 delvar(var,None)
1844 delvar(var,None)
1819 # and clean builtins we may have overridden
1845 # and clean builtins we may have overridden
1820 self.clean_builtins()
1846 self.clean_builtins()
1821
1847
1822 def interact_prompt(self):
1848 def interact_prompt(self):
1823 """ Print the prompt (in read-eval-print loop)
1849 """ Print the prompt (in read-eval-print loop)
1824
1850
1825 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1851 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1826 used in standard IPython flow.
1852 used in standard IPython flow.
1827 """
1853 """
1828 if self.more:
1854 if self.more:
1829 try:
1855 try:
1830 prompt = self.hooks.generate_prompt(True)
1856 prompt = self.hooks.generate_prompt(True)
1831 except:
1857 except:
1832 self.showtraceback()
1858 self.showtraceback()
1833 if self.autoindent:
1859 if self.autoindent:
1834 self.rl_do_indent = True
1860 self.rl_do_indent = True
1835
1861
1836 else:
1862 else:
1837 try:
1863 try:
1838 prompt = self.hooks.generate_prompt(False)
1864 prompt = self.hooks.generate_prompt(False)
1839 except:
1865 except:
1840 self.showtraceback()
1866 self.showtraceback()
1841 self.write(prompt)
1867 self.write(prompt)
1842
1868
1843 def interact_handle_input(self,line):
1869 def interact_handle_input(self,line):
1844 """ Handle the input line (in read-eval-print loop)
1870 """ Handle the input line (in read-eval-print loop)
1845
1871
1846 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1872 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1847 used in standard IPython flow.
1873 used in standard IPython flow.
1848 """
1874 """
1849 if line.lstrip() == line:
1875 if line.lstrip() == line:
1850 self.shadowhist.add(line.strip())
1876 self.shadowhist.add(line.strip())
1851 lineout = self.prefilter(line,self.more)
1877 lineout = self.prefilter(line,self.more)
1852
1878
1853 if line.strip():
1879 if line.strip():
1854 if self.more:
1880 if self.more:
1855 self.input_hist_raw[-1] += '%s\n' % line
1881 self.input_hist_raw[-1] += '%s\n' % line
1856 else:
1882 else:
1857 self.input_hist_raw.append('%s\n' % line)
1883 self.input_hist_raw.append('%s\n' % line)
1858
1884
1859
1885
1860 self.more = self.push(lineout)
1886 self.more = self.push(lineout)
1861 if (self.SyntaxTB.last_syntax_error and
1887 if (self.SyntaxTB.last_syntax_error and
1862 self.rc.autoedit_syntax):
1888 self.rc.autoedit_syntax):
1863 self.edit_syntax_error()
1889 self.edit_syntax_error()
1864
1890
1865 def interact_with_readline(self):
1891 def interact_with_readline(self):
1866 """ Demo of using interact_handle_input, interact_prompt
1892 """ Demo of using interact_handle_input, interact_prompt
1867
1893
1868 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1894 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1869 it should work like this.
1895 it should work like this.
1870 """
1896 """
1871 self.readline_startup_hook(self.pre_readline)
1897 self.readline_startup_hook(self.pre_readline)
1872 while not self.exit_now:
1898 while not self.exit_now:
1873 self.interact_prompt()
1899 self.interact_prompt()
1874 if self.more:
1900 if self.more:
1875 self.rl_do_indent = True
1901 self.rl_do_indent = True
1876 else:
1902 else:
1877 self.rl_do_indent = False
1903 self.rl_do_indent = False
1878 line = raw_input_original().decode(self.stdin_encoding)
1904 line = raw_input_original().decode(self.stdin_encoding)
1879 self.interact_handle_input(line)
1905 self.interact_handle_input(line)
1880
1906
1881
1907
1882 def interact(self, banner=None):
1908 def interact(self, banner=None):
1883 """Closely emulate the interactive Python console.
1909 """Closely emulate the interactive Python console.
1884
1910
1885 The optional banner argument specify the banner to print
1911 The optional banner argument specify the banner to print
1886 before the first interaction; by default it prints a banner
1912 before the first interaction; by default it prints a banner
1887 similar to the one printed by the real Python interpreter,
1913 similar to the one printed by the real Python interpreter,
1888 followed by the current class name in parentheses (so as not
1914 followed by the current class name in parentheses (so as not
1889 to confuse this with the real interpreter -- since it's so
1915 to confuse this with the real interpreter -- since it's so
1890 close!).
1916 close!).
1891
1917
1892 """
1918 """
1893
1919
1894 if self.exit_now:
1920 if self.exit_now:
1895 # batch run -> do not interact
1921 # batch run -> do not interact
1896 return
1922 return
1897 cprt = 'Type "copyright", "credits" or "license" for more information.'
1923 cprt = 'Type "copyright", "credits" or "license" for more information.'
1898 if banner is None:
1924 if banner is None:
1899 self.write("Python %s on %s\n%s\n(%s)\n" %
1925 self.write("Python %s on %s\n%s\n(%s)\n" %
1900 (sys.version, sys.platform, cprt,
1926 (sys.version, sys.platform, cprt,
1901 self.__class__.__name__))
1927 self.__class__.__name__))
1902 else:
1928 else:
1903 self.write(banner)
1929 self.write(banner)
1904
1930
1905 more = 0
1931 more = 0
1906
1932
1907 # Mark activity in the builtins
1933 # Mark activity in the builtins
1908 __builtin__.__dict__['__IPYTHON__active'] += 1
1934 __builtin__.__dict__['__IPYTHON__active'] += 1
1909
1935
1910 if self.has_readline:
1936 if self.has_readline:
1911 self.readline_startup_hook(self.pre_readline)
1937 self.readline_startup_hook(self.pre_readline)
1912 # exit_now is set by a call to %Exit or %Quit, through the
1938 # exit_now is set by a call to %Exit or %Quit, through the
1913 # ask_exit callback.
1939 # ask_exit callback.
1914
1940
1915 while not self.exit_now:
1941 while not self.exit_now:
1916 self.hooks.pre_prompt_hook()
1942 self.hooks.pre_prompt_hook()
1917 if more:
1943 if more:
1918 try:
1944 try:
1919 prompt = self.hooks.generate_prompt(True)
1945 prompt = self.hooks.generate_prompt(True)
1920 except:
1946 except:
1921 self.showtraceback()
1947 self.showtraceback()
1922 if self.autoindent:
1948 if self.autoindent:
1923 self.rl_do_indent = True
1949 self.rl_do_indent = True
1924
1950
1925 else:
1951 else:
1926 try:
1952 try:
1927 prompt = self.hooks.generate_prompt(False)
1953 prompt = self.hooks.generate_prompt(False)
1928 except:
1954 except:
1929 self.showtraceback()
1955 self.showtraceback()
1930 try:
1956 try:
1931 line = self.raw_input(prompt,more)
1957 line = self.raw_input(prompt,more)
1932 if self.exit_now:
1958 if self.exit_now:
1933 # quick exit on sys.std[in|out] close
1959 # quick exit on sys.std[in|out] close
1934 break
1960 break
1935 if self.autoindent:
1961 if self.autoindent:
1936 self.rl_do_indent = False
1962 self.rl_do_indent = False
1937
1963
1938 except KeyboardInterrupt:
1964 except KeyboardInterrupt:
1939 #double-guard against keyboardinterrupts during kbdint handling
1965 #double-guard against keyboardinterrupts during kbdint handling
1940 try:
1966 try:
1941 self.write('\nKeyboardInterrupt\n')
1967 self.write('\nKeyboardInterrupt\n')
1942 self.resetbuffer()
1968 self.resetbuffer()
1943 # keep cache in sync with the prompt counter:
1969 # keep cache in sync with the prompt counter:
1944 self.outputcache.prompt_count -= 1
1970 self.outputcache.prompt_count -= 1
1945
1971
1946 if self.autoindent:
1972 if self.autoindent:
1947 self.indent_current_nsp = 0
1973 self.indent_current_nsp = 0
1948 more = 0
1974 more = 0
1949 except KeyboardInterrupt:
1975 except KeyboardInterrupt:
1950 pass
1976 pass
1951 except EOFError:
1977 except EOFError:
1952 if self.autoindent:
1978 if self.autoindent:
1953 self.rl_do_indent = False
1979 self.rl_do_indent = False
1954 self.readline_startup_hook(None)
1980 self.readline_startup_hook(None)
1955 self.write('\n')
1981 self.write('\n')
1956 self.exit()
1982 self.exit()
1957 except bdb.BdbQuit:
1983 except bdb.BdbQuit:
1958 warn('The Python debugger has exited with a BdbQuit exception.\n'
1984 warn('The Python debugger has exited with a BdbQuit exception.\n'
1959 'Because of how pdb handles the stack, it is impossible\n'
1985 'Because of how pdb handles the stack, it is impossible\n'
1960 'for IPython to properly format this particular exception.\n'
1986 'for IPython to properly format this particular exception.\n'
1961 'IPython will resume normal operation.')
1987 'IPython will resume normal operation.')
1962 except:
1988 except:
1963 # exceptions here are VERY RARE, but they can be triggered
1989 # exceptions here are VERY RARE, but they can be triggered
1964 # asynchronously by signal handlers, for example.
1990 # asynchronously by signal handlers, for example.
1965 self.showtraceback()
1991 self.showtraceback()
1966 else:
1992 else:
1967 more = self.push(line)
1993 more = self.push(line)
1968 if (self.SyntaxTB.last_syntax_error and
1994 if (self.SyntaxTB.last_syntax_error and
1969 self.rc.autoedit_syntax):
1995 self.rc.autoedit_syntax):
1970 self.edit_syntax_error()
1996 self.edit_syntax_error()
1971
1997
1972 # We are off again...
1998 # We are off again...
1973 __builtin__.__dict__['__IPYTHON__active'] -= 1
1999 __builtin__.__dict__['__IPYTHON__active'] -= 1
1974
2000
1975 def excepthook(self, etype, value, tb):
2001 def excepthook(self, etype, value, tb):
1976 """One more defense for GUI apps that call sys.excepthook.
2002 """One more defense for GUI apps that call sys.excepthook.
1977
2003
1978 GUI frameworks like wxPython trap exceptions and call
2004 GUI frameworks like wxPython trap exceptions and call
1979 sys.excepthook themselves. I guess this is a feature that
2005 sys.excepthook themselves. I guess this is a feature that
1980 enables them to keep running after exceptions that would
2006 enables them to keep running after exceptions that would
1981 otherwise kill their mainloop. This is a bother for IPython
2007 otherwise kill their mainloop. This is a bother for IPython
1982 which excepts to catch all of the program exceptions with a try:
2008 which excepts to catch all of the program exceptions with a try:
1983 except: statement.
2009 except: statement.
1984
2010
1985 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
2011 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1986 any app directly invokes sys.excepthook, it will look to the user like
2012 any app directly invokes sys.excepthook, it will look to the user like
1987 IPython crashed. In order to work around this, we can disable the
2013 IPython crashed. In order to work around this, we can disable the
1988 CrashHandler and replace it with this excepthook instead, which prints a
2014 CrashHandler and replace it with this excepthook instead, which prints a
1989 regular traceback using our InteractiveTB. In this fashion, apps which
2015 regular traceback using our InteractiveTB. In this fashion, apps which
1990 call sys.excepthook will generate a regular-looking exception from
2016 call sys.excepthook will generate a regular-looking exception from
1991 IPython, and the CrashHandler will only be triggered by real IPython
2017 IPython, and the CrashHandler will only be triggered by real IPython
1992 crashes.
2018 crashes.
1993
2019
1994 This hook should be used sparingly, only in places which are not likely
2020 This hook should be used sparingly, only in places which are not likely
1995 to be true IPython errors.
2021 to be true IPython errors.
1996 """
2022 """
1997 self.showtraceback((etype,value,tb),tb_offset=0)
2023 self.showtraceback((etype,value,tb),tb_offset=0)
1998
2024
1999 def expand_aliases(self,fn,rest):
2025 def expand_aliases(self,fn,rest):
2000 """ Expand multiple levels of aliases:
2026 """ Expand multiple levels of aliases:
2001
2027
2002 if:
2028 if:
2003
2029
2004 alias foo bar /tmp
2030 alias foo bar /tmp
2005 alias baz foo
2031 alias baz foo
2006
2032
2007 then:
2033 then:
2008
2034
2009 baz huhhahhei -> bar /tmp huhhahhei
2035 baz huhhahhei -> bar /tmp huhhahhei
2010
2036
2011 """
2037 """
2012 line = fn + " " + rest
2038 line = fn + " " + rest
2013
2039
2014 done = set()
2040 done = set()
2015 while 1:
2041 while 1:
2016 pre,fn,rest = prefilter.splitUserInput(line,
2042 pre,fn,rest = prefilter.splitUserInput(line,
2017 prefilter.shell_line_split)
2043 prefilter.shell_line_split)
2018 if fn in self.alias_table:
2044 if fn in self.alias_table:
2019 if fn in done:
2045 if fn in done:
2020 warn("Cyclic alias definition, repeated '%s'" % fn)
2046 warn("Cyclic alias definition, repeated '%s'" % fn)
2021 return ""
2047 return ""
2022 done.add(fn)
2048 done.add(fn)
2023
2049
2024 l2 = self.transform_alias(fn,rest)
2050 l2 = self.transform_alias(fn,rest)
2025 # dir -> dir
2051 # dir -> dir
2026 # print "alias",line, "->",l2 #dbg
2052 # print "alias",line, "->",l2 #dbg
2027 if l2 == line:
2053 if l2 == line:
2028 break
2054 break
2029 # ls -> ls -F should not recurse forever
2055 # ls -> ls -F should not recurse forever
2030 if l2.split(None,1)[0] == line.split(None,1)[0]:
2056 if l2.split(None,1)[0] == line.split(None,1)[0]:
2031 line = l2
2057 line = l2
2032 break
2058 break
2033
2059
2034 line=l2
2060 line=l2
2035
2061
2036
2062
2037 # print "al expand to",line #dbg
2063 # print "al expand to",line #dbg
2038 else:
2064 else:
2039 break
2065 break
2040
2066
2041 return line
2067 return line
2042
2068
2043 def transform_alias(self, alias,rest=''):
2069 def transform_alias(self, alias,rest=''):
2044 """ Transform alias to system command string.
2070 """ Transform alias to system command string.
2045 """
2071 """
2046 trg = self.alias_table[alias]
2072 trg = self.alias_table[alias]
2047
2073
2048 nargs,cmd = trg
2074 nargs,cmd = trg
2049 # print trg #dbg
2075 # print trg #dbg
2050 if ' ' in cmd and os.path.isfile(cmd):
2076 if ' ' in cmd and os.path.isfile(cmd):
2051 cmd = '"%s"' % cmd
2077 cmd = '"%s"' % cmd
2052
2078
2053 # Expand the %l special to be the user's input line
2079 # Expand the %l special to be the user's input line
2054 if cmd.find('%l') >= 0:
2080 if cmd.find('%l') >= 0:
2055 cmd = cmd.replace('%l',rest)
2081 cmd = cmd.replace('%l',rest)
2056 rest = ''
2082 rest = ''
2057 if nargs==0:
2083 if nargs==0:
2058 # Simple, argument-less aliases
2084 # Simple, argument-less aliases
2059 cmd = '%s %s' % (cmd,rest)
2085 cmd = '%s %s' % (cmd,rest)
2060 else:
2086 else:
2061 # Handle aliases with positional arguments
2087 # Handle aliases with positional arguments
2062 args = rest.split(None,nargs)
2088 args = rest.split(None,nargs)
2063 if len(args)< nargs:
2089 if len(args)< nargs:
2064 error('Alias <%s> requires %s arguments, %s given.' %
2090 error('Alias <%s> requires %s arguments, %s given.' %
2065 (alias,nargs,len(args)))
2091 (alias,nargs,len(args)))
2066 return None
2092 return None
2067 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2093 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2068 # Now call the macro, evaluating in the user's namespace
2094 # Now call the macro, evaluating in the user's namespace
2069 #print 'new command: <%r>' % cmd # dbg
2095 #print 'new command: <%r>' % cmd # dbg
2070 return cmd
2096 return cmd
2071
2097
2072 def call_alias(self,alias,rest=''):
2098 def call_alias(self,alias,rest=''):
2073 """Call an alias given its name and the rest of the line.
2099 """Call an alias given its name and the rest of the line.
2074
2100
2075 This is only used to provide backwards compatibility for users of
2101 This is only used to provide backwards compatibility for users of
2076 ipalias(), use of which is not recommended for anymore."""
2102 ipalias(), use of which is not recommended for anymore."""
2077
2103
2078 # Now call the macro, evaluating in the user's namespace
2104 # Now call the macro, evaluating in the user's namespace
2079 cmd = self.transform_alias(alias, rest)
2105 cmd = self.transform_alias(alias, rest)
2080 try:
2106 try:
2081 self.system(cmd)
2107 self.system(cmd)
2082 except:
2108 except:
2083 self.showtraceback()
2109 self.showtraceback()
2084
2110
2085 def indent_current_str(self):
2111 def indent_current_str(self):
2086 """return the current level of indentation as a string"""
2112 """return the current level of indentation as a string"""
2087 return self.indent_current_nsp * ' '
2113 return self.indent_current_nsp * ' '
2088
2114
2089 def autoindent_update(self,line):
2115 def autoindent_update(self,line):
2090 """Keep track of the indent level."""
2116 """Keep track of the indent level."""
2091
2117
2092 #debugx('line')
2118 #debugx('line')
2093 #debugx('self.indent_current_nsp')
2119 #debugx('self.indent_current_nsp')
2094 if self.autoindent:
2120 if self.autoindent:
2095 if line:
2121 if line:
2096 inisp = num_ini_spaces(line)
2122 inisp = num_ini_spaces(line)
2097 if inisp < self.indent_current_nsp:
2123 if inisp < self.indent_current_nsp:
2098 self.indent_current_nsp = inisp
2124 self.indent_current_nsp = inisp
2099
2125
2100 if line[-1] == ':':
2126 if line[-1] == ':':
2101 self.indent_current_nsp += 4
2127 self.indent_current_nsp += 4
2102 elif dedent_re.match(line):
2128 elif dedent_re.match(line):
2103 self.indent_current_nsp -= 4
2129 self.indent_current_nsp -= 4
2104 else:
2130 else:
2105 self.indent_current_nsp = 0
2131 self.indent_current_nsp = 0
2106
2132
2107 def runlines(self,lines):
2133 def runlines(self,lines):
2108 """Run a string of one or more lines of source.
2134 """Run a string of one or more lines of source.
2109
2135
2110 This method is capable of running a string containing multiple source
2136 This method is capable of running a string containing multiple source
2111 lines, as if they had been entered at the IPython prompt. Since it
2137 lines, as if they had been entered at the IPython prompt. Since it
2112 exposes IPython's processing machinery, the given strings can contain
2138 exposes IPython's processing machinery, the given strings can contain
2113 magic calls (%magic), special shell access (!cmd), etc."""
2139 magic calls (%magic), special shell access (!cmd), etc."""
2114
2140
2115 # We must start with a clean buffer, in case this is run from an
2141 # We must start with a clean buffer, in case this is run from an
2116 # interactive IPython session (via a magic, for example).
2142 # interactive IPython session (via a magic, for example).
2117 self.resetbuffer()
2143 self.resetbuffer()
2118 lines = lines.split('\n')
2144 lines = lines.split('\n')
2119 more = 0
2145 more = 0
2120
2146
2121 for line in lines:
2147 for line in lines:
2122 # skip blank lines so we don't mess up the prompt counter, but do
2148 # skip blank lines so we don't mess up the prompt counter, but do
2123 # NOT skip even a blank line if we are in a code block (more is
2149 # NOT skip even a blank line if we are in a code block (more is
2124 # true)
2150 # true)
2125
2151
2126 if line or more:
2152 if line or more:
2127 # push to raw history, so hist line numbers stay in sync
2153 # push to raw history, so hist line numbers stay in sync
2128 self.input_hist_raw.append("# " + line + "\n")
2154 self.input_hist_raw.append("# " + line + "\n")
2129 more = self.push(self.prefilter(line,more))
2155 more = self.push(self.prefilter(line,more))
2130 # IPython's runsource returns None if there was an error
2156 # IPython's runsource returns None if there was an error
2131 # compiling the code. This allows us to stop processing right
2157 # compiling the code. This allows us to stop processing right
2132 # away, so the user gets the error message at the right place.
2158 # away, so the user gets the error message at the right place.
2133 if more is None:
2159 if more is None:
2134 break
2160 break
2135 else:
2161 else:
2136 self.input_hist_raw.append("\n")
2162 self.input_hist_raw.append("\n")
2137 # final newline in case the input didn't have it, so that the code
2163 # final newline in case the input didn't have it, so that the code
2138 # actually does get executed
2164 # actually does get executed
2139 if more:
2165 if more:
2140 self.push('\n')
2166 self.push('\n')
2141
2167
2142 def runsource(self, source, filename='<input>', symbol='single'):
2168 def runsource(self, source, filename='<input>', symbol='single'):
2143 """Compile and run some source in the interpreter.
2169 """Compile and run some source in the interpreter.
2144
2170
2145 Arguments are as for compile_command().
2171 Arguments are as for compile_command().
2146
2172
2147 One several things can happen:
2173 One several things can happen:
2148
2174
2149 1) The input is incorrect; compile_command() raised an
2175 1) The input is incorrect; compile_command() raised an
2150 exception (SyntaxError or OverflowError). A syntax traceback
2176 exception (SyntaxError or OverflowError). A syntax traceback
2151 will be printed by calling the showsyntaxerror() method.
2177 will be printed by calling the showsyntaxerror() method.
2152
2178
2153 2) The input is incomplete, and more input is required;
2179 2) The input is incomplete, and more input is required;
2154 compile_command() returned None. Nothing happens.
2180 compile_command() returned None. Nothing happens.
2155
2181
2156 3) The input is complete; compile_command() returned a code
2182 3) The input is complete; compile_command() returned a code
2157 object. The code is executed by calling self.runcode() (which
2183 object. The code is executed by calling self.runcode() (which
2158 also handles run-time exceptions, except for SystemExit).
2184 also handles run-time exceptions, except for SystemExit).
2159
2185
2160 The return value is:
2186 The return value is:
2161
2187
2162 - True in case 2
2188 - True in case 2
2163
2189
2164 - False in the other cases, unless an exception is raised, where
2190 - False in the other cases, unless an exception is raised, where
2165 None is returned instead. This can be used by external callers to
2191 None is returned instead. This can be used by external callers to
2166 know whether to continue feeding input or not.
2192 know whether to continue feeding input or not.
2167
2193
2168 The return value can be used to decide whether to use sys.ps1 or
2194 The return value can be used to decide whether to use sys.ps1 or
2169 sys.ps2 to prompt the next line."""
2195 sys.ps2 to prompt the next line."""
2170
2196
2171 # if the source code has leading blanks, add 'if 1:\n' to it
2197 # if the source code has leading blanks, add 'if 1:\n' to it
2172 # this allows execution of indented pasted code. It is tempting
2198 # this allows execution of indented pasted code. It is tempting
2173 # to add '\n' at the end of source to run commands like ' a=1'
2199 # to add '\n' at the end of source to run commands like ' a=1'
2174 # directly, but this fails for more complicated scenarios
2200 # directly, but this fails for more complicated scenarios
2175 source=source.encode(self.stdin_encoding)
2201 source=source.encode(self.stdin_encoding)
2176 if source[:1] in [' ', '\t']:
2202 if source[:1] in [' ', '\t']:
2177 source = 'if 1:\n%s' % source
2203 source = 'if 1:\n%s' % source
2178
2204
2179 try:
2205 try:
2180 code = self.compile(source,filename,symbol)
2206 code = self.compile(source,filename,symbol)
2181 except (OverflowError, SyntaxError, ValueError, TypeError):
2207 except (OverflowError, SyntaxError, ValueError, TypeError):
2182 # Case 1
2208 # Case 1
2183 self.showsyntaxerror(filename)
2209 self.showsyntaxerror(filename)
2184 return None
2210 return None
2185
2211
2186 if code is None:
2212 if code is None:
2187 # Case 2
2213 # Case 2
2188 return True
2214 return True
2189
2215
2190 # Case 3
2216 # Case 3
2191 # We store the code object so that threaded shells and
2217 # We store the code object so that threaded shells and
2192 # custom exception handlers can access all this info if needed.
2218 # custom exception handlers can access all this info if needed.
2193 # The source corresponding to this can be obtained from the
2219 # The source corresponding to this can be obtained from the
2194 # buffer attribute as '\n'.join(self.buffer).
2220 # buffer attribute as '\n'.join(self.buffer).
2195 self.code_to_run = code
2221 self.code_to_run = code
2196 # now actually execute the code object
2222 # now actually execute the code object
2197 if self.runcode(code) == 0:
2223 if self.runcode(code) == 0:
2198 return False
2224 return False
2199 else:
2225 else:
2200 return None
2226 return None
2201
2227
2202 def runcode(self,code_obj):
2228 def runcode(self,code_obj):
2203 """Execute a code object.
2229 """Execute a code object.
2204
2230
2205 When an exception occurs, self.showtraceback() is called to display a
2231 When an exception occurs, self.showtraceback() is called to display a
2206 traceback.
2232 traceback.
2207
2233
2208 Return value: a flag indicating whether the code to be run completed
2234 Return value: a flag indicating whether the code to be run completed
2209 successfully:
2235 successfully:
2210
2236
2211 - 0: successful execution.
2237 - 0: successful execution.
2212 - 1: an error occurred.
2238 - 1: an error occurred.
2213 """
2239 """
2214
2240
2215 # Set our own excepthook in case the user code tries to call it
2241 # Set our own excepthook in case the user code tries to call it
2216 # directly, so that the IPython crash handler doesn't get triggered
2242 # directly, so that the IPython crash handler doesn't get triggered
2217 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2243 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2218
2244
2219 # we save the original sys.excepthook in the instance, in case config
2245 # we save the original sys.excepthook in the instance, in case config
2220 # code (such as magics) needs access to it.
2246 # code (such as magics) needs access to it.
2221 self.sys_excepthook = old_excepthook
2247 self.sys_excepthook = old_excepthook
2222 outflag = 1 # happens in more places, so it's easier as default
2248 outflag = 1 # happens in more places, so it's easier as default
2223 try:
2249 try:
2224 try:
2250 try:
2225 self.hooks.pre_runcode_hook()
2251 self.hooks.pre_runcode_hook()
2226 exec code_obj in self.user_global_ns, self.user_ns
2252 exec code_obj in self.user_global_ns, self.user_ns
2227 finally:
2253 finally:
2228 # Reset our crash handler in place
2254 # Reset our crash handler in place
2229 sys.excepthook = old_excepthook
2255 sys.excepthook = old_excepthook
2230 except SystemExit:
2256 except SystemExit:
2231 self.resetbuffer()
2257 self.resetbuffer()
2232 self.showtraceback()
2258 self.showtraceback()
2233 warn("Type %exit or %quit to exit IPython "
2259 warn("Type %exit or %quit to exit IPython "
2234 "(%Exit or %Quit do so unconditionally).",level=1)
2260 "(%Exit or %Quit do so unconditionally).",level=1)
2235 except self.custom_exceptions:
2261 except self.custom_exceptions:
2236 etype,value,tb = sys.exc_info()
2262 etype,value,tb = sys.exc_info()
2237 self.CustomTB(etype,value,tb)
2263 self.CustomTB(etype,value,tb)
2238 except:
2264 except:
2239 self.showtraceback()
2265 self.showtraceback()
2240 else:
2266 else:
2241 outflag = 0
2267 outflag = 0
2242 if softspace(sys.stdout, 0):
2268 if softspace(sys.stdout, 0):
2243 print
2269 print
2244 # Flush out code object which has been run (and source)
2270 # Flush out code object which has been run (and source)
2245 self.code_to_run = None
2271 self.code_to_run = None
2246 return outflag
2272 return outflag
2247
2273
2248 def push(self, line):
2274 def push(self, line):
2249 """Push a line to the interpreter.
2275 """Push a line to the interpreter.
2250
2276
2251 The line should not have a trailing newline; it may have
2277 The line should not have a trailing newline; it may have
2252 internal newlines. The line is appended to a buffer and the
2278 internal newlines. The line is appended to a buffer and the
2253 interpreter's runsource() method is called with the
2279 interpreter's runsource() method is called with the
2254 concatenated contents of the buffer as source. If this
2280 concatenated contents of the buffer as source. If this
2255 indicates that the command was executed or invalid, the buffer
2281 indicates that the command was executed or invalid, the buffer
2256 is reset; otherwise, the command is incomplete, and the buffer
2282 is reset; otherwise, the command is incomplete, and the buffer
2257 is left as it was after the line was appended. The return
2283 is left as it was after the line was appended. The return
2258 value is 1 if more input is required, 0 if the line was dealt
2284 value is 1 if more input is required, 0 if the line was dealt
2259 with in some way (this is the same as runsource()).
2285 with in some way (this is the same as runsource()).
2260 """
2286 """
2261
2287
2262 # autoindent management should be done here, and not in the
2288 # autoindent management should be done here, and not in the
2263 # interactive loop, since that one is only seen by keyboard input. We
2289 # interactive loop, since that one is only seen by keyboard input. We
2264 # need this done correctly even for code run via runlines (which uses
2290 # need this done correctly even for code run via runlines (which uses
2265 # push).
2291 # push).
2266
2292
2267 #print 'push line: <%s>' % line # dbg
2293 #print 'push line: <%s>' % line # dbg
2268 for subline in line.splitlines():
2294 for subline in line.splitlines():
2269 self.autoindent_update(subline)
2295 self.autoindent_update(subline)
2270 self.buffer.append(line)
2296 self.buffer.append(line)
2271 more = self.runsource('\n'.join(self.buffer), self.filename)
2297 more = self.runsource('\n'.join(self.buffer), self.filename)
2272 if not more:
2298 if not more:
2273 self.resetbuffer()
2299 self.resetbuffer()
2274 return more
2300 return more
2275
2301
2276 def split_user_input(self, line):
2302 def split_user_input(self, line):
2277 # This is really a hold-over to support ipapi and some extensions
2303 # This is really a hold-over to support ipapi and some extensions
2278 return prefilter.splitUserInput(line)
2304 return prefilter.splitUserInput(line)
2279
2305
2280 def resetbuffer(self):
2306 def resetbuffer(self):
2281 """Reset the input buffer."""
2307 """Reset the input buffer."""
2282 self.buffer[:] = []
2308 self.buffer[:] = []
2283
2309
2284 def raw_input(self,prompt='',continue_prompt=False):
2310 def raw_input(self,prompt='',continue_prompt=False):
2285 """Write a prompt and read a line.
2311 """Write a prompt and read a line.
2286
2312
2287 The returned line does not include the trailing newline.
2313 The returned line does not include the trailing newline.
2288 When the user enters the EOF key sequence, EOFError is raised.
2314 When the user enters the EOF key sequence, EOFError is raised.
2289
2315
2290 Optional inputs:
2316 Optional inputs:
2291
2317
2292 - prompt(''): a string to be printed to prompt the user.
2318 - prompt(''): a string to be printed to prompt the user.
2293
2319
2294 - continue_prompt(False): whether this line is the first one or a
2320 - continue_prompt(False): whether this line is the first one or a
2295 continuation in a sequence of inputs.
2321 continuation in a sequence of inputs.
2296 """
2322 """
2297
2323
2298 # Code run by the user may have modified the readline completer state.
2324 # Code run by the user may have modified the readline completer state.
2299 # We must ensure that our completer is back in place.
2325 # We must ensure that our completer is back in place.
2300 if self.has_readline:
2326 if self.has_readline:
2301 self.set_completer()
2327 self.set_completer()
2302
2328
2303 try:
2329 try:
2304 line = raw_input_original(prompt).decode(self.stdin_encoding)
2330 line = raw_input_original(prompt).decode(self.stdin_encoding)
2305 except ValueError:
2331 except ValueError:
2306 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2332 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2307 " or sys.stdout.close()!\nExiting IPython!")
2333 " or sys.stdout.close()!\nExiting IPython!")
2308 self.ask_exit()
2334 self.ask_exit()
2309 return ""
2335 return ""
2310
2336
2311 # Try to be reasonably smart about not re-indenting pasted input more
2337 # Try to be reasonably smart about not re-indenting pasted input more
2312 # than necessary. We do this by trimming out the auto-indent initial
2338 # than necessary. We do this by trimming out the auto-indent initial
2313 # spaces, if the user's actual input started itself with whitespace.
2339 # spaces, if the user's actual input started itself with whitespace.
2314 #debugx('self.buffer[-1]')
2340 #debugx('self.buffer[-1]')
2315
2341
2316 if self.autoindent:
2342 if self.autoindent:
2317 if num_ini_spaces(line) > self.indent_current_nsp:
2343 if num_ini_spaces(line) > self.indent_current_nsp:
2318 line = line[self.indent_current_nsp:]
2344 line = line[self.indent_current_nsp:]
2319 self.indent_current_nsp = 0
2345 self.indent_current_nsp = 0
2320
2346
2321 # store the unfiltered input before the user has any chance to modify
2347 # store the unfiltered input before the user has any chance to modify
2322 # it.
2348 # it.
2323 if line.strip():
2349 if line.strip():
2324 if continue_prompt:
2350 if continue_prompt:
2325 self.input_hist_raw[-1] += '%s\n' % line
2351 self.input_hist_raw[-1] += '%s\n' % line
2326 if self.has_readline: # and some config option is set?
2352 if self.has_readline: # and some config option is set?
2327 try:
2353 try:
2328 histlen = self.readline.get_current_history_length()
2354 histlen = self.readline.get_current_history_length()
2329 if histlen > 1:
2355 if histlen > 1:
2330 newhist = self.input_hist_raw[-1].rstrip()
2356 newhist = self.input_hist_raw[-1].rstrip()
2331 self.readline.remove_history_item(histlen-1)
2357 self.readline.remove_history_item(histlen-1)
2332 self.readline.replace_history_item(histlen-2,
2358 self.readline.replace_history_item(histlen-2,
2333 newhist.encode(self.stdin_encoding))
2359 newhist.encode(self.stdin_encoding))
2334 except AttributeError:
2360 except AttributeError:
2335 pass # re{move,place}_history_item are new in 2.4.
2361 pass # re{move,place}_history_item are new in 2.4.
2336 else:
2362 else:
2337 self.input_hist_raw.append('%s\n' % line)
2363 self.input_hist_raw.append('%s\n' % line)
2338 # only entries starting at first column go to shadow history
2364 # only entries starting at first column go to shadow history
2339 if line.lstrip() == line:
2365 if line.lstrip() == line:
2340 self.shadowhist.add(line.strip())
2366 self.shadowhist.add(line.strip())
2341 elif not continue_prompt:
2367 elif not continue_prompt:
2342 self.input_hist_raw.append('\n')
2368 self.input_hist_raw.append('\n')
2343 try:
2369 try:
2344 lineout = self.prefilter(line,continue_prompt)
2370 lineout = self.prefilter(line,continue_prompt)
2345 except:
2371 except:
2346 # blanket except, in case a user-defined prefilter crashes, so it
2372 # blanket except, in case a user-defined prefilter crashes, so it
2347 # can't take all of ipython with it.
2373 # can't take all of ipython with it.
2348 self.showtraceback()
2374 self.showtraceback()
2349 return ''
2375 return ''
2350 else:
2376 else:
2351 return lineout
2377 return lineout
2352
2378
2353 def _prefilter(self, line, continue_prompt):
2379 def _prefilter(self, line, continue_prompt):
2354 """Calls different preprocessors, depending on the form of line."""
2380 """Calls different preprocessors, depending on the form of line."""
2355
2381
2356 # All handlers *must* return a value, even if it's blank ('').
2382 # All handlers *must* return a value, even if it's blank ('').
2357
2383
2358 # Lines are NOT logged here. Handlers should process the line as
2384 # Lines are NOT logged here. Handlers should process the line as
2359 # needed, update the cache AND log it (so that the input cache array
2385 # needed, update the cache AND log it (so that the input cache array
2360 # stays synced).
2386 # stays synced).
2361
2387
2362 #.....................................................................
2388 #.....................................................................
2363 # Code begins
2389 # Code begins
2364
2390
2365 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2391 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2366
2392
2367 # save the line away in case we crash, so the post-mortem handler can
2393 # save the line away in case we crash, so the post-mortem handler can
2368 # record it
2394 # record it
2369 self._last_input_line = line
2395 self._last_input_line = line
2370
2396
2371 #print '***line: <%s>' % line # dbg
2397 #print '***line: <%s>' % line # dbg
2372
2398
2373 if not line:
2399 if not line:
2374 # Return immediately on purely empty lines, so that if the user
2400 # Return immediately on purely empty lines, so that if the user
2375 # previously typed some whitespace that started a continuation
2401 # previously typed some whitespace that started a continuation
2376 # prompt, he can break out of that loop with just an empty line.
2402 # prompt, he can break out of that loop with just an empty line.
2377 # This is how the default python prompt works.
2403 # This is how the default python prompt works.
2378
2404
2379 # Only return if the accumulated input buffer was just whitespace!
2405 # Only return if the accumulated input buffer was just whitespace!
2380 if ''.join(self.buffer).isspace():
2406 if ''.join(self.buffer).isspace():
2381 self.buffer[:] = []
2407 self.buffer[:] = []
2382 return ''
2408 return ''
2383
2409
2384 line_info = prefilter.LineInfo(line, continue_prompt)
2410 line_info = prefilter.LineInfo(line, continue_prompt)
2385
2411
2386 # the input history needs to track even empty lines
2412 # the input history needs to track even empty lines
2387 stripped = line.strip()
2413 stripped = line.strip()
2388
2414
2389 if not stripped:
2415 if not stripped:
2390 if not continue_prompt:
2416 if not continue_prompt:
2391 self.outputcache.prompt_count -= 1
2417 self.outputcache.prompt_count -= 1
2392 return self.handle_normal(line_info)
2418 return self.handle_normal(line_info)
2393
2419
2394 # print '***cont',continue_prompt # dbg
2420 # print '***cont',continue_prompt # dbg
2395 # special handlers are only allowed for single line statements
2421 # special handlers are only allowed for single line statements
2396 if continue_prompt and not self.rc.multi_line_specials:
2422 if continue_prompt and not self.rc.multi_line_specials:
2397 return self.handle_normal(line_info)
2423 return self.handle_normal(line_info)
2398
2424
2399
2425
2400 # See whether any pre-existing handler can take care of it
2426 # See whether any pre-existing handler can take care of it
2401 rewritten = self.hooks.input_prefilter(stripped)
2427 rewritten = self.hooks.input_prefilter(stripped)
2402 if rewritten != stripped: # ok, some prefilter did something
2428 if rewritten != stripped: # ok, some prefilter did something
2403 rewritten = line_info.pre + rewritten # add indentation
2429 rewritten = line_info.pre + rewritten # add indentation
2404 return self.handle_normal(prefilter.LineInfo(rewritten,
2430 return self.handle_normal(prefilter.LineInfo(rewritten,
2405 continue_prompt))
2431 continue_prompt))
2406
2432
2407 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2433 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2408
2434
2409 return prefilter.prefilter(line_info, self)
2435 return prefilter.prefilter(line_info, self)
2410
2436
2411
2437
2412 def _prefilter_dumb(self, line, continue_prompt):
2438 def _prefilter_dumb(self, line, continue_prompt):
2413 """simple prefilter function, for debugging"""
2439 """simple prefilter function, for debugging"""
2414 return self.handle_normal(line,continue_prompt)
2440 return self.handle_normal(line,continue_prompt)
2415
2441
2416
2442
2417 def multiline_prefilter(self, line, continue_prompt):
2443 def multiline_prefilter(self, line, continue_prompt):
2418 """ Run _prefilter for each line of input
2444 """ Run _prefilter for each line of input
2419
2445
2420 Covers cases where there are multiple lines in the user entry,
2446 Covers cases where there are multiple lines in the user entry,
2421 which is the case when the user goes back to a multiline history
2447 which is the case when the user goes back to a multiline history
2422 entry and presses enter.
2448 entry and presses enter.
2423
2449
2424 """
2450 """
2425 out = []
2451 out = []
2426 for l in line.rstrip('\n').split('\n'):
2452 for l in line.rstrip('\n').split('\n'):
2427 out.append(self._prefilter(l, continue_prompt))
2453 out.append(self._prefilter(l, continue_prompt))
2428 return '\n'.join(out)
2454 return '\n'.join(out)
2429
2455
2430 # Set the default prefilter() function (this can be user-overridden)
2456 # Set the default prefilter() function (this can be user-overridden)
2431 prefilter = multiline_prefilter
2457 prefilter = multiline_prefilter
2432
2458
2433 def handle_normal(self,line_info):
2459 def handle_normal(self,line_info):
2434 """Handle normal input lines. Use as a template for handlers."""
2460 """Handle normal input lines. Use as a template for handlers."""
2435
2461
2436 # With autoindent on, we need some way to exit the input loop, and I
2462 # With autoindent on, we need some way to exit the input loop, and I
2437 # don't want to force the user to have to backspace all the way to
2463 # don't want to force the user to have to backspace all the way to
2438 # clear the line. The rule will be in this case, that either two
2464 # clear the line. The rule will be in this case, that either two
2439 # lines of pure whitespace in a row, or a line of pure whitespace but
2465 # lines of pure whitespace in a row, or a line of pure whitespace but
2440 # of a size different to the indent level, will exit the input loop.
2466 # of a size different to the indent level, will exit the input loop.
2441 line = line_info.line
2467 line = line_info.line
2442 continue_prompt = line_info.continue_prompt
2468 continue_prompt = line_info.continue_prompt
2443
2469
2444 if (continue_prompt and self.autoindent and line.isspace() and
2470 if (continue_prompt and self.autoindent and line.isspace() and
2445 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2471 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2446 (self.buffer[-1]).isspace() )):
2472 (self.buffer[-1]).isspace() )):
2447 line = ''
2473 line = ''
2448
2474
2449 self.log(line,line,continue_prompt)
2475 self.log(line,line,continue_prompt)
2450 return line
2476 return line
2451
2477
2452 def handle_alias(self,line_info):
2478 def handle_alias(self,line_info):
2453 """Handle alias input lines. """
2479 """Handle alias input lines. """
2454 tgt = self.alias_table[line_info.iFun]
2480 tgt = self.alias_table[line_info.iFun]
2455 # print "=>",tgt #dbg
2481 # print "=>",tgt #dbg
2456 if callable(tgt):
2482 if callable(tgt):
2457 if '$' in line_info.line:
2483 if '$' in line_info.line:
2458 call_meth = '(_ip, _ip.itpl(%s))'
2484 call_meth = '(_ip, _ip.itpl(%s))'
2459 else:
2485 else:
2460 call_meth = '(_ip,%s)'
2486 call_meth = '(_ip,%s)'
2461 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2487 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2462 line_info.iFun,
2488 line_info.iFun,
2463 make_quoted_expr(line_info.line))
2489 make_quoted_expr(line_info.line))
2464 else:
2490 else:
2465 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2491 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2466
2492
2467 # pre is needed, because it carries the leading whitespace. Otherwise
2493 # pre is needed, because it carries the leading whitespace. Otherwise
2468 # aliases won't work in indented sections.
2494 # aliases won't work in indented sections.
2469 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2495 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2470 make_quoted_expr( transformed ))
2496 make_quoted_expr( transformed ))
2471
2497
2472 self.log(line_info.line,line_out,line_info.continue_prompt)
2498 self.log(line_info.line,line_out,line_info.continue_prompt)
2473 #print 'line out:',line_out # dbg
2499 #print 'line out:',line_out # dbg
2474 return line_out
2500 return line_out
2475
2501
2476 def handle_shell_escape(self, line_info):
2502 def handle_shell_escape(self, line_info):
2477 """Execute the line in a shell, empty return value"""
2503 """Execute the line in a shell, empty return value"""
2478 #print 'line in :', `line` # dbg
2504 #print 'line in :', `line` # dbg
2479 line = line_info.line
2505 line = line_info.line
2480 if line.lstrip().startswith('!!'):
2506 if line.lstrip().startswith('!!'):
2481 # rewrite LineInfo's line, iFun and theRest to properly hold the
2507 # rewrite LineInfo's line, iFun and theRest to properly hold the
2482 # call to %sx and the actual command to be executed, so
2508 # call to %sx and the actual command to be executed, so
2483 # handle_magic can work correctly. Note that this works even if
2509 # handle_magic can work correctly. Note that this works even if
2484 # the line is indented, so it handles multi_line_specials
2510 # the line is indented, so it handles multi_line_specials
2485 # properly.
2511 # properly.
2486 new_rest = line.lstrip()[2:]
2512 new_rest = line.lstrip()[2:]
2487 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2513 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2488 line_info.iFun = 'sx'
2514 line_info.iFun = 'sx'
2489 line_info.theRest = new_rest
2515 line_info.theRest = new_rest
2490 return self.handle_magic(line_info)
2516 return self.handle_magic(line_info)
2491 else:
2517 else:
2492 cmd = line.lstrip().lstrip('!')
2518 cmd = line.lstrip().lstrip('!')
2493 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2519 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2494 make_quoted_expr(cmd))
2520 make_quoted_expr(cmd))
2495 # update cache/log and return
2521 # update cache/log and return
2496 self.log(line,line_out,line_info.continue_prompt)
2522 self.log(line,line_out,line_info.continue_prompt)
2497 return line_out
2523 return line_out
2498
2524
2499 def handle_magic(self, line_info):
2525 def handle_magic(self, line_info):
2500 """Execute magic functions."""
2526 """Execute magic functions."""
2501 iFun = line_info.iFun
2527 iFun = line_info.iFun
2502 theRest = line_info.theRest
2528 theRest = line_info.theRest
2503 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2529 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2504 make_quoted_expr(iFun + " " + theRest))
2530 make_quoted_expr(iFun + " " + theRest))
2505 self.log(line_info.line,cmd,line_info.continue_prompt)
2531 self.log(line_info.line,cmd,line_info.continue_prompt)
2506 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2532 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2507 return cmd
2533 return cmd
2508
2534
2509 def handle_auto(self, line_info):
2535 def handle_auto(self, line_info):
2510 """Hande lines which can be auto-executed, quoting if requested."""
2536 """Hande lines which can be auto-executed, quoting if requested."""
2511
2537
2512 line = line_info.line
2538 line = line_info.line
2513 iFun = line_info.iFun
2539 iFun = line_info.iFun
2514 theRest = line_info.theRest
2540 theRest = line_info.theRest
2515 pre = line_info.pre
2541 pre = line_info.pre
2516 continue_prompt = line_info.continue_prompt
2542 continue_prompt = line_info.continue_prompt
2517 obj = line_info.ofind(self)['obj']
2543 obj = line_info.ofind(self)['obj']
2518
2544
2519 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2545 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2520
2546
2521 # This should only be active for single-line input!
2547 # This should only be active for single-line input!
2522 if continue_prompt:
2548 if continue_prompt:
2523 self.log(line,line,continue_prompt)
2549 self.log(line,line,continue_prompt)
2524 return line
2550 return line
2525
2551
2526 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2552 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2527 auto_rewrite = True
2553 auto_rewrite = True
2528
2554
2529 if pre == self.ESC_QUOTE:
2555 if pre == self.ESC_QUOTE:
2530 # Auto-quote splitting on whitespace
2556 # Auto-quote splitting on whitespace
2531 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2557 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2532 elif pre == self.ESC_QUOTE2:
2558 elif pre == self.ESC_QUOTE2:
2533 # Auto-quote whole string
2559 # Auto-quote whole string
2534 newcmd = '%s("%s")' % (iFun,theRest)
2560 newcmd = '%s("%s")' % (iFun,theRest)
2535 elif pre == self.ESC_PAREN:
2561 elif pre == self.ESC_PAREN:
2536 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2562 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2537 else:
2563 else:
2538 # Auto-paren.
2564 # Auto-paren.
2539 # We only apply it to argument-less calls if the autocall
2565 # We only apply it to argument-less calls if the autocall
2540 # parameter is set to 2. We only need to check that autocall is <
2566 # parameter is set to 2. We only need to check that autocall is <
2541 # 2, since this function isn't called unless it's at least 1.
2567 # 2, since this function isn't called unless it's at least 1.
2542 if not theRest and (self.rc.autocall < 2) and not force_auto:
2568 if not theRest and (self.rc.autocall < 2) and not force_auto:
2543 newcmd = '%s %s' % (iFun,theRest)
2569 newcmd = '%s %s' % (iFun,theRest)
2544 auto_rewrite = False
2570 auto_rewrite = False
2545 else:
2571 else:
2546 if not force_auto and theRest.startswith('['):
2572 if not force_auto and theRest.startswith('['):
2547 if hasattr(obj,'__getitem__'):
2573 if hasattr(obj,'__getitem__'):
2548 # Don't autocall in this case: item access for an object
2574 # Don't autocall in this case: item access for an object
2549 # which is BOTH callable and implements __getitem__.
2575 # which is BOTH callable and implements __getitem__.
2550 newcmd = '%s %s' % (iFun,theRest)
2576 newcmd = '%s %s' % (iFun,theRest)
2551 auto_rewrite = False
2577 auto_rewrite = False
2552 else:
2578 else:
2553 # if the object doesn't support [] access, go ahead and
2579 # if the object doesn't support [] access, go ahead and
2554 # autocall
2580 # autocall
2555 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2581 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2556 elif theRest.endswith(';'):
2582 elif theRest.endswith(';'):
2557 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2583 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2558 else:
2584 else:
2559 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2585 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2560
2586
2561 if auto_rewrite:
2587 if auto_rewrite:
2562 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2588 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2563
2589
2564 try:
2590 try:
2565 # plain ascii works better w/ pyreadline, on some machines, so
2591 # plain ascii works better w/ pyreadline, on some machines, so
2566 # we use it and only print uncolored rewrite if we have unicode
2592 # we use it and only print uncolored rewrite if we have unicode
2567 rw = str(rw)
2593 rw = str(rw)
2568 print >>Term.cout, rw
2594 print >>Term.cout, rw
2569 except UnicodeEncodeError:
2595 except UnicodeEncodeError:
2570 print "-------------->" + newcmd
2596 print "-------------->" + newcmd
2571
2597
2572 # log what is now valid Python, not the actual user input (without the
2598 # log what is now valid Python, not the actual user input (without the
2573 # final newline)
2599 # final newline)
2574 self.log(line,newcmd,continue_prompt)
2600 self.log(line,newcmd,continue_prompt)
2575 return newcmd
2601 return newcmd
2576
2602
2577 def handle_help(self, line_info):
2603 def handle_help(self, line_info):
2578 """Try to get some help for the object.
2604 """Try to get some help for the object.
2579
2605
2580 obj? or ?obj -> basic information.
2606 obj? or ?obj -> basic information.
2581 obj?? or ??obj -> more details.
2607 obj?? or ??obj -> more details.
2582 """
2608 """
2583
2609
2584 line = line_info.line
2610 line = line_info.line
2585 # We need to make sure that we don't process lines which would be
2611 # We need to make sure that we don't process lines which would be
2586 # otherwise valid python, such as "x=1 # what?"
2612 # otherwise valid python, such as "x=1 # what?"
2587 try:
2613 try:
2588 codeop.compile_command(line)
2614 codeop.compile_command(line)
2589 except SyntaxError:
2615 except SyntaxError:
2590 # We should only handle as help stuff which is NOT valid syntax
2616 # We should only handle as help stuff which is NOT valid syntax
2591 if line[0]==self.ESC_HELP:
2617 if line[0]==self.ESC_HELP:
2592 line = line[1:]
2618 line = line[1:]
2593 elif line[-1]==self.ESC_HELP:
2619 elif line[-1]==self.ESC_HELP:
2594 line = line[:-1]
2620 line = line[:-1]
2595 self.log(line,'#?'+line,line_info.continue_prompt)
2621 self.log(line,'#?'+line,line_info.continue_prompt)
2596 if line:
2622 if line:
2597 #print 'line:<%r>' % line # dbg
2623 #print 'line:<%r>' % line # dbg
2598 self.magic_pinfo(line)
2624 self.magic_pinfo(line)
2599 else:
2625 else:
2600 page(self.usage,screen_lines=self.rc.screen_length)
2626 page(self.usage,screen_lines=self.rc.screen_length)
2601 return '' # Empty string is needed here!
2627 return '' # Empty string is needed here!
2602 except:
2628 except:
2603 # Pass any other exceptions through to the normal handler
2629 # Pass any other exceptions through to the normal handler
2604 return self.handle_normal(line_info)
2630 return self.handle_normal(line_info)
2605 else:
2631 else:
2606 # If the code compiles ok, we should handle it normally
2632 # If the code compiles ok, we should handle it normally
2607 return self.handle_normal(line_info)
2633 return self.handle_normal(line_info)
2608
2634
2609 def getapi(self):
2635 def getapi(self):
2610 """ Get an IPApi object for this shell instance
2636 """ Get an IPApi object for this shell instance
2611
2637
2612 Getting an IPApi object is always preferable to accessing the shell
2638 Getting an IPApi object is always preferable to accessing the shell
2613 directly, but this holds true especially for extensions.
2639 directly, but this holds true especially for extensions.
2614
2640
2615 It should always be possible to implement an extension with IPApi
2641 It should always be possible to implement an extension with IPApi
2616 alone. If not, contact maintainer to request an addition.
2642 alone. If not, contact maintainer to request an addition.
2617
2643
2618 """
2644 """
2619 return self.api
2645 return self.api
2620
2646
2621 def handle_emacs(self, line_info):
2647 def handle_emacs(self, line_info):
2622 """Handle input lines marked by python-mode."""
2648 """Handle input lines marked by python-mode."""
2623
2649
2624 # Currently, nothing is done. Later more functionality can be added
2650 # Currently, nothing is done. Later more functionality can be added
2625 # here if needed.
2651 # here if needed.
2626
2652
2627 # The input cache shouldn't be updated
2653 # The input cache shouldn't be updated
2628 return line_info.line
2654 return line_info.line
2629
2655
2630
2656
2631 def mktempfile(self,data=None):
2657 def mktempfile(self,data=None):
2632 """Make a new tempfile and return its filename.
2658 """Make a new tempfile and return its filename.
2633
2659
2634 This makes a call to tempfile.mktemp, but it registers the created
2660 This makes a call to tempfile.mktemp, but it registers the created
2635 filename internally so ipython cleans it up at exit time.
2661 filename internally so ipython cleans it up at exit time.
2636
2662
2637 Optional inputs:
2663 Optional inputs:
2638
2664
2639 - data(None): if data is given, it gets written out to the temp file
2665 - data(None): if data is given, it gets written out to the temp file
2640 immediately, and the file is closed again."""
2666 immediately, and the file is closed again."""
2641
2667
2642 filename = tempfile.mktemp('.py','ipython_edit_')
2668 filename = tempfile.mktemp('.py','ipython_edit_')
2643 self.tempfiles.append(filename)
2669 self.tempfiles.append(filename)
2644
2670
2645 if data:
2671 if data:
2646 tmp_file = open(filename,'w')
2672 tmp_file = open(filename,'w')
2647 tmp_file.write(data)
2673 tmp_file.write(data)
2648 tmp_file.close()
2674 tmp_file.close()
2649 return filename
2675 return filename
2650
2676
2651 def write(self,data):
2677 def write(self,data):
2652 """Write a string to the default output"""
2678 """Write a string to the default output"""
2653 Term.cout.write(data)
2679 Term.cout.write(data)
2654
2680
2655 def write_err(self,data):
2681 def write_err(self,data):
2656 """Write a string to the default error output"""
2682 """Write a string to the default error output"""
2657 Term.cerr.write(data)
2683 Term.cerr.write(data)
2658
2684
2659 def ask_exit(self):
2685 def ask_exit(self):
2660 """ Call for exiting. Can be overiden and used as a callback. """
2686 """ Call for exiting. Can be overiden and used as a callback. """
2661 self.exit_now = True
2687 self.exit_now = True
2662
2688
2663 def exit(self):
2689 def exit(self):
2664 """Handle interactive exit.
2690 """Handle interactive exit.
2665
2691
2666 This method calls the ask_exit callback."""
2692 This method calls the ask_exit callback."""
2667
2693
2668 if self.rc.confirm_exit:
2694 if self.rc.confirm_exit:
2669 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2695 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2670 self.ask_exit()
2696 self.ask_exit()
2671 else:
2697 else:
2672 self.ask_exit()
2698 self.ask_exit()
2673
2699
2674 def safe_execfile(self,fname,*where,**kw):
2700 def safe_execfile(self,fname,*where,**kw):
2675 """A safe version of the builtin execfile().
2701 """A safe version of the builtin execfile().
2676
2702
2677 This version will never throw an exception, and knows how to handle
2703 This version will never throw an exception, and knows how to handle
2678 ipython logs as well.
2704 ipython logs as well.
2679
2705
2680 :Parameters:
2706 :Parameters:
2681 fname : string
2707 fname : string
2682 Name of the file to be executed.
2708 Name of the file to be executed.
2683
2709
2684 where : tuple
2710 where : tuple
2685 One or two namespaces, passed to execfile() as (globals,locals).
2711 One or two namespaces, passed to execfile() as (globals,locals).
2686 If only one is given, it is passed as both.
2712 If only one is given, it is passed as both.
2687
2713
2688 :Keywords:
2714 :Keywords:
2689 islog : boolean (False)
2715 islog : boolean (False)
2690
2716
2691 quiet : boolean (True)
2717 quiet : boolean (True)
2692
2718
2693 exit_ignore : boolean (False)
2719 exit_ignore : boolean (False)
2694 """
2720 """
2695
2721
2696 def syspath_cleanup():
2722 def syspath_cleanup():
2697 """Internal cleanup routine for sys.path."""
2723 """Internal cleanup routine for sys.path."""
2698 if add_dname:
2724 if add_dname:
2699 try:
2725 try:
2700 sys.path.remove(dname)
2726 sys.path.remove(dname)
2701 except ValueError:
2727 except ValueError:
2702 # For some reason the user has already removed it, ignore.
2728 # For some reason the user has already removed it, ignore.
2703 pass
2729 pass
2704
2730
2705 fname = os.path.expanduser(fname)
2731 fname = os.path.expanduser(fname)
2706
2732
2707 # Find things also in current directory. This is needed to mimic the
2733 # Find things also in current directory. This is needed to mimic the
2708 # behavior of running a script from the system command line, where
2734 # behavior of running a script from the system command line, where
2709 # Python inserts the script's directory into sys.path
2735 # Python inserts the script's directory into sys.path
2710 dname = os.path.dirname(os.path.abspath(fname))
2736 dname = os.path.dirname(os.path.abspath(fname))
2711 add_dname = False
2737 add_dname = False
2712 if dname not in sys.path:
2738 if dname not in sys.path:
2713 sys.path.insert(0,dname)
2739 sys.path.insert(0,dname)
2714 add_dname = True
2740 add_dname = True
2715
2741
2716 try:
2742 try:
2717 xfile = open(fname)
2743 xfile = open(fname)
2718 except:
2744 except:
2719 print >> Term.cerr, \
2745 print >> Term.cerr, \
2720 'Could not open file <%s> for safe execution.' % fname
2746 'Could not open file <%s> for safe execution.' % fname
2721 syspath_cleanup()
2747 syspath_cleanup()
2722 return None
2748 return None
2723
2749
2724 kw.setdefault('islog',0)
2750 kw.setdefault('islog',0)
2725 kw.setdefault('quiet',1)
2751 kw.setdefault('quiet',1)
2726 kw.setdefault('exit_ignore',0)
2752 kw.setdefault('exit_ignore',0)
2727
2753
2728 first = xfile.readline()
2754 first = xfile.readline()
2729 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2755 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2730 xfile.close()
2756 xfile.close()
2731 # line by line execution
2757 # line by line execution
2732 if first.startswith(loghead) or kw['islog']:
2758 if first.startswith(loghead) or kw['islog']:
2733 print 'Loading log file <%s> one line at a time...' % fname
2759 print 'Loading log file <%s> one line at a time...' % fname
2734 if kw['quiet']:
2760 if kw['quiet']:
2735 stdout_save = sys.stdout
2761 stdout_save = sys.stdout
2736 sys.stdout = StringIO.StringIO()
2762 sys.stdout = StringIO.StringIO()
2737 try:
2763 try:
2738 globs,locs = where[0:2]
2764 globs,locs = where[0:2]
2739 except:
2765 except:
2740 try:
2766 try:
2741 globs = locs = where[0]
2767 globs = locs = where[0]
2742 except:
2768 except:
2743 globs = locs = globals()
2769 globs = locs = globals()
2744 badblocks = []
2770 badblocks = []
2745
2771
2746 # we also need to identify indented blocks of code when replaying
2772 # we also need to identify indented blocks of code when replaying
2747 # logs and put them together before passing them to an exec
2773 # logs and put them together before passing them to an exec
2748 # statement. This takes a bit of regexp and look-ahead work in the
2774 # statement. This takes a bit of regexp and look-ahead work in the
2749 # file. It's easiest if we swallow the whole thing in memory
2775 # file. It's easiest if we swallow the whole thing in memory
2750 # first, and manually walk through the lines list moving the
2776 # first, and manually walk through the lines list moving the
2751 # counter ourselves.
2777 # counter ourselves.
2752 indent_re = re.compile('\s+\S')
2778 indent_re = re.compile('\s+\S')
2753 xfile = open(fname)
2779 xfile = open(fname)
2754 filelines = xfile.readlines()
2780 filelines = xfile.readlines()
2755 xfile.close()
2781 xfile.close()
2756 nlines = len(filelines)
2782 nlines = len(filelines)
2757 lnum = 0
2783 lnum = 0
2758 while lnum < nlines:
2784 while lnum < nlines:
2759 line = filelines[lnum]
2785 line = filelines[lnum]
2760 lnum += 1
2786 lnum += 1
2761 # don't re-insert logger status info into cache
2787 # don't re-insert logger status info into cache
2762 if line.startswith('#log#'):
2788 if line.startswith('#log#'):
2763 continue
2789 continue
2764 else:
2790 else:
2765 # build a block of code (maybe a single line) for execution
2791 # build a block of code (maybe a single line) for execution
2766 block = line
2792 block = line
2767 try:
2793 try:
2768 next = filelines[lnum] # lnum has already incremented
2794 next = filelines[lnum] # lnum has already incremented
2769 except:
2795 except:
2770 next = None
2796 next = None
2771 while next and indent_re.match(next):
2797 while next and indent_re.match(next):
2772 block += next
2798 block += next
2773 lnum += 1
2799 lnum += 1
2774 try:
2800 try:
2775 next = filelines[lnum]
2801 next = filelines[lnum]
2776 except:
2802 except:
2777 next = None
2803 next = None
2778 # now execute the block of one or more lines
2804 # now execute the block of one or more lines
2779 try:
2805 try:
2780 exec block in globs,locs
2806 exec block in globs,locs
2781 except SystemExit:
2807 except SystemExit:
2782 pass
2808 pass
2783 except:
2809 except:
2784 badblocks.append(block.rstrip())
2810 badblocks.append(block.rstrip())
2785 if kw['quiet']: # restore stdout
2811 if kw['quiet']: # restore stdout
2786 sys.stdout.close()
2812 sys.stdout.close()
2787 sys.stdout = stdout_save
2813 sys.stdout = stdout_save
2788 print 'Finished replaying log file <%s>' % fname
2814 print 'Finished replaying log file <%s>' % fname
2789 if badblocks:
2815 if badblocks:
2790 print >> sys.stderr, ('\nThe following lines/blocks in file '
2816 print >> sys.stderr, ('\nThe following lines/blocks in file '
2791 '<%s> reported errors:' % fname)
2817 '<%s> reported errors:' % fname)
2792
2818
2793 for badline in badblocks:
2819 for badline in badblocks:
2794 print >> sys.stderr, badline
2820 print >> sys.stderr, badline
2795 else: # regular file execution
2821 else: # regular file execution
2796 try:
2822 try:
2797 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2823 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2798 # Work around a bug in Python for Windows. The bug was
2824 # Work around a bug in Python for Windows. The bug was
2799 # fixed in in Python 2.5 r54159 and 54158, but that's still
2825 # fixed in in Python 2.5 r54159 and 54158, but that's still
2800 # SVN Python as of March/07. For details, see:
2826 # SVN Python as of March/07. For details, see:
2801 # http://projects.scipy.org/ipython/ipython/ticket/123
2827 # http://projects.scipy.org/ipython/ipython/ticket/123
2802 try:
2828 try:
2803 globs,locs = where[0:2]
2829 globs,locs = where[0:2]
2804 except:
2830 except:
2805 try:
2831 try:
2806 globs = locs = where[0]
2832 globs = locs = where[0]
2807 except:
2833 except:
2808 globs = locs = globals()
2834 globs = locs = globals()
2809 exec file(fname) in globs,locs
2835 exec file(fname) in globs,locs
2810 else:
2836 else:
2811 execfile(fname,*where)
2837 execfile(fname,*where)
2812 except SyntaxError:
2838 except SyntaxError:
2813 self.showsyntaxerror()
2839 self.showsyntaxerror()
2814 warn('Failure executing file: <%s>' % fname)
2840 warn('Failure executing file: <%s>' % fname)
2815 except SystemExit,status:
2841 except SystemExit,status:
2816 # Code that correctly sets the exit status flag to success (0)
2842 # Code that correctly sets the exit status flag to success (0)
2817 # shouldn't be bothered with a traceback. Note that a plain
2843 # shouldn't be bothered with a traceback. Note that a plain
2818 # sys.exit() does NOT set the message to 0 (it's empty) so that
2844 # sys.exit() does NOT set the message to 0 (it's empty) so that
2819 # will still get a traceback. Note that the structure of the
2845 # will still get a traceback. Note that the structure of the
2820 # SystemExit exception changed between Python 2.4 and 2.5, so
2846 # SystemExit exception changed between Python 2.4 and 2.5, so
2821 # the checks must be done in a version-dependent way.
2847 # the checks must be done in a version-dependent way.
2822 show = False
2848 show = False
2823
2849
2824 if sys.version_info[:2] > (2,5):
2850 if sys.version_info[:2] > (2,5):
2825 if status.message!=0 and not kw['exit_ignore']:
2851 if status.message!=0 and not kw['exit_ignore']:
2826 show = True
2852 show = True
2827 else:
2853 else:
2828 if status.code and not kw['exit_ignore']:
2854 if status.code and not kw['exit_ignore']:
2829 show = True
2855 show = True
2830 if show:
2856 if show:
2831 self.showtraceback()
2857 self.showtraceback()
2832 warn('Failure executing file: <%s>' % fname)
2858 warn('Failure executing file: <%s>' % fname)
2833 except:
2859 except:
2834 self.showtraceback()
2860 self.showtraceback()
2835 warn('Failure executing file: <%s>' % fname)
2861 warn('Failure executing file: <%s>' % fname)
2836
2862
2837 syspath_cleanup()
2863 syspath_cleanup()
2838
2864
2839 #************************* end of file <iplib.py> *****************************
2865 #************************* end of file <iplib.py> *****************************
@@ -1,149 +1,151 b''
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5
5
6 # Standard library imports
6 # Standard library imports
7 import os
7 import os
8 import sys
8 import sys
9
9
10 # Third-party imports
10 # Third-party imports
11 import nose.tools as nt
11 import nose.tools as nt
12
12
13 # From our own code
13 # From our own code
14 from IPython.testing import decorators as dec
14 from IPython.testing import decorators as dec
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Test functions begin
17 # Test functions begin
18
18
19 def test_rehashx():
19 def test_rehashx():
20 # clear up everything
20 # clear up everything
21 _ip.IP.alias_table.clear()
21 _ip.IP.alias_table.clear()
22 del _ip.db['syscmdlist']
22 del _ip.db['syscmdlist']
23
23
24 _ip.magic('rehashx')
24 _ip.magic('rehashx')
25 # Practically ALL ipython development systems will have more than 10 aliases
25 # Practically ALL ipython development systems will have more than 10 aliases
26
26
27 assert len(_ip.IP.alias_table) > 10
27 assert len(_ip.IP.alias_table) > 10
28 for key, val in _ip.IP.alias_table.items():
28 for key, val in _ip.IP.alias_table.items():
29 # we must strip dots from alias names
29 # we must strip dots from alias names
30 assert '.' not in key
30 assert '.' not in key
31
31
32 # rehashx must fill up syscmdlist
32 # rehashx must fill up syscmdlist
33 scoms = _ip.db['syscmdlist']
33 scoms = _ip.db['syscmdlist']
34 assert len(scoms) > 10
34 assert len(scoms) > 10
35
35
36
36
37 def doctest_run_ns():
37 def doctest_run_ns():
38 """Classes declared %run scripts must be instantiable afterwards.
38 """Classes declared %run scripts must be instantiable afterwards.
39
39
40 In [11]: run tclass foo
40 In [11]: run tclass foo
41
41
42 In [12]: isinstance(f(),foo)
42 In [12]: isinstance(f(),foo)
43 Out[12]: True
43 Out[12]: True
44 """
44 """
45
45
46
46
47 def doctest_run_ns2():
47 def doctest_run_ns2():
48 """Classes declared %run scripts must be instantiable afterwards.
48 """Classes declared %run scripts must be instantiable afterwards.
49
49
50 In [4]: run tclass C-first_pass
50 In [4]: run tclass C-first_pass
51
51
52 In [5]: run tclass C-second_pass
52 In [5]: run tclass C-second_pass
53 tclass.py: deleting object: C-first_pass
53 tclass.py: deleting object: C-first_pass
54 """
54 """
55
55
56
56
57 def doctest_hist_f():
57 def doctest_hist_f():
58 """Test %hist -f with temporary filename.
58 """Test %hist -f with temporary filename.
59
59
60 In [9]: import tempfile
60 In [9]: import tempfile
61
61
62 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
62 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
63
63
64 In [11]: %history -n -f $tfile 3
64 In [11]: %history -n -f $tfile 3
65 """
65 """
66
66
67
67
68 def doctest_hist_r():
68 def doctest_hist_r():
69 """Test %hist -r
69 """Test %hist -r
70
70
71 XXX - This test is not recording the output correctly. Not sure why...
71 XXX - This test is not recording the output correctly. Not sure why...
72
72
73 In [6]: x=1
73 In [6]: x=1
74
74
75 In [7]: hist -n -r 2
75 In [7]: hist -n -r 2
76 x=1 # random
76 x=1 # random
77 hist -n -r 2 # random
77 hist -n -r 2 # random
78 """
78 """
79
79
80
80
81 def test_obj_del():
81 def test_obj_del():
82 """Test that object's __del__ methods are called on exit."""
82 """Test that object's __del__ methods are called on exit."""
83 test_dir = os.path.dirname(__file__)
83 test_dir = os.path.dirname(__file__)
84 del_file = os.path.join(test_dir,'obj_del.py')
84 del_file = os.path.join(test_dir,'obj_del.py')
85 out = _ip.IP.getoutput('ipython %s' % del_file)
85 out = _ip.IP.getoutput('ipython %s' % del_file)
86 nt.assert_equals(out,'obj_del.py: object A deleted')
86 nt.assert_equals(out,'obj_del.py: object A deleted')
87
87
88
88
89 def test_shist():
89 def test_shist():
90 # Simple tests of ShadowHist class - test generator.
90 # Simple tests of ShadowHist class - test generator.
91 import os, shutil, tempfile
91 import os, shutil, tempfile
92
92
93 from IPython.Extensions import pickleshare
93 from IPython.Extensions import pickleshare
94 from IPython.history import ShadowHist
94 from IPython.history import ShadowHist
95
95
96 tfile = tempfile.mktemp('','tmp-ipython-')
96 tfile = tempfile.mktemp('','tmp-ipython-')
97
97
98 db = pickleshare.PickleShareDB(tfile)
98 db = pickleshare.PickleShareDB(tfile)
99 s = ShadowHist(db)
99 s = ShadowHist(db)
100 s.add('hello')
100 s.add('hello')
101 s.add('world')
101 s.add('world')
102 s.add('hello')
102 s.add('hello')
103 s.add('hello')
103 s.add('hello')
104 s.add('karhu')
104 s.add('karhu')
105
105
106 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
106 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
107
107
108 yield nt.assert_equal,s.get(2),'world'
108 yield nt.assert_equal,s.get(2),'world'
109
109
110 shutil.rmtree(tfile)
110 shutil.rmtree(tfile)
111
111
112 @dec.skipif_not_numpy
112 @dec.skipif_not_numpy
113 def test_numpy_clear_array_undec():
113 def test_numpy_clear_array_undec():
114 _ip.ex('import numpy as np')
114 _ip.ex('import numpy as np')
115 _ip.ex('a = np.empty(2)')
115 _ip.ex('a = np.empty(2)')
116
116
117 yield nt.assert_true,'a' in _ip.user_ns
117 yield nt.assert_true,'a' in _ip.user_ns
118 _ip.magic('clear array')
118 _ip.magic('clear array')
119 yield nt.assert_false,'a' in _ip.user_ns
119 yield nt.assert_false,'a' in _ip.user_ns
120
120
121
121
122 @dec.skip()
122 @dec.skip()
123 def test_fail_dec(*a,**k):
123 def test_fail_dec(*a,**k):
124 yield nt.assert_true, False
124 yield nt.assert_true, False
125
125
126 @dec.skip('This one shouldn not run')
126 @dec.skip('This one shouldn not run')
127 def test_fail_dec2(*a,**k):
127 def test_fail_dec2(*a,**k):
128 yield nt.assert_true, False
128 yield nt.assert_true, False
129
129
130 @dec.skipknownfailure
130 @dec.skipknownfailure
131 def test_fail_dec3(*a,**k):
131 def test_fail_dec3(*a,**k):
132 yield nt.assert_true, False
132 yield nt.assert_true, False
133
133
134
134
135 def doctest_refbug():
135 def doctest_refbug():
136 """Very nasty problem with references held by multiple runs of a script.
136 """Very nasty problem with references held by multiple runs of a script.
137 See: https://bugs.launchpad.net/ipython/+bug/269966
137 See: https://bugs.launchpad.net/ipython/+bug/269966
138
138
139 In [1]: _ip.IP.clear_main_mod_cache()
140
139 In [2]: run refbug
141 In [2]: run refbug
140
142
141 In [3]: call_f()
143 In [3]: call_f()
142 lowercased: hello
144 lowercased: hello
143
145
144 In [4]: run refbug
146 In [4]: run refbug
145
147
146 In [5]: call_f()
148 In [5]: call_f()
147 lowercased: hello
149 lowercased: hello
148 lowercased: hello
150 lowercased: hello
149 """
151 """
General Comments 0
You need to be logged in to leave comments. Login now