Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,315 +1,411 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Pdb debugger class. |
|
3 | Pdb debugger class. | |
4 |
|
4 | |||
5 | Modified from the standard pdb.Pdb class to avoid including readline, so that |
|
5 | Modified from the standard pdb.Pdb class to avoid including readline, so that | |
6 | the command line completion of other programs which include this isn't |
|
6 | the command line completion of other programs which include this isn't | |
7 | damaged. |
|
7 | damaged. | |
8 |
|
8 | |||
9 | In the future, this class will be expanded with improvements over the standard |
|
9 | In the future, this class will be expanded with improvements over the standard | |
10 | pdb. |
|
10 | pdb. | |
11 |
|
11 | |||
12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor |
|
12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor | |
13 | changes. Licensing should therefore be under the standard Python terms. For |
|
13 | changes. Licensing should therefore be under the standard Python terms. For | |
14 | details on the PSF (Python Software Foundation) standard license, see: |
|
14 | details on the PSF (Python Software Foundation) standard license, see: | |
15 |
|
15 | |||
16 | http://www.python.org/2.2.3/license.html |
|
16 | http://www.python.org/2.2.3/license.html | |
17 |
|
17 | |||
18 |
$Id: Debugger.py 1 |
|
18 | $Id: Debugger.py 1853 2006-10-30 17:00:39Z vivainio $""" | |
19 |
|
19 | |||
20 | #***************************************************************************** |
|
20 | #***************************************************************************** | |
21 | # |
|
21 | # | |
22 | # Since this file is essentially a modified copy of the pdb module which is |
|
22 | # Since this file is essentially a modified copy of the pdb module which is | |
23 | # part of the standard Python distribution, I assume that the proper procedure |
|
23 | # part of the standard Python distribution, I assume that the proper procedure | |
24 | # is to maintain its copyright as belonging to the Python Software Foundation |
|
24 | # is to maintain its copyright as belonging to the Python Software Foundation | |
25 | # (in addition to my own, for all new code). |
|
25 | # (in addition to my own, for all new code). | |
26 | # |
|
26 | # | |
27 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
27 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
28 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> |
|
28 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> | |
29 | # |
|
29 | # | |
30 | # Distributed under the terms of the BSD License. The full license is in |
|
30 | # Distributed under the terms of the BSD License. The full license is in | |
31 | # the file COPYING, distributed as part of this software. |
|
31 | # the file COPYING, distributed as part of this software. | |
32 | # |
|
32 | # | |
33 | #***************************************************************************** |
|
33 | #***************************************************************************** | |
34 |
|
34 | |||
35 | from IPython import Release |
|
35 | from IPython import Release | |
36 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
36 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
37 | __license__ = 'Python' |
|
37 | __license__ = 'Python' | |
38 |
|
38 | |||
39 | import bdb |
|
39 | import bdb | |
40 | import cmd |
|
40 | import cmd | |
41 | import linecache |
|
41 | import linecache | |
42 | import os |
|
42 | import os | |
43 | import pdb |
|
|||
44 | import sys |
|
43 | import sys | |
45 |
|
44 | |||
46 | from IPython import PyColorize, ColorANSI |
|
45 | from IPython import PyColorize, ColorANSI | |
47 | from IPython.genutils import Term |
|
46 | from IPython.genutils import Term | |
48 | from IPython.excolors import ExceptionColors |
|
47 | from IPython.excolors import ExceptionColors | |
49 |
|
48 | |||
|
49 | # See if we can use pydb. | |||
|
50 | has_pydb = False | |||
|
51 | prompt = 'ipdb>' | |||
|
52 | if sys.version[:3] >= '2.5': | |||
|
53 | try: | |||
|
54 | import pydb | |||
|
55 | if hasattr(pydb.pydb, "runl"): | |||
|
56 | has_pydb = True | |||
|
57 | from pydb import Pdb as OldPdb | |||
|
58 | prompt = 'ipydb>' | |||
|
59 | except ImportError: | |||
|
60 | pass | |||
|
61 | ||||
|
62 | if has_pydb: | |||
|
63 | from pydb import Pdb as OldPdb | |||
|
64 | else: | |||
|
65 | from pdb import Pdb as OldPdb | |||
|
66 | ||||
|
67 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): | |||
|
68 | """Make new_fn have old_fn's doc string. This is particularly useful | |||
|
69 | for the do_... commands that hook into the help system. | |||
|
70 | Adapted from from a comp.lang.python posting | |||
|
71 | by Duncan Booth.""" | |||
|
72 | def wrapper(*args, **kw): | |||
|
73 | return new_fn(*args, **kw) | |||
|
74 | if old_fn.__doc__: | |||
|
75 | wrapper.__doc__ = old_fn.__doc__ + additional_text | |||
|
76 | return wrapper | |||
|
77 | ||||
50 | def _file_lines(fname): |
|
78 | def _file_lines(fname): | |
51 | """Return the contents of a named file as a list of lines. |
|
79 | """Return the contents of a named file as a list of lines. | |
52 |
|
80 | |||
53 | This function never raises an IOError exception: if the file can't be |
|
81 | This function never raises an IOError exception: if the file can't be | |
54 | read, it simply returns an empty list.""" |
|
82 | read, it simply returns an empty list.""" | |
55 |
|
83 | |||
56 | try: |
|
84 | try: | |
57 | outfile = open(fname) |
|
85 | outfile = open(fname) | |
58 | except IOError: |
|
86 | except IOError: | |
59 | return [] |
|
87 | return [] | |
60 | else: |
|
88 | else: | |
61 | out = outfile.readlines() |
|
89 | out = outfile.readlines() | |
62 | outfile.close() |
|
90 | outfile.close() | |
63 | return out |
|
91 | return out | |
64 |
|
92 | |||
65 |
class Pdb( |
|
93 | class Pdb(OldPdb): | |
66 | """Modified Pdb class, does not load readline.""" |
|
94 | """Modified Pdb class, does not load readline.""" | |
67 |
|
95 | |||
68 | if sys.version[:3] >= '2.5': |
|
96 | if sys.version[:3] >= '2.5': | |
69 | def __init__(self,color_scheme='NoColor',completekey=None, |
|
97 | def __init__(self,color_scheme='NoColor',completekey=None, | |
70 | stdin=None, stdout=None): |
|
98 | stdin=None, stdout=None): | |
71 |
|
99 | |||
72 | # Parent constructor: |
|
100 | # Parent constructor: | |
73 |
|
|
101 | OldPdb.__init__(self,completekey,stdin,stdout) | |
74 |
|
102 | |||
75 | # IPython changes... |
|
103 | # IPython changes... | |
76 |
self.prompt = |
|
104 | self.prompt = prompt # The default prompt is '(Pdb)' | |
|
105 | self.is_pydb = prompt == 'ipydb>' | |||
|
106 | ||||
|
107 | if self.is_pydb: | |||
|
108 | ||||
|
109 | # iplib.py's ipalias seems to want pdb's checkline | |||
|
110 | # which located in pydb.fn | |||
|
111 | import pydb.fns | |||
|
112 | self.checkline = lambda filename, lineno: \ | |||
|
113 | pydb.fns.checkline(self, filename, lineno) | |||
|
114 | ||||
|
115 | self.curframe = None | |||
|
116 | self.do_restart = self.new_do_restart | |||
|
117 | ||||
|
118 | self.old_all_completions = __IPYTHON__.Completer.all_completions | |||
|
119 | __IPYTHON__.Completer.all_completions=self.all_completions | |||
|
120 | ||||
|
121 | # Do we have access to pydb's list command parser? | |||
|
122 | self.do_list = decorate_fn_with_doc(self.list_command_pydb, | |||
|
123 | OldPdb.do_list) | |||
|
124 | self.do_l = self.do_list | |||
|
125 | self.do_frame = decorate_fn_with_doc(self.new_do_frame, | |||
|
126 | OldPdb.do_frame) | |||
|
127 | ||||
77 | self.aliases = {} |
|
128 | self.aliases = {} | |
78 |
|
129 | |||
79 | # Create color table: we copy the default one from the traceback |
|
130 | # Create color table: we copy the default one from the traceback | |
80 | # module and add a few attributes needed for debugging |
|
131 | # module and add a few attributes needed for debugging | |
81 | self.color_scheme_table = ExceptionColors.copy() |
|
132 | self.color_scheme_table = ExceptionColors.copy() | |
82 |
|
133 | |||
83 | # shorthands |
|
134 | # shorthands | |
84 | C = ColorANSI.TermColors |
|
135 | C = ColorANSI.TermColors | |
85 | cst = self.color_scheme_table |
|
136 | cst = self.color_scheme_table | |
86 |
|
137 | |||
87 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
138 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor | |
88 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
139 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor | |
89 |
|
140 | |||
90 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
141 | cst['Linux'].colors.breakpoint_enabled = C.LightRed | |
91 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
142 | cst['Linux'].colors.breakpoint_disabled = C.Red | |
92 |
|
143 | |||
93 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
144 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed | |
94 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
145 | cst['LightBG'].colors.breakpoint_disabled = C.Red | |
95 |
|
146 | |||
96 | self.set_colors(color_scheme) |
|
147 | self.set_colors(color_scheme) | |
97 |
|
148 | |||
98 | else: |
|
149 | else: | |
99 | # Ugly hack: for Python 2.3-2.4, we can't call the parent constructor, |
|
150 | # Ugly hack: for Python 2.3-2.4, we can't call the parent constructor, | |
100 | # because it binds readline and breaks tab-completion. This means we |
|
151 | # because it binds readline and breaks tab-completion. This means we | |
101 | # have to COPY the constructor here. |
|
152 | # have to COPY the constructor here. | |
102 | def __init__(self,color_scheme='NoColor'): |
|
153 | def __init__(self,color_scheme='NoColor'): | |
103 | bdb.Bdb.__init__(self) |
|
154 | bdb.Bdb.__init__(self) | |
104 | cmd.Cmd.__init__(self,completekey=None) # don't load readline |
|
155 | cmd.Cmd.__init__(self,completekey=None) # don't load readline | |
105 | self.prompt = 'ipdb> ' # The default prompt is '(Pdb)' |
|
156 | self.prompt = 'ipdb> ' # The default prompt is '(Pdb)' | |
106 | self.aliases = {} |
|
157 | self.aliases = {} | |
107 |
|
158 | |||
108 | # These two lines are part of the py2.4 constructor, let's put them |
|
159 | # These two lines are part of the py2.4 constructor, let's put them | |
109 | # unconditionally here as they won't cause any problems in 2.3. |
|
160 | # unconditionally here as they won't cause any problems in 2.3. | |
110 | self.mainpyfile = '' |
|
161 | self.mainpyfile = '' | |
111 | self._wait_for_mainpyfile = 0 |
|
162 | self._wait_for_mainpyfile = 0 | |
112 |
|
163 | |||
113 | # Read $HOME/.pdbrc and ./.pdbrc |
|
164 | # Read $HOME/.pdbrc and ./.pdbrc | |
114 | try: |
|
165 | try: | |
115 | self.rcLines = _file_lines(os.path.join(os.environ['HOME'], |
|
166 | self.rcLines = _file_lines(os.path.join(os.environ['HOME'], | |
116 | ".pdbrc")) |
|
167 | ".pdbrc")) | |
117 | except KeyError: |
|
168 | except KeyError: | |
118 | self.rcLines = [] |
|
169 | self.rcLines = [] | |
119 | self.rcLines.extend(_file_lines(".pdbrc")) |
|
170 | self.rcLines.extend(_file_lines(".pdbrc")) | |
120 |
|
171 | |||
121 | # Create color table: we copy the default one from the traceback |
|
172 | # Create color table: we copy the default one from the traceback | |
122 | # module and add a few attributes needed for debugging |
|
173 | # module and add a few attributes needed for debugging | |
123 | self.color_scheme_table = ExceptionColors.copy() |
|
174 | self.color_scheme_table = ExceptionColors.copy() | |
124 |
|
175 | |||
125 | # shorthands |
|
176 | # shorthands | |
126 | C = ColorANSI.TermColors |
|
177 | C = ColorANSI.TermColors | |
127 | cst = self.color_scheme_table |
|
178 | cst = self.color_scheme_table | |
128 |
|
179 | |||
129 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
180 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor | |
130 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
181 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor | |
131 |
|
182 | |||
132 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
183 | cst['Linux'].colors.breakpoint_enabled = C.LightRed | |
133 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
184 | cst['Linux'].colors.breakpoint_disabled = C.Red | |
134 |
|
185 | |||
135 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
186 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed | |
136 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
187 | cst['LightBG'].colors.breakpoint_disabled = C.Red | |
137 |
|
188 | |||
138 | self.set_colors(color_scheme) |
|
189 | self.set_colors(color_scheme) | |
139 |
|
190 | |||
140 | def set_colors(self, scheme): |
|
191 | def set_colors(self, scheme): | |
141 | """Shorthand access to the color table scheme selector method.""" |
|
192 | """Shorthand access to the color table scheme selector method.""" | |
142 | self.color_scheme_table.set_active_scheme(scheme) |
|
193 | self.color_scheme_table.set_active_scheme(scheme) | |
143 |
|
194 | |||
144 | def interaction(self, frame, traceback): |
|
195 | def interaction(self, frame, traceback): | |
145 | __IPYTHON__.set_completer_frame(frame) |
|
196 | __IPYTHON__.set_completer_frame(frame) | |
146 |
|
|
197 | OldPdb.interaction(self, frame, traceback) | |
|
198 | ||||
|
199 | def new_do_up(self, arg): | |||
|
200 | OldPdb.do_up(self, arg) | |||
|
201 | __IPYTHON__.set_completer_frame(self.curframe) | |||
|
202 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) | |||
147 |
|
203 | |||
148 |
def |
|
204 | def new_do_down(self, arg): | |
149 |
|
|
205 | OldPdb.do_down(self, arg) | |
150 | __IPYTHON__.set_completer_frame(self.curframe) |
|
206 | __IPYTHON__.set_completer_frame(self.curframe) | |
151 | do_u = do_up |
|
|||
152 |
|
207 | |||
153 | def do_down(self, arg): |
|
208 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) | |
154 | pdb.Pdb.do_down(self, arg) |
|
209 | ||
|
210 | def new_do_frame(self, arg): | |||
|
211 | OldPdb.do_frame(self, arg) | |||
155 | __IPYTHON__.set_completer_frame(self.curframe) |
|
212 | __IPYTHON__.set_completer_frame(self.curframe) | |
156 | do_d = do_down |
|
213 | ||
|
214 | def new_do_quit(self, arg): | |||
|
215 | __IPYTHON__.Completer.all_completions=self.old_all_completions | |||
|
216 | return OldPdb.do_quit(self, arg) | |||
|
217 | ||||
|
218 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) | |||
|
219 | ||||
|
220 | def new_do_restart(self, arg): | |||
|
221 | """Restart command. In the context of ipython this is exactly the same | |||
|
222 | thing as 'quit'.""" | |||
|
223 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") | |||
|
224 | return self.do_quit(arg) | |||
157 |
|
225 | |||
158 | def postloop(self): |
|
226 | def postloop(self): | |
159 | __IPYTHON__.set_completer_frame(None) |
|
227 | __IPYTHON__.set_completer_frame(None) | |
160 |
|
228 | |||
161 | def print_stack_trace(self): |
|
229 | def print_stack_trace(self): | |
162 | try: |
|
230 | try: | |
163 | for frame_lineno in self.stack: |
|
231 | for frame_lineno in self.stack: | |
164 | self.print_stack_entry(frame_lineno, context = 5) |
|
232 | self.print_stack_entry(frame_lineno, context = 5) | |
165 | except KeyboardInterrupt: |
|
233 | except KeyboardInterrupt: | |
166 | pass |
|
234 | pass | |
167 |
|
235 | |||
168 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', |
|
236 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', | |
169 | context = 3): |
|
237 | context = 3): | |
170 | frame, lineno = frame_lineno |
|
238 | frame, lineno = frame_lineno | |
171 | print >>Term.cout, self.format_stack_entry(frame_lineno, '', context) |
|
239 | print >>Term.cout, self.format_stack_entry(frame_lineno, '', context) | |
172 |
|
240 | |||
173 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): |
|
241 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): | |
174 | import linecache, repr |
|
242 | import linecache, repr | |
175 |
|
243 | |||
176 | ret = [] |
|
244 | ret = [] | |
177 |
|
245 | |||
178 | Colors = self.color_scheme_table.active_colors |
|
246 | Colors = self.color_scheme_table.active_colors | |
179 | ColorsNormal = Colors.Normal |
|
247 | ColorsNormal = Colors.Normal | |
180 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
248 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) | |
181 | tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
249 | tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) | |
182 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
250 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) | |
183 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
251 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, | |
184 | ColorsNormal) |
|
252 | ColorsNormal) | |
185 |
|
253 | |||
186 | frame, lineno = frame_lineno |
|
254 | frame, lineno = frame_lineno | |
187 |
|
255 | |||
188 | return_value = '' |
|
256 | return_value = '' | |
189 | if '__return__' in frame.f_locals: |
|
257 | if '__return__' in frame.f_locals: | |
190 | rv = frame.f_locals['__return__'] |
|
258 | rv = frame.f_locals['__return__'] | |
191 | #return_value += '->' |
|
259 | #return_value += '->' | |
192 | return_value += repr.repr(rv) + '\n' |
|
260 | return_value += repr.repr(rv) + '\n' | |
193 | ret.append(return_value) |
|
261 | ret.append(return_value) | |
194 |
|
262 | |||
195 | #s = filename + '(' + `lineno` + ')' |
|
263 | #s = filename + '(' + `lineno` + ')' | |
196 | filename = self.canonic(frame.f_code.co_filename) |
|
264 | filename = self.canonic(frame.f_code.co_filename) | |
197 | link = tpl_link % filename |
|
265 | link = tpl_link % filename | |
198 |
|
266 | |||
199 | if frame.f_code.co_name: |
|
267 | if frame.f_code.co_name: | |
200 | func = frame.f_code.co_name |
|
268 | func = frame.f_code.co_name | |
201 | else: |
|
269 | else: | |
202 | func = "<lambda>" |
|
270 | func = "<lambda>" | |
203 |
|
271 | |||
204 | call = '' |
|
272 | call = '' | |
205 | if func != '?': |
|
273 | if func != '?': | |
206 | if '__args__' in frame.f_locals: |
|
274 | if '__args__' in frame.f_locals: | |
207 | args = repr.repr(frame.f_locals['__args__']) |
|
275 | args = repr.repr(frame.f_locals['__args__']) | |
208 | else: |
|
276 | else: | |
209 | args = '()' |
|
277 | args = '()' | |
210 | call = tpl_call % (func, args) |
|
278 | call = tpl_call % (func, args) | |
211 |
|
279 | |||
212 | # The level info should be generated in the same format pdb uses, to |
|
280 | # The level info should be generated in the same format pdb uses, to | |
213 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
281 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. | |
214 | ret.append('> %s(%s)%s\n' % (link,lineno,call)) |
|
282 | ret.append('> %s(%s)%s\n' % (link,lineno,call)) | |
215 |
|
283 | |||
216 | start = lineno - 1 - context//2 |
|
284 | start = lineno - 1 - context//2 | |
217 | lines = linecache.getlines(filename) |
|
285 | lines = linecache.getlines(filename) | |
218 | start = max(start, 0) |
|
286 | start = max(start, 0) | |
219 | start = min(start, len(lines) - context) |
|
287 | start = min(start, len(lines) - context) | |
220 | lines = lines[start : start + context] |
|
288 | lines = lines[start : start + context] | |
221 |
|
289 | |||
222 | for i,line in enumerate(lines): |
|
290 | for i,line in enumerate(lines): | |
223 | show_arrow = (start + 1 + i == lineno) |
|
291 | show_arrow = (start + 1 + i == lineno) | |
224 | ret.append(self.__format_line(tpl_line_em, filename, |
|
292 | ret.append(self.__format_line(tpl_line_em, filename, | |
225 | start + 1 + i, line, |
|
293 | start + 1 + i, line, | |
226 | arrow = show_arrow) ) |
|
294 | arrow = show_arrow) ) | |
227 |
|
295 | |||
228 | return ''.join(ret) |
|
296 | return ''.join(ret) | |
229 |
|
297 | |||
230 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
298 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): | |
231 | bp_mark = "" |
|
299 | bp_mark = "" | |
232 | bp_mark_color = "" |
|
300 | bp_mark_color = "" | |
233 |
|
301 | |||
234 | bp = None |
|
302 | bp = None | |
235 | if lineno in self.get_file_breaks(filename): |
|
303 | if lineno in self.get_file_breaks(filename): | |
236 | bps = self.get_breaks(filename, lineno) |
|
304 | bps = self.get_breaks(filename, lineno) | |
237 | bp = bps[-1] |
|
305 | bp = bps[-1] | |
238 |
|
306 | |||
239 | if bp: |
|
307 | if bp: | |
240 | Colors = self.color_scheme_table.active_colors |
|
308 | Colors = self.color_scheme_table.active_colors | |
241 | bp_mark = str(bp.number) |
|
309 | bp_mark = str(bp.number) | |
242 | bp_mark_color = Colors.breakpoint_enabled |
|
310 | bp_mark_color = Colors.breakpoint_enabled | |
243 | if not bp.enabled: |
|
311 | if not bp.enabled: | |
244 | bp_mark_color = Colors.breakpoint_disabled |
|
312 | bp_mark_color = Colors.breakpoint_disabled | |
245 |
|
313 | |||
246 | numbers_width = 7 |
|
314 | numbers_width = 7 | |
247 | if arrow: |
|
315 | if arrow: | |
248 | # This is the line with the error |
|
316 | # This is the line with the error | |
249 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
317 | pad = numbers_width - len(str(lineno)) - len(bp_mark) | |
250 | if pad >= 3: |
|
318 | if pad >= 3: | |
251 | marker = '-'*(pad-3) + '-> ' |
|
319 | marker = '-'*(pad-3) + '-> ' | |
252 | elif pad == 2: |
|
320 | elif pad == 2: | |
253 | marker = '> ' |
|
321 | marker = '> ' | |
254 | elif pad == 1: |
|
322 | elif pad == 1: | |
255 | marker = '>' |
|
323 | marker = '>' | |
256 | else: |
|
324 | else: | |
257 | marker = '' |
|
325 | marker = '' | |
258 | num = '%s%s' % (marker, str(lineno)) |
|
326 | num = '%s%s' % (marker, str(lineno)) | |
259 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
327 | line = tpl_line % (bp_mark_color + bp_mark, num, line) | |
260 | else: |
|
328 | else: | |
261 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
329 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) | |
262 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
330 | line = tpl_line % (bp_mark_color + bp_mark, num, line) | |
263 |
|
331 | |||
264 | return line |
|
332 | return line | |
265 |
|
333 | |||
|
334 | def list_command_pydb(self, arg): | |||
|
335 | """List command to use if we have a newer pydb installed""" | |||
|
336 | filename, first, last = OldPdb.parse_list_cmd(self, arg) | |||
|
337 | if filename is not None: | |||
|
338 | self.print_list_lines(filename, first, last) | |||
|
339 | ||||
|
340 | def print_list_lines(self, filename, first, last): | |||
|
341 | """The printing (as opposed to the parsing part of a 'list' | |||
|
342 | command.""" | |||
|
343 | try: | |||
|
344 | Colors = self.color_scheme_table.active_colors | |||
|
345 | ColorsNormal = Colors.Normal | |||
|
346 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) | |||
|
347 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) | |||
|
348 | src = [] | |||
|
349 | for lineno in range(first, last+1): | |||
|
350 | line = linecache.getline(filename, lineno) | |||
|
351 | if not line: | |||
|
352 | break | |||
|
353 | ||||
|
354 | if lineno == self.curframe.f_lineno: | |||
|
355 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) | |||
|
356 | else: | |||
|
357 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) | |||
|
358 | ||||
|
359 | src.append(line) | |||
|
360 | self.lineno = lineno | |||
|
361 | ||||
|
362 | print >>Term.cout, ''.join(src) | |||
|
363 | ||||
|
364 | except KeyboardInterrupt: | |||
|
365 | pass | |||
|
366 | ||||
266 | def do_list(self, arg): |
|
367 | def do_list(self, arg): | |
267 | self.lastcmd = 'list' |
|
368 | self.lastcmd = 'list' | |
268 | last = None |
|
369 | last = None | |
269 | if arg: |
|
370 | if arg: | |
270 | try: |
|
371 | try: | |
271 | x = eval(arg, {}, {}) |
|
372 | x = eval(arg, {}, {}) | |
272 | if type(x) == type(()): |
|
373 | if type(x) == type(()): | |
273 | first, last = x |
|
374 | first, last = x | |
274 | first = int(first) |
|
375 | first = int(first) | |
275 | last = int(last) |
|
376 | last = int(last) | |
276 | if last < first: |
|
377 | if last < first: | |
277 | # Assume it's a count |
|
378 | # Assume it's a count | |
278 | last = first + last |
|
379 | last = first + last | |
279 | else: |
|
380 | else: | |
280 | first = max(1, int(x) - 5) |
|
381 | first = max(1, int(x) - 5) | |
281 | except: |
|
382 | except: | |
282 | print '*** Error in argument:', `arg` |
|
383 | print '*** Error in argument:', `arg` | |
283 | return |
|
384 | return | |
284 | elif self.lineno is None: |
|
385 | elif self.lineno is None: | |
285 | first = max(1, self.curframe.f_lineno - 5) |
|
386 | first = max(1, self.curframe.f_lineno - 5) | |
286 | else: |
|
387 | else: | |
287 | first = self.lineno + 1 |
|
388 | first = self.lineno + 1 | |
288 | if last is None: |
|
389 | if last is None: | |
289 | last = first + 10 |
|
390 | last = first + 10 | |
290 |
|
|
391 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) | |
291 | try: |
|
|||
292 | Colors = self.color_scheme_table.active_colors |
|
|||
293 | ColorsNormal = Colors.Normal |
|
|||
294 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
|||
295 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
|||
296 | src = [] |
|
|||
297 | for lineno in range(first, last+1): |
|
|||
298 | line = linecache.getline(filename, lineno) |
|
|||
299 | if not line: |
|
|||
300 | break |
|
|||
301 |
|
||||
302 | if lineno == self.curframe.f_lineno: |
|
|||
303 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
|||
304 | else: |
|
|||
305 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
|||
306 |
|
||||
307 | src.append(line) |
|
|||
308 | self.lineno = lineno |
|
|||
309 |
|
||||
310 | print >>Term.cout, ''.join(src) |
|
|||
311 |
|
||||
312 | except KeyboardInterrupt: |
|
|||
313 | pass |
|
|||
314 |
|
392 | |||
315 | do_l = do_list |
|
393 | do_l = do_list | |
|
394 | ||||
|
395 | def do_pdef(self, arg): | |||
|
396 | """The debugger interface to magic_pdef""" | |||
|
397 | namespaces = [('Locals', self.curframe.f_locals), | |||
|
398 | ('Globals', self.curframe.f_globals)] | |||
|
399 | __IPYTHON__.magic_pdef(arg, namespaces=namespaces) | |||
|
400 | ||||
|
401 | def do_pdoc(self, arg): | |||
|
402 | """The debugger interface to magic_pdoc""" | |||
|
403 | namespaces = [('Locals', self.curframe.f_locals), | |||
|
404 | ('Globals', self.curframe.f_globals)] | |||
|
405 | __IPYTHON__.magic_pdoc(arg, namespaces=namespaces) | |||
|
406 | ||||
|
407 | def do_pinfo(self, arg): | |||
|
408 | """The debugger equivalant of ?obj""" | |||
|
409 | namespaces = [('Locals', self.curframe.f_locals), | |||
|
410 | ('Globals', self.curframe.f_globals)] | |||
|
411 | __IPYTHON__.magic_pinfo("pinfo %s" % arg, namespaces=namespaces) |
@@ -1,2434 +1,2442 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.3 or newer. |
|
5 | Requires Python 2.3 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 |
$Id: iplib.py 185 |
|
9 | $Id: iplib.py 1853 2006-10-30 17:00:39Z vivainio $ | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
14 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
14 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
15 | # |
|
15 | # | |
16 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | # Distributed under the terms of the BSD License. The full license is in | |
17 | # the file COPYING, distributed as part of this software. |
|
17 | # the file COPYING, distributed as part of this software. | |
18 | # |
|
18 | # | |
19 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
19 | # Note: this code originally subclassed code.InteractiveConsole from the | |
20 | # Python standard library. Over time, all of that class has been copied |
|
20 | # Python standard library. Over time, all of that class has been copied | |
21 | # verbatim here for modifications which could not be accomplished by |
|
21 | # verbatim here for modifications which could not be accomplished by | |
22 | # subclassing. At this point, there are no dependencies at all on the code |
|
22 | # subclassing. At this point, there are no dependencies at all on the code | |
23 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
23 | # module anymore (it is not even imported). The Python License (sec. 2) | |
24 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
24 | # allows for this, but it's always nice to acknowledge credit where credit is | |
25 | # due. |
|
25 | # due. | |
26 | #***************************************************************************** |
|
26 | #***************************************************************************** | |
27 |
|
27 | |||
28 | #**************************************************************************** |
|
28 | #**************************************************************************** | |
29 | # Modules and globals |
|
29 | # Modules and globals | |
30 |
|
30 | |||
31 | from IPython import Release |
|
31 | from IPython import Release | |
32 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
32 | __author__ = '%s <%s>\n%s <%s>' % \ | |
33 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
33 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
34 | __license__ = Release.license |
|
34 | __license__ = Release.license | |
35 | __version__ = Release.version |
|
35 | __version__ = Release.version | |
36 |
|
36 | |||
37 | # Python standard modules |
|
37 | # Python standard modules | |
38 | import __main__ |
|
38 | import __main__ | |
39 | import __builtin__ |
|
39 | import __builtin__ | |
40 | import StringIO |
|
40 | import StringIO | |
41 | import bdb |
|
41 | import bdb | |
42 | import cPickle as pickle |
|
42 | import cPickle as pickle | |
43 | import codeop |
|
43 | import codeop | |
44 | import exceptions |
|
44 | import exceptions | |
45 | import glob |
|
45 | import glob | |
46 | import inspect |
|
46 | import inspect | |
47 | import keyword |
|
47 | import keyword | |
48 | import new |
|
48 | import new | |
49 | import os |
|
49 | import os | |
50 | import pdb |
|
|||
51 | import pydoc |
|
50 | import pydoc | |
52 | import re |
|
51 | import re | |
53 | import shutil |
|
52 | import shutil | |
54 | import string |
|
53 | import string | |
55 | import sys |
|
54 | import sys | |
56 | import tempfile |
|
55 | import tempfile | |
57 | import traceback |
|
56 | import traceback | |
58 | import types |
|
57 | import types | |
59 | import pickleshare |
|
58 | import pickleshare | |
60 | from sets import Set |
|
59 | from sets import Set | |
61 | from pprint import pprint, pformat |
|
60 | from pprint import pprint, pformat | |
62 |
|
61 | |||
63 | # IPython's own modules |
|
62 | # IPython's own modules | |
64 | import IPython |
|
63 | import IPython | |
65 | from IPython import OInspect,PyColorize,ultraTB |
|
64 | from IPython import OInspect,PyColorize,ultraTB | |
66 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
65 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names | |
67 | from IPython.FakeModule import FakeModule |
|
66 | from IPython.FakeModule import FakeModule | |
68 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
67 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
69 | from IPython.Logger import Logger |
|
68 | from IPython.Logger import Logger | |
70 | from IPython.Magic import Magic |
|
69 | from IPython.Magic import Magic | |
71 | from IPython.Prompts import CachedOutput |
|
70 | from IPython.Prompts import CachedOutput | |
72 | from IPython.ipstruct import Struct |
|
71 | from IPython.ipstruct import Struct | |
73 | from IPython.background_jobs import BackgroundJobManager |
|
72 | from IPython.background_jobs import BackgroundJobManager | |
74 | from IPython.usage import cmd_line_usage,interactive_usage |
|
73 | from IPython.usage import cmd_line_usage,interactive_usage | |
75 | from IPython.genutils import * |
|
74 | from IPython.genutils import * | |
76 | import IPython.ipapi |
|
75 | import IPython.ipapi | |
77 |
|
76 | |||
78 | # Globals |
|
77 | # Globals | |
79 |
|
78 | |||
80 | # store the builtin raw_input globally, and use this always, in case user code |
|
79 | # store the builtin raw_input globally, and use this always, in case user code | |
81 | # overwrites it (like wx.py.PyShell does) |
|
80 | # overwrites it (like wx.py.PyShell does) | |
82 | raw_input_original = raw_input |
|
81 | raw_input_original = raw_input | |
83 |
|
82 | |||
84 | # compiled regexps for autoindent management |
|
83 | # compiled regexps for autoindent management | |
85 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
84 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
86 |
|
85 | |||
87 |
|
86 | |||
88 | #**************************************************************************** |
|
87 | #**************************************************************************** | |
89 | # Some utility function definitions |
|
88 | # Some utility function definitions | |
90 |
|
89 | |||
91 | ini_spaces_re = re.compile(r'^(\s+)') |
|
90 | ini_spaces_re = re.compile(r'^(\s+)') | |
92 |
|
91 | |||
93 | def num_ini_spaces(strng): |
|
92 | def num_ini_spaces(strng): | |
94 | """Return the number of initial spaces in a string""" |
|
93 | """Return the number of initial spaces in a string""" | |
95 |
|
94 | |||
96 | ini_spaces = ini_spaces_re.match(strng) |
|
95 | ini_spaces = ini_spaces_re.match(strng) | |
97 | if ini_spaces: |
|
96 | if ini_spaces: | |
98 | return ini_spaces.end() |
|
97 | return ini_spaces.end() | |
99 | else: |
|
98 | else: | |
100 | return 0 |
|
99 | return 0 | |
101 |
|
100 | |||
102 | def softspace(file, newvalue): |
|
101 | def softspace(file, newvalue): | |
103 | """Copied from code.py, to remove the dependency""" |
|
102 | """Copied from code.py, to remove the dependency""" | |
104 |
|
103 | |||
105 | oldvalue = 0 |
|
104 | oldvalue = 0 | |
106 | try: |
|
105 | try: | |
107 | oldvalue = file.softspace |
|
106 | oldvalue = file.softspace | |
108 | except AttributeError: |
|
107 | except AttributeError: | |
109 | pass |
|
108 | pass | |
110 | try: |
|
109 | try: | |
111 | file.softspace = newvalue |
|
110 | file.softspace = newvalue | |
112 | except (AttributeError, TypeError): |
|
111 | except (AttributeError, TypeError): | |
113 | # "attribute-less object" or "read-only attributes" |
|
112 | # "attribute-less object" or "read-only attributes" | |
114 | pass |
|
113 | pass | |
115 | return oldvalue |
|
114 | return oldvalue | |
116 |
|
115 | |||
117 |
|
116 | |||
118 | #**************************************************************************** |
|
117 | #**************************************************************************** | |
119 | # Local use exceptions |
|
118 | # Local use exceptions | |
120 | class SpaceInInput(exceptions.Exception): pass |
|
119 | class SpaceInInput(exceptions.Exception): pass | |
121 |
|
120 | |||
122 |
|
121 | |||
123 | #**************************************************************************** |
|
122 | #**************************************************************************** | |
124 | # Local use classes |
|
123 | # Local use classes | |
125 | class Bunch: pass |
|
124 | class Bunch: pass | |
126 |
|
125 | |||
127 | class Undefined: pass |
|
126 | class Undefined: pass | |
128 |
|
127 | |||
129 | class Quitter(object): |
|
128 | class Quitter(object): | |
130 | """Simple class to handle exit, similar to Python 2.5's. |
|
129 | """Simple class to handle exit, similar to Python 2.5's. | |
131 |
|
130 | |||
132 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
131 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 | |
133 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
132 | doesn't do (obviously, since it doesn't know about ipython).""" | |
134 |
|
133 | |||
135 | def __init__(self,shell,name): |
|
134 | def __init__(self,shell,name): | |
136 | self.shell = shell |
|
135 | self.shell = shell | |
137 | self.name = name |
|
136 | self.name = name | |
138 |
|
137 | |||
139 | def __repr__(self): |
|
138 | def __repr__(self): | |
140 | return 'Type %s() to exit.' % self.name |
|
139 | return 'Type %s() to exit.' % self.name | |
141 | __str__ = __repr__ |
|
140 | __str__ = __repr__ | |
142 |
|
141 | |||
143 | def __call__(self): |
|
142 | def __call__(self): | |
144 | self.shell.exit() |
|
143 | self.shell.exit() | |
145 |
|
144 | |||
146 | class InputList(list): |
|
145 | class InputList(list): | |
147 | """Class to store user input. |
|
146 | """Class to store user input. | |
148 |
|
147 | |||
149 | It's basically a list, but slices return a string instead of a list, thus |
|
148 | It's basically a list, but slices return a string instead of a list, thus | |
150 | allowing things like (assuming 'In' is an instance): |
|
149 | allowing things like (assuming 'In' is an instance): | |
151 |
|
150 | |||
152 | exec In[4:7] |
|
151 | exec In[4:7] | |
153 |
|
152 | |||
154 | or |
|
153 | or | |
155 |
|
154 | |||
156 | exec In[5:9] + In[14] + In[21:25]""" |
|
155 | exec In[5:9] + In[14] + In[21:25]""" | |
157 |
|
156 | |||
158 | def __getslice__(self,i,j): |
|
157 | def __getslice__(self,i,j): | |
159 | return ''.join(list.__getslice__(self,i,j)) |
|
158 | return ''.join(list.__getslice__(self,i,j)) | |
160 |
|
159 | |||
161 | class SyntaxTB(ultraTB.ListTB): |
|
160 | class SyntaxTB(ultraTB.ListTB): | |
162 | """Extension which holds some state: the last exception value""" |
|
161 | """Extension which holds some state: the last exception value""" | |
163 |
|
162 | |||
164 | def __init__(self,color_scheme = 'NoColor'): |
|
163 | def __init__(self,color_scheme = 'NoColor'): | |
165 | ultraTB.ListTB.__init__(self,color_scheme) |
|
164 | ultraTB.ListTB.__init__(self,color_scheme) | |
166 | self.last_syntax_error = None |
|
165 | self.last_syntax_error = None | |
167 |
|
166 | |||
168 | def __call__(self, etype, value, elist): |
|
167 | def __call__(self, etype, value, elist): | |
169 | self.last_syntax_error = value |
|
168 | self.last_syntax_error = value | |
170 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
169 | ultraTB.ListTB.__call__(self,etype,value,elist) | |
171 |
|
170 | |||
172 | def clear_err_state(self): |
|
171 | def clear_err_state(self): | |
173 | """Return the current error state and clear it""" |
|
172 | """Return the current error state and clear it""" | |
174 | e = self.last_syntax_error |
|
173 | e = self.last_syntax_error | |
175 | self.last_syntax_error = None |
|
174 | self.last_syntax_error = None | |
176 | return e |
|
175 | return e | |
177 |
|
176 | |||
178 | #**************************************************************************** |
|
177 | #**************************************************************************** | |
179 | # Main IPython class |
|
178 | # Main IPython class | |
180 |
|
179 | |||
181 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
180 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so | |
182 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
181 | # until a full rewrite is made. I've cleaned all cross-class uses of | |
183 | # attributes and methods, but too much user code out there relies on the |
|
182 | # attributes and methods, but too much user code out there relies on the | |
184 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
183 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. | |
185 | # |
|
184 | # | |
186 | # But at least now, all the pieces have been separated and we could, in |
|
185 | # But at least now, all the pieces have been separated and we could, in | |
187 | # principle, stop using the mixin. This will ease the transition to the |
|
186 | # principle, stop using the mixin. This will ease the transition to the | |
188 | # chainsaw branch. |
|
187 | # chainsaw branch. | |
189 |
|
188 | |||
190 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
189 | # For reference, the following is the list of 'self.foo' uses in the Magic | |
191 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
190 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython | |
192 | # class, to prevent clashes. |
|
191 | # class, to prevent clashes. | |
193 |
|
192 | |||
194 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
193 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', | |
195 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
194 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', | |
196 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
195 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', | |
197 | # 'self.value'] |
|
196 | # 'self.value'] | |
198 |
|
197 | |||
199 | class InteractiveShell(object,Magic): |
|
198 | class InteractiveShell(object,Magic): | |
200 | """An enhanced console for Python.""" |
|
199 | """An enhanced console for Python.""" | |
201 |
|
200 | |||
202 | # class attribute to indicate whether the class supports threads or not. |
|
201 | # class attribute to indicate whether the class supports threads or not. | |
203 | # Subclasses with thread support should override this as needed. |
|
202 | # Subclasses with thread support should override this as needed. | |
204 | isthreaded = False |
|
203 | isthreaded = False | |
205 |
|
204 | |||
206 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
205 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
207 | user_ns = None,user_global_ns=None,banner2='', |
|
206 | user_ns = None,user_global_ns=None,banner2='', | |
208 | custom_exceptions=((),None),embedded=False): |
|
207 | custom_exceptions=((),None),embedded=False): | |
209 |
|
208 | |||
210 | # log system |
|
209 | # log system | |
211 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
210 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |
212 |
|
211 | |||
213 | # some minimal strict typechecks. For some core data structures, I |
|
212 | # some minimal strict typechecks. For some core data structures, I | |
214 | # want actual basic python types, not just anything that looks like |
|
213 | # want actual basic python types, not just anything that looks like | |
215 | # one. This is especially true for namespaces. |
|
214 | # one. This is especially true for namespaces. | |
216 | for ns in (user_ns,user_global_ns): |
|
215 | for ns in (user_ns,user_global_ns): | |
217 | if ns is not None and type(ns) != types.DictType: |
|
216 | if ns is not None and type(ns) != types.DictType: | |
218 | raise TypeError,'namespace must be a dictionary' |
|
217 | raise TypeError,'namespace must be a dictionary' | |
219 |
|
218 | |||
220 | # Job manager (for jobs run as background threads) |
|
219 | # Job manager (for jobs run as background threads) | |
221 | self.jobs = BackgroundJobManager() |
|
220 | self.jobs = BackgroundJobManager() | |
222 |
|
221 | |||
223 | # Store the actual shell's name |
|
222 | # Store the actual shell's name | |
224 | self.name = name |
|
223 | self.name = name | |
225 |
|
224 | |||
226 | # We need to know whether the instance is meant for embedding, since |
|
225 | # We need to know whether the instance is meant for embedding, since | |
227 | # global/local namespaces need to be handled differently in that case |
|
226 | # global/local namespaces need to be handled differently in that case | |
228 | self.embedded = embedded |
|
227 | self.embedded = embedded | |
229 |
|
228 | |||
230 | # command compiler |
|
229 | # command compiler | |
231 | self.compile = codeop.CommandCompiler() |
|
230 | self.compile = codeop.CommandCompiler() | |
232 |
|
231 | |||
233 | # User input buffer |
|
232 | # User input buffer | |
234 | self.buffer = [] |
|
233 | self.buffer = [] | |
235 |
|
234 | |||
236 | # Default name given in compilation of code |
|
235 | # Default name given in compilation of code | |
237 | self.filename = '<ipython console>' |
|
236 | self.filename = '<ipython console>' | |
238 |
|
237 | |||
239 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
238 | # Install our own quitter instead of the builtins. For python2.3-2.4, | |
240 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
239 | # this brings in behavior like 2.5, and for 2.5 it's identical. | |
241 | __builtin__.exit = Quitter(self,'exit') |
|
240 | __builtin__.exit = Quitter(self,'exit') | |
242 | __builtin__.quit = Quitter(self,'quit') |
|
241 | __builtin__.quit = Quitter(self,'quit') | |
243 |
|
242 | |||
244 | # Make an empty namespace, which extension writers can rely on both |
|
243 | # Make an empty namespace, which extension writers can rely on both | |
245 | # existing and NEVER being used by ipython itself. This gives them a |
|
244 | # existing and NEVER being used by ipython itself. This gives them a | |
246 | # convenient location for storing additional information and state |
|
245 | # convenient location for storing additional information and state | |
247 | # their extensions may require, without fear of collisions with other |
|
246 | # their extensions may require, without fear of collisions with other | |
248 | # ipython names that may develop later. |
|
247 | # ipython names that may develop later. | |
249 | self.meta = Struct() |
|
248 | self.meta = Struct() | |
250 |
|
249 | |||
251 | # Create the namespace where the user will operate. user_ns is |
|
250 | # Create the namespace where the user will operate. user_ns is | |
252 | # normally the only one used, and it is passed to the exec calls as |
|
251 | # normally the only one used, and it is passed to the exec calls as | |
253 | # the locals argument. But we do carry a user_global_ns namespace |
|
252 | # the locals argument. But we do carry a user_global_ns namespace | |
254 | # given as the exec 'globals' argument, This is useful in embedding |
|
253 | # given as the exec 'globals' argument, This is useful in embedding | |
255 | # situations where the ipython shell opens in a context where the |
|
254 | # situations where the ipython shell opens in a context where the | |
256 | # distinction between locals and globals is meaningful. |
|
255 | # distinction between locals and globals is meaningful. | |
257 |
|
256 | |||
258 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
257 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
259 | # level as a dict instead of a module. This is a manual fix, but I |
|
258 | # level as a dict instead of a module. This is a manual fix, but I | |
260 | # should really track down where the problem is coming from. Alex |
|
259 | # should really track down where the problem is coming from. Alex | |
261 | # Schmolck reported this problem first. |
|
260 | # Schmolck reported this problem first. | |
262 |
|
261 | |||
263 | # A useful post by Alex Martelli on this topic: |
|
262 | # A useful post by Alex Martelli on this topic: | |
264 | # Re: inconsistent value from __builtins__ |
|
263 | # Re: inconsistent value from __builtins__ | |
265 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
264 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
266 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
265 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
267 | # Gruppen: comp.lang.python |
|
266 | # Gruppen: comp.lang.python | |
268 |
|
267 | |||
269 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
268 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
270 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
269 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
271 | # > <type 'dict'> |
|
270 | # > <type 'dict'> | |
272 | # > >>> print type(__builtins__) |
|
271 | # > >>> print type(__builtins__) | |
273 | # > <type 'module'> |
|
272 | # > <type 'module'> | |
274 | # > Is this difference in return value intentional? |
|
273 | # > Is this difference in return value intentional? | |
275 |
|
274 | |||
276 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
275 | # Well, it's documented that '__builtins__' can be either a dictionary | |
277 | # or a module, and it's been that way for a long time. Whether it's |
|
276 | # or a module, and it's been that way for a long time. Whether it's | |
278 | # intentional (or sensible), I don't know. In any case, the idea is |
|
277 | # intentional (or sensible), I don't know. In any case, the idea is | |
279 | # that if you need to access the built-in namespace directly, you |
|
278 | # that if you need to access the built-in namespace directly, you | |
280 | # should start with "import __builtin__" (note, no 's') which will |
|
279 | # should start with "import __builtin__" (note, no 's') which will | |
281 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
280 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
282 |
|
281 | |||
283 | # These routines return properly built dicts as needed by the rest of |
|
282 | # These routines return properly built dicts as needed by the rest of | |
284 | # the code, and can also be used by extension writers to generate |
|
283 | # the code, and can also be used by extension writers to generate | |
285 | # properly initialized namespaces. |
|
284 | # properly initialized namespaces. | |
286 | user_ns = IPython.ipapi.make_user_ns(user_ns) |
|
285 | user_ns = IPython.ipapi.make_user_ns(user_ns) | |
287 | user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns) |
|
286 | user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns) | |
288 |
|
287 | |||
289 | # Assign namespaces |
|
288 | # Assign namespaces | |
290 | # This is the namespace where all normal user variables live |
|
289 | # This is the namespace where all normal user variables live | |
291 | self.user_ns = user_ns |
|
290 | self.user_ns = user_ns | |
292 | # Embedded instances require a separate namespace for globals. |
|
291 | # Embedded instances require a separate namespace for globals. | |
293 | # Normally this one is unused by non-embedded instances. |
|
292 | # Normally this one is unused by non-embedded instances. | |
294 | self.user_global_ns = user_global_ns |
|
293 | self.user_global_ns = user_global_ns | |
295 | # A namespace to keep track of internal data structures to prevent |
|
294 | # A namespace to keep track of internal data structures to prevent | |
296 | # them from cluttering user-visible stuff. Will be updated later |
|
295 | # them from cluttering user-visible stuff. Will be updated later | |
297 | self.internal_ns = {} |
|
296 | self.internal_ns = {} | |
298 |
|
297 | |||
299 | # Namespace of system aliases. Each entry in the alias |
|
298 | # Namespace of system aliases. Each entry in the alias | |
300 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
299 | # table must be a 2-tuple of the form (N,name), where N is the number | |
301 | # of positional arguments of the alias. |
|
300 | # of positional arguments of the alias. | |
302 | self.alias_table = {} |
|
301 | self.alias_table = {} | |
303 |
|
302 | |||
304 | # A table holding all the namespaces IPython deals with, so that |
|
303 | # A table holding all the namespaces IPython deals with, so that | |
305 | # introspection facilities can search easily. |
|
304 | # introspection facilities can search easily. | |
306 | self.ns_table = {'user':user_ns, |
|
305 | self.ns_table = {'user':user_ns, | |
307 | 'user_global':user_global_ns, |
|
306 | 'user_global':user_global_ns, | |
308 | 'alias':self.alias_table, |
|
307 | 'alias':self.alias_table, | |
309 | 'internal':self.internal_ns, |
|
308 | 'internal':self.internal_ns, | |
310 | 'builtin':__builtin__.__dict__ |
|
309 | 'builtin':__builtin__.__dict__ | |
311 | } |
|
310 | } | |
312 |
|
311 | |||
313 | # The user namespace MUST have a pointer to the shell itself. |
|
312 | # The user namespace MUST have a pointer to the shell itself. | |
314 | self.user_ns[name] = self |
|
313 | self.user_ns[name] = self | |
315 |
|
314 | |||
316 | # We need to insert into sys.modules something that looks like a |
|
315 | # We need to insert into sys.modules something that looks like a | |
317 | # module but which accesses the IPython namespace, for shelve and |
|
316 | # module but which accesses the IPython namespace, for shelve and | |
318 | # pickle to work interactively. Normally they rely on getting |
|
317 | # pickle to work interactively. Normally they rely on getting | |
319 | # everything out of __main__, but for embedding purposes each IPython |
|
318 | # everything out of __main__, but for embedding purposes each IPython | |
320 | # instance has its own private namespace, so we can't go shoving |
|
319 | # instance has its own private namespace, so we can't go shoving | |
321 | # everything into __main__. |
|
320 | # everything into __main__. | |
322 |
|
321 | |||
323 | # note, however, that we should only do this for non-embedded |
|
322 | # note, however, that we should only do this for non-embedded | |
324 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
323 | # ipythons, which really mimic the __main__.__dict__ with their own | |
325 | # namespace. Embedded instances, on the other hand, should not do |
|
324 | # namespace. Embedded instances, on the other hand, should not do | |
326 | # this because they need to manage the user local/global namespaces |
|
325 | # this because they need to manage the user local/global namespaces | |
327 | # only, but they live within a 'normal' __main__ (meaning, they |
|
326 | # only, but they live within a 'normal' __main__ (meaning, they | |
328 | # shouldn't overtake the execution environment of the script they're |
|
327 | # shouldn't overtake the execution environment of the script they're | |
329 | # embedded in). |
|
328 | # embedded in). | |
330 |
|
329 | |||
331 | if not embedded: |
|
330 | if not embedded: | |
332 | try: |
|
331 | try: | |
333 | main_name = self.user_ns['__name__'] |
|
332 | main_name = self.user_ns['__name__'] | |
334 | except KeyError: |
|
333 | except KeyError: | |
335 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
334 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
336 | else: |
|
335 | else: | |
337 | #print "pickle hack in place" # dbg |
|
336 | #print "pickle hack in place" # dbg | |
338 | #print 'main_name:',main_name # dbg |
|
337 | #print 'main_name:',main_name # dbg | |
339 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
338 | sys.modules[main_name] = FakeModule(self.user_ns) | |
340 |
|
339 | |||
341 | # List of input with multi-line handling. |
|
340 | # List of input with multi-line handling. | |
342 | # Fill its zero entry, user counter starts at 1 |
|
341 | # Fill its zero entry, user counter starts at 1 | |
343 | self.input_hist = InputList(['\n']) |
|
342 | self.input_hist = InputList(['\n']) | |
344 | # This one will hold the 'raw' input history, without any |
|
343 | # This one will hold the 'raw' input history, without any | |
345 | # pre-processing. This will allow users to retrieve the input just as |
|
344 | # pre-processing. This will allow users to retrieve the input just as | |
346 | # it was exactly typed in by the user, with %hist -r. |
|
345 | # it was exactly typed in by the user, with %hist -r. | |
347 | self.input_hist_raw = InputList(['\n']) |
|
346 | self.input_hist_raw = InputList(['\n']) | |
348 |
|
347 | |||
349 | # list of visited directories |
|
348 | # list of visited directories | |
350 | try: |
|
349 | try: | |
351 | self.dir_hist = [os.getcwd()] |
|
350 | self.dir_hist = [os.getcwd()] | |
352 | except IOError, e: |
|
351 | except IOError, e: | |
353 | self.dir_hist = [] |
|
352 | self.dir_hist = [] | |
354 |
|
353 | |||
355 | # dict of output history |
|
354 | # dict of output history | |
356 | self.output_hist = {} |
|
355 | self.output_hist = {} | |
357 |
|
356 | |||
358 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
357 | # dict of things NOT to alias (keywords, builtins and some magics) | |
359 | no_alias = {} |
|
358 | no_alias = {} | |
360 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
359 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
361 | for key in keyword.kwlist + no_alias_magics: |
|
360 | for key in keyword.kwlist + no_alias_magics: | |
362 | no_alias[key] = 1 |
|
361 | no_alias[key] = 1 | |
363 | no_alias.update(__builtin__.__dict__) |
|
362 | no_alias.update(__builtin__.__dict__) | |
364 | self.no_alias = no_alias |
|
363 | self.no_alias = no_alias | |
365 |
|
364 | |||
366 | # make global variables for user access to these |
|
365 | # make global variables for user access to these | |
367 | self.user_ns['_ih'] = self.input_hist |
|
366 | self.user_ns['_ih'] = self.input_hist | |
368 | self.user_ns['_oh'] = self.output_hist |
|
367 | self.user_ns['_oh'] = self.output_hist | |
369 | self.user_ns['_dh'] = self.dir_hist |
|
368 | self.user_ns['_dh'] = self.dir_hist | |
370 |
|
369 | |||
371 | # user aliases to input and output histories |
|
370 | # user aliases to input and output histories | |
372 | self.user_ns['In'] = self.input_hist |
|
371 | self.user_ns['In'] = self.input_hist | |
373 | self.user_ns['Out'] = self.output_hist |
|
372 | self.user_ns['Out'] = self.output_hist | |
374 |
|
373 | |||
375 | # Object variable to store code object waiting execution. This is |
|
374 | # Object variable to store code object waiting execution. This is | |
376 | # used mainly by the multithreaded shells, but it can come in handy in |
|
375 | # used mainly by the multithreaded shells, but it can come in handy in | |
377 | # other situations. No need to use a Queue here, since it's a single |
|
376 | # other situations. No need to use a Queue here, since it's a single | |
378 | # item which gets cleared once run. |
|
377 | # item which gets cleared once run. | |
379 | self.code_to_run = None |
|
378 | self.code_to_run = None | |
380 |
|
379 | |||
381 | # escapes for automatic behavior on the command line |
|
380 | # escapes for automatic behavior on the command line | |
382 | self.ESC_SHELL = '!' |
|
381 | self.ESC_SHELL = '!' | |
383 | self.ESC_HELP = '?' |
|
382 | self.ESC_HELP = '?' | |
384 | self.ESC_MAGIC = '%' |
|
383 | self.ESC_MAGIC = '%' | |
385 | self.ESC_QUOTE = ',' |
|
384 | self.ESC_QUOTE = ',' | |
386 | self.ESC_QUOTE2 = ';' |
|
385 | self.ESC_QUOTE2 = ';' | |
387 | self.ESC_PAREN = '/' |
|
386 | self.ESC_PAREN = '/' | |
388 |
|
387 | |||
389 | # And their associated handlers |
|
388 | # And their associated handlers | |
390 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
389 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
391 | self.ESC_QUOTE : self.handle_auto, |
|
390 | self.ESC_QUOTE : self.handle_auto, | |
392 | self.ESC_QUOTE2 : self.handle_auto, |
|
391 | self.ESC_QUOTE2 : self.handle_auto, | |
393 | self.ESC_MAGIC : self.handle_magic, |
|
392 | self.ESC_MAGIC : self.handle_magic, | |
394 | self.ESC_HELP : self.handle_help, |
|
393 | self.ESC_HELP : self.handle_help, | |
395 | self.ESC_SHELL : self.handle_shell_escape, |
|
394 | self.ESC_SHELL : self.handle_shell_escape, | |
396 | } |
|
395 | } | |
397 |
|
396 | |||
398 | # class initializations |
|
397 | # class initializations | |
399 | Magic.__init__(self,self) |
|
398 | Magic.__init__(self,self) | |
400 |
|
399 | |||
401 | # Python source parser/formatter for syntax highlighting |
|
400 | # Python source parser/formatter for syntax highlighting | |
402 | pyformat = PyColorize.Parser().format |
|
401 | pyformat = PyColorize.Parser().format | |
403 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
402 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |
404 |
|
403 | |||
405 | # hooks holds pointers used for user-side customizations |
|
404 | # hooks holds pointers used for user-side customizations | |
406 | self.hooks = Struct() |
|
405 | self.hooks = Struct() | |
407 |
|
406 | |||
408 | # Set all default hooks, defined in the IPython.hooks module. |
|
407 | # Set all default hooks, defined in the IPython.hooks module. | |
409 | hooks = IPython.hooks |
|
408 | hooks = IPython.hooks | |
410 | for hook_name in hooks.__all__: |
|
409 | for hook_name in hooks.__all__: | |
411 | # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority |
|
410 | # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority | |
412 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
411 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
413 | #print "bound hook",hook_name |
|
412 | #print "bound hook",hook_name | |
414 |
|
413 | |||
415 | # Flag to mark unconditional exit |
|
414 | # Flag to mark unconditional exit | |
416 | self.exit_now = False |
|
415 | self.exit_now = False | |
417 |
|
416 | |||
418 | self.usage_min = """\ |
|
417 | self.usage_min = """\ | |
419 | An enhanced console for Python. |
|
418 | An enhanced console for Python. | |
420 | Some of its features are: |
|
419 | Some of its features are: | |
421 | - Readline support if the readline library is present. |
|
420 | - Readline support if the readline library is present. | |
422 | - Tab completion in the local namespace. |
|
421 | - Tab completion in the local namespace. | |
423 | - Logging of input, see command-line options. |
|
422 | - Logging of input, see command-line options. | |
424 | - System shell escape via ! , eg !ls. |
|
423 | - System shell escape via ! , eg !ls. | |
425 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
424 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
426 | - Keeps track of locally defined variables via %who, %whos. |
|
425 | - Keeps track of locally defined variables via %who, %whos. | |
427 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
426 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
428 | """ |
|
427 | """ | |
429 | if usage: self.usage = usage |
|
428 | if usage: self.usage = usage | |
430 | else: self.usage = self.usage_min |
|
429 | else: self.usage = self.usage_min | |
431 |
|
430 | |||
432 | # Storage |
|
431 | # Storage | |
433 | self.rc = rc # This will hold all configuration information |
|
432 | self.rc = rc # This will hold all configuration information | |
434 | self.pager = 'less' |
|
433 | self.pager = 'less' | |
435 | # temporary files used for various purposes. Deleted at exit. |
|
434 | # temporary files used for various purposes. Deleted at exit. | |
436 | self.tempfiles = [] |
|
435 | self.tempfiles = [] | |
437 |
|
436 | |||
438 | # Keep track of readline usage (later set by init_readline) |
|
437 | # Keep track of readline usage (later set by init_readline) | |
439 | self.has_readline = False |
|
438 | self.has_readline = False | |
440 |
|
439 | |||
441 | # template for logfile headers. It gets resolved at runtime by the |
|
440 | # template for logfile headers. It gets resolved at runtime by the | |
442 | # logstart method. |
|
441 | # logstart method. | |
443 | self.loghead_tpl = \ |
|
442 | self.loghead_tpl = \ | |
444 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
443 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
445 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
444 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
446 | #log# opts = %s |
|
445 | #log# opts = %s | |
447 | #log# args = %s |
|
446 | #log# args = %s | |
448 | #log# It is safe to make manual edits below here. |
|
447 | #log# It is safe to make manual edits below here. | |
449 | #log#----------------------------------------------------------------------- |
|
448 | #log#----------------------------------------------------------------------- | |
450 | """ |
|
449 | """ | |
451 | # for pushd/popd management |
|
450 | # for pushd/popd management | |
452 | try: |
|
451 | try: | |
453 | self.home_dir = get_home_dir() |
|
452 | self.home_dir = get_home_dir() | |
454 | except HomeDirError,msg: |
|
453 | except HomeDirError,msg: | |
455 | fatal(msg) |
|
454 | fatal(msg) | |
456 |
|
455 | |||
457 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] |
|
456 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] | |
458 |
|
457 | |||
459 | # Functions to call the underlying shell. |
|
458 | # Functions to call the underlying shell. | |
460 |
|
459 | |||
461 | # utility to expand user variables via Itpl |
|
460 | # utility to expand user variables via Itpl | |
462 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), |
|
461 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), | |
463 | self.user_ns)) |
|
462 | self.user_ns)) | |
464 | # The first is similar to os.system, but it doesn't return a value, |
|
463 | # The first is similar to os.system, but it doesn't return a value, | |
465 | # and it allows interpolation of variables in the user's namespace. |
|
464 | # and it allows interpolation of variables in the user's namespace. | |
466 | self.system = lambda cmd: shell(self.var_expand(cmd), |
|
465 | self.system = lambda cmd: shell(self.var_expand(cmd), | |
467 | header='IPython system call: ', |
|
466 | header='IPython system call: ', | |
468 | verbose=self.rc.system_verbose) |
|
467 | verbose=self.rc.system_verbose) | |
469 | # These are for getoutput and getoutputerror: |
|
468 | # These are for getoutput and getoutputerror: | |
470 | self.getoutput = lambda cmd: \ |
|
469 | self.getoutput = lambda cmd: \ | |
471 | getoutput(self.var_expand(cmd), |
|
470 | getoutput(self.var_expand(cmd), | |
472 | header='IPython system call: ', |
|
471 | header='IPython system call: ', | |
473 | verbose=self.rc.system_verbose) |
|
472 | verbose=self.rc.system_verbose) | |
474 | self.getoutputerror = lambda cmd: \ |
|
473 | self.getoutputerror = lambda cmd: \ | |
475 | getoutputerror(self.var_expand(cmd), |
|
474 | getoutputerror(self.var_expand(cmd), | |
476 | header='IPython system call: ', |
|
475 | header='IPython system call: ', | |
477 | verbose=self.rc.system_verbose) |
|
476 | verbose=self.rc.system_verbose) | |
478 |
|
477 | |||
479 | # RegExp for splitting line contents into pre-char//first |
|
478 | # RegExp for splitting line contents into pre-char//first | |
480 | # word-method//rest. For clarity, each group in on one line. |
|
479 | # word-method//rest. For clarity, each group in on one line. | |
481 |
|
480 | |||
482 | # WARNING: update the regexp if the above escapes are changed, as they |
|
481 | # WARNING: update the regexp if the above escapes are changed, as they | |
483 | # are hardwired in. |
|
482 | # are hardwired in. | |
484 |
|
483 | |||
485 | # Don't get carried away with trying to make the autocalling catch too |
|
484 | # Don't get carried away with trying to make the autocalling catch too | |
486 | # much: it's better to be conservative rather than to trigger hidden |
|
485 | # much: it's better to be conservative rather than to trigger hidden | |
487 | # evals() somewhere and end up causing side effects. |
|
486 | # evals() somewhere and end up causing side effects. | |
488 |
|
487 | |||
489 | self.line_split = re.compile(r'^([\s*,;/])' |
|
488 | self.line_split = re.compile(r'^([\s*,;/])' | |
490 | r'([\?\w\.]+\w*\s*)' |
|
489 | r'([\?\w\.]+\w*\s*)' | |
491 | r'(\(?.*$)') |
|
490 | r'(\(?.*$)') | |
492 |
|
491 | |||
493 | # Original re, keep around for a while in case changes break something |
|
492 | # Original re, keep around for a while in case changes break something | |
494 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' |
|
493 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' | |
495 | # r'(\s*[\?\w\.]+\w*\s*)' |
|
494 | # r'(\s*[\?\w\.]+\w*\s*)' | |
496 | # r'(\(?.*$)') |
|
495 | # r'(\(?.*$)') | |
497 |
|
496 | |||
498 | # RegExp to identify potential function names |
|
497 | # RegExp to identify potential function names | |
499 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
498 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
500 |
|
499 | |||
501 | # RegExp to exclude strings with this start from autocalling. In |
|
500 | # RegExp to exclude strings with this start from autocalling. In | |
502 | # particular, all binary operators should be excluded, so that if foo |
|
501 | # particular, all binary operators should be excluded, so that if foo | |
503 | # is callable, foo OP bar doesn't become foo(OP bar), which is |
|
502 | # is callable, foo OP bar doesn't become foo(OP bar), which is | |
504 | # invalid. The characters '!=()' don't need to be checked for, as the |
|
503 | # invalid. The characters '!=()' don't need to be checked for, as the | |
505 | # _prefilter routine explicitely does so, to catch direct calls and |
|
504 | # _prefilter routine explicitely does so, to catch direct calls and | |
506 | # rebindings of existing names. |
|
505 | # rebindings of existing names. | |
507 |
|
506 | |||
508 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
507 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise | |
509 | # it affects the rest of the group in square brackets. |
|
508 | # it affects the rest of the group in square brackets. | |
510 | self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]' |
|
509 | self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]' | |
511 | '|^is |^not |^in |^and |^or ') |
|
510 | '|^is |^not |^in |^and |^or ') | |
512 |
|
511 | |||
513 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
512 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
514 | # (experimental). For this to work, the line_split regexp would need |
|
513 | # (experimental). For this to work, the line_split regexp would need | |
515 | # to be modified so it wouldn't break things at '['. That line is |
|
514 | # to be modified so it wouldn't break things at '['. That line is | |
516 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
515 | # nasty enough that I shouldn't change it until I can test it _well_. | |
517 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
516 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
518 |
|
517 | |||
519 | # keep track of where we started running (mainly for crash post-mortem) |
|
518 | # keep track of where we started running (mainly for crash post-mortem) | |
520 | self.starting_dir = os.getcwd() |
|
519 | self.starting_dir = os.getcwd() | |
521 |
|
520 | |||
522 | # Various switches which can be set |
|
521 | # Various switches which can be set | |
523 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
522 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
524 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
523 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
525 | self.banner2 = banner2 |
|
524 | self.banner2 = banner2 | |
526 |
|
525 | |||
527 | # TraceBack handlers: |
|
526 | # TraceBack handlers: | |
528 |
|
527 | |||
529 | # Syntax error handler. |
|
528 | # Syntax error handler. | |
530 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
529 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
531 |
|
530 | |||
532 | # The interactive one is initialized with an offset, meaning we always |
|
531 | # The interactive one is initialized with an offset, meaning we always | |
533 | # want to remove the topmost item in the traceback, which is our own |
|
532 | # want to remove the topmost item in the traceback, which is our own | |
534 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
533 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
535 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
534 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
536 | color_scheme='NoColor', |
|
535 | color_scheme='NoColor', | |
537 | tb_offset = 1) |
|
536 | tb_offset = 1) | |
538 |
|
537 | |||
539 | # IPython itself shouldn't crash. This will produce a detailed |
|
538 | # IPython itself shouldn't crash. This will produce a detailed | |
540 | # post-mortem if it does. But we only install the crash handler for |
|
539 | # post-mortem if it does. But we only install the crash handler for | |
541 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
540 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
542 | # and lose the crash handler. This is because exceptions in the main |
|
541 | # and lose the crash handler. This is because exceptions in the main | |
543 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
542 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
544 | # and there's no point in printing crash dumps for every user exception. |
|
543 | # and there's no point in printing crash dumps for every user exception. | |
545 | if self.isthreaded: |
|
544 | if self.isthreaded: | |
546 | ipCrashHandler = ultraTB.FormattedTB() |
|
545 | ipCrashHandler = ultraTB.FormattedTB() | |
547 | else: |
|
546 | else: | |
548 | from IPython import CrashHandler |
|
547 | from IPython import CrashHandler | |
549 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
548 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) | |
550 | self.set_crash_handler(ipCrashHandler) |
|
549 | self.set_crash_handler(ipCrashHandler) | |
551 |
|
550 | |||
552 | # and add any custom exception handlers the user may have specified |
|
551 | # and add any custom exception handlers the user may have specified | |
553 | self.set_custom_exc(*custom_exceptions) |
|
552 | self.set_custom_exc(*custom_exceptions) | |
554 |
|
553 | |||
555 | # indentation management |
|
554 | # indentation management | |
556 | self.autoindent = False |
|
555 | self.autoindent = False | |
557 | self.indent_current_nsp = 0 |
|
556 | self.indent_current_nsp = 0 | |
558 |
|
557 | |||
559 | # Make some aliases automatically |
|
558 | # Make some aliases automatically | |
560 | # Prepare list of shell aliases to auto-define |
|
559 | # Prepare list of shell aliases to auto-define | |
561 | if os.name == 'posix': |
|
560 | if os.name == 'posix': | |
562 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
561 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
563 | 'mv mv -i','rm rm -i','cp cp -i', |
|
562 | 'mv mv -i','rm rm -i','cp cp -i', | |
564 | 'cat cat','less less','clear clear', |
|
563 | 'cat cat','less less','clear clear', | |
565 | # a better ls |
|
564 | # a better ls | |
566 | 'ls ls -F', |
|
565 | 'ls ls -F', | |
567 | # long ls |
|
566 | # long ls | |
568 | 'll ls -lF') |
|
567 | 'll ls -lF') | |
569 | # Extra ls aliases with color, which need special treatment on BSD |
|
568 | # Extra ls aliases with color, which need special treatment on BSD | |
570 | # variants |
|
569 | # variants | |
571 | ls_extra = ( # color ls |
|
570 | ls_extra = ( # color ls | |
572 | 'lc ls -F -o --color', |
|
571 | 'lc ls -F -o --color', | |
573 | # ls normal files only |
|
572 | # ls normal files only | |
574 | 'lf ls -F -o --color %l | grep ^-', |
|
573 | 'lf ls -F -o --color %l | grep ^-', | |
575 | # ls symbolic links |
|
574 | # ls symbolic links | |
576 | 'lk ls -F -o --color %l | grep ^l', |
|
575 | 'lk ls -F -o --color %l | grep ^l', | |
577 | # directories or links to directories, |
|
576 | # directories or links to directories, | |
578 | 'ldir ls -F -o --color %l | grep /$', |
|
577 | 'ldir ls -F -o --color %l | grep /$', | |
579 | # things which are executable |
|
578 | # things which are executable | |
580 | 'lx ls -F -o --color %l | grep ^-..x', |
|
579 | 'lx ls -F -o --color %l | grep ^-..x', | |
581 | ) |
|
580 | ) | |
582 | # The BSDs don't ship GNU ls, so they don't understand the |
|
581 | # The BSDs don't ship GNU ls, so they don't understand the | |
583 | # --color switch out of the box |
|
582 | # --color switch out of the box | |
584 | if 'bsd' in sys.platform: |
|
583 | if 'bsd' in sys.platform: | |
585 | ls_extra = ( # ls normal files only |
|
584 | ls_extra = ( # ls normal files only | |
586 | 'lf ls -lF | grep ^-', |
|
585 | 'lf ls -lF | grep ^-', | |
587 | # ls symbolic links |
|
586 | # ls symbolic links | |
588 | 'lk ls -lF | grep ^l', |
|
587 | 'lk ls -lF | grep ^l', | |
589 | # directories or links to directories, |
|
588 | # directories or links to directories, | |
590 | 'ldir ls -lF | grep /$', |
|
589 | 'ldir ls -lF | grep /$', | |
591 | # things which are executable |
|
590 | # things which are executable | |
592 | 'lx ls -lF | grep ^-..x', |
|
591 | 'lx ls -lF | grep ^-..x', | |
593 | ) |
|
592 | ) | |
594 | auto_alias = auto_alias + ls_extra |
|
593 | auto_alias = auto_alias + ls_extra | |
595 | elif os.name in ['nt','dos']: |
|
594 | elif os.name in ['nt','dos']: | |
596 | auto_alias = ('dir dir /on', 'ls dir /on', |
|
595 | auto_alias = ('dir dir /on', 'ls dir /on', | |
597 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
596 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
598 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
597 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
599 | 'ren ren','cls cls','copy copy') |
|
598 | 'ren ren','cls cls','copy copy') | |
600 | else: |
|
599 | else: | |
601 | auto_alias = () |
|
600 | auto_alias = () | |
602 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
601 | self.auto_alias = [s.split(None,1) for s in auto_alias] | |
603 | # Call the actual (public) initializer |
|
602 | # Call the actual (public) initializer | |
604 | self.init_auto_alias() |
|
603 | self.init_auto_alias() | |
605 |
|
604 | |||
606 | # Produce a public API instance |
|
605 | # Produce a public API instance | |
607 | self.api = IPython.ipapi.IPApi(self) |
|
606 | self.api = IPython.ipapi.IPApi(self) | |
608 |
|
607 | |||
609 | # track which builtins we add, so we can clean up later |
|
608 | # track which builtins we add, so we can clean up later | |
610 | self.builtins_added = {} |
|
609 | self.builtins_added = {} | |
611 | # This method will add the necessary builtins for operation, but |
|
610 | # This method will add the necessary builtins for operation, but | |
612 | # tracking what it did via the builtins_added dict. |
|
611 | # tracking what it did via the builtins_added dict. | |
613 | self.add_builtins() |
|
612 | self.add_builtins() | |
614 |
|
613 | |||
615 | # end __init__ |
|
614 | # end __init__ | |
616 |
|
615 | |||
617 | def pre_config_initialization(self): |
|
616 | def pre_config_initialization(self): | |
618 | """Pre-configuration init method |
|
617 | """Pre-configuration init method | |
619 |
|
618 | |||
620 | This is called before the configuration files are processed to |
|
619 | This is called before the configuration files are processed to | |
621 | prepare the services the config files might need. |
|
620 | prepare the services the config files might need. | |
622 |
|
621 | |||
623 | self.rc already has reasonable default values at this point. |
|
622 | self.rc already has reasonable default values at this point. | |
624 | """ |
|
623 | """ | |
625 | rc = self.rc |
|
624 | rc = self.rc | |
626 |
|
625 | |||
627 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
626 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") | |
628 |
|
627 | |||
629 | def post_config_initialization(self): |
|
628 | def post_config_initialization(self): | |
630 | """Post configuration init method |
|
629 | """Post configuration init method | |
631 |
|
630 | |||
632 | This is called after the configuration files have been processed to |
|
631 | This is called after the configuration files have been processed to | |
633 | 'finalize' the initialization.""" |
|
632 | 'finalize' the initialization.""" | |
634 |
|
633 | |||
635 | rc = self.rc |
|
634 | rc = self.rc | |
636 |
|
635 | |||
637 | # Object inspector |
|
636 | # Object inspector | |
638 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
637 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
639 | PyColorize.ANSICodeColors, |
|
638 | PyColorize.ANSICodeColors, | |
640 | 'NoColor', |
|
639 | 'NoColor', | |
641 | rc.object_info_string_level) |
|
640 | rc.object_info_string_level) | |
642 |
|
641 | |||
643 | # Load readline proper |
|
642 | # Load readline proper | |
644 | if rc.readline: |
|
643 | if rc.readline: | |
645 | self.init_readline() |
|
644 | self.init_readline() | |
646 |
|
645 | |||
647 | # local shortcut, this is used a LOT |
|
646 | # local shortcut, this is used a LOT | |
648 | self.log = self.logger.log |
|
647 | self.log = self.logger.log | |
649 |
|
648 | |||
650 | # Initialize cache, set in/out prompts and printing system |
|
649 | # Initialize cache, set in/out prompts and printing system | |
651 | self.outputcache = CachedOutput(self, |
|
650 | self.outputcache = CachedOutput(self, | |
652 | rc.cache_size, |
|
651 | rc.cache_size, | |
653 | rc.pprint, |
|
652 | rc.pprint, | |
654 | input_sep = rc.separate_in, |
|
653 | input_sep = rc.separate_in, | |
655 | output_sep = rc.separate_out, |
|
654 | output_sep = rc.separate_out, | |
656 | output_sep2 = rc.separate_out2, |
|
655 | output_sep2 = rc.separate_out2, | |
657 | ps1 = rc.prompt_in1, |
|
656 | ps1 = rc.prompt_in1, | |
658 | ps2 = rc.prompt_in2, |
|
657 | ps2 = rc.prompt_in2, | |
659 | ps_out = rc.prompt_out, |
|
658 | ps_out = rc.prompt_out, | |
660 | pad_left = rc.prompts_pad_left) |
|
659 | pad_left = rc.prompts_pad_left) | |
661 |
|
660 | |||
662 | # user may have over-ridden the default print hook: |
|
661 | # user may have over-ridden the default print hook: | |
663 | try: |
|
662 | try: | |
664 | self.outputcache.__class__.display = self.hooks.display |
|
663 | self.outputcache.__class__.display = self.hooks.display | |
665 | except AttributeError: |
|
664 | except AttributeError: | |
666 | pass |
|
665 | pass | |
667 |
|
666 | |||
668 | # I don't like assigning globally to sys, because it means when |
|
667 | # I don't like assigning globally to sys, because it means when | |
669 | # embedding instances, each embedded instance overrides the previous |
|
668 | # embedding instances, each embedded instance overrides the previous | |
670 | # choice. But sys.displayhook seems to be called internally by exec, |
|
669 | # choice. But sys.displayhook seems to be called internally by exec, | |
671 | # so I don't see a way around it. We first save the original and then |
|
670 | # so I don't see a way around it. We first save the original and then | |
672 | # overwrite it. |
|
671 | # overwrite it. | |
673 | self.sys_displayhook = sys.displayhook |
|
672 | self.sys_displayhook = sys.displayhook | |
674 | sys.displayhook = self.outputcache |
|
673 | sys.displayhook = self.outputcache | |
675 |
|
674 | |||
676 | # Set user colors (don't do it in the constructor above so that it |
|
675 | # Set user colors (don't do it in the constructor above so that it | |
677 | # doesn't crash if colors option is invalid) |
|
676 | # doesn't crash if colors option is invalid) | |
678 | self.magic_colors(rc.colors) |
|
677 | self.magic_colors(rc.colors) | |
679 |
|
678 | |||
680 | # Set calling of pdb on exceptions |
|
679 | # Set calling of pdb on exceptions | |
681 | self.call_pdb = rc.pdb |
|
680 | self.call_pdb = rc.pdb | |
682 |
|
681 | |||
683 | # Load user aliases |
|
682 | # Load user aliases | |
684 | for alias in rc.alias: |
|
683 | for alias in rc.alias: | |
685 | self.magic_alias(alias) |
|
684 | self.magic_alias(alias) | |
686 | self.hooks.late_startup_hook() |
|
685 | self.hooks.late_startup_hook() | |
687 |
|
686 | |||
688 | batchrun = False |
|
687 | batchrun = False | |
689 | for batchfile in [path(arg) for arg in self.rc.args |
|
688 | for batchfile in [path(arg) for arg in self.rc.args | |
690 | if arg.lower().endswith('.ipy')]: |
|
689 | if arg.lower().endswith('.ipy')]: | |
691 | if not batchfile.isfile(): |
|
690 | if not batchfile.isfile(): | |
692 | print "No such batch file:", batchfile |
|
691 | print "No such batch file:", batchfile | |
693 | continue |
|
692 | continue | |
694 | self.api.runlines(batchfile.text()) |
|
693 | self.api.runlines(batchfile.text()) | |
695 | batchrun = True |
|
694 | batchrun = True | |
696 | if batchrun: |
|
695 | if batchrun: | |
697 | self.exit_now = True |
|
696 | self.exit_now = True | |
698 |
|
697 | |||
699 | def add_builtins(self): |
|
698 | def add_builtins(self): | |
700 | """Store ipython references into the builtin namespace. |
|
699 | """Store ipython references into the builtin namespace. | |
701 |
|
700 | |||
702 | Some parts of ipython operate via builtins injected here, which hold a |
|
701 | Some parts of ipython operate via builtins injected here, which hold a | |
703 | reference to IPython itself.""" |
|
702 | reference to IPython itself.""" | |
704 |
|
703 | |||
705 | # TODO: deprecate all except _ip; 'jobs' should be installed |
|
704 | # TODO: deprecate all except _ip; 'jobs' should be installed | |
706 | # by an extension and the rest are under _ip, ipalias is redundant |
|
705 | # by an extension and the rest are under _ip, ipalias is redundant | |
707 | builtins_new = dict(__IPYTHON__ = self, |
|
706 | builtins_new = dict(__IPYTHON__ = self, | |
708 | ip_set_hook = self.set_hook, |
|
707 | ip_set_hook = self.set_hook, | |
709 | jobs = self.jobs, |
|
708 | jobs = self.jobs, | |
710 | ipmagic = self.ipmagic, |
|
709 | ipmagic = self.ipmagic, | |
711 | ipalias = self.ipalias, |
|
710 | ipalias = self.ipalias, | |
712 | ipsystem = self.ipsystem, |
|
711 | ipsystem = self.ipsystem, | |
713 | _ip = self.api |
|
712 | _ip = self.api | |
714 | ) |
|
713 | ) | |
715 | for biname,bival in builtins_new.items(): |
|
714 | for biname,bival in builtins_new.items(): | |
716 | try: |
|
715 | try: | |
717 | # store the orignal value so we can restore it |
|
716 | # store the orignal value so we can restore it | |
718 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
717 | self.builtins_added[biname] = __builtin__.__dict__[biname] | |
719 | except KeyError: |
|
718 | except KeyError: | |
720 | # or mark that it wasn't defined, and we'll just delete it at |
|
719 | # or mark that it wasn't defined, and we'll just delete it at | |
721 | # cleanup |
|
720 | # cleanup | |
722 | self.builtins_added[biname] = Undefined |
|
721 | self.builtins_added[biname] = Undefined | |
723 | __builtin__.__dict__[biname] = bival |
|
722 | __builtin__.__dict__[biname] = bival | |
724 |
|
723 | |||
725 | # Keep in the builtins a flag for when IPython is active. We set it |
|
724 | # Keep in the builtins a flag for when IPython is active. We set it | |
726 | # with setdefault so that multiple nested IPythons don't clobber one |
|
725 | # with setdefault so that multiple nested IPythons don't clobber one | |
727 | # another. Each will increase its value by one upon being activated, |
|
726 | # another. Each will increase its value by one upon being activated, | |
728 | # which also gives us a way to determine the nesting level. |
|
727 | # which also gives us a way to determine the nesting level. | |
729 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
728 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
730 |
|
729 | |||
731 | def clean_builtins(self): |
|
730 | def clean_builtins(self): | |
732 | """Remove any builtins which might have been added by add_builtins, or |
|
731 | """Remove any builtins which might have been added by add_builtins, or | |
733 | restore overwritten ones to their previous values.""" |
|
732 | restore overwritten ones to their previous values.""" | |
734 | for biname,bival in self.builtins_added.items(): |
|
733 | for biname,bival in self.builtins_added.items(): | |
735 | if bival is Undefined: |
|
734 | if bival is Undefined: | |
736 | del __builtin__.__dict__[biname] |
|
735 | del __builtin__.__dict__[biname] | |
737 | else: |
|
736 | else: | |
738 | __builtin__.__dict__[biname] = bival |
|
737 | __builtin__.__dict__[biname] = bival | |
739 | self.builtins_added.clear() |
|
738 | self.builtins_added.clear() | |
740 |
|
739 | |||
741 | def set_hook(self,name,hook, priority = 50): |
|
740 | def set_hook(self,name,hook, priority = 50): | |
742 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
741 | """set_hook(name,hook) -> sets an internal IPython hook. | |
743 |
|
742 | |||
744 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
743 | IPython exposes some of its internal API as user-modifiable hooks. By | |
745 | adding your function to one of these hooks, you can modify IPython's |
|
744 | adding your function to one of these hooks, you can modify IPython's | |
746 | behavior to call at runtime your own routines.""" |
|
745 | behavior to call at runtime your own routines.""" | |
747 |
|
746 | |||
748 | # At some point in the future, this should validate the hook before it |
|
747 | # At some point in the future, this should validate the hook before it | |
749 | # accepts it. Probably at least check that the hook takes the number |
|
748 | # accepts it. Probably at least check that the hook takes the number | |
750 | # of args it's supposed to. |
|
749 | # of args it's supposed to. | |
751 | dp = getattr(self.hooks, name, None) |
|
750 | dp = getattr(self.hooks, name, None) | |
752 | if name not in IPython.hooks.__all__: |
|
751 | if name not in IPython.hooks.__all__: | |
753 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
752 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) | |
754 | if not dp: |
|
753 | if not dp: | |
755 | dp = IPython.hooks.CommandChainDispatcher() |
|
754 | dp = IPython.hooks.CommandChainDispatcher() | |
756 |
|
755 | |||
757 | f = new.instancemethod(hook,self,self.__class__) |
|
756 | f = new.instancemethod(hook,self,self.__class__) | |
758 | try: |
|
757 | try: | |
759 | dp.add(f,priority) |
|
758 | dp.add(f,priority) | |
760 | except AttributeError: |
|
759 | except AttributeError: | |
761 | # it was not commandchain, plain old func - replace |
|
760 | # it was not commandchain, plain old func - replace | |
762 | dp = f |
|
761 | dp = f | |
763 |
|
762 | |||
764 | setattr(self.hooks,name, dp) |
|
763 | setattr(self.hooks,name, dp) | |
765 |
|
764 | |||
766 |
|
765 | |||
767 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
766 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
768 |
|
767 | |||
769 | def set_crash_handler(self,crashHandler): |
|
768 | def set_crash_handler(self,crashHandler): | |
770 | """Set the IPython crash handler. |
|
769 | """Set the IPython crash handler. | |
771 |
|
770 | |||
772 | This must be a callable with a signature suitable for use as |
|
771 | This must be a callable with a signature suitable for use as | |
773 | sys.excepthook.""" |
|
772 | sys.excepthook.""" | |
774 |
|
773 | |||
775 | # Install the given crash handler as the Python exception hook |
|
774 | # Install the given crash handler as the Python exception hook | |
776 | sys.excepthook = crashHandler |
|
775 | sys.excepthook = crashHandler | |
777 |
|
776 | |||
778 | # The instance will store a pointer to this, so that runtime code |
|
777 | # The instance will store a pointer to this, so that runtime code | |
779 | # (such as magics) can access it. This is because during the |
|
778 | # (such as magics) can access it. This is because during the | |
780 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
779 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
781 | # frameworks). |
|
780 | # frameworks). | |
782 | self.sys_excepthook = sys.excepthook |
|
781 | self.sys_excepthook = sys.excepthook | |
783 |
|
782 | |||
784 |
|
783 | |||
785 | def set_custom_exc(self,exc_tuple,handler): |
|
784 | def set_custom_exc(self,exc_tuple,handler): | |
786 | """set_custom_exc(exc_tuple,handler) |
|
785 | """set_custom_exc(exc_tuple,handler) | |
787 |
|
786 | |||
788 | Set a custom exception handler, which will be called if any of the |
|
787 | Set a custom exception handler, which will be called if any of the | |
789 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
788 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
790 | runcode() method. |
|
789 | runcode() method. | |
791 |
|
790 | |||
792 | Inputs: |
|
791 | Inputs: | |
793 |
|
792 | |||
794 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
793 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
795 | handler for. It is very important that you use a tuple, and NOT A |
|
794 | handler for. It is very important that you use a tuple, and NOT A | |
796 | LIST here, because of the way Python's except statement works. If |
|
795 | LIST here, because of the way Python's except statement works. If | |
797 | you only want to trap a single exception, use a singleton tuple: |
|
796 | you only want to trap a single exception, use a singleton tuple: | |
798 |
|
797 | |||
799 | exc_tuple == (MyCustomException,) |
|
798 | exc_tuple == (MyCustomException,) | |
800 |
|
799 | |||
801 | - handler: this must be defined as a function with the following |
|
800 | - handler: this must be defined as a function with the following | |
802 | basic interface: def my_handler(self,etype,value,tb). |
|
801 | basic interface: def my_handler(self,etype,value,tb). | |
803 |
|
802 | |||
804 | This will be made into an instance method (via new.instancemethod) |
|
803 | This will be made into an instance method (via new.instancemethod) | |
805 | of IPython itself, and it will be called if any of the exceptions |
|
804 | of IPython itself, and it will be called if any of the exceptions | |
806 | listed in the exc_tuple are caught. If the handler is None, an |
|
805 | listed in the exc_tuple are caught. If the handler is None, an | |
807 | internal basic one is used, which just prints basic info. |
|
806 | internal basic one is used, which just prints basic info. | |
808 |
|
807 | |||
809 | WARNING: by putting in your own exception handler into IPython's main |
|
808 | WARNING: by putting in your own exception handler into IPython's main | |
810 | execution loop, you run a very good chance of nasty crashes. This |
|
809 | execution loop, you run a very good chance of nasty crashes. This | |
811 | facility should only be used if you really know what you are doing.""" |
|
810 | facility should only be used if you really know what you are doing.""" | |
812 |
|
811 | |||
813 | assert type(exc_tuple)==type(()) , \ |
|
812 | assert type(exc_tuple)==type(()) , \ | |
814 | "The custom exceptions must be given AS A TUPLE." |
|
813 | "The custom exceptions must be given AS A TUPLE." | |
815 |
|
814 | |||
816 | def dummy_handler(self,etype,value,tb): |
|
815 | def dummy_handler(self,etype,value,tb): | |
817 | print '*** Simple custom exception handler ***' |
|
816 | print '*** Simple custom exception handler ***' | |
818 | print 'Exception type :',etype |
|
817 | print 'Exception type :',etype | |
819 | print 'Exception value:',value |
|
818 | print 'Exception value:',value | |
820 | print 'Traceback :',tb |
|
819 | print 'Traceback :',tb | |
821 | print 'Source code :','\n'.join(self.buffer) |
|
820 | print 'Source code :','\n'.join(self.buffer) | |
822 |
|
821 | |||
823 | if handler is None: handler = dummy_handler |
|
822 | if handler is None: handler = dummy_handler | |
824 |
|
823 | |||
825 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
824 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
826 | self.custom_exceptions = exc_tuple |
|
825 | self.custom_exceptions = exc_tuple | |
827 |
|
826 | |||
828 | def set_custom_completer(self,completer,pos=0): |
|
827 | def set_custom_completer(self,completer,pos=0): | |
829 | """set_custom_completer(completer,pos=0) |
|
828 | """set_custom_completer(completer,pos=0) | |
830 |
|
829 | |||
831 | Adds a new custom completer function. |
|
830 | Adds a new custom completer function. | |
832 |
|
831 | |||
833 | The position argument (defaults to 0) is the index in the completers |
|
832 | The position argument (defaults to 0) is the index in the completers | |
834 | list where you want the completer to be inserted.""" |
|
833 | list where you want the completer to be inserted.""" | |
835 |
|
834 | |||
836 | newcomp = new.instancemethod(completer,self.Completer, |
|
835 | newcomp = new.instancemethod(completer,self.Completer, | |
837 | self.Completer.__class__) |
|
836 | self.Completer.__class__) | |
838 | self.Completer.matchers.insert(pos,newcomp) |
|
837 | self.Completer.matchers.insert(pos,newcomp) | |
839 |
|
838 | |||
840 | def _get_call_pdb(self): |
|
839 | def _get_call_pdb(self): | |
841 | return self._call_pdb |
|
840 | return self._call_pdb | |
842 |
|
841 | |||
843 | def _set_call_pdb(self,val): |
|
842 | def _set_call_pdb(self,val): | |
844 |
|
843 | |||
845 | if val not in (0,1,False,True): |
|
844 | if val not in (0,1,False,True): | |
846 | raise ValueError,'new call_pdb value must be boolean' |
|
845 | raise ValueError,'new call_pdb value must be boolean' | |
847 |
|
846 | |||
848 | # store value in instance |
|
847 | # store value in instance | |
849 | self._call_pdb = val |
|
848 | self._call_pdb = val | |
850 |
|
849 | |||
851 | # notify the actual exception handlers |
|
850 | # notify the actual exception handlers | |
852 | self.InteractiveTB.call_pdb = val |
|
851 | self.InteractiveTB.call_pdb = val | |
853 | if self.isthreaded: |
|
852 | if self.isthreaded: | |
854 | try: |
|
853 | try: | |
855 | self.sys_excepthook.call_pdb = val |
|
854 | self.sys_excepthook.call_pdb = val | |
856 | except: |
|
855 | except: | |
857 | warn('Failed to activate pdb for threaded exception handler') |
|
856 | warn('Failed to activate pdb for threaded exception handler') | |
858 |
|
857 | |||
859 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
858 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
860 | 'Control auto-activation of pdb at exceptions') |
|
859 | 'Control auto-activation of pdb at exceptions') | |
861 |
|
860 | |||
862 |
|
861 | |||
863 | # These special functions get installed in the builtin namespace, to |
|
862 | # These special functions get installed in the builtin namespace, to | |
864 | # provide programmatic (pure python) access to magics, aliases and system |
|
863 | # provide programmatic (pure python) access to magics, aliases and system | |
865 | # calls. This is important for logging, user scripting, and more. |
|
864 | # calls. This is important for logging, user scripting, and more. | |
866 |
|
865 | |||
867 | # We are basically exposing, via normal python functions, the three |
|
866 | # We are basically exposing, via normal python functions, the three | |
868 | # mechanisms in which ipython offers special call modes (magics for |
|
867 | # mechanisms in which ipython offers special call modes (magics for | |
869 | # internal control, aliases for direct system access via pre-selected |
|
868 | # internal control, aliases for direct system access via pre-selected | |
870 | # names, and !cmd for calling arbitrary system commands). |
|
869 | # names, and !cmd for calling arbitrary system commands). | |
871 |
|
870 | |||
872 | def ipmagic(self,arg_s): |
|
871 | def ipmagic(self,arg_s): | |
873 | """Call a magic function by name. |
|
872 | """Call a magic function by name. | |
874 |
|
873 | |||
875 | Input: a string containing the name of the magic function to call and any |
|
874 | Input: a string containing the name of the magic function to call and any | |
876 | additional arguments to be passed to the magic. |
|
875 | additional arguments to be passed to the magic. | |
877 |
|
876 | |||
878 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
877 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
879 | prompt: |
|
878 | prompt: | |
880 |
|
879 | |||
881 | In[1]: %name -opt foo bar |
|
880 | In[1]: %name -opt foo bar | |
882 |
|
881 | |||
883 | To call a magic without arguments, simply use ipmagic('name'). |
|
882 | To call a magic without arguments, simply use ipmagic('name'). | |
884 |
|
883 | |||
885 | This provides a proper Python function to call IPython's magics in any |
|
884 | This provides a proper Python function to call IPython's magics in any | |
886 | valid Python code you can type at the interpreter, including loops and |
|
885 | valid Python code you can type at the interpreter, including loops and | |
887 | compound statements. It is added by IPython to the Python builtin |
|
886 | compound statements. It is added by IPython to the Python builtin | |
888 | namespace upon initialization.""" |
|
887 | namespace upon initialization.""" | |
889 |
|
888 | |||
890 | args = arg_s.split(' ',1) |
|
889 | args = arg_s.split(' ',1) | |
891 | magic_name = args[0] |
|
890 | magic_name = args[0] | |
892 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
891 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |
893 |
|
892 | |||
894 | try: |
|
893 | try: | |
895 | magic_args = args[1] |
|
894 | magic_args = args[1] | |
896 | except IndexError: |
|
895 | except IndexError: | |
897 | magic_args = '' |
|
896 | magic_args = '' | |
898 | fn = getattr(self,'magic_'+magic_name,None) |
|
897 | fn = getattr(self,'magic_'+magic_name,None) | |
899 | if fn is None: |
|
898 | if fn is None: | |
900 | error("Magic function `%s` not found." % magic_name) |
|
899 | error("Magic function `%s` not found." % magic_name) | |
901 | else: |
|
900 | else: | |
902 | magic_args = self.var_expand(magic_args) |
|
901 | magic_args = self.var_expand(magic_args) | |
903 | return fn(magic_args) |
|
902 | return fn(magic_args) | |
904 |
|
903 | |||
905 | def ipalias(self,arg_s): |
|
904 | def ipalias(self,arg_s): | |
906 | """Call an alias by name. |
|
905 | """Call an alias by name. | |
907 |
|
906 | |||
908 | Input: a string containing the name of the alias to call and any |
|
907 | Input: a string containing the name of the alias to call and any | |
909 | additional arguments to be passed to the magic. |
|
908 | additional arguments to be passed to the magic. | |
910 |
|
909 | |||
911 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
910 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
912 | prompt: |
|
911 | prompt: | |
913 |
|
912 | |||
914 | In[1]: name -opt foo bar |
|
913 | In[1]: name -opt foo bar | |
915 |
|
914 | |||
916 | To call an alias without arguments, simply use ipalias('name'). |
|
915 | To call an alias without arguments, simply use ipalias('name'). | |
917 |
|
916 | |||
918 | This provides a proper Python function to call IPython's aliases in any |
|
917 | This provides a proper Python function to call IPython's aliases in any | |
919 | valid Python code you can type at the interpreter, including loops and |
|
918 | valid Python code you can type at the interpreter, including loops and | |
920 | compound statements. It is added by IPython to the Python builtin |
|
919 | compound statements. It is added by IPython to the Python builtin | |
921 | namespace upon initialization.""" |
|
920 | namespace upon initialization.""" | |
922 |
|
921 | |||
923 | args = arg_s.split(' ',1) |
|
922 | args = arg_s.split(' ',1) | |
924 | alias_name = args[0] |
|
923 | alias_name = args[0] | |
925 | try: |
|
924 | try: | |
926 | alias_args = args[1] |
|
925 | alias_args = args[1] | |
927 | except IndexError: |
|
926 | except IndexError: | |
928 | alias_args = '' |
|
927 | alias_args = '' | |
929 | if alias_name in self.alias_table: |
|
928 | if alias_name in self.alias_table: | |
930 | self.call_alias(alias_name,alias_args) |
|
929 | self.call_alias(alias_name,alias_args) | |
931 | else: |
|
930 | else: | |
932 | error("Alias `%s` not found." % alias_name) |
|
931 | error("Alias `%s` not found." % alias_name) | |
933 |
|
932 | |||
934 | def ipsystem(self,arg_s): |
|
933 | def ipsystem(self,arg_s): | |
935 | """Make a system call, using IPython.""" |
|
934 | """Make a system call, using IPython.""" | |
936 |
|
935 | |||
937 | self.system(arg_s) |
|
936 | self.system(arg_s) | |
938 |
|
937 | |||
939 | def complete(self,text): |
|
938 | def complete(self,text): | |
940 | """Return a sorted list of all possible completions on text. |
|
939 | """Return a sorted list of all possible completions on text. | |
941 |
|
940 | |||
942 | Inputs: |
|
941 | Inputs: | |
943 |
|
942 | |||
944 | - text: a string of text to be completed on. |
|
943 | - text: a string of text to be completed on. | |
945 |
|
944 | |||
946 | This is a wrapper around the completion mechanism, similar to what |
|
945 | This is a wrapper around the completion mechanism, similar to what | |
947 | readline does at the command line when the TAB key is hit. By |
|
946 | readline does at the command line when the TAB key is hit. By | |
948 | exposing it as a method, it can be used by other non-readline |
|
947 | exposing it as a method, it can be used by other non-readline | |
949 | environments (such as GUIs) for text completion. |
|
948 | environments (such as GUIs) for text completion. | |
950 |
|
949 | |||
951 | Simple usage example: |
|
950 | Simple usage example: | |
952 |
|
951 | |||
953 | In [1]: x = 'hello' |
|
952 | In [1]: x = 'hello' | |
954 |
|
953 | |||
955 | In [2]: __IP.complete('x.l') |
|
954 | In [2]: __IP.complete('x.l') | |
956 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" |
|
955 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" | |
957 |
|
956 | |||
958 | complete = self.Completer.complete |
|
957 | complete = self.Completer.complete | |
959 | state = 0 |
|
958 | state = 0 | |
960 | # use a dict so we get unique keys, since ipyhton's multiple |
|
959 | # use a dict so we get unique keys, since ipyhton's multiple | |
961 | # completers can return duplicates. |
|
960 | # completers can return duplicates. | |
962 | comps = {} |
|
961 | comps = {} | |
963 | while True: |
|
962 | while True: | |
964 | newcomp = complete(text,state) |
|
963 | newcomp = complete(text,state) | |
965 | if newcomp is None: |
|
964 | if newcomp is None: | |
966 | break |
|
965 | break | |
967 | comps[newcomp] = 1 |
|
966 | comps[newcomp] = 1 | |
968 | state += 1 |
|
967 | state += 1 | |
969 | outcomps = comps.keys() |
|
968 | outcomps = comps.keys() | |
970 | outcomps.sort() |
|
969 | outcomps.sort() | |
971 | return outcomps |
|
970 | return outcomps | |
972 |
|
971 | |||
973 | def set_completer_frame(self, frame=None): |
|
972 | def set_completer_frame(self, frame=None): | |
974 | if frame: |
|
973 | if frame: | |
975 | self.Completer.namespace = frame.f_locals |
|
974 | self.Completer.namespace = frame.f_locals | |
976 | self.Completer.global_namespace = frame.f_globals |
|
975 | self.Completer.global_namespace = frame.f_globals | |
977 | else: |
|
976 | else: | |
978 | self.Completer.namespace = self.user_ns |
|
977 | self.Completer.namespace = self.user_ns | |
979 | self.Completer.global_namespace = self.user_global_ns |
|
978 | self.Completer.global_namespace = self.user_global_ns | |
980 |
|
979 | |||
981 | def init_auto_alias(self): |
|
980 | def init_auto_alias(self): | |
982 | """Define some aliases automatically. |
|
981 | """Define some aliases automatically. | |
983 |
|
982 | |||
984 | These are ALL parameter-less aliases""" |
|
983 | These are ALL parameter-less aliases""" | |
985 |
|
984 | |||
986 | for alias,cmd in self.auto_alias: |
|
985 | for alias,cmd in self.auto_alias: | |
987 | self.alias_table[alias] = (0,cmd) |
|
986 | self.alias_table[alias] = (0,cmd) | |
988 |
|
987 | |||
989 | def alias_table_validate(self,verbose=0): |
|
988 | def alias_table_validate(self,verbose=0): | |
990 | """Update information about the alias table. |
|
989 | """Update information about the alias table. | |
991 |
|
990 | |||
992 | In particular, make sure no Python keywords/builtins are in it.""" |
|
991 | In particular, make sure no Python keywords/builtins are in it.""" | |
993 |
|
992 | |||
994 | no_alias = self.no_alias |
|
993 | no_alias = self.no_alias | |
995 | for k in self.alias_table.keys(): |
|
994 | for k in self.alias_table.keys(): | |
996 | if k in no_alias: |
|
995 | if k in no_alias: | |
997 | del self.alias_table[k] |
|
996 | del self.alias_table[k] | |
998 | if verbose: |
|
997 | if verbose: | |
999 | print ("Deleting alias <%s>, it's a Python " |
|
998 | print ("Deleting alias <%s>, it's a Python " | |
1000 | "keyword or builtin." % k) |
|
999 | "keyword or builtin." % k) | |
1001 |
|
1000 | |||
1002 | def set_autoindent(self,value=None): |
|
1001 | def set_autoindent(self,value=None): | |
1003 | """Set the autoindent flag, checking for readline support. |
|
1002 | """Set the autoindent flag, checking for readline support. | |
1004 |
|
1003 | |||
1005 | If called with no arguments, it acts as a toggle.""" |
|
1004 | If called with no arguments, it acts as a toggle.""" | |
1006 |
|
1005 | |||
1007 | if not self.has_readline: |
|
1006 | if not self.has_readline: | |
1008 | if os.name == 'posix': |
|
1007 | if os.name == 'posix': | |
1009 | warn("The auto-indent feature requires the readline library") |
|
1008 | warn("The auto-indent feature requires the readline library") | |
1010 | self.autoindent = 0 |
|
1009 | self.autoindent = 0 | |
1011 | return |
|
1010 | return | |
1012 | if value is None: |
|
1011 | if value is None: | |
1013 | self.autoindent = not self.autoindent |
|
1012 | self.autoindent = not self.autoindent | |
1014 | else: |
|
1013 | else: | |
1015 | self.autoindent = value |
|
1014 | self.autoindent = value | |
1016 |
|
1015 | |||
1017 | def rc_set_toggle(self,rc_field,value=None): |
|
1016 | def rc_set_toggle(self,rc_field,value=None): | |
1018 | """Set or toggle a field in IPython's rc config. structure. |
|
1017 | """Set or toggle a field in IPython's rc config. structure. | |
1019 |
|
1018 | |||
1020 | If called with no arguments, it acts as a toggle. |
|
1019 | If called with no arguments, it acts as a toggle. | |
1021 |
|
1020 | |||
1022 | If called with a non-existent field, the resulting AttributeError |
|
1021 | If called with a non-existent field, the resulting AttributeError | |
1023 | exception will propagate out.""" |
|
1022 | exception will propagate out.""" | |
1024 |
|
1023 | |||
1025 | rc_val = getattr(self.rc,rc_field) |
|
1024 | rc_val = getattr(self.rc,rc_field) | |
1026 | if value is None: |
|
1025 | if value is None: | |
1027 | value = not rc_val |
|
1026 | value = not rc_val | |
1028 | setattr(self.rc,rc_field,value) |
|
1027 | setattr(self.rc,rc_field,value) | |
1029 |
|
1028 | |||
1030 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1029 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
1031 | """Install the user configuration directory. |
|
1030 | """Install the user configuration directory. | |
1032 |
|
1031 | |||
1033 | Can be called when running for the first time or to upgrade the user's |
|
1032 | Can be called when running for the first time or to upgrade the user's | |
1034 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
1033 | .ipython/ directory with the mode parameter. Valid modes are 'install' | |
1035 | and 'upgrade'.""" |
|
1034 | and 'upgrade'.""" | |
1036 |
|
1035 | |||
1037 | def wait(): |
|
1036 | def wait(): | |
1038 | try: |
|
1037 | try: | |
1039 | raw_input("Please press <RETURN> to start IPython.") |
|
1038 | raw_input("Please press <RETURN> to start IPython.") | |
1040 | except EOFError: |
|
1039 | except EOFError: | |
1041 | print >> Term.cout |
|
1040 | print >> Term.cout | |
1042 | print '*'*70 |
|
1041 | print '*'*70 | |
1043 |
|
1042 | |||
1044 | cwd = os.getcwd() # remember where we started |
|
1043 | cwd = os.getcwd() # remember where we started | |
1045 | glb = glob.glob |
|
1044 | glb = glob.glob | |
1046 | print '*'*70 |
|
1045 | print '*'*70 | |
1047 | if mode == 'install': |
|
1046 | if mode == 'install': | |
1048 | print \ |
|
1047 | print \ | |
1049 | """Welcome to IPython. I will try to create a personal configuration directory |
|
1048 | """Welcome to IPython. I will try to create a personal configuration directory | |
1050 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1049 | where you can customize many aspects of IPython's functionality in:\n""" | |
1051 | else: |
|
1050 | else: | |
1052 | print 'I am going to upgrade your configuration in:' |
|
1051 | print 'I am going to upgrade your configuration in:' | |
1053 |
|
1052 | |||
1054 | print ipythondir |
|
1053 | print ipythondir | |
1055 |
|
1054 | |||
1056 | rcdirend = os.path.join('IPython','UserConfig') |
|
1055 | rcdirend = os.path.join('IPython','UserConfig') | |
1057 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1056 | cfg = lambda d: os.path.join(d,rcdirend) | |
1058 | try: |
|
1057 | try: | |
1059 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1058 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
1060 | except IOError: |
|
1059 | except IOError: | |
1061 | warning = """ |
|
1060 | warning = """ | |
1062 | Installation error. IPython's directory was not found. |
|
1061 | Installation error. IPython's directory was not found. | |
1063 |
|
1062 | |||
1064 | Check the following: |
|
1063 | Check the following: | |
1065 |
|
1064 | |||
1066 | The ipython/IPython directory should be in a directory belonging to your |
|
1065 | The ipython/IPython directory should be in a directory belonging to your | |
1067 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1066 | PYTHONPATH environment variable (that is, it should be in a directory | |
1068 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1067 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
1069 |
|
1068 | |||
1070 | IPython will proceed with builtin defaults. |
|
1069 | IPython will proceed with builtin defaults. | |
1071 | """ |
|
1070 | """ | |
1072 | warn(warning) |
|
1071 | warn(warning) | |
1073 | wait() |
|
1072 | wait() | |
1074 | return |
|
1073 | return | |
1075 |
|
1074 | |||
1076 | if mode == 'install': |
|
1075 | if mode == 'install': | |
1077 | try: |
|
1076 | try: | |
1078 | shutil.copytree(rcdir,ipythondir) |
|
1077 | shutil.copytree(rcdir,ipythondir) | |
1079 | os.chdir(ipythondir) |
|
1078 | os.chdir(ipythondir) | |
1080 | rc_files = glb("ipythonrc*") |
|
1079 | rc_files = glb("ipythonrc*") | |
1081 | for rc_file in rc_files: |
|
1080 | for rc_file in rc_files: | |
1082 | os.rename(rc_file,rc_file+rc_suffix) |
|
1081 | os.rename(rc_file,rc_file+rc_suffix) | |
1083 | except: |
|
1082 | except: | |
1084 | warning = """ |
|
1083 | warning = """ | |
1085 |
|
1084 | |||
1086 | There was a problem with the installation: |
|
1085 | There was a problem with the installation: | |
1087 | %s |
|
1086 | %s | |
1088 | Try to correct it or contact the developers if you think it's a bug. |
|
1087 | Try to correct it or contact the developers if you think it's a bug. | |
1089 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1088 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
1090 | warn(warning) |
|
1089 | warn(warning) | |
1091 | wait() |
|
1090 | wait() | |
1092 | return |
|
1091 | return | |
1093 |
|
1092 | |||
1094 | elif mode == 'upgrade': |
|
1093 | elif mode == 'upgrade': | |
1095 | try: |
|
1094 | try: | |
1096 | os.chdir(ipythondir) |
|
1095 | os.chdir(ipythondir) | |
1097 | except: |
|
1096 | except: | |
1098 | print """ |
|
1097 | print """ | |
1099 | Can not upgrade: changing to directory %s failed. Details: |
|
1098 | Can not upgrade: changing to directory %s failed. Details: | |
1100 | %s |
|
1099 | %s | |
1101 | """ % (ipythondir,sys.exc_info()[1]) |
|
1100 | """ % (ipythondir,sys.exc_info()[1]) | |
1102 | wait() |
|
1101 | wait() | |
1103 | return |
|
1102 | return | |
1104 | else: |
|
1103 | else: | |
1105 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1104 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
1106 | for new_full_path in sources: |
|
1105 | for new_full_path in sources: | |
1107 | new_filename = os.path.basename(new_full_path) |
|
1106 | new_filename = os.path.basename(new_full_path) | |
1108 | if new_filename.startswith('ipythonrc'): |
|
1107 | if new_filename.startswith('ipythonrc'): | |
1109 | new_filename = new_filename + rc_suffix |
|
1108 | new_filename = new_filename + rc_suffix | |
1110 | # The config directory should only contain files, skip any |
|
1109 | # The config directory should only contain files, skip any | |
1111 | # directories which may be there (like CVS) |
|
1110 | # directories which may be there (like CVS) | |
1112 | if os.path.isdir(new_full_path): |
|
1111 | if os.path.isdir(new_full_path): | |
1113 | continue |
|
1112 | continue | |
1114 | if os.path.exists(new_filename): |
|
1113 | if os.path.exists(new_filename): | |
1115 | old_file = new_filename+'.old' |
|
1114 | old_file = new_filename+'.old' | |
1116 | if os.path.exists(old_file): |
|
1115 | if os.path.exists(old_file): | |
1117 | os.remove(old_file) |
|
1116 | os.remove(old_file) | |
1118 | os.rename(new_filename,old_file) |
|
1117 | os.rename(new_filename,old_file) | |
1119 | shutil.copy(new_full_path,new_filename) |
|
1118 | shutil.copy(new_full_path,new_filename) | |
1120 | else: |
|
1119 | else: | |
1121 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1120 | raise ValueError,'unrecognized mode for install:',`mode` | |
1122 |
|
1121 | |||
1123 | # Fix line-endings to those native to each platform in the config |
|
1122 | # Fix line-endings to those native to each platform in the config | |
1124 | # directory. |
|
1123 | # directory. | |
1125 | try: |
|
1124 | try: | |
1126 | os.chdir(ipythondir) |
|
1125 | os.chdir(ipythondir) | |
1127 | except: |
|
1126 | except: | |
1128 | print """ |
|
1127 | print """ | |
1129 | Problem: changing to directory %s failed. |
|
1128 | Problem: changing to directory %s failed. | |
1130 | Details: |
|
1129 | Details: | |
1131 | %s |
|
1130 | %s | |
1132 |
|
1131 | |||
1133 | Some configuration files may have incorrect line endings. This should not |
|
1132 | Some configuration files may have incorrect line endings. This should not | |
1134 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1133 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) | |
1135 | wait() |
|
1134 | wait() | |
1136 | else: |
|
1135 | else: | |
1137 | for fname in glb('ipythonrc*'): |
|
1136 | for fname in glb('ipythonrc*'): | |
1138 | try: |
|
1137 | try: | |
1139 | native_line_ends(fname,backup=0) |
|
1138 | native_line_ends(fname,backup=0) | |
1140 | except IOError: |
|
1139 | except IOError: | |
1141 | pass |
|
1140 | pass | |
1142 |
|
1141 | |||
1143 | if mode == 'install': |
|
1142 | if mode == 'install': | |
1144 | print """ |
|
1143 | print """ | |
1145 | Successful installation! |
|
1144 | Successful installation! | |
1146 |
|
1145 | |||
1147 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1146 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
1148 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1147 | IPython manual (there are both HTML and PDF versions supplied with the | |
1149 | distribution) to make sure that your system environment is properly configured |
|
1148 | distribution) to make sure that your system environment is properly configured | |
1150 | to take advantage of IPython's features. |
|
1149 | to take advantage of IPython's features. | |
1151 |
|
1150 | |||
1152 | Important note: the configuration system has changed! The old system is |
|
1151 | Important note: the configuration system has changed! The old system is | |
1153 | still in place, but its setting may be partly overridden by the settings in |
|
1152 | still in place, but its setting may be partly overridden by the settings in | |
1154 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
1153 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |
1155 | if some of the new settings bother you. |
|
1154 | if some of the new settings bother you. | |
1156 |
|
1155 | |||
1157 | """ |
|
1156 | """ | |
1158 | else: |
|
1157 | else: | |
1159 | print """ |
|
1158 | print """ | |
1160 | Successful upgrade! |
|
1159 | Successful upgrade! | |
1161 |
|
1160 | |||
1162 | All files in your directory: |
|
1161 | All files in your directory: | |
1163 | %(ipythondir)s |
|
1162 | %(ipythondir)s | |
1164 | which would have been overwritten by the upgrade were backed up with a .old |
|
1163 | which would have been overwritten by the upgrade were backed up with a .old | |
1165 | extension. If you had made particular customizations in those files you may |
|
1164 | extension. If you had made particular customizations in those files you may | |
1166 | want to merge them back into the new files.""" % locals() |
|
1165 | want to merge them back into the new files.""" % locals() | |
1167 | wait() |
|
1166 | wait() | |
1168 | os.chdir(cwd) |
|
1167 | os.chdir(cwd) | |
1169 | # end user_setup() |
|
1168 | # end user_setup() | |
1170 |
|
1169 | |||
1171 | def atexit_operations(self): |
|
1170 | def atexit_operations(self): | |
1172 | """This will be executed at the time of exit. |
|
1171 | """This will be executed at the time of exit. | |
1173 |
|
1172 | |||
1174 | Saving of persistent data should be performed here. """ |
|
1173 | Saving of persistent data should be performed here. """ | |
1175 |
|
1174 | |||
1176 | #print '*** IPython exit cleanup ***' # dbg |
|
1175 | #print '*** IPython exit cleanup ***' # dbg | |
1177 | # input history |
|
1176 | # input history | |
1178 | self.savehist() |
|
1177 | self.savehist() | |
1179 |
|
1178 | |||
1180 | # Cleanup all tempfiles left around |
|
1179 | # Cleanup all tempfiles left around | |
1181 | for tfile in self.tempfiles: |
|
1180 | for tfile in self.tempfiles: | |
1182 | try: |
|
1181 | try: | |
1183 | os.unlink(tfile) |
|
1182 | os.unlink(tfile) | |
1184 | except OSError: |
|
1183 | except OSError: | |
1185 | pass |
|
1184 | pass | |
1186 |
|
1185 | |||
1187 | # save the "persistent data" catch-all dictionary |
|
1186 | # save the "persistent data" catch-all dictionary | |
1188 | self.hooks.shutdown_hook() |
|
1187 | self.hooks.shutdown_hook() | |
1189 |
|
1188 | |||
1190 | def savehist(self): |
|
1189 | def savehist(self): | |
1191 | """Save input history to a file (via readline library).""" |
|
1190 | """Save input history to a file (via readline library).""" | |
1192 | try: |
|
1191 | try: | |
1193 | self.readline.write_history_file(self.histfile) |
|
1192 | self.readline.write_history_file(self.histfile) | |
1194 | except: |
|
1193 | except: | |
1195 | print 'Unable to save IPython command history to file: ' + \ |
|
1194 | print 'Unable to save IPython command history to file: ' + \ | |
1196 | `self.histfile` |
|
1195 | `self.histfile` | |
1197 |
|
1196 | |||
1198 | def pre_readline(self): |
|
1197 | def pre_readline(self): | |
1199 | """readline hook to be used at the start of each line. |
|
1198 | """readline hook to be used at the start of each line. | |
1200 |
|
1199 | |||
1201 | Currently it handles auto-indent only.""" |
|
1200 | Currently it handles auto-indent only.""" | |
1202 |
|
1201 | |||
1203 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1202 | #debugx('self.indent_current_nsp','pre_readline:') | |
1204 | self.readline.insert_text(self.indent_current_str()) |
|
1203 | self.readline.insert_text(self.indent_current_str()) | |
1205 |
|
1204 | |||
1206 | def init_readline(self): |
|
1205 | def init_readline(self): | |
1207 | """Command history completion/saving/reloading.""" |
|
1206 | """Command history completion/saving/reloading.""" | |
1208 |
|
1207 | |||
1209 | import IPython.rlineimpl as readline |
|
1208 | import IPython.rlineimpl as readline | |
1210 | if not readline.have_readline: |
|
1209 | if not readline.have_readline: | |
1211 | self.has_readline = 0 |
|
1210 | self.has_readline = 0 | |
1212 | self.readline = None |
|
1211 | self.readline = None | |
1213 | # no point in bugging windows users with this every time: |
|
1212 | # no point in bugging windows users with this every time: | |
1214 | warn('Readline services not available on this platform.') |
|
1213 | warn('Readline services not available on this platform.') | |
1215 | else: |
|
1214 | else: | |
1216 | sys.modules['readline'] = readline |
|
1215 | sys.modules['readline'] = readline | |
1217 | import atexit |
|
1216 | import atexit | |
1218 | from IPython.completer import IPCompleter |
|
1217 | from IPython.completer import IPCompleter | |
1219 | self.Completer = IPCompleter(self, |
|
1218 | self.Completer = IPCompleter(self, | |
1220 | self.user_ns, |
|
1219 | self.user_ns, | |
1221 | self.user_global_ns, |
|
1220 | self.user_global_ns, | |
1222 | self.rc.readline_omit__names, |
|
1221 | self.rc.readline_omit__names, | |
1223 | self.alias_table) |
|
1222 | self.alias_table) | |
1224 |
|
1223 | |||
1225 | # Platform-specific configuration |
|
1224 | # Platform-specific configuration | |
1226 | if os.name == 'nt': |
|
1225 | if os.name == 'nt': | |
1227 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1226 | self.readline_startup_hook = readline.set_pre_input_hook | |
1228 | else: |
|
1227 | else: | |
1229 | self.readline_startup_hook = readline.set_startup_hook |
|
1228 | self.readline_startup_hook = readline.set_startup_hook | |
1230 |
|
1229 | |||
1231 | # Load user's initrc file (readline config) |
|
1230 | # Load user's initrc file (readline config) | |
1232 | inputrc_name = os.environ.get('INPUTRC') |
|
1231 | inputrc_name = os.environ.get('INPUTRC') | |
1233 | if inputrc_name is None: |
|
1232 | if inputrc_name is None: | |
1234 | home_dir = get_home_dir() |
|
1233 | home_dir = get_home_dir() | |
1235 | if home_dir is not None: |
|
1234 | if home_dir is not None: | |
1236 | inputrc_name = os.path.join(home_dir,'.inputrc') |
|
1235 | inputrc_name = os.path.join(home_dir,'.inputrc') | |
1237 | if os.path.isfile(inputrc_name): |
|
1236 | if os.path.isfile(inputrc_name): | |
1238 | try: |
|
1237 | try: | |
1239 | readline.read_init_file(inputrc_name) |
|
1238 | readline.read_init_file(inputrc_name) | |
1240 | except: |
|
1239 | except: | |
1241 | warn('Problems reading readline initialization file <%s>' |
|
1240 | warn('Problems reading readline initialization file <%s>' | |
1242 | % inputrc_name) |
|
1241 | % inputrc_name) | |
1243 |
|
1242 | |||
1244 | self.has_readline = 1 |
|
1243 | self.has_readline = 1 | |
1245 | self.readline = readline |
|
1244 | self.readline = readline | |
1246 | # save this in sys so embedded copies can restore it properly |
|
1245 | # save this in sys so embedded copies can restore it properly | |
1247 | sys.ipcompleter = self.Completer.complete |
|
1246 | sys.ipcompleter = self.Completer.complete | |
1248 | readline.set_completer(self.Completer.complete) |
|
1247 | readline.set_completer(self.Completer.complete) | |
1249 |
|
1248 | |||
1250 | # Configure readline according to user's prefs |
|
1249 | # Configure readline according to user's prefs | |
1251 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1250 | for rlcommand in self.rc.readline_parse_and_bind: | |
1252 | readline.parse_and_bind(rlcommand) |
|
1251 | readline.parse_and_bind(rlcommand) | |
1253 |
|
1252 | |||
1254 | # remove some chars from the delimiters list |
|
1253 | # remove some chars from the delimiters list | |
1255 | delims = readline.get_completer_delims() |
|
1254 | delims = readline.get_completer_delims() | |
1256 | delims = delims.translate(string._idmap, |
|
1255 | delims = delims.translate(string._idmap, | |
1257 | self.rc.readline_remove_delims) |
|
1256 | self.rc.readline_remove_delims) | |
1258 | readline.set_completer_delims(delims) |
|
1257 | readline.set_completer_delims(delims) | |
1259 | # otherwise we end up with a monster history after a while: |
|
1258 | # otherwise we end up with a monster history after a while: | |
1260 | readline.set_history_length(1000) |
|
1259 | readline.set_history_length(1000) | |
1261 | try: |
|
1260 | try: | |
1262 | #print '*** Reading readline history' # dbg |
|
1261 | #print '*** Reading readline history' # dbg | |
1263 | readline.read_history_file(self.histfile) |
|
1262 | readline.read_history_file(self.histfile) | |
1264 | except IOError: |
|
1263 | except IOError: | |
1265 | pass # It doesn't exist yet. |
|
1264 | pass # It doesn't exist yet. | |
1266 |
|
1265 | |||
1267 | atexit.register(self.atexit_operations) |
|
1266 | atexit.register(self.atexit_operations) | |
1268 | del atexit |
|
1267 | del atexit | |
1269 |
|
1268 | |||
1270 | # Configure auto-indent for all platforms |
|
1269 | # Configure auto-indent for all platforms | |
1271 | self.set_autoindent(self.rc.autoindent) |
|
1270 | self.set_autoindent(self.rc.autoindent) | |
1272 |
|
1271 | |||
1273 | def ask_yes_no(self,prompt,default=True): |
|
1272 | def ask_yes_no(self,prompt,default=True): | |
1274 | if self.rc.quiet: |
|
1273 | if self.rc.quiet: | |
1275 | return True |
|
1274 | return True | |
1276 | return ask_yes_no(prompt,default) |
|
1275 | return ask_yes_no(prompt,default) | |
1277 |
|
1276 | |||
1278 | def _should_recompile(self,e): |
|
1277 | def _should_recompile(self,e): | |
1279 | """Utility routine for edit_syntax_error""" |
|
1278 | """Utility routine for edit_syntax_error""" | |
1280 |
|
1279 | |||
1281 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1280 | if e.filename in ('<ipython console>','<input>','<string>', | |
1282 | '<console>','<BackgroundJob compilation>', |
|
1281 | '<console>','<BackgroundJob compilation>', | |
1283 | None): |
|
1282 | None): | |
1284 |
|
1283 | |||
1285 | return False |
|
1284 | return False | |
1286 | try: |
|
1285 | try: | |
1287 | if (self.rc.autoedit_syntax and |
|
1286 | if (self.rc.autoedit_syntax and | |
1288 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1287 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1289 | '[Y/n] ','y')): |
|
1288 | '[Y/n] ','y')): | |
1290 | return False |
|
1289 | return False | |
1291 | except EOFError: |
|
1290 | except EOFError: | |
1292 | return False |
|
1291 | return False | |
1293 |
|
1292 | |||
1294 | def int0(x): |
|
1293 | def int0(x): | |
1295 | try: |
|
1294 | try: | |
1296 | return int(x) |
|
1295 | return int(x) | |
1297 | except TypeError: |
|
1296 | except TypeError: | |
1298 | return 0 |
|
1297 | return 0 | |
1299 | # always pass integer line and offset values to editor hook |
|
1298 | # always pass integer line and offset values to editor hook | |
1300 | self.hooks.fix_error_editor(e.filename, |
|
1299 | self.hooks.fix_error_editor(e.filename, | |
1301 | int0(e.lineno),int0(e.offset),e.msg) |
|
1300 | int0(e.lineno),int0(e.offset),e.msg) | |
1302 | return True |
|
1301 | return True | |
1303 |
|
1302 | |||
1304 | def edit_syntax_error(self): |
|
1303 | def edit_syntax_error(self): | |
1305 | """The bottom half of the syntax error handler called in the main loop. |
|
1304 | """The bottom half of the syntax error handler called in the main loop. | |
1306 |
|
1305 | |||
1307 | Loop until syntax error is fixed or user cancels. |
|
1306 | Loop until syntax error is fixed or user cancels. | |
1308 | """ |
|
1307 | """ | |
1309 |
|
1308 | |||
1310 | while self.SyntaxTB.last_syntax_error: |
|
1309 | while self.SyntaxTB.last_syntax_error: | |
1311 | # copy and clear last_syntax_error |
|
1310 | # copy and clear last_syntax_error | |
1312 | err = self.SyntaxTB.clear_err_state() |
|
1311 | err = self.SyntaxTB.clear_err_state() | |
1313 | if not self._should_recompile(err): |
|
1312 | if not self._should_recompile(err): | |
1314 | return |
|
1313 | return | |
1315 | try: |
|
1314 | try: | |
1316 | # may set last_syntax_error again if a SyntaxError is raised |
|
1315 | # may set last_syntax_error again if a SyntaxError is raised | |
1317 | self.safe_execfile(err.filename,self.user_ns) |
|
1316 | self.safe_execfile(err.filename,self.user_ns) | |
1318 | except: |
|
1317 | except: | |
1319 | self.showtraceback() |
|
1318 | self.showtraceback() | |
1320 | else: |
|
1319 | else: | |
1321 | try: |
|
1320 | try: | |
1322 | f = file(err.filename) |
|
1321 | f = file(err.filename) | |
1323 | try: |
|
1322 | try: | |
1324 | sys.displayhook(f.read()) |
|
1323 | sys.displayhook(f.read()) | |
1325 | finally: |
|
1324 | finally: | |
1326 | f.close() |
|
1325 | f.close() | |
1327 | except: |
|
1326 | except: | |
1328 | self.showtraceback() |
|
1327 | self.showtraceback() | |
1329 |
|
1328 | |||
1330 | def showsyntaxerror(self, filename=None): |
|
1329 | def showsyntaxerror(self, filename=None): | |
1331 | """Display the syntax error that just occurred. |
|
1330 | """Display the syntax error that just occurred. | |
1332 |
|
1331 | |||
1333 | This doesn't display a stack trace because there isn't one. |
|
1332 | This doesn't display a stack trace because there isn't one. | |
1334 |
|
1333 | |||
1335 | If a filename is given, it is stuffed in the exception instead |
|
1334 | If a filename is given, it is stuffed in the exception instead | |
1336 | of what was there before (because Python's parser always uses |
|
1335 | of what was there before (because Python's parser always uses | |
1337 | "<string>" when reading from a string). |
|
1336 | "<string>" when reading from a string). | |
1338 | """ |
|
1337 | """ | |
1339 | etype, value, last_traceback = sys.exc_info() |
|
1338 | etype, value, last_traceback = sys.exc_info() | |
1340 |
|
1339 | |||
1341 | # See note about these variables in showtraceback() below |
|
1340 | # See note about these variables in showtraceback() below | |
1342 | sys.last_type = etype |
|
1341 | sys.last_type = etype | |
1343 | sys.last_value = value |
|
1342 | sys.last_value = value | |
1344 | sys.last_traceback = last_traceback |
|
1343 | sys.last_traceback = last_traceback | |
1345 |
|
1344 | |||
1346 | if filename and etype is SyntaxError: |
|
1345 | if filename and etype is SyntaxError: | |
1347 | # Work hard to stuff the correct filename in the exception |
|
1346 | # Work hard to stuff the correct filename in the exception | |
1348 | try: |
|
1347 | try: | |
1349 | msg, (dummy_filename, lineno, offset, line) = value |
|
1348 | msg, (dummy_filename, lineno, offset, line) = value | |
1350 | except: |
|
1349 | except: | |
1351 | # Not the format we expect; leave it alone |
|
1350 | # Not the format we expect; leave it alone | |
1352 | pass |
|
1351 | pass | |
1353 | else: |
|
1352 | else: | |
1354 | # Stuff in the right filename |
|
1353 | # Stuff in the right filename | |
1355 | try: |
|
1354 | try: | |
1356 | # Assume SyntaxError is a class exception |
|
1355 | # Assume SyntaxError is a class exception | |
1357 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1356 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1358 | except: |
|
1357 | except: | |
1359 | # If that failed, assume SyntaxError is a string |
|
1358 | # If that failed, assume SyntaxError is a string | |
1360 | value = msg, (filename, lineno, offset, line) |
|
1359 | value = msg, (filename, lineno, offset, line) | |
1361 | self.SyntaxTB(etype,value,[]) |
|
1360 | self.SyntaxTB(etype,value,[]) | |
1362 |
|
1361 | |||
1363 | def debugger(self): |
|
1362 | def debugger(self): | |
1364 | """Call the pdb debugger.""" |
|
1363 | """Call the pydb/pdb debugger.""" | |
1365 |
|
1364 | |||
1366 | if not self.rc.pdb: |
|
1365 | if not self.rc.pdb: | |
1367 | return |
|
1366 | return | |
1368 | pdb.pm() |
|
1367 | have_pydb = False | |
|
1368 | if sys.version[:3] >= '2.5': | |||
|
1369 | try: | |||
|
1370 | from pydb import pm | |||
|
1371 | have_pydb = True | |||
|
1372 | except ImportError: | |||
|
1373 | pass | |||
|
1374 | if not have_pydb: | |||
|
1375 | from pdb import pm | |||
|
1376 | pm() | |||
1369 |
|
1377 | |||
1370 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1378 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1371 | """Display the exception that just occurred. |
|
1379 | """Display the exception that just occurred. | |
1372 |
|
1380 | |||
1373 | If nothing is known about the exception, this is the method which |
|
1381 | If nothing is known about the exception, this is the method which | |
1374 | should be used throughout the code for presenting user tracebacks, |
|
1382 | should be used throughout the code for presenting user tracebacks, | |
1375 | rather than directly invoking the InteractiveTB object. |
|
1383 | rather than directly invoking the InteractiveTB object. | |
1376 |
|
1384 | |||
1377 | A specific showsyntaxerror() also exists, but this method can take |
|
1385 | A specific showsyntaxerror() also exists, but this method can take | |
1378 | care of calling it if needed, so unless you are explicitly catching a |
|
1386 | care of calling it if needed, so unless you are explicitly catching a | |
1379 | SyntaxError exception, don't try to analyze the stack manually and |
|
1387 | SyntaxError exception, don't try to analyze the stack manually and | |
1380 | simply call this method.""" |
|
1388 | simply call this method.""" | |
1381 |
|
1389 | |||
1382 | # Though this won't be called by syntax errors in the input line, |
|
1390 | # Though this won't be called by syntax errors in the input line, | |
1383 | # there may be SyntaxError cases whith imported code. |
|
1391 | # there may be SyntaxError cases whith imported code. | |
1384 | if exc_tuple is None: |
|
1392 | if exc_tuple is None: | |
1385 | etype, value, tb = sys.exc_info() |
|
1393 | etype, value, tb = sys.exc_info() | |
1386 | else: |
|
1394 | else: | |
1387 | etype, value, tb = exc_tuple |
|
1395 | etype, value, tb = exc_tuple | |
1388 | if etype is SyntaxError: |
|
1396 | if etype is SyntaxError: | |
1389 | self.showsyntaxerror(filename) |
|
1397 | self.showsyntaxerror(filename) | |
1390 | else: |
|
1398 | else: | |
1391 | # WARNING: these variables are somewhat deprecated and not |
|
1399 | # WARNING: these variables are somewhat deprecated and not | |
1392 | # necessarily safe to use in a threaded environment, but tools |
|
1400 | # necessarily safe to use in a threaded environment, but tools | |
1393 | # like pdb depend on their existence, so let's set them. If we |
|
1401 | # like pdb depend on their existence, so let's set them. If we | |
1394 | # find problems in the field, we'll need to revisit their use. |
|
1402 | # find problems in the field, we'll need to revisit their use. | |
1395 | sys.last_type = etype |
|
1403 | sys.last_type = etype | |
1396 | sys.last_value = value |
|
1404 | sys.last_value = value | |
1397 | sys.last_traceback = tb |
|
1405 | sys.last_traceback = tb | |
1398 |
|
1406 | |||
1399 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1407 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1400 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1408 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1401 | # pdb mucks up readline, fix it back |
|
1409 | # pdb mucks up readline, fix it back | |
1402 | self.readline.set_completer(self.Completer.complete) |
|
1410 | self.readline.set_completer(self.Completer.complete) | |
1403 |
|
1411 | |||
1404 | def mainloop(self,banner=None): |
|
1412 | def mainloop(self,banner=None): | |
1405 | """Creates the local namespace and starts the mainloop. |
|
1413 | """Creates the local namespace and starts the mainloop. | |
1406 |
|
1414 | |||
1407 | If an optional banner argument is given, it will override the |
|
1415 | If an optional banner argument is given, it will override the | |
1408 | internally created default banner.""" |
|
1416 | internally created default banner.""" | |
1409 |
|
1417 | |||
1410 | if self.rc.c: # Emulate Python's -c option |
|
1418 | if self.rc.c: # Emulate Python's -c option | |
1411 | self.exec_init_cmd() |
|
1419 | self.exec_init_cmd() | |
1412 | if banner is None: |
|
1420 | if banner is None: | |
1413 | if not self.rc.banner: |
|
1421 | if not self.rc.banner: | |
1414 | banner = '' |
|
1422 | banner = '' | |
1415 | # banner is string? Use it directly! |
|
1423 | # banner is string? Use it directly! | |
1416 | elif isinstance(self.rc.banner,basestring): |
|
1424 | elif isinstance(self.rc.banner,basestring): | |
1417 | banner = self.rc.banner |
|
1425 | banner = self.rc.banner | |
1418 | else: |
|
1426 | else: | |
1419 | banner = self.BANNER+self.banner2 |
|
1427 | banner = self.BANNER+self.banner2 | |
1420 |
|
1428 | |||
1421 | self.interact(banner) |
|
1429 | self.interact(banner) | |
1422 |
|
1430 | |||
1423 | def exec_init_cmd(self): |
|
1431 | def exec_init_cmd(self): | |
1424 | """Execute a command given at the command line. |
|
1432 | """Execute a command given at the command line. | |
1425 |
|
1433 | |||
1426 | This emulates Python's -c option.""" |
|
1434 | This emulates Python's -c option.""" | |
1427 |
|
1435 | |||
1428 | #sys.argv = ['-c'] |
|
1436 | #sys.argv = ['-c'] | |
1429 | self.push(self.rc.c) |
|
1437 | self.push(self.rc.c) | |
1430 |
|
1438 | |||
1431 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1439 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1432 | """Embeds IPython into a running python program. |
|
1440 | """Embeds IPython into a running python program. | |
1433 |
|
1441 | |||
1434 | Input: |
|
1442 | Input: | |
1435 |
|
1443 | |||
1436 | - header: An optional header message can be specified. |
|
1444 | - header: An optional header message can be specified. | |
1437 |
|
1445 | |||
1438 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1446 | - local_ns, global_ns: working namespaces. If given as None, the | |
1439 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1447 | IPython-initialized one is updated with __main__.__dict__, so that | |
1440 | program variables become visible but user-specific configuration |
|
1448 | program variables become visible but user-specific configuration | |
1441 | remains possible. |
|
1449 | remains possible. | |
1442 |
|
1450 | |||
1443 | - stack_depth: specifies how many levels in the stack to go to |
|
1451 | - stack_depth: specifies how many levels in the stack to go to | |
1444 | looking for namespaces (when local_ns and global_ns are None). This |
|
1452 | looking for namespaces (when local_ns and global_ns are None). This | |
1445 | allows an intermediate caller to make sure that this function gets |
|
1453 | allows an intermediate caller to make sure that this function gets | |
1446 | the namespace from the intended level in the stack. By default (0) |
|
1454 | the namespace from the intended level in the stack. By default (0) | |
1447 | it will get its locals and globals from the immediate caller. |
|
1455 | it will get its locals and globals from the immediate caller. | |
1448 |
|
1456 | |||
1449 | Warning: it's possible to use this in a program which is being run by |
|
1457 | Warning: it's possible to use this in a program which is being run by | |
1450 | IPython itself (via %run), but some funny things will happen (a few |
|
1458 | IPython itself (via %run), but some funny things will happen (a few | |
1451 | globals get overwritten). In the future this will be cleaned up, as |
|
1459 | globals get overwritten). In the future this will be cleaned up, as | |
1452 | there is no fundamental reason why it can't work perfectly.""" |
|
1460 | there is no fundamental reason why it can't work perfectly.""" | |
1453 |
|
1461 | |||
1454 | # Get locals and globals from caller |
|
1462 | # Get locals and globals from caller | |
1455 | if local_ns is None or global_ns is None: |
|
1463 | if local_ns is None or global_ns is None: | |
1456 | call_frame = sys._getframe(stack_depth).f_back |
|
1464 | call_frame = sys._getframe(stack_depth).f_back | |
1457 |
|
1465 | |||
1458 | if local_ns is None: |
|
1466 | if local_ns is None: | |
1459 | local_ns = call_frame.f_locals |
|
1467 | local_ns = call_frame.f_locals | |
1460 | if global_ns is None: |
|
1468 | if global_ns is None: | |
1461 | global_ns = call_frame.f_globals |
|
1469 | global_ns = call_frame.f_globals | |
1462 |
|
1470 | |||
1463 | # Update namespaces and fire up interpreter |
|
1471 | # Update namespaces and fire up interpreter | |
1464 |
|
1472 | |||
1465 | # The global one is easy, we can just throw it in |
|
1473 | # The global one is easy, we can just throw it in | |
1466 | self.user_global_ns = global_ns |
|
1474 | self.user_global_ns = global_ns | |
1467 |
|
1475 | |||
1468 | # but the user/local one is tricky: ipython needs it to store internal |
|
1476 | # but the user/local one is tricky: ipython needs it to store internal | |
1469 | # data, but we also need the locals. We'll copy locals in the user |
|
1477 | # data, but we also need the locals. We'll copy locals in the user | |
1470 | # one, but will track what got copied so we can delete them at exit. |
|
1478 | # one, but will track what got copied so we can delete them at exit. | |
1471 | # This is so that a later embedded call doesn't see locals from a |
|
1479 | # This is so that a later embedded call doesn't see locals from a | |
1472 | # previous call (which most likely existed in a separate scope). |
|
1480 | # previous call (which most likely existed in a separate scope). | |
1473 | local_varnames = local_ns.keys() |
|
1481 | local_varnames = local_ns.keys() | |
1474 | self.user_ns.update(local_ns) |
|
1482 | self.user_ns.update(local_ns) | |
1475 |
|
1483 | |||
1476 | # Patch for global embedding to make sure that things don't overwrite |
|
1484 | # Patch for global embedding to make sure that things don't overwrite | |
1477 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1485 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1478 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1486 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1479 | if local_ns is None and global_ns is None: |
|
1487 | if local_ns is None and global_ns is None: | |
1480 | self.user_global_ns.update(__main__.__dict__) |
|
1488 | self.user_global_ns.update(__main__.__dict__) | |
1481 |
|
1489 | |||
1482 | # make sure the tab-completer has the correct frame information, so it |
|
1490 | # make sure the tab-completer has the correct frame information, so it | |
1483 | # actually completes using the frame's locals/globals |
|
1491 | # actually completes using the frame's locals/globals | |
1484 | self.set_completer_frame() |
|
1492 | self.set_completer_frame() | |
1485 |
|
1493 | |||
1486 | # before activating the interactive mode, we need to make sure that |
|
1494 | # before activating the interactive mode, we need to make sure that | |
1487 | # all names in the builtin namespace needed by ipython point to |
|
1495 | # all names in the builtin namespace needed by ipython point to | |
1488 | # ourselves, and not to other instances. |
|
1496 | # ourselves, and not to other instances. | |
1489 | self.add_builtins() |
|
1497 | self.add_builtins() | |
1490 |
|
1498 | |||
1491 | self.interact(header) |
|
1499 | self.interact(header) | |
1492 |
|
1500 | |||
1493 | # now, purge out the user namespace from anything we might have added |
|
1501 | # now, purge out the user namespace from anything we might have added | |
1494 | # from the caller's local namespace |
|
1502 | # from the caller's local namespace | |
1495 | delvar = self.user_ns.pop |
|
1503 | delvar = self.user_ns.pop | |
1496 | for var in local_varnames: |
|
1504 | for var in local_varnames: | |
1497 | delvar(var,None) |
|
1505 | delvar(var,None) | |
1498 | # and clean builtins we may have overridden |
|
1506 | # and clean builtins we may have overridden | |
1499 | self.clean_builtins() |
|
1507 | self.clean_builtins() | |
1500 |
|
1508 | |||
1501 | def interact(self, banner=None): |
|
1509 | def interact(self, banner=None): | |
1502 | """Closely emulate the interactive Python console. |
|
1510 | """Closely emulate the interactive Python console. | |
1503 |
|
1511 | |||
1504 | The optional banner argument specify the banner to print |
|
1512 | The optional banner argument specify the banner to print | |
1505 | before the first interaction; by default it prints a banner |
|
1513 | before the first interaction; by default it prints a banner | |
1506 | similar to the one printed by the real Python interpreter, |
|
1514 | similar to the one printed by the real Python interpreter, | |
1507 | followed by the current class name in parentheses (so as not |
|
1515 | followed by the current class name in parentheses (so as not | |
1508 | to confuse this with the real interpreter -- since it's so |
|
1516 | to confuse this with the real interpreter -- since it's so | |
1509 | close!). |
|
1517 | close!). | |
1510 |
|
1518 | |||
1511 | """ |
|
1519 | """ | |
1512 |
|
1520 | |||
1513 | if self.exit_now: |
|
1521 | if self.exit_now: | |
1514 | # batch run -> do not interact |
|
1522 | # batch run -> do not interact | |
1515 | return |
|
1523 | return | |
1516 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1524 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1517 | if banner is None: |
|
1525 | if banner is None: | |
1518 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1526 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1519 | (sys.version, sys.platform, cprt, |
|
1527 | (sys.version, sys.platform, cprt, | |
1520 | self.__class__.__name__)) |
|
1528 | self.__class__.__name__)) | |
1521 | else: |
|
1529 | else: | |
1522 | self.write(banner) |
|
1530 | self.write(banner) | |
1523 |
|
1531 | |||
1524 | more = 0 |
|
1532 | more = 0 | |
1525 |
|
1533 | |||
1526 | # Mark activity in the builtins |
|
1534 | # Mark activity in the builtins | |
1527 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1535 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1528 |
|
1536 | |||
1529 | # exit_now is set by a call to %Exit or %Quit |
|
1537 | # exit_now is set by a call to %Exit or %Quit | |
1530 | while not self.exit_now: |
|
1538 | while not self.exit_now: | |
1531 | if more: |
|
1539 | if more: | |
1532 | prompt = self.hooks.generate_prompt(True) |
|
1540 | prompt = self.hooks.generate_prompt(True) | |
1533 | if self.autoindent: |
|
1541 | if self.autoindent: | |
1534 | self.readline_startup_hook(self.pre_readline) |
|
1542 | self.readline_startup_hook(self.pre_readline) | |
1535 | else: |
|
1543 | else: | |
1536 | prompt = self.hooks.generate_prompt(False) |
|
1544 | prompt = self.hooks.generate_prompt(False) | |
1537 | try: |
|
1545 | try: | |
1538 | line = self.raw_input(prompt,more) |
|
1546 | line = self.raw_input(prompt,more) | |
1539 | if self.exit_now: |
|
1547 | if self.exit_now: | |
1540 | # quick exit on sys.std[in|out] close |
|
1548 | # quick exit on sys.std[in|out] close | |
1541 | break |
|
1549 | break | |
1542 | if self.autoindent: |
|
1550 | if self.autoindent: | |
1543 | self.readline_startup_hook(None) |
|
1551 | self.readline_startup_hook(None) | |
1544 | except KeyboardInterrupt: |
|
1552 | except KeyboardInterrupt: | |
1545 | self.write('\nKeyboardInterrupt\n') |
|
1553 | self.write('\nKeyboardInterrupt\n') | |
1546 | self.resetbuffer() |
|
1554 | self.resetbuffer() | |
1547 | # keep cache in sync with the prompt counter: |
|
1555 | # keep cache in sync with the prompt counter: | |
1548 | self.outputcache.prompt_count -= 1 |
|
1556 | self.outputcache.prompt_count -= 1 | |
1549 |
|
1557 | |||
1550 | if self.autoindent: |
|
1558 | if self.autoindent: | |
1551 | self.indent_current_nsp = 0 |
|
1559 | self.indent_current_nsp = 0 | |
1552 | more = 0 |
|
1560 | more = 0 | |
1553 | except EOFError: |
|
1561 | except EOFError: | |
1554 | if self.autoindent: |
|
1562 | if self.autoindent: | |
1555 | self.readline_startup_hook(None) |
|
1563 | self.readline_startup_hook(None) | |
1556 | self.write('\n') |
|
1564 | self.write('\n') | |
1557 | self.exit() |
|
1565 | self.exit() | |
1558 | except bdb.BdbQuit: |
|
1566 | except bdb.BdbQuit: | |
1559 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1567 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1560 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1568 | 'Because of how pdb handles the stack, it is impossible\n' | |
1561 | 'for IPython to properly format this particular exception.\n' |
|
1569 | 'for IPython to properly format this particular exception.\n' | |
1562 | 'IPython will resume normal operation.') |
|
1570 | 'IPython will resume normal operation.') | |
1563 | except: |
|
1571 | except: | |
1564 | # exceptions here are VERY RARE, but they can be triggered |
|
1572 | # exceptions here are VERY RARE, but they can be triggered | |
1565 | # asynchronously by signal handlers, for example. |
|
1573 | # asynchronously by signal handlers, for example. | |
1566 | self.showtraceback() |
|
1574 | self.showtraceback() | |
1567 | else: |
|
1575 | else: | |
1568 | more = self.push(line) |
|
1576 | more = self.push(line) | |
1569 | if (self.SyntaxTB.last_syntax_error and |
|
1577 | if (self.SyntaxTB.last_syntax_error and | |
1570 | self.rc.autoedit_syntax): |
|
1578 | self.rc.autoedit_syntax): | |
1571 | self.edit_syntax_error() |
|
1579 | self.edit_syntax_error() | |
1572 |
|
1580 | |||
1573 | # We are off again... |
|
1581 | # We are off again... | |
1574 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1582 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1575 |
|
1583 | |||
1576 | def excepthook(self, etype, value, tb): |
|
1584 | def excepthook(self, etype, value, tb): | |
1577 | """One more defense for GUI apps that call sys.excepthook. |
|
1585 | """One more defense for GUI apps that call sys.excepthook. | |
1578 |
|
1586 | |||
1579 | GUI frameworks like wxPython trap exceptions and call |
|
1587 | GUI frameworks like wxPython trap exceptions and call | |
1580 | sys.excepthook themselves. I guess this is a feature that |
|
1588 | sys.excepthook themselves. I guess this is a feature that | |
1581 | enables them to keep running after exceptions that would |
|
1589 | enables them to keep running after exceptions that would | |
1582 | otherwise kill their mainloop. This is a bother for IPython |
|
1590 | otherwise kill their mainloop. This is a bother for IPython | |
1583 | which excepts to catch all of the program exceptions with a try: |
|
1591 | which excepts to catch all of the program exceptions with a try: | |
1584 | except: statement. |
|
1592 | except: statement. | |
1585 |
|
1593 | |||
1586 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1594 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1587 | any app directly invokes sys.excepthook, it will look to the user like |
|
1595 | any app directly invokes sys.excepthook, it will look to the user like | |
1588 | IPython crashed. In order to work around this, we can disable the |
|
1596 | IPython crashed. In order to work around this, we can disable the | |
1589 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1597 | CrashHandler and replace it with this excepthook instead, which prints a | |
1590 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1598 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1591 | call sys.excepthook will generate a regular-looking exception from |
|
1599 | call sys.excepthook will generate a regular-looking exception from | |
1592 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1600 | IPython, and the CrashHandler will only be triggered by real IPython | |
1593 | crashes. |
|
1601 | crashes. | |
1594 |
|
1602 | |||
1595 | This hook should be used sparingly, only in places which are not likely |
|
1603 | This hook should be used sparingly, only in places which are not likely | |
1596 | to be true IPython errors. |
|
1604 | to be true IPython errors. | |
1597 | """ |
|
1605 | """ | |
1598 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1606 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1599 |
|
1607 | |||
1600 | def expand_aliases(self,fn,rest): |
|
1608 | def expand_aliases(self,fn,rest): | |
1601 | """ Expand multiple levels of aliases: |
|
1609 | """ Expand multiple levels of aliases: | |
1602 |
|
1610 | |||
1603 | if: |
|
1611 | if: | |
1604 |
|
1612 | |||
1605 | alias foo bar /tmp |
|
1613 | alias foo bar /tmp | |
1606 | alias baz foo |
|
1614 | alias baz foo | |
1607 |
|
1615 | |||
1608 | then: |
|
1616 | then: | |
1609 |
|
1617 | |||
1610 | baz huhhahhei -> bar /tmp huhhahhei |
|
1618 | baz huhhahhei -> bar /tmp huhhahhei | |
1611 |
|
1619 | |||
1612 | """ |
|
1620 | """ | |
1613 | line = fn + " " + rest |
|
1621 | line = fn + " " + rest | |
1614 |
|
1622 | |||
1615 | done = Set() |
|
1623 | done = Set() | |
1616 | while 1: |
|
1624 | while 1: | |
1617 | pre,fn,rest = self.split_user_input(line) |
|
1625 | pre,fn,rest = self.split_user_input(line) | |
1618 | if fn in self.alias_table: |
|
1626 | if fn in self.alias_table: | |
1619 | if fn in done: |
|
1627 | if fn in done: | |
1620 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
1628 | warn("Cyclic alias definition, repeated '%s'" % fn) | |
1621 | return "" |
|
1629 | return "" | |
1622 | done.add(fn) |
|
1630 | done.add(fn) | |
1623 |
|
1631 | |||
1624 | l2 = self.transform_alias(fn,rest) |
|
1632 | l2 = self.transform_alias(fn,rest) | |
1625 | # dir -> dir |
|
1633 | # dir -> dir | |
1626 | if l2 == line: |
|
1634 | if l2 == line: | |
1627 | break |
|
1635 | break | |
1628 | # ls -> ls -F should not recurse forever |
|
1636 | # ls -> ls -F should not recurse forever | |
1629 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
1637 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
1630 | line = l2 |
|
1638 | line = l2 | |
1631 | break |
|
1639 | break | |
1632 |
|
1640 | |||
1633 | line=l2 |
|
1641 | line=l2 | |
1634 |
|
1642 | |||
1635 |
|
1643 | |||
1636 | # print "al expand to",line #dbg |
|
1644 | # print "al expand to",line #dbg | |
1637 | else: |
|
1645 | else: | |
1638 | break |
|
1646 | break | |
1639 |
|
1647 | |||
1640 | return line |
|
1648 | return line | |
1641 |
|
1649 | |||
1642 | def transform_alias(self, alias,rest=''): |
|
1650 | def transform_alias(self, alias,rest=''): | |
1643 | """ Transform alias to system command string. |
|
1651 | """ Transform alias to system command string. | |
1644 | """ |
|
1652 | """ | |
1645 | nargs,cmd = self.alias_table[alias] |
|
1653 | nargs,cmd = self.alias_table[alias] | |
1646 | if ' ' in cmd and os.path.isfile(cmd): |
|
1654 | if ' ' in cmd and os.path.isfile(cmd): | |
1647 | cmd = '"%s"' % cmd |
|
1655 | cmd = '"%s"' % cmd | |
1648 |
|
1656 | |||
1649 | # Expand the %l special to be the user's input line |
|
1657 | # Expand the %l special to be the user's input line | |
1650 | if cmd.find('%l') >= 0: |
|
1658 | if cmd.find('%l') >= 0: | |
1651 | cmd = cmd.replace('%l',rest) |
|
1659 | cmd = cmd.replace('%l',rest) | |
1652 | rest = '' |
|
1660 | rest = '' | |
1653 | if nargs==0: |
|
1661 | if nargs==0: | |
1654 | # Simple, argument-less aliases |
|
1662 | # Simple, argument-less aliases | |
1655 | cmd = '%s %s' % (cmd,rest) |
|
1663 | cmd = '%s %s' % (cmd,rest) | |
1656 | else: |
|
1664 | else: | |
1657 | # Handle aliases with positional arguments |
|
1665 | # Handle aliases with positional arguments | |
1658 | args = rest.split(None,nargs) |
|
1666 | args = rest.split(None,nargs) | |
1659 | if len(args)< nargs: |
|
1667 | if len(args)< nargs: | |
1660 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1668 | error('Alias <%s> requires %s arguments, %s given.' % | |
1661 | (alias,nargs,len(args))) |
|
1669 | (alias,nargs,len(args))) | |
1662 | return None |
|
1670 | return None | |
1663 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1671 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
1664 | # Now call the macro, evaluating in the user's namespace |
|
1672 | # Now call the macro, evaluating in the user's namespace | |
1665 | #print 'new command: <%r>' % cmd # dbg |
|
1673 | #print 'new command: <%r>' % cmd # dbg | |
1666 | return cmd |
|
1674 | return cmd | |
1667 |
|
1675 | |||
1668 | def call_alias(self,alias,rest=''): |
|
1676 | def call_alias(self,alias,rest=''): | |
1669 | """Call an alias given its name and the rest of the line. |
|
1677 | """Call an alias given its name and the rest of the line. | |
1670 |
|
1678 | |||
1671 | This is only used to provide backwards compatibility for users of |
|
1679 | This is only used to provide backwards compatibility for users of | |
1672 | ipalias(), use of which is not recommended for anymore.""" |
|
1680 | ipalias(), use of which is not recommended for anymore.""" | |
1673 |
|
1681 | |||
1674 | # Now call the macro, evaluating in the user's namespace |
|
1682 | # Now call the macro, evaluating in the user's namespace | |
1675 | cmd = self.transform_alias(alias, rest) |
|
1683 | cmd = self.transform_alias(alias, rest) | |
1676 | try: |
|
1684 | try: | |
1677 | self.system(cmd) |
|
1685 | self.system(cmd) | |
1678 | except: |
|
1686 | except: | |
1679 | self.showtraceback() |
|
1687 | self.showtraceback() | |
1680 |
|
1688 | |||
1681 | def indent_current_str(self): |
|
1689 | def indent_current_str(self): | |
1682 | """return the current level of indentation as a string""" |
|
1690 | """return the current level of indentation as a string""" | |
1683 | return self.indent_current_nsp * ' ' |
|
1691 | return self.indent_current_nsp * ' ' | |
1684 |
|
1692 | |||
1685 | def autoindent_update(self,line): |
|
1693 | def autoindent_update(self,line): | |
1686 | """Keep track of the indent level.""" |
|
1694 | """Keep track of the indent level.""" | |
1687 |
|
1695 | |||
1688 | #debugx('line') |
|
1696 | #debugx('line') | |
1689 | #debugx('self.indent_current_nsp') |
|
1697 | #debugx('self.indent_current_nsp') | |
1690 | if self.autoindent: |
|
1698 | if self.autoindent: | |
1691 | if line: |
|
1699 | if line: | |
1692 | inisp = num_ini_spaces(line) |
|
1700 | inisp = num_ini_spaces(line) | |
1693 | if inisp < self.indent_current_nsp: |
|
1701 | if inisp < self.indent_current_nsp: | |
1694 | self.indent_current_nsp = inisp |
|
1702 | self.indent_current_nsp = inisp | |
1695 |
|
1703 | |||
1696 | if line[-1] == ':': |
|
1704 | if line[-1] == ':': | |
1697 | self.indent_current_nsp += 4 |
|
1705 | self.indent_current_nsp += 4 | |
1698 | elif dedent_re.match(line): |
|
1706 | elif dedent_re.match(line): | |
1699 | self.indent_current_nsp -= 4 |
|
1707 | self.indent_current_nsp -= 4 | |
1700 | else: |
|
1708 | else: | |
1701 | self.indent_current_nsp = 0 |
|
1709 | self.indent_current_nsp = 0 | |
1702 |
|
1710 | |||
1703 | def runlines(self,lines): |
|
1711 | def runlines(self,lines): | |
1704 | """Run a string of one or more lines of source. |
|
1712 | """Run a string of one or more lines of source. | |
1705 |
|
1713 | |||
1706 | This method is capable of running a string containing multiple source |
|
1714 | This method is capable of running a string containing multiple source | |
1707 | lines, as if they had been entered at the IPython prompt. Since it |
|
1715 | lines, as if they had been entered at the IPython prompt. Since it | |
1708 | exposes IPython's processing machinery, the given strings can contain |
|
1716 | exposes IPython's processing machinery, the given strings can contain | |
1709 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1717 | magic calls (%magic), special shell access (!cmd), etc.""" | |
1710 |
|
1718 | |||
1711 | # We must start with a clean buffer, in case this is run from an |
|
1719 | # We must start with a clean buffer, in case this is run from an | |
1712 | # interactive IPython session (via a magic, for example). |
|
1720 | # interactive IPython session (via a magic, for example). | |
1713 | self.resetbuffer() |
|
1721 | self.resetbuffer() | |
1714 | lines = lines.split('\n') |
|
1722 | lines = lines.split('\n') | |
1715 | more = 0 |
|
1723 | more = 0 | |
1716 | for line in lines: |
|
1724 | for line in lines: | |
1717 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1725 | # skip blank lines so we don't mess up the prompt counter, but do | |
1718 | # NOT skip even a blank line if we are in a code block (more is |
|
1726 | # NOT skip even a blank line if we are in a code block (more is | |
1719 | # true) |
|
1727 | # true) | |
1720 | if line or more: |
|
1728 | if line or more: | |
1721 | more = self.push(self.prefilter(line,more)) |
|
1729 | more = self.push(self.prefilter(line,more)) | |
1722 | # IPython's runsource returns None if there was an error |
|
1730 | # IPython's runsource returns None if there was an error | |
1723 | # compiling the code. This allows us to stop processing right |
|
1731 | # compiling the code. This allows us to stop processing right | |
1724 | # away, so the user gets the error message at the right place. |
|
1732 | # away, so the user gets the error message at the right place. | |
1725 | if more is None: |
|
1733 | if more is None: | |
1726 | break |
|
1734 | break | |
1727 | # final newline in case the input didn't have it, so that the code |
|
1735 | # final newline in case the input didn't have it, so that the code | |
1728 | # actually does get executed |
|
1736 | # actually does get executed | |
1729 | if more: |
|
1737 | if more: | |
1730 | self.push('\n') |
|
1738 | self.push('\n') | |
1731 |
|
1739 | |||
1732 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1740 | def runsource(self, source, filename='<input>', symbol='single'): | |
1733 | """Compile and run some source in the interpreter. |
|
1741 | """Compile and run some source in the interpreter. | |
1734 |
|
1742 | |||
1735 | Arguments are as for compile_command(). |
|
1743 | Arguments are as for compile_command(). | |
1736 |
|
1744 | |||
1737 | One several things can happen: |
|
1745 | One several things can happen: | |
1738 |
|
1746 | |||
1739 | 1) The input is incorrect; compile_command() raised an |
|
1747 | 1) The input is incorrect; compile_command() raised an | |
1740 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1748 | exception (SyntaxError or OverflowError). A syntax traceback | |
1741 | will be printed by calling the showsyntaxerror() method. |
|
1749 | will be printed by calling the showsyntaxerror() method. | |
1742 |
|
1750 | |||
1743 | 2) The input is incomplete, and more input is required; |
|
1751 | 2) The input is incomplete, and more input is required; | |
1744 | compile_command() returned None. Nothing happens. |
|
1752 | compile_command() returned None. Nothing happens. | |
1745 |
|
1753 | |||
1746 | 3) The input is complete; compile_command() returned a code |
|
1754 | 3) The input is complete; compile_command() returned a code | |
1747 | object. The code is executed by calling self.runcode() (which |
|
1755 | object. The code is executed by calling self.runcode() (which | |
1748 | also handles run-time exceptions, except for SystemExit). |
|
1756 | also handles run-time exceptions, except for SystemExit). | |
1749 |
|
1757 | |||
1750 | The return value is: |
|
1758 | The return value is: | |
1751 |
|
1759 | |||
1752 | - True in case 2 |
|
1760 | - True in case 2 | |
1753 |
|
1761 | |||
1754 | - False in the other cases, unless an exception is raised, where |
|
1762 | - False in the other cases, unless an exception is raised, where | |
1755 | None is returned instead. This can be used by external callers to |
|
1763 | None is returned instead. This can be used by external callers to | |
1756 | know whether to continue feeding input or not. |
|
1764 | know whether to continue feeding input or not. | |
1757 |
|
1765 | |||
1758 | The return value can be used to decide whether to use sys.ps1 or |
|
1766 | The return value can be used to decide whether to use sys.ps1 or | |
1759 | sys.ps2 to prompt the next line.""" |
|
1767 | sys.ps2 to prompt the next line.""" | |
1760 |
|
1768 | |||
1761 | try: |
|
1769 | try: | |
1762 | code = self.compile(source,filename,symbol) |
|
1770 | code = self.compile(source,filename,symbol) | |
1763 | except (OverflowError, SyntaxError, ValueError): |
|
1771 | except (OverflowError, SyntaxError, ValueError): | |
1764 | # Case 1 |
|
1772 | # Case 1 | |
1765 | self.showsyntaxerror(filename) |
|
1773 | self.showsyntaxerror(filename) | |
1766 | return None |
|
1774 | return None | |
1767 |
|
1775 | |||
1768 | if code is None: |
|
1776 | if code is None: | |
1769 | # Case 2 |
|
1777 | # Case 2 | |
1770 | return True |
|
1778 | return True | |
1771 |
|
1779 | |||
1772 | # Case 3 |
|
1780 | # Case 3 | |
1773 | # We store the code object so that threaded shells and |
|
1781 | # We store the code object so that threaded shells and | |
1774 | # custom exception handlers can access all this info if needed. |
|
1782 | # custom exception handlers can access all this info if needed. | |
1775 | # The source corresponding to this can be obtained from the |
|
1783 | # The source corresponding to this can be obtained from the | |
1776 | # buffer attribute as '\n'.join(self.buffer). |
|
1784 | # buffer attribute as '\n'.join(self.buffer). | |
1777 | self.code_to_run = code |
|
1785 | self.code_to_run = code | |
1778 | # now actually execute the code object |
|
1786 | # now actually execute the code object | |
1779 | if self.runcode(code) == 0: |
|
1787 | if self.runcode(code) == 0: | |
1780 | return False |
|
1788 | return False | |
1781 | else: |
|
1789 | else: | |
1782 | return None |
|
1790 | return None | |
1783 |
|
1791 | |||
1784 | def runcode(self,code_obj): |
|
1792 | def runcode(self,code_obj): | |
1785 | """Execute a code object. |
|
1793 | """Execute a code object. | |
1786 |
|
1794 | |||
1787 | When an exception occurs, self.showtraceback() is called to display a |
|
1795 | When an exception occurs, self.showtraceback() is called to display a | |
1788 | traceback. |
|
1796 | traceback. | |
1789 |
|
1797 | |||
1790 | Return value: a flag indicating whether the code to be run completed |
|
1798 | Return value: a flag indicating whether the code to be run completed | |
1791 | successfully: |
|
1799 | successfully: | |
1792 |
|
1800 | |||
1793 | - 0: successful execution. |
|
1801 | - 0: successful execution. | |
1794 | - 1: an error occurred. |
|
1802 | - 1: an error occurred. | |
1795 | """ |
|
1803 | """ | |
1796 |
|
1804 | |||
1797 | # Set our own excepthook in case the user code tries to call it |
|
1805 | # Set our own excepthook in case the user code tries to call it | |
1798 | # directly, so that the IPython crash handler doesn't get triggered |
|
1806 | # directly, so that the IPython crash handler doesn't get triggered | |
1799 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
1807 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
1800 |
|
1808 | |||
1801 | # we save the original sys.excepthook in the instance, in case config |
|
1809 | # we save the original sys.excepthook in the instance, in case config | |
1802 | # code (such as magics) needs access to it. |
|
1810 | # code (such as magics) needs access to it. | |
1803 | self.sys_excepthook = old_excepthook |
|
1811 | self.sys_excepthook = old_excepthook | |
1804 | outflag = 1 # happens in more places, so it's easier as default |
|
1812 | outflag = 1 # happens in more places, so it's easier as default | |
1805 | try: |
|
1813 | try: | |
1806 | try: |
|
1814 | try: | |
1807 | # Embedded instances require separate global/local namespaces |
|
1815 | # Embedded instances require separate global/local namespaces | |
1808 | # so they can see both the surrounding (local) namespace and |
|
1816 | # so they can see both the surrounding (local) namespace and | |
1809 | # the module-level globals when called inside another function. |
|
1817 | # the module-level globals when called inside another function. | |
1810 | if self.embedded: |
|
1818 | if self.embedded: | |
1811 | exec code_obj in self.user_global_ns, self.user_ns |
|
1819 | exec code_obj in self.user_global_ns, self.user_ns | |
1812 | # Normal (non-embedded) instances should only have a single |
|
1820 | # Normal (non-embedded) instances should only have a single | |
1813 | # namespace for user code execution, otherwise functions won't |
|
1821 | # namespace for user code execution, otherwise functions won't | |
1814 | # see interactive top-level globals. |
|
1822 | # see interactive top-level globals. | |
1815 | else: |
|
1823 | else: | |
1816 | exec code_obj in self.user_ns |
|
1824 | exec code_obj in self.user_ns | |
1817 | finally: |
|
1825 | finally: | |
1818 | # Reset our crash handler in place |
|
1826 | # Reset our crash handler in place | |
1819 | sys.excepthook = old_excepthook |
|
1827 | sys.excepthook = old_excepthook | |
1820 | except SystemExit: |
|
1828 | except SystemExit: | |
1821 | self.resetbuffer() |
|
1829 | self.resetbuffer() | |
1822 | self.showtraceback() |
|
1830 | self.showtraceback() | |
1823 | warn("Type %exit or %quit to exit IPython " |
|
1831 | warn("Type %exit or %quit to exit IPython " | |
1824 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
1832 | "(%Exit or %Quit do so unconditionally).",level=1) | |
1825 | except self.custom_exceptions: |
|
1833 | except self.custom_exceptions: | |
1826 | etype,value,tb = sys.exc_info() |
|
1834 | etype,value,tb = sys.exc_info() | |
1827 | self.CustomTB(etype,value,tb) |
|
1835 | self.CustomTB(etype,value,tb) | |
1828 | except: |
|
1836 | except: | |
1829 | self.showtraceback() |
|
1837 | self.showtraceback() | |
1830 | else: |
|
1838 | else: | |
1831 | outflag = 0 |
|
1839 | outflag = 0 | |
1832 | if softspace(sys.stdout, 0): |
|
1840 | if softspace(sys.stdout, 0): | |
1833 |
|
1841 | |||
1834 | # Flush out code object which has been run (and source) |
|
1842 | # Flush out code object which has been run (and source) | |
1835 | self.code_to_run = None |
|
1843 | self.code_to_run = None | |
1836 | return outflag |
|
1844 | return outflag | |
1837 |
|
1845 | |||
1838 | def push(self, line): |
|
1846 | def push(self, line): | |
1839 | """Push a line to the interpreter. |
|
1847 | """Push a line to the interpreter. | |
1840 |
|
1848 | |||
1841 | The line should not have a trailing newline; it may have |
|
1849 | The line should not have a trailing newline; it may have | |
1842 | internal newlines. The line is appended to a buffer and the |
|
1850 | internal newlines. The line is appended to a buffer and the | |
1843 | interpreter's runsource() method is called with the |
|
1851 | interpreter's runsource() method is called with the | |
1844 | concatenated contents of the buffer as source. If this |
|
1852 | concatenated contents of the buffer as source. If this | |
1845 | indicates that the command was executed or invalid, the buffer |
|
1853 | indicates that the command was executed or invalid, the buffer | |
1846 | is reset; otherwise, the command is incomplete, and the buffer |
|
1854 | is reset; otherwise, the command is incomplete, and the buffer | |
1847 | is left as it was after the line was appended. The return |
|
1855 | is left as it was after the line was appended. The return | |
1848 | value is 1 if more input is required, 0 if the line was dealt |
|
1856 | value is 1 if more input is required, 0 if the line was dealt | |
1849 | with in some way (this is the same as runsource()). |
|
1857 | with in some way (this is the same as runsource()). | |
1850 | """ |
|
1858 | """ | |
1851 |
|
1859 | |||
1852 | # autoindent management should be done here, and not in the |
|
1860 | # autoindent management should be done here, and not in the | |
1853 | # interactive loop, since that one is only seen by keyboard input. We |
|
1861 | # interactive loop, since that one is only seen by keyboard input. We | |
1854 | # need this done correctly even for code run via runlines (which uses |
|
1862 | # need this done correctly even for code run via runlines (which uses | |
1855 | # push). |
|
1863 | # push). | |
1856 |
|
1864 | |||
1857 | #print 'push line: <%s>' % line # dbg |
|
1865 | #print 'push line: <%s>' % line # dbg | |
1858 | for subline in line.splitlines(): |
|
1866 | for subline in line.splitlines(): | |
1859 | self.autoindent_update(subline) |
|
1867 | self.autoindent_update(subline) | |
1860 | self.buffer.append(line) |
|
1868 | self.buffer.append(line) | |
1861 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
1869 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
1862 | if not more: |
|
1870 | if not more: | |
1863 | self.resetbuffer() |
|
1871 | self.resetbuffer() | |
1864 | return more |
|
1872 | return more | |
1865 |
|
1873 | |||
1866 | def resetbuffer(self): |
|
1874 | def resetbuffer(self): | |
1867 | """Reset the input buffer.""" |
|
1875 | """Reset the input buffer.""" | |
1868 | self.buffer[:] = [] |
|
1876 | self.buffer[:] = [] | |
1869 |
|
1877 | |||
1870 | def raw_input(self,prompt='',continue_prompt=False): |
|
1878 | def raw_input(self,prompt='',continue_prompt=False): | |
1871 | """Write a prompt and read a line. |
|
1879 | """Write a prompt and read a line. | |
1872 |
|
1880 | |||
1873 | The returned line does not include the trailing newline. |
|
1881 | The returned line does not include the trailing newline. | |
1874 | When the user enters the EOF key sequence, EOFError is raised. |
|
1882 | When the user enters the EOF key sequence, EOFError is raised. | |
1875 |
|
1883 | |||
1876 | Optional inputs: |
|
1884 | Optional inputs: | |
1877 |
|
1885 | |||
1878 | - prompt(''): a string to be printed to prompt the user. |
|
1886 | - prompt(''): a string to be printed to prompt the user. | |
1879 |
|
1887 | |||
1880 | - continue_prompt(False): whether this line is the first one or a |
|
1888 | - continue_prompt(False): whether this line is the first one or a | |
1881 | continuation in a sequence of inputs. |
|
1889 | continuation in a sequence of inputs. | |
1882 | """ |
|
1890 | """ | |
1883 |
|
1891 | |||
1884 | try: |
|
1892 | try: | |
1885 | line = raw_input_original(prompt) |
|
1893 | line = raw_input_original(prompt) | |
1886 | except ValueError: |
|
1894 | except ValueError: | |
1887 | warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!") |
|
1895 | warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!") | |
1888 | self.exit_now = True |
|
1896 | self.exit_now = True | |
1889 | return "" |
|
1897 | return "" | |
1890 |
|
1898 | |||
1891 |
|
1899 | |||
1892 | # Try to be reasonably smart about not re-indenting pasted input more |
|
1900 | # Try to be reasonably smart about not re-indenting pasted input more | |
1893 | # than necessary. We do this by trimming out the auto-indent initial |
|
1901 | # than necessary. We do this by trimming out the auto-indent initial | |
1894 | # spaces, if the user's actual input started itself with whitespace. |
|
1902 | # spaces, if the user's actual input started itself with whitespace. | |
1895 | #debugx('self.buffer[-1]') |
|
1903 | #debugx('self.buffer[-1]') | |
1896 |
|
1904 | |||
1897 | if self.autoindent: |
|
1905 | if self.autoindent: | |
1898 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
1906 | if num_ini_spaces(line) > self.indent_current_nsp: | |
1899 | line = line[self.indent_current_nsp:] |
|
1907 | line = line[self.indent_current_nsp:] | |
1900 | self.indent_current_nsp = 0 |
|
1908 | self.indent_current_nsp = 0 | |
1901 |
|
1909 | |||
1902 | # store the unfiltered input before the user has any chance to modify |
|
1910 | # store the unfiltered input before the user has any chance to modify | |
1903 | # it. |
|
1911 | # it. | |
1904 | if line.strip(): |
|
1912 | if line.strip(): | |
1905 | if continue_prompt: |
|
1913 | if continue_prompt: | |
1906 | self.input_hist_raw[-1] += '%s\n' % line |
|
1914 | self.input_hist_raw[-1] += '%s\n' % line | |
1907 | if self.has_readline: # and some config option is set? |
|
1915 | if self.has_readline: # and some config option is set? | |
1908 | try: |
|
1916 | try: | |
1909 | histlen = self.readline.get_current_history_length() |
|
1917 | histlen = self.readline.get_current_history_length() | |
1910 | newhist = self.input_hist_raw[-1].rstrip() |
|
1918 | newhist = self.input_hist_raw[-1].rstrip() | |
1911 | self.readline.remove_history_item(histlen-1) |
|
1919 | self.readline.remove_history_item(histlen-1) | |
1912 | self.readline.replace_history_item(histlen-2,newhist) |
|
1920 | self.readline.replace_history_item(histlen-2,newhist) | |
1913 | except AttributeError: |
|
1921 | except AttributeError: | |
1914 | pass # re{move,place}_history_item are new in 2.4. |
|
1922 | pass # re{move,place}_history_item are new in 2.4. | |
1915 | else: |
|
1923 | else: | |
1916 | self.input_hist_raw.append('%s\n' % line) |
|
1924 | self.input_hist_raw.append('%s\n' % line) | |
1917 |
|
1925 | |||
1918 | try: |
|
1926 | try: | |
1919 | lineout = self.prefilter(line,continue_prompt) |
|
1927 | lineout = self.prefilter(line,continue_prompt) | |
1920 | except: |
|
1928 | except: | |
1921 | # blanket except, in case a user-defined prefilter crashes, so it |
|
1929 | # blanket except, in case a user-defined prefilter crashes, so it | |
1922 | # can't take all of ipython with it. |
|
1930 | # can't take all of ipython with it. | |
1923 | self.showtraceback() |
|
1931 | self.showtraceback() | |
1924 | return '' |
|
1932 | return '' | |
1925 | else: |
|
1933 | else: | |
1926 | return lineout |
|
1934 | return lineout | |
1927 |
|
1935 | |||
1928 | def split_user_input(self,line): |
|
1936 | def split_user_input(self,line): | |
1929 | """Split user input into pre-char, function part and rest.""" |
|
1937 | """Split user input into pre-char, function part and rest.""" | |
1930 |
|
1938 | |||
1931 | lsplit = self.line_split.match(line) |
|
1939 | lsplit = self.line_split.match(line) | |
1932 | if lsplit is None: # no regexp match returns None |
|
1940 | if lsplit is None: # no regexp match returns None | |
1933 | try: |
|
1941 | try: | |
1934 | iFun,theRest = line.split(None,1) |
|
1942 | iFun,theRest = line.split(None,1) | |
1935 | except ValueError: |
|
1943 | except ValueError: | |
1936 | iFun,theRest = line,'' |
|
1944 | iFun,theRest = line,'' | |
1937 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
1945 | pre = re.match('^(\s*)(.*)',line).groups()[0] | |
1938 | else: |
|
1946 | else: | |
1939 | pre,iFun,theRest = lsplit.groups() |
|
1947 | pre,iFun,theRest = lsplit.groups() | |
1940 |
|
1948 | |||
1941 | #print 'line:<%s>' % line # dbg |
|
1949 | #print 'line:<%s>' % line # dbg | |
1942 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
1950 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg | |
1943 | return pre,iFun.strip(),theRest |
|
1951 | return pre,iFun.strip(),theRest | |
1944 |
|
1952 | |||
1945 | def _prefilter(self, line, continue_prompt): |
|
1953 | def _prefilter(self, line, continue_prompt): | |
1946 | """Calls different preprocessors, depending on the form of line.""" |
|
1954 | """Calls different preprocessors, depending on the form of line.""" | |
1947 |
|
1955 | |||
1948 | # All handlers *must* return a value, even if it's blank (''). |
|
1956 | # All handlers *must* return a value, even if it's blank (''). | |
1949 |
|
1957 | |||
1950 | # Lines are NOT logged here. Handlers should process the line as |
|
1958 | # Lines are NOT logged here. Handlers should process the line as | |
1951 | # needed, update the cache AND log it (so that the input cache array |
|
1959 | # needed, update the cache AND log it (so that the input cache array | |
1952 | # stays synced). |
|
1960 | # stays synced). | |
1953 |
|
1961 | |||
1954 | # This function is _very_ delicate, and since it's also the one which |
|
1962 | # This function is _very_ delicate, and since it's also the one which | |
1955 | # determines IPython's response to user input, it must be as efficient |
|
1963 | # determines IPython's response to user input, it must be as efficient | |
1956 | # as possible. For this reason it has _many_ returns in it, trying |
|
1964 | # as possible. For this reason it has _many_ returns in it, trying | |
1957 | # always to exit as quickly as it can figure out what it needs to do. |
|
1965 | # always to exit as quickly as it can figure out what it needs to do. | |
1958 |
|
1966 | |||
1959 | # This function is the main responsible for maintaining IPython's |
|
1967 | # This function is the main responsible for maintaining IPython's | |
1960 | # behavior respectful of Python's semantics. So be _very_ careful if |
|
1968 | # behavior respectful of Python's semantics. So be _very_ careful if | |
1961 | # making changes to anything here. |
|
1969 | # making changes to anything here. | |
1962 |
|
1970 | |||
1963 | #..................................................................... |
|
1971 | #..................................................................... | |
1964 | # Code begins |
|
1972 | # Code begins | |
1965 |
|
1973 | |||
1966 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
1974 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
1967 |
|
1975 | |||
1968 | # save the line away in case we crash, so the post-mortem handler can |
|
1976 | # save the line away in case we crash, so the post-mortem handler can | |
1969 | # record it |
|
1977 | # record it | |
1970 | self._last_input_line = line |
|
1978 | self._last_input_line = line | |
1971 |
|
1979 | |||
1972 | #print '***line: <%s>' % line # dbg |
|
1980 | #print '***line: <%s>' % line # dbg | |
1973 |
|
1981 | |||
1974 | # the input history needs to track even empty lines |
|
1982 | # the input history needs to track even empty lines | |
1975 | stripped = line.strip() |
|
1983 | stripped = line.strip() | |
1976 |
|
1984 | |||
1977 | if not stripped: |
|
1985 | if not stripped: | |
1978 | if not continue_prompt: |
|
1986 | if not continue_prompt: | |
1979 | self.outputcache.prompt_count -= 1 |
|
1987 | self.outputcache.prompt_count -= 1 | |
1980 | return self.handle_normal(line,continue_prompt) |
|
1988 | return self.handle_normal(line,continue_prompt) | |
1981 | #return self.handle_normal('',continue_prompt) |
|
1989 | #return self.handle_normal('',continue_prompt) | |
1982 |
|
1990 | |||
1983 | # print '***cont',continue_prompt # dbg |
|
1991 | # print '***cont',continue_prompt # dbg | |
1984 | # special handlers are only allowed for single line statements |
|
1992 | # special handlers are only allowed for single line statements | |
1985 | if continue_prompt and not self.rc.multi_line_specials: |
|
1993 | if continue_prompt and not self.rc.multi_line_specials: | |
1986 | return self.handle_normal(line,continue_prompt) |
|
1994 | return self.handle_normal(line,continue_prompt) | |
1987 |
|
1995 | |||
1988 |
|
1996 | |||
1989 | # For the rest, we need the structure of the input |
|
1997 | # For the rest, we need the structure of the input | |
1990 | pre,iFun,theRest = self.split_user_input(line) |
|
1998 | pre,iFun,theRest = self.split_user_input(line) | |
1991 |
|
1999 | |||
1992 | # See whether any pre-existing handler can take care of it |
|
2000 | # See whether any pre-existing handler can take care of it | |
1993 |
|
2001 | |||
1994 | rewritten = self.hooks.input_prefilter(stripped) |
|
2002 | rewritten = self.hooks.input_prefilter(stripped) | |
1995 | if rewritten != stripped: # ok, some prefilter did something |
|
2003 | if rewritten != stripped: # ok, some prefilter did something | |
1996 | rewritten = pre + rewritten # add indentation |
|
2004 | rewritten = pre + rewritten # add indentation | |
1997 | return self.handle_normal(rewritten) |
|
2005 | return self.handle_normal(rewritten) | |
1998 |
|
2006 | |||
1999 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2007 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2000 |
|
2008 | |||
2001 | # First check for explicit escapes in the last/first character |
|
2009 | # First check for explicit escapes in the last/first character | |
2002 | handler = None |
|
2010 | handler = None | |
2003 | if line[-1] == self.ESC_HELP: |
|
2011 | if line[-1] == self.ESC_HELP: | |
2004 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end |
|
2012 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end | |
2005 | if handler is None: |
|
2013 | if handler is None: | |
2006 | # look at the first character of iFun, NOT of line, so we skip |
|
2014 | # look at the first character of iFun, NOT of line, so we skip | |
2007 | # leading whitespace in multiline input |
|
2015 | # leading whitespace in multiline input | |
2008 | handler = self.esc_handlers.get(iFun[0:1]) |
|
2016 | handler = self.esc_handlers.get(iFun[0:1]) | |
2009 | if handler is not None: |
|
2017 | if handler is not None: | |
2010 | return handler(line,continue_prompt,pre,iFun,theRest) |
|
2018 | return handler(line,continue_prompt,pre,iFun,theRest) | |
2011 | # Emacs ipython-mode tags certain input lines |
|
2019 | # Emacs ipython-mode tags certain input lines | |
2012 | if line.endswith('# PYTHON-MODE'): |
|
2020 | if line.endswith('# PYTHON-MODE'): | |
2013 | return self.handle_emacs(line,continue_prompt) |
|
2021 | return self.handle_emacs(line,continue_prompt) | |
2014 |
|
2022 | |||
2015 | # Next, check if we can automatically execute this thing |
|
2023 | # Next, check if we can automatically execute this thing | |
2016 |
|
2024 | |||
2017 | # Allow ! in multi-line statements if multi_line_specials is on: |
|
2025 | # Allow ! in multi-line statements if multi_line_specials is on: | |
2018 | if continue_prompt and self.rc.multi_line_specials and \ |
|
2026 | if continue_prompt and self.rc.multi_line_specials and \ | |
2019 | iFun.startswith(self.ESC_SHELL): |
|
2027 | iFun.startswith(self.ESC_SHELL): | |
2020 | return self.handle_shell_escape(line,continue_prompt, |
|
2028 | return self.handle_shell_escape(line,continue_prompt, | |
2021 | pre=pre,iFun=iFun, |
|
2029 | pre=pre,iFun=iFun, | |
2022 | theRest=theRest) |
|
2030 | theRest=theRest) | |
2023 |
|
2031 | |||
2024 | # Let's try to find if the input line is a magic fn |
|
2032 | # Let's try to find if the input line is a magic fn | |
2025 | oinfo = None |
|
2033 | oinfo = None | |
2026 | if hasattr(self,'magic_'+iFun): |
|
2034 | if hasattr(self,'magic_'+iFun): | |
2027 | # WARNING: _ofind uses getattr(), so it can consume generators and |
|
2035 | # WARNING: _ofind uses getattr(), so it can consume generators and | |
2028 | # cause other side effects. |
|
2036 | # cause other side effects. | |
2029 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
2037 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
2030 | if oinfo['ismagic']: |
|
2038 | if oinfo['ismagic']: | |
2031 | # Be careful not to call magics when a variable assignment is |
|
2039 | # Be careful not to call magics when a variable assignment is | |
2032 | # being made (ls='hi', for example) |
|
2040 | # being made (ls='hi', for example) | |
2033 | if self.rc.automagic and \ |
|
2041 | if self.rc.automagic and \ | |
2034 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ |
|
2042 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ | |
2035 | (self.rc.multi_line_specials or not continue_prompt): |
|
2043 | (self.rc.multi_line_specials or not continue_prompt): | |
2036 | return self.handle_magic(line,continue_prompt, |
|
2044 | return self.handle_magic(line,continue_prompt, | |
2037 | pre,iFun,theRest) |
|
2045 | pre,iFun,theRest) | |
2038 | else: |
|
2046 | else: | |
2039 | return self.handle_normal(line,continue_prompt) |
|
2047 | return self.handle_normal(line,continue_prompt) | |
2040 |
|
2048 | |||
2041 | # If the rest of the line begins with an (in)equality, assginment or |
|
2049 | # If the rest of the line begins with an (in)equality, assginment or | |
2042 | # function call, we should not call _ofind but simply execute it. |
|
2050 | # function call, we should not call _ofind but simply execute it. | |
2043 | # This avoids spurious geattr() accesses on objects upon assignment. |
|
2051 | # This avoids spurious geattr() accesses on objects upon assignment. | |
2044 | # |
|
2052 | # | |
2045 | # It also allows users to assign to either alias or magic names true |
|
2053 | # It also allows users to assign to either alias or magic names true | |
2046 | # python variables (the magic/alias systems always take second seat to |
|
2054 | # python variables (the magic/alias systems always take second seat to | |
2047 | # true python code). |
|
2055 | # true python code). | |
2048 | if theRest and theRest[0] in '!=()': |
|
2056 | if theRest and theRest[0] in '!=()': | |
2049 | return self.handle_normal(line,continue_prompt) |
|
2057 | return self.handle_normal(line,continue_prompt) | |
2050 |
|
2058 | |||
2051 | if oinfo is None: |
|
2059 | if oinfo is None: | |
2052 | # let's try to ensure that _oinfo is ONLY called when autocall is |
|
2060 | # let's try to ensure that _oinfo is ONLY called when autocall is | |
2053 | # on. Since it has inevitable potential side effects, at least |
|
2061 | # on. Since it has inevitable potential side effects, at least | |
2054 | # having autocall off should be a guarantee to the user that no |
|
2062 | # having autocall off should be a guarantee to the user that no | |
2055 | # weird things will happen. |
|
2063 | # weird things will happen. | |
2056 |
|
2064 | |||
2057 | if self.rc.autocall: |
|
2065 | if self.rc.autocall: | |
2058 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
2066 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
2059 | else: |
|
2067 | else: | |
2060 | # in this case, all that's left is either an alias or |
|
2068 | # in this case, all that's left is either an alias or | |
2061 | # processing the line normally. |
|
2069 | # processing the line normally. | |
2062 | if iFun in self.alias_table: |
|
2070 | if iFun in self.alias_table: | |
2063 | # if autocall is off, by not running _ofind we won't know |
|
2071 | # if autocall is off, by not running _ofind we won't know | |
2064 | # whether the given name may also exist in one of the |
|
2072 | # whether the given name may also exist in one of the | |
2065 | # user's namespace. At this point, it's best to do a |
|
2073 | # user's namespace. At this point, it's best to do a | |
2066 | # quick check just to be sure that we don't let aliases |
|
2074 | # quick check just to be sure that we don't let aliases | |
2067 | # shadow variables. |
|
2075 | # shadow variables. | |
2068 | head = iFun.split('.',1)[0] |
|
2076 | head = iFun.split('.',1)[0] | |
2069 | if head in self.user_ns or head in self.internal_ns \ |
|
2077 | if head in self.user_ns or head in self.internal_ns \ | |
2070 | or head in __builtin__.__dict__: |
|
2078 | or head in __builtin__.__dict__: | |
2071 | return self.handle_normal(line,continue_prompt) |
|
2079 | return self.handle_normal(line,continue_prompt) | |
2072 | else: |
|
2080 | else: | |
2073 | return self.handle_alias(line,continue_prompt, |
|
2081 | return self.handle_alias(line,continue_prompt, | |
2074 | pre,iFun,theRest) |
|
2082 | pre,iFun,theRest) | |
2075 |
|
2083 | |||
2076 | else: |
|
2084 | else: | |
2077 | return self.handle_normal(line,continue_prompt) |
|
2085 | return self.handle_normal(line,continue_prompt) | |
2078 |
|
2086 | |||
2079 | if not oinfo['found']: |
|
2087 | if not oinfo['found']: | |
2080 | return self.handle_normal(line,continue_prompt) |
|
2088 | return self.handle_normal(line,continue_prompt) | |
2081 | else: |
|
2089 | else: | |
2082 | #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2090 | #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2083 | if oinfo['isalias']: |
|
2091 | if oinfo['isalias']: | |
2084 | return self.handle_alias(line,continue_prompt, |
|
2092 | return self.handle_alias(line,continue_prompt, | |
2085 | pre,iFun,theRest) |
|
2093 | pre,iFun,theRest) | |
2086 |
|
2094 | |||
2087 | if (self.rc.autocall |
|
2095 | if (self.rc.autocall | |
2088 | and |
|
2096 | and | |
2089 | ( |
|
2097 | ( | |
2090 | #only consider exclusion re if not "," or ";" autoquoting |
|
2098 | #only consider exclusion re if not "," or ";" autoquoting | |
2091 | (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2 |
|
2099 | (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2 | |
2092 | or pre == self.ESC_PAREN) or |
|
2100 | or pre == self.ESC_PAREN) or | |
2093 | (not self.re_exclude_auto.match(theRest))) |
|
2101 | (not self.re_exclude_auto.match(theRest))) | |
2094 | and |
|
2102 | and | |
2095 | self.re_fun_name.match(iFun) and |
|
2103 | self.re_fun_name.match(iFun) and | |
2096 | callable(oinfo['obj'])) : |
|
2104 | callable(oinfo['obj'])) : | |
2097 | #print 'going auto' # dbg |
|
2105 | #print 'going auto' # dbg | |
2098 | return self.handle_auto(line,continue_prompt, |
|
2106 | return self.handle_auto(line,continue_prompt, | |
2099 | pre,iFun,theRest,oinfo['obj']) |
|
2107 | pre,iFun,theRest,oinfo['obj']) | |
2100 | else: |
|
2108 | else: | |
2101 | #print 'was callable?', callable(oinfo['obj']) # dbg |
|
2109 | #print 'was callable?', callable(oinfo['obj']) # dbg | |
2102 | return self.handle_normal(line,continue_prompt) |
|
2110 | return self.handle_normal(line,continue_prompt) | |
2103 |
|
2111 | |||
2104 | # If we get here, we have a normal Python line. Log and return. |
|
2112 | # If we get here, we have a normal Python line. Log and return. | |
2105 | return self.handle_normal(line,continue_prompt) |
|
2113 | return self.handle_normal(line,continue_prompt) | |
2106 |
|
2114 | |||
2107 | def _prefilter_dumb(self, line, continue_prompt): |
|
2115 | def _prefilter_dumb(self, line, continue_prompt): | |
2108 | """simple prefilter function, for debugging""" |
|
2116 | """simple prefilter function, for debugging""" | |
2109 | return self.handle_normal(line,continue_prompt) |
|
2117 | return self.handle_normal(line,continue_prompt) | |
2110 |
|
2118 | |||
2111 |
|
2119 | |||
2112 | def multiline_prefilter(self, line, continue_prompt): |
|
2120 | def multiline_prefilter(self, line, continue_prompt): | |
2113 | """ Run _prefilter for each line of input |
|
2121 | """ Run _prefilter for each line of input | |
2114 |
|
2122 | |||
2115 | Covers cases where there are multiple lines in the user entry, |
|
2123 | Covers cases where there are multiple lines in the user entry, | |
2116 | which is the case when the user goes back to a multiline history |
|
2124 | which is the case when the user goes back to a multiline history | |
2117 | entry and presses enter. |
|
2125 | entry and presses enter. | |
2118 |
|
2126 | |||
2119 | """ |
|
2127 | """ | |
2120 | out = [] |
|
2128 | out = [] | |
2121 | for l in line.rstrip('\n').split('\n'): |
|
2129 | for l in line.rstrip('\n').split('\n'): | |
2122 | out.append(self._prefilter(l, continue_prompt)) |
|
2130 | out.append(self._prefilter(l, continue_prompt)) | |
2123 | return '\n'.join(out) |
|
2131 | return '\n'.join(out) | |
2124 |
|
2132 | |||
2125 | # Set the default prefilter() function (this can be user-overridden) |
|
2133 | # Set the default prefilter() function (this can be user-overridden) | |
2126 | prefilter = multiline_prefilter |
|
2134 | prefilter = multiline_prefilter | |
2127 |
|
2135 | |||
2128 | def handle_normal(self,line,continue_prompt=None, |
|
2136 | def handle_normal(self,line,continue_prompt=None, | |
2129 | pre=None,iFun=None,theRest=None): |
|
2137 | pre=None,iFun=None,theRest=None): | |
2130 | """Handle normal input lines. Use as a template for handlers.""" |
|
2138 | """Handle normal input lines. Use as a template for handlers.""" | |
2131 |
|
2139 | |||
2132 | # With autoindent on, we need some way to exit the input loop, and I |
|
2140 | # With autoindent on, we need some way to exit the input loop, and I | |
2133 | # don't want to force the user to have to backspace all the way to |
|
2141 | # don't want to force the user to have to backspace all the way to | |
2134 | # clear the line. The rule will be in this case, that either two |
|
2142 | # clear the line. The rule will be in this case, that either two | |
2135 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2143 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
2136 | # of a size different to the indent level, will exit the input loop. |
|
2144 | # of a size different to the indent level, will exit the input loop. | |
2137 |
|
2145 | |||
2138 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2146 | if (continue_prompt and self.autoindent and line.isspace() and | |
2139 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2147 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
2140 | (self.buffer[-1]).isspace() )): |
|
2148 | (self.buffer[-1]).isspace() )): | |
2141 | line = '' |
|
2149 | line = '' | |
2142 |
|
2150 | |||
2143 | self.log(line,line,continue_prompt) |
|
2151 | self.log(line,line,continue_prompt) | |
2144 | return line |
|
2152 | return line | |
2145 |
|
2153 | |||
2146 | def handle_alias(self,line,continue_prompt=None, |
|
2154 | def handle_alias(self,line,continue_prompt=None, | |
2147 | pre=None,iFun=None,theRest=None): |
|
2155 | pre=None,iFun=None,theRest=None): | |
2148 | """Handle alias input lines. """ |
|
2156 | """Handle alias input lines. """ | |
2149 |
|
2157 | |||
2150 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2158 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2151 | # aliases won't work in indented sections. |
|
2159 | # aliases won't work in indented sections. | |
2152 | transformed = self.expand_aliases(iFun, theRest) |
|
2160 | transformed = self.expand_aliases(iFun, theRest) | |
2153 | line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed )) |
|
2161 | line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed )) | |
2154 | self.log(line,line_out,continue_prompt) |
|
2162 | self.log(line,line_out,continue_prompt) | |
2155 | #print 'line out:',line_out # dbg |
|
2163 | #print 'line out:',line_out # dbg | |
2156 | return line_out |
|
2164 | return line_out | |
2157 |
|
2165 | |||
2158 | def handle_shell_escape(self, line, continue_prompt=None, |
|
2166 | def handle_shell_escape(self, line, continue_prompt=None, | |
2159 | pre=None,iFun=None,theRest=None): |
|
2167 | pre=None,iFun=None,theRest=None): | |
2160 | """Execute the line in a shell, empty return value""" |
|
2168 | """Execute the line in a shell, empty return value""" | |
2161 |
|
2169 | |||
2162 | #print 'line in :', `line` # dbg |
|
2170 | #print 'line in :', `line` # dbg | |
2163 | # Example of a special handler. Others follow a similar pattern. |
|
2171 | # Example of a special handler. Others follow a similar pattern. | |
2164 | if line.lstrip().startswith('!!'): |
|
2172 | if line.lstrip().startswith('!!'): | |
2165 | # rewrite iFun/theRest to properly hold the call to %sx and |
|
2173 | # rewrite iFun/theRest to properly hold the call to %sx and | |
2166 | # the actual command to be executed, so handle_magic can work |
|
2174 | # the actual command to be executed, so handle_magic can work | |
2167 | # correctly |
|
2175 | # correctly | |
2168 | theRest = '%s %s' % (iFun[2:],theRest) |
|
2176 | theRest = '%s %s' % (iFun[2:],theRest) | |
2169 | iFun = 'sx' |
|
2177 | iFun = 'sx' | |
2170 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC, |
|
2178 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC, | |
2171 | line.lstrip()[2:]), |
|
2179 | line.lstrip()[2:]), | |
2172 | continue_prompt,pre,iFun,theRest) |
|
2180 | continue_prompt,pre,iFun,theRest) | |
2173 | else: |
|
2181 | else: | |
2174 | cmd=line.lstrip().lstrip('!') |
|
2182 | cmd=line.lstrip().lstrip('!') | |
2175 | line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd)) |
|
2183 | line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd)) | |
2176 | # update cache/log and return |
|
2184 | # update cache/log and return | |
2177 | self.log(line,line_out,continue_prompt) |
|
2185 | self.log(line,line_out,continue_prompt) | |
2178 | return line_out |
|
2186 | return line_out | |
2179 |
|
2187 | |||
2180 | def handle_magic(self, line, continue_prompt=None, |
|
2188 | def handle_magic(self, line, continue_prompt=None, | |
2181 | pre=None,iFun=None,theRest=None): |
|
2189 | pre=None,iFun=None,theRest=None): | |
2182 | """Execute magic functions.""" |
|
2190 | """Execute magic functions.""" | |
2183 |
|
2191 | |||
2184 |
|
2192 | |||
2185 | cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest)) |
|
2193 | cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest)) | |
2186 | self.log(line,cmd,continue_prompt) |
|
2194 | self.log(line,cmd,continue_prompt) | |
2187 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2195 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2188 | return cmd |
|
2196 | return cmd | |
2189 |
|
2197 | |||
2190 | def handle_auto(self, line, continue_prompt=None, |
|
2198 | def handle_auto(self, line, continue_prompt=None, | |
2191 | pre=None,iFun=None,theRest=None,obj=None): |
|
2199 | pre=None,iFun=None,theRest=None,obj=None): | |
2192 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2200 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2193 |
|
2201 | |||
2194 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2202 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2195 |
|
2203 | |||
2196 | # This should only be active for single-line input! |
|
2204 | # This should only be active for single-line input! | |
2197 | if continue_prompt: |
|
2205 | if continue_prompt: | |
2198 | self.log(line,line,continue_prompt) |
|
2206 | self.log(line,line,continue_prompt) | |
2199 | return line |
|
2207 | return line | |
2200 |
|
2208 | |||
2201 | auto_rewrite = True |
|
2209 | auto_rewrite = True | |
2202 |
|
2210 | |||
2203 | if pre == self.ESC_QUOTE: |
|
2211 | if pre == self.ESC_QUOTE: | |
2204 | # Auto-quote splitting on whitespace |
|
2212 | # Auto-quote splitting on whitespace | |
2205 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2213 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2206 | elif pre == self.ESC_QUOTE2: |
|
2214 | elif pre == self.ESC_QUOTE2: | |
2207 | # Auto-quote whole string |
|
2215 | # Auto-quote whole string | |
2208 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2216 | newcmd = '%s("%s")' % (iFun,theRest) | |
2209 | elif pre == self.ESC_PAREN: |
|
2217 | elif pre == self.ESC_PAREN: | |
2210 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2218 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2211 | else: |
|
2219 | else: | |
2212 | # Auto-paren. |
|
2220 | # Auto-paren. | |
2213 | # We only apply it to argument-less calls if the autocall |
|
2221 | # We only apply it to argument-less calls if the autocall | |
2214 | # parameter is set to 2. We only need to check that autocall is < |
|
2222 | # parameter is set to 2. We only need to check that autocall is < | |
2215 | # 2, since this function isn't called unless it's at least 1. |
|
2223 | # 2, since this function isn't called unless it's at least 1. | |
2216 | if not theRest and (self.rc.autocall < 2): |
|
2224 | if not theRest and (self.rc.autocall < 2): | |
2217 | newcmd = '%s %s' % (iFun,theRest) |
|
2225 | newcmd = '%s %s' % (iFun,theRest) | |
2218 | auto_rewrite = False |
|
2226 | auto_rewrite = False | |
2219 | else: |
|
2227 | else: | |
2220 | if theRest.startswith('['): |
|
2228 | if theRest.startswith('['): | |
2221 | if hasattr(obj,'__getitem__'): |
|
2229 | if hasattr(obj,'__getitem__'): | |
2222 | # Don't autocall in this case: item access for an object |
|
2230 | # Don't autocall in this case: item access for an object | |
2223 | # which is BOTH callable and implements __getitem__. |
|
2231 | # which is BOTH callable and implements __getitem__. | |
2224 | newcmd = '%s %s' % (iFun,theRest) |
|
2232 | newcmd = '%s %s' % (iFun,theRest) | |
2225 | auto_rewrite = False |
|
2233 | auto_rewrite = False | |
2226 | else: |
|
2234 | else: | |
2227 | # if the object doesn't support [] access, go ahead and |
|
2235 | # if the object doesn't support [] access, go ahead and | |
2228 | # autocall |
|
2236 | # autocall | |
2229 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2237 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2230 | elif theRest.endswith(';'): |
|
2238 | elif theRest.endswith(';'): | |
2231 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2239 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2232 | else: |
|
2240 | else: | |
2233 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2241 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2234 |
|
2242 | |||
2235 | if auto_rewrite: |
|
2243 | if auto_rewrite: | |
2236 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2244 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd | |
2237 | # log what is now valid Python, not the actual user input (without the |
|
2245 | # log what is now valid Python, not the actual user input (without the | |
2238 | # final newline) |
|
2246 | # final newline) | |
2239 | self.log(line,newcmd,continue_prompt) |
|
2247 | self.log(line,newcmd,continue_prompt) | |
2240 | return newcmd |
|
2248 | return newcmd | |
2241 |
|
2249 | |||
2242 | def handle_help(self, line, continue_prompt=None, |
|
2250 | def handle_help(self, line, continue_prompt=None, | |
2243 | pre=None,iFun=None,theRest=None): |
|
2251 | pre=None,iFun=None,theRest=None): | |
2244 | """Try to get some help for the object. |
|
2252 | """Try to get some help for the object. | |
2245 |
|
2253 | |||
2246 | obj? or ?obj -> basic information. |
|
2254 | obj? or ?obj -> basic information. | |
2247 | obj?? or ??obj -> more details. |
|
2255 | obj?? or ??obj -> more details. | |
2248 | """ |
|
2256 | """ | |
2249 |
|
2257 | |||
2250 | # We need to make sure that we don't process lines which would be |
|
2258 | # We need to make sure that we don't process lines which would be | |
2251 | # otherwise valid python, such as "x=1 # what?" |
|
2259 | # otherwise valid python, such as "x=1 # what?" | |
2252 | try: |
|
2260 | try: | |
2253 | codeop.compile_command(line) |
|
2261 | codeop.compile_command(line) | |
2254 | except SyntaxError: |
|
2262 | except SyntaxError: | |
2255 | # We should only handle as help stuff which is NOT valid syntax |
|
2263 | # We should only handle as help stuff which is NOT valid syntax | |
2256 | if line[0]==self.ESC_HELP: |
|
2264 | if line[0]==self.ESC_HELP: | |
2257 | line = line[1:] |
|
2265 | line = line[1:] | |
2258 | elif line[-1]==self.ESC_HELP: |
|
2266 | elif line[-1]==self.ESC_HELP: | |
2259 | line = line[:-1] |
|
2267 | line = line[:-1] | |
2260 | self.log(line,'#?'+line,continue_prompt) |
|
2268 | self.log(line,'#?'+line,continue_prompt) | |
2261 | if line: |
|
2269 | if line: | |
2262 | self.magic_pinfo(line) |
|
2270 | self.magic_pinfo(line) | |
2263 | else: |
|
2271 | else: | |
2264 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2272 | page(self.usage,screen_lines=self.rc.screen_length) | |
2265 | return '' # Empty string is needed here! |
|
2273 | return '' # Empty string is needed here! | |
2266 | except: |
|
2274 | except: | |
2267 | # Pass any other exceptions through to the normal handler |
|
2275 | # Pass any other exceptions through to the normal handler | |
2268 | return self.handle_normal(line,continue_prompt) |
|
2276 | return self.handle_normal(line,continue_prompt) | |
2269 | else: |
|
2277 | else: | |
2270 | # If the code compiles ok, we should handle it normally |
|
2278 | # If the code compiles ok, we should handle it normally | |
2271 | return self.handle_normal(line,continue_prompt) |
|
2279 | return self.handle_normal(line,continue_prompt) | |
2272 |
|
2280 | |||
2273 | def getapi(self): |
|
2281 | def getapi(self): | |
2274 | """ Get an IPApi object for this shell instance |
|
2282 | """ Get an IPApi object for this shell instance | |
2275 |
|
2283 | |||
2276 | Getting an IPApi object is always preferable to accessing the shell |
|
2284 | Getting an IPApi object is always preferable to accessing the shell | |
2277 | directly, but this holds true especially for extensions. |
|
2285 | directly, but this holds true especially for extensions. | |
2278 |
|
2286 | |||
2279 | It should always be possible to implement an extension with IPApi |
|
2287 | It should always be possible to implement an extension with IPApi | |
2280 | alone. If not, contact maintainer to request an addition. |
|
2288 | alone. If not, contact maintainer to request an addition. | |
2281 |
|
2289 | |||
2282 | """ |
|
2290 | """ | |
2283 | return self.api |
|
2291 | return self.api | |
2284 |
|
2292 | |||
2285 | def handle_emacs(self,line,continue_prompt=None, |
|
2293 | def handle_emacs(self,line,continue_prompt=None, | |
2286 | pre=None,iFun=None,theRest=None): |
|
2294 | pre=None,iFun=None,theRest=None): | |
2287 | """Handle input lines marked by python-mode.""" |
|
2295 | """Handle input lines marked by python-mode.""" | |
2288 |
|
2296 | |||
2289 | # Currently, nothing is done. Later more functionality can be added |
|
2297 | # Currently, nothing is done. Later more functionality can be added | |
2290 | # here if needed. |
|
2298 | # here if needed. | |
2291 |
|
2299 | |||
2292 | # The input cache shouldn't be updated |
|
2300 | # The input cache shouldn't be updated | |
2293 |
|
2301 | |||
2294 | return line |
|
2302 | return line | |
2295 |
|
2303 | |||
2296 | def mktempfile(self,data=None): |
|
2304 | def mktempfile(self,data=None): | |
2297 | """Make a new tempfile and return its filename. |
|
2305 | """Make a new tempfile and return its filename. | |
2298 |
|
2306 | |||
2299 | This makes a call to tempfile.mktemp, but it registers the created |
|
2307 | This makes a call to tempfile.mktemp, but it registers the created | |
2300 | filename internally so ipython cleans it up at exit time. |
|
2308 | filename internally so ipython cleans it up at exit time. | |
2301 |
|
2309 | |||
2302 | Optional inputs: |
|
2310 | Optional inputs: | |
2303 |
|
2311 | |||
2304 | - data(None): if data is given, it gets written out to the temp file |
|
2312 | - data(None): if data is given, it gets written out to the temp file | |
2305 | immediately, and the file is closed again.""" |
|
2313 | immediately, and the file is closed again.""" | |
2306 |
|
2314 | |||
2307 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2315 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2308 | self.tempfiles.append(filename) |
|
2316 | self.tempfiles.append(filename) | |
2309 |
|
2317 | |||
2310 | if data: |
|
2318 | if data: | |
2311 | tmp_file = open(filename,'w') |
|
2319 | tmp_file = open(filename,'w') | |
2312 | tmp_file.write(data) |
|
2320 | tmp_file.write(data) | |
2313 | tmp_file.close() |
|
2321 | tmp_file.close() | |
2314 | return filename |
|
2322 | return filename | |
2315 |
|
2323 | |||
2316 | def write(self,data): |
|
2324 | def write(self,data): | |
2317 | """Write a string to the default output""" |
|
2325 | """Write a string to the default output""" | |
2318 | Term.cout.write(data) |
|
2326 | Term.cout.write(data) | |
2319 |
|
2327 | |||
2320 | def write_err(self,data): |
|
2328 | def write_err(self,data): | |
2321 | """Write a string to the default error output""" |
|
2329 | """Write a string to the default error output""" | |
2322 | Term.cerr.write(data) |
|
2330 | Term.cerr.write(data) | |
2323 |
|
2331 | |||
2324 | def exit(self): |
|
2332 | def exit(self): | |
2325 | """Handle interactive exit. |
|
2333 | """Handle interactive exit. | |
2326 |
|
2334 | |||
2327 | This method sets the exit_now attribute.""" |
|
2335 | This method sets the exit_now attribute.""" | |
2328 |
|
2336 | |||
2329 | if self.rc.confirm_exit: |
|
2337 | if self.rc.confirm_exit: | |
2330 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2338 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2331 | self.exit_now = True |
|
2339 | self.exit_now = True | |
2332 | else: |
|
2340 | else: | |
2333 | self.exit_now = True |
|
2341 | self.exit_now = True | |
2334 |
|
2342 | |||
2335 | def safe_execfile(self,fname,*where,**kw): |
|
2343 | def safe_execfile(self,fname,*where,**kw): | |
2336 | fname = os.path.expanduser(fname) |
|
2344 | fname = os.path.expanduser(fname) | |
2337 |
|
2345 | |||
2338 | # find things also in current directory |
|
2346 | # find things also in current directory | |
2339 | dname = os.path.dirname(fname) |
|
2347 | dname = os.path.dirname(fname) | |
2340 | if not sys.path.count(dname): |
|
2348 | if not sys.path.count(dname): | |
2341 | sys.path.append(dname) |
|
2349 | sys.path.append(dname) | |
2342 |
|
2350 | |||
2343 | try: |
|
2351 | try: | |
2344 | xfile = open(fname) |
|
2352 | xfile = open(fname) | |
2345 | except: |
|
2353 | except: | |
2346 | print >> Term.cerr, \ |
|
2354 | print >> Term.cerr, \ | |
2347 | 'Could not open file <%s> for safe execution.' % fname |
|
2355 | 'Could not open file <%s> for safe execution.' % fname | |
2348 | return None |
|
2356 | return None | |
2349 |
|
2357 | |||
2350 | kw.setdefault('islog',0) |
|
2358 | kw.setdefault('islog',0) | |
2351 | kw.setdefault('quiet',1) |
|
2359 | kw.setdefault('quiet',1) | |
2352 | kw.setdefault('exit_ignore',0) |
|
2360 | kw.setdefault('exit_ignore',0) | |
2353 | first = xfile.readline() |
|
2361 | first = xfile.readline() | |
2354 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2362 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
2355 | xfile.close() |
|
2363 | xfile.close() | |
2356 | # line by line execution |
|
2364 | # line by line execution | |
2357 | if first.startswith(loghead) or kw['islog']: |
|
2365 | if first.startswith(loghead) or kw['islog']: | |
2358 | print 'Loading log file <%s> one line at a time...' % fname |
|
2366 | print 'Loading log file <%s> one line at a time...' % fname | |
2359 | if kw['quiet']: |
|
2367 | if kw['quiet']: | |
2360 | stdout_save = sys.stdout |
|
2368 | stdout_save = sys.stdout | |
2361 | sys.stdout = StringIO.StringIO() |
|
2369 | sys.stdout = StringIO.StringIO() | |
2362 | try: |
|
2370 | try: | |
2363 | globs,locs = where[0:2] |
|
2371 | globs,locs = where[0:2] | |
2364 | except: |
|
2372 | except: | |
2365 | try: |
|
2373 | try: | |
2366 | globs = locs = where[0] |
|
2374 | globs = locs = where[0] | |
2367 | except: |
|
2375 | except: | |
2368 | globs = locs = globals() |
|
2376 | globs = locs = globals() | |
2369 | badblocks = [] |
|
2377 | badblocks = [] | |
2370 |
|
2378 | |||
2371 | # we also need to identify indented blocks of code when replaying |
|
2379 | # we also need to identify indented blocks of code when replaying | |
2372 | # logs and put them together before passing them to an exec |
|
2380 | # logs and put them together before passing them to an exec | |
2373 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2381 | # statement. This takes a bit of regexp and look-ahead work in the | |
2374 | # file. It's easiest if we swallow the whole thing in memory |
|
2382 | # file. It's easiest if we swallow the whole thing in memory | |
2375 | # first, and manually walk through the lines list moving the |
|
2383 | # first, and manually walk through the lines list moving the | |
2376 | # counter ourselves. |
|
2384 | # counter ourselves. | |
2377 | indent_re = re.compile('\s+\S') |
|
2385 | indent_re = re.compile('\s+\S') | |
2378 | xfile = open(fname) |
|
2386 | xfile = open(fname) | |
2379 | filelines = xfile.readlines() |
|
2387 | filelines = xfile.readlines() | |
2380 | xfile.close() |
|
2388 | xfile.close() | |
2381 | nlines = len(filelines) |
|
2389 | nlines = len(filelines) | |
2382 | lnum = 0 |
|
2390 | lnum = 0 | |
2383 | while lnum < nlines: |
|
2391 | while lnum < nlines: | |
2384 | line = filelines[lnum] |
|
2392 | line = filelines[lnum] | |
2385 | lnum += 1 |
|
2393 | lnum += 1 | |
2386 | # don't re-insert logger status info into cache |
|
2394 | # don't re-insert logger status info into cache | |
2387 | if line.startswith('#log#'): |
|
2395 | if line.startswith('#log#'): | |
2388 | continue |
|
2396 | continue | |
2389 | else: |
|
2397 | else: | |
2390 | # build a block of code (maybe a single line) for execution |
|
2398 | # build a block of code (maybe a single line) for execution | |
2391 | block = line |
|
2399 | block = line | |
2392 | try: |
|
2400 | try: | |
2393 | next = filelines[lnum] # lnum has already incremented |
|
2401 | next = filelines[lnum] # lnum has already incremented | |
2394 | except: |
|
2402 | except: | |
2395 | next = None |
|
2403 | next = None | |
2396 | while next and indent_re.match(next): |
|
2404 | while next and indent_re.match(next): | |
2397 | block += next |
|
2405 | block += next | |
2398 | lnum += 1 |
|
2406 | lnum += 1 | |
2399 | try: |
|
2407 | try: | |
2400 | next = filelines[lnum] |
|
2408 | next = filelines[lnum] | |
2401 | except: |
|
2409 | except: | |
2402 | next = None |
|
2410 | next = None | |
2403 | # now execute the block of one or more lines |
|
2411 | # now execute the block of one or more lines | |
2404 | try: |
|
2412 | try: | |
2405 | exec block in globs,locs |
|
2413 | exec block in globs,locs | |
2406 | except SystemExit: |
|
2414 | except SystemExit: | |
2407 | pass |
|
2415 | pass | |
2408 | except: |
|
2416 | except: | |
2409 | badblocks.append(block.rstrip()) |
|
2417 | badblocks.append(block.rstrip()) | |
2410 | if kw['quiet']: # restore stdout |
|
2418 | if kw['quiet']: # restore stdout | |
2411 | sys.stdout.close() |
|
2419 | sys.stdout.close() | |
2412 | sys.stdout = stdout_save |
|
2420 | sys.stdout = stdout_save | |
2413 | print 'Finished replaying log file <%s>' % fname |
|
2421 | print 'Finished replaying log file <%s>' % fname | |
2414 | if badblocks: |
|
2422 | if badblocks: | |
2415 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2423 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2416 | '<%s> reported errors:' % fname) |
|
2424 | '<%s> reported errors:' % fname) | |
2417 |
|
2425 | |||
2418 | for badline in badblocks: |
|
2426 | for badline in badblocks: | |
2419 | print >> sys.stderr, badline |
|
2427 | print >> sys.stderr, badline | |
2420 | else: # regular file execution |
|
2428 | else: # regular file execution | |
2421 | try: |
|
2429 | try: | |
2422 | execfile(fname,*where) |
|
2430 | execfile(fname,*where) | |
2423 | except SyntaxError: |
|
2431 | except SyntaxError: | |
2424 | self.showsyntaxerror() |
|
2432 | self.showsyntaxerror() | |
2425 | warn('Failure executing file: <%s>' % fname) |
|
2433 | warn('Failure executing file: <%s>' % fname) | |
2426 | except SystemExit,status: |
|
2434 | except SystemExit,status: | |
2427 | if not kw['exit_ignore']: |
|
2435 | if not kw['exit_ignore']: | |
2428 | self.showtraceback() |
|
2436 | self.showtraceback() | |
2429 | warn('Failure executing file: <%s>' % fname) |
|
2437 | warn('Failure executing file: <%s>' % fname) | |
2430 | except: |
|
2438 | except: | |
2431 | self.showtraceback() |
|
2439 | self.showtraceback() | |
2432 | warn('Failure executing file: <%s>' % fname) |
|
2440 | warn('Failure executing file: <%s>' % fname) | |
2433 |
|
2441 | |||
2434 | #************************* end of file <iplib.py> ***************************** |
|
2442 | #************************* end of file <iplib.py> ***************************** |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now