Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,2007 +1,2041 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.1 or newer. |
|
5 | Requires Python 2.1 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 7 |
|
9 | $Id: iplib.py 774 2005-09-01 00:27:53Z fperez $ | |
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-2004 Fernando Perez. <fperez@colorado.edu> |
|
14 | # Copyright (C) 2001-2004 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, much of that class has been copied |
|
20 | # Python standard library. Over time, much 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. The Python License (sec. 2) allows for this, but it's always |
|
22 | # subclassing. The Python License (sec. 2) allows for this, but it's always | |
23 | # nice to acknowledge credit where credit is due. |
|
23 | # nice to acknowledge credit where credit is due. | |
24 | #***************************************************************************** |
|
24 | #***************************************************************************** | |
25 |
|
25 | |||
26 | #**************************************************************************** |
|
26 | #**************************************************************************** | |
27 | # Modules and globals |
|
27 | # Modules and globals | |
28 |
|
28 | |||
29 | from __future__ import generators # for 2.2 backwards-compatibility |
|
29 | from __future__ import generators # for 2.2 backwards-compatibility | |
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 exceptions |
|
40 | import exceptions | |
41 | import keyword |
|
41 | import keyword | |
42 | import new |
|
42 | import new | |
43 | import os, sys, shutil |
|
43 | import os, sys, shutil | |
44 | import code, glob, types, re |
|
44 | import code, glob, types, re | |
45 | import string, StringIO |
|
45 | import string, StringIO | |
46 | import inspect, pydoc |
|
46 | import inspect, pydoc | |
47 | import bdb, pdb |
|
47 | import bdb, pdb | |
48 | import UserList # don't subclass list so this works with Python2.1 |
|
48 | import UserList # don't subclass list so this works with Python2.1 | |
49 | from pprint import pprint, pformat |
|
49 | from pprint import pprint, pformat | |
50 | import cPickle as pickle |
|
50 | import cPickle as pickle | |
51 | import traceback |
|
51 | import traceback | |
52 |
|
52 | |||
53 | # IPython's own modules |
|
53 | # IPython's own modules | |
54 | import IPython |
|
54 | import IPython | |
55 | from IPython import OInspect,PyColorize,ultraTB |
|
55 | from IPython import OInspect,PyColorize,ultraTB | |
56 | from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names |
|
56 | from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names | |
57 | from IPython.Logger import Logger |
|
57 | from IPython.Logger import Logger | |
58 | from IPython.Magic import Magic,magic2python,shlex_split |
|
58 | from IPython.Magic import Magic,magic2python,shlex_split | |
59 | from IPython.usage import cmd_line_usage,interactive_usage |
|
59 | from IPython.usage import cmd_line_usage,interactive_usage | |
60 | from IPython.Struct import Struct |
|
60 | from IPython.Struct import Struct | |
61 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
61 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
62 | from IPython.FakeModule import FakeModule |
|
62 | from IPython.FakeModule import FakeModule | |
63 | from IPython.background_jobs import BackgroundJobManager |
|
63 | from IPython.background_jobs import BackgroundJobManager | |
64 | from IPython.genutils import * |
|
64 | from IPython.genutils import * | |
65 |
|
65 | |||
66 | # Global pointer to the running |
|
66 | # Global pointer to the running | |
67 |
|
67 | |||
68 | # store the builtin raw_input globally, and use this always, in case user code |
|
68 | # store the builtin raw_input globally, and use this always, in case user code | |
69 | # overwrites it (like wx.py.PyShell does) |
|
69 | # overwrites it (like wx.py.PyShell does) | |
70 | raw_input_original = raw_input |
|
70 | raw_input_original = raw_input | |
71 |
|
71 | |||
72 | #**************************************************************************** |
|
72 | #**************************************************************************** | |
73 | # Some utility function definitions |
|
73 | # Some utility function definitions | |
74 |
|
74 | |||
75 | class Bunch: pass |
|
75 | class Bunch: pass | |
76 |
|
76 | |||
77 | def esc_quotes(strng): |
|
77 | def esc_quotes(strng): | |
78 | """Return the input string with single and double quotes escaped out""" |
|
78 | """Return the input string with single and double quotes escaped out""" | |
79 |
|
79 | |||
80 | return strng.replace('"','\\"').replace("'","\\'") |
|
80 | return strng.replace('"','\\"').replace("'","\\'") | |
81 |
|
81 | |||
82 | def import_fail_info(mod_name,fns=None): |
|
82 | def import_fail_info(mod_name,fns=None): | |
83 | """Inform load failure for a module.""" |
|
83 | """Inform load failure for a module.""" | |
84 |
|
84 | |||
85 | if fns == None: |
|
85 | if fns == None: | |
86 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
86 | warn("Loading of %s failed.\n" % (mod_name,)) | |
87 | else: |
|
87 | else: | |
88 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
88 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) | |
89 |
|
89 | |||
90 | def qw_lol(indata): |
|
90 | def qw_lol(indata): | |
91 | """qw_lol('a b') -> [['a','b']], |
|
91 | """qw_lol('a b') -> [['a','b']], | |
92 | otherwise it's just a call to qw(). |
|
92 | otherwise it's just a call to qw(). | |
93 |
|
93 | |||
94 | We need this to make sure the modules_some keys *always* end up as a |
|
94 | We need this to make sure the modules_some keys *always* end up as a | |
95 | list of lists.""" |
|
95 | list of lists.""" | |
96 |
|
96 | |||
97 | if type(indata) in StringTypes: |
|
97 | if type(indata) in StringTypes: | |
98 | return [qw(indata)] |
|
98 | return [qw(indata)] | |
99 | else: |
|
99 | else: | |
100 | return qw(indata) |
|
100 | return qw(indata) | |
101 |
|
101 | |||
102 | def ipmagic(arg_s): |
|
102 | def ipmagic(arg_s): | |
103 | """Call a magic function by name. |
|
103 | """Call a magic function by name. | |
104 |
|
104 | |||
105 | Input: a string containing the name of the magic function to call and any |
|
105 | Input: a string containing the name of the magic function to call and any | |
106 | additional arguments to be passed to the magic. |
|
106 | additional arguments to be passed to the magic. | |
107 |
|
107 | |||
108 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
108 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
109 | prompt: |
|
109 | prompt: | |
110 |
|
110 | |||
111 | In[1]: %name -opt foo bar |
|
111 | In[1]: %name -opt foo bar | |
112 |
|
112 | |||
113 | To call a magic without arguments, simply use ipmagic('name'). |
|
113 | To call a magic without arguments, simply use ipmagic('name'). | |
114 |
|
114 | |||
115 | This provides a proper Python function to call IPython's magics in any |
|
115 | This provides a proper Python function to call IPython's magics in any | |
116 | valid Python code you can type at the interpreter, including loops and |
|
116 | valid Python code you can type at the interpreter, including loops and | |
117 | compound statements. It is added by IPython to the Python builtin |
|
117 | compound statements. It is added by IPython to the Python builtin | |
118 | namespace upon initialization.""" |
|
118 | namespace upon initialization.""" | |
119 |
|
119 | |||
120 | args = arg_s.split(' ',1) |
|
120 | args = arg_s.split(' ',1) | |
121 | magic_name = args[0] |
|
121 | magic_name = args[0] | |
122 | if magic_name.startswith(__IPYTHON__.ESC_MAGIC): |
|
122 | if magic_name.startswith(__IPYTHON__.ESC_MAGIC): | |
123 | magic_name = magic_name[1:] |
|
123 | magic_name = magic_name[1:] | |
124 | try: |
|
124 | try: | |
125 | magic_args = args[1] |
|
125 | magic_args = args[1] | |
126 | except IndexError: |
|
126 | except IndexError: | |
127 | magic_args = '' |
|
127 | magic_args = '' | |
128 | fn = getattr(__IPYTHON__,'magic_'+magic_name,None) |
|
128 | fn = getattr(__IPYTHON__,'magic_'+magic_name,None) | |
129 | if fn is None: |
|
129 | if fn is None: | |
130 | error("Magic function `%s` not found." % magic_name) |
|
130 | error("Magic function `%s` not found." % magic_name) | |
131 | else: |
|
131 | else: | |
132 | magic_args = __IPYTHON__.var_expand(magic_args) |
|
132 | magic_args = __IPYTHON__.var_expand(magic_args) | |
133 | return fn(magic_args) |
|
133 | return fn(magic_args) | |
134 |
|
134 | |||
135 | def ipalias(arg_s): |
|
135 | def ipalias(arg_s): | |
136 | """Call an alias by name. |
|
136 | """Call an alias by name. | |
137 |
|
137 | |||
138 | Input: a string containing the name of the alias to call and any |
|
138 | Input: a string containing the name of the alias to call and any | |
139 | additional arguments to be passed to the magic. |
|
139 | additional arguments to be passed to the magic. | |
140 |
|
140 | |||
141 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
141 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
142 | prompt: |
|
142 | prompt: | |
143 |
|
143 | |||
144 | In[1]: name -opt foo bar |
|
144 | In[1]: name -opt foo bar | |
145 |
|
145 | |||
146 | To call an alias without arguments, simply use ipalias('name'). |
|
146 | To call an alias without arguments, simply use ipalias('name'). | |
147 |
|
147 | |||
148 | This provides a proper Python function to call IPython's aliases in any |
|
148 | This provides a proper Python function to call IPython's aliases in any | |
149 | valid Python code you can type at the interpreter, including loops and |
|
149 | valid Python code you can type at the interpreter, including loops and | |
150 | compound statements. It is added by IPython to the Python builtin |
|
150 | compound statements. It is added by IPython to the Python builtin | |
151 | namespace upon initialization.""" |
|
151 | namespace upon initialization.""" | |
152 |
|
152 | |||
153 | args = arg_s.split(' ',1) |
|
153 | args = arg_s.split(' ',1) | |
154 | alias_name = args[0] |
|
154 | alias_name = args[0] | |
155 | try: |
|
155 | try: | |
156 | alias_args = args[1] |
|
156 | alias_args = args[1] | |
157 | except IndexError: |
|
157 | except IndexError: | |
158 | alias_args = '' |
|
158 | alias_args = '' | |
159 | if alias_name in __IPYTHON__.alias_table: |
|
159 | if alias_name in __IPYTHON__.alias_table: | |
160 | __IPYTHON__.call_alias(alias_name,alias_args) |
|
160 | __IPYTHON__.call_alias(alias_name,alias_args) | |
161 | else: |
|
161 | else: | |
162 | error("Alias `%s` not found." % alias_name) |
|
162 | error("Alias `%s` not found." % alias_name) | |
163 |
|
163 | |||
164 | #----------------------------------------------------------------------------- |
|
164 | #----------------------------------------------------------------------------- | |
165 | # Local use classes |
|
165 | # Local use classes | |
166 | try: |
|
166 | try: | |
167 | from IPython import FlexCompleter |
|
167 | from IPython import FlexCompleter | |
168 |
|
168 | |||
169 | class MagicCompleter(FlexCompleter.Completer): |
|
169 | class MagicCompleter(FlexCompleter.Completer): | |
170 | """Extension of the completer class to work on %-prefixed lines.""" |
|
170 | """Extension of the completer class to work on %-prefixed lines.""" | |
171 |
|
171 | |||
172 | def __init__(self,shell,namespace=None,omit__names=0,alias_table=None): |
|
172 | def __init__(self,shell,namespace=None,omit__names=0,alias_table=None): | |
173 | """MagicCompleter() -> completer |
|
173 | """MagicCompleter() -> completer | |
174 |
|
174 | |||
175 | Return a completer object suitable for use by the readline library |
|
175 | Return a completer object suitable for use by the readline library | |
176 | via readline.set_completer(). |
|
176 | via readline.set_completer(). | |
177 |
|
177 | |||
178 | Inputs: |
|
178 | Inputs: | |
179 |
|
179 | |||
180 | - shell: a pointer to the ipython shell itself. This is needed |
|
180 | - shell: a pointer to the ipython shell itself. This is needed | |
181 | because this completer knows about magic functions, and those can |
|
181 | because this completer knows about magic functions, and those can | |
182 | only be accessed via the ipython instance. |
|
182 | only be accessed via the ipython instance. | |
183 |
|
183 | |||
184 | - namespace: an optional dict where completions are performed. |
|
184 | - namespace: an optional dict where completions are performed. | |
185 |
|
185 | |||
186 | - The optional omit__names parameter sets the completer to omit the |
|
186 | - The optional omit__names parameter sets the completer to omit the | |
187 | 'magic' names (__magicname__) for python objects unless the text |
|
187 | 'magic' names (__magicname__) for python objects unless the text | |
188 | to be completed explicitly starts with one or more underscores. |
|
188 | to be completed explicitly starts with one or more underscores. | |
189 |
|
189 | |||
190 | - If alias_table is supplied, it should be a dictionary of aliases |
|
190 | - If alias_table is supplied, it should be a dictionary of aliases | |
191 | to complete. """ |
|
191 | to complete. """ | |
192 |
|
192 | |||
193 | FlexCompleter.Completer.__init__(self,namespace) |
|
193 | FlexCompleter.Completer.__init__(self,namespace) | |
194 | self.magic_prefix = shell.name+'.magic_' |
|
194 | self.magic_prefix = shell.name+'.magic_' | |
195 | self.magic_escape = shell.ESC_MAGIC |
|
195 | self.magic_escape = shell.ESC_MAGIC | |
196 | self.readline = FlexCompleter.readline |
|
196 | self.readline = FlexCompleter.readline | |
197 | delims = self.readline.get_completer_delims() |
|
197 | delims = self.readline.get_completer_delims() | |
198 | delims = delims.replace(self.magic_escape,'') |
|
198 | delims = delims.replace(self.magic_escape,'') | |
199 | self.readline.set_completer_delims(delims) |
|
199 | self.readline.set_completer_delims(delims) | |
200 | self.get_line_buffer = self.readline.get_line_buffer |
|
200 | self.get_line_buffer = self.readline.get_line_buffer | |
201 | self.omit__names = omit__names |
|
201 | self.omit__names = omit__names | |
202 | self.merge_completions = shell.rc.readline_merge_completions |
|
202 | self.merge_completions = shell.rc.readline_merge_completions | |
203 |
|
203 | |||
204 | if alias_table is None: |
|
204 | if alias_table is None: | |
205 | alias_table = {} |
|
205 | alias_table = {} | |
206 | self.alias_table = alias_table |
|
206 | self.alias_table = alias_table | |
207 | # Regexp to split filenames with spaces in them |
|
207 | # Regexp to split filenames with spaces in them | |
208 | self.space_name_re = re.compile(r'([^\\] )') |
|
208 | self.space_name_re = re.compile(r'([^\\] )') | |
209 | # Hold a local ref. to glob.glob for speed |
|
209 | # Hold a local ref. to glob.glob for speed | |
210 | self.glob = glob.glob |
|
210 | self.glob = glob.glob | |
211 | # Special handling of backslashes needed in win32 platforms |
|
211 | # Special handling of backslashes needed in win32 platforms | |
212 | if sys.platform == "win32": |
|
212 | if sys.platform == "win32": | |
213 | self.clean_glob = self._clean_glob_win32 |
|
213 | self.clean_glob = self._clean_glob_win32 | |
214 | else: |
|
214 | else: | |
215 | self.clean_glob = self._clean_glob |
|
215 | self.clean_glob = self._clean_glob | |
216 | self.matchers = [self.python_matches, |
|
216 | self.matchers = [self.python_matches, | |
217 | self.file_matches, |
|
217 | self.file_matches, | |
218 | self.alias_matches, |
|
218 | self.alias_matches, | |
219 | self.python_func_kw_matches] |
|
219 | self.python_func_kw_matches] | |
220 |
|
220 | |||
221 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
221 | # Code contributed by Alex Schmolck, for ipython/emacs integration | |
222 | def all_completions(self, text): |
|
222 | def all_completions(self, text): | |
223 | """Return all possible completions for the benefit of emacs.""" |
|
223 | """Return all possible completions for the benefit of emacs.""" | |
224 |
|
224 | |||
225 | completions = [] |
|
225 | completions = [] | |
226 | try: |
|
226 | try: | |
227 | for i in xrange(sys.maxint): |
|
227 | for i in xrange(sys.maxint): | |
228 | res = self.complete(text, i) |
|
228 | res = self.complete(text, i) | |
229 |
|
229 | |||
230 | if not res: break |
|
230 | if not res: break | |
231 |
|
231 | |||
232 | completions.append(res) |
|
232 | completions.append(res) | |
233 | #XXX workaround for ``notDefined.<tab>`` |
|
233 | #XXX workaround for ``notDefined.<tab>`` | |
234 | except NameError: |
|
234 | except NameError: | |
235 | pass |
|
235 | pass | |
236 | return completions |
|
236 | return completions | |
237 | # /end Alex Schmolck code. |
|
237 | # /end Alex Schmolck code. | |
238 |
|
238 | |||
239 | def _clean_glob(self,text): |
|
239 | def _clean_glob(self,text): | |
240 | return self.glob("%s*" % text) |
|
240 | return self.glob("%s*" % text) | |
241 |
|
241 | |||
242 | def _clean_glob_win32(self,text): |
|
242 | def _clean_glob_win32(self,text): | |
243 | return [f.replace("\\","/") |
|
243 | return [f.replace("\\","/") | |
244 | for f in self.glob("%s*" % text)] |
|
244 | for f in self.glob("%s*" % text)] | |
245 |
|
245 | |||
246 | def file_matches(self, text): |
|
246 | def file_matches(self, text): | |
247 | """Match filneames, expanding ~USER type strings. |
|
247 | """Match filneames, expanding ~USER type strings. | |
248 |
|
248 | |||
249 | Most of the seemingly convoluted logic in this completer is an |
|
249 | Most of the seemingly convoluted logic in this completer is an | |
250 | attempt to handle filenames with spaces in them. And yet it's not |
|
250 | attempt to handle filenames with spaces in them. And yet it's not | |
251 | quite perfect, because Python's readline doesn't expose all of the |
|
251 | quite perfect, because Python's readline doesn't expose all of the | |
252 | GNU readline details needed for this to be done correctly. |
|
252 | GNU readline details needed for this to be done correctly. | |
253 |
|
253 | |||
254 | For a filename with a space in it, the printed completions will be |
|
254 | For a filename with a space in it, the printed completions will be | |
255 | only the parts after what's already been typed (instead of the |
|
255 | only the parts after what's already been typed (instead of the | |
256 | full completions, as is normally done). I don't think with the |
|
256 | full completions, as is normally done). I don't think with the | |
257 | current (as of Python 2.3) Python readline it's possible to do |
|
257 | current (as of Python 2.3) Python readline it's possible to do | |
258 | better.""" |
|
258 | better.""" | |
259 |
|
259 | |||
260 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
260 | #print 'Completer->file_matches: <%s>' % text # dbg | |
261 |
|
261 | |||
262 | # chars that require escaping with backslash - i.e. chars |
|
262 | # chars that require escaping with backslash - i.e. chars | |
263 | # that readline treats incorrectly as delimiters, but we |
|
263 | # that readline treats incorrectly as delimiters, but we | |
264 | # don't want to treat as delimiters in filename matching |
|
264 | # don't want to treat as delimiters in filename matching | |
265 | # when escaped with backslash |
|
265 | # when escaped with backslash | |
266 |
|
266 | |||
267 | protectables = ' ()[]{}' |
|
267 | protectables = ' ()[]{}' | |
268 |
|
268 | |||
269 | def protect_filename(s): |
|
269 | def protect_filename(s): | |
270 | return "".join([(ch in protectables and '\\' + ch or ch) |
|
270 | return "".join([(ch in protectables and '\\' + ch or ch) | |
271 | for ch in s]) |
|
271 | for ch in s]) | |
272 |
|
272 | |||
273 | lbuf = self.get_line_buffer()[:self.readline.get_endidx()] |
|
273 | lbuf = self.get_line_buffer()[:self.readline.get_endidx()] | |
274 | open_quotes = 0 # track strings with open quotes |
|
274 | open_quotes = 0 # track strings with open quotes | |
275 | try: |
|
275 | try: | |
276 | lsplit = shlex_split(lbuf)[-1] |
|
276 | lsplit = shlex_split(lbuf)[-1] | |
277 | except ValueError: |
|
277 | except ValueError: | |
278 | # typically an unmatched ", or backslash without escaped char. |
|
278 | # typically an unmatched ", or backslash without escaped char. | |
279 | if lbuf.count('"')==1: |
|
279 | if lbuf.count('"')==1: | |
280 | open_quotes = 1 |
|
280 | open_quotes = 1 | |
281 | lsplit = lbuf.split('"')[-1] |
|
281 | lsplit = lbuf.split('"')[-1] | |
282 | elif lbuf.count("'")==1: |
|
282 | elif lbuf.count("'")==1: | |
283 | open_quotes = 1 |
|
283 | open_quotes = 1 | |
284 | lsplit = lbuf.split("'")[-1] |
|
284 | lsplit = lbuf.split("'")[-1] | |
285 | else: |
|
285 | else: | |
286 | return None |
|
286 | return None | |
287 | except IndexError: |
|
287 | except IndexError: | |
288 | # tab pressed on empty line |
|
288 | # tab pressed on empty line | |
289 | lsplit = "" |
|
289 | lsplit = "" | |
290 |
|
290 | |||
291 | if lsplit != protect_filename(lsplit): |
|
291 | if lsplit != protect_filename(lsplit): | |
292 | # if protectables are found, do matching on the whole escaped |
|
292 | # if protectables are found, do matching on the whole escaped | |
293 | # name |
|
293 | # name | |
294 | has_protectables = 1 |
|
294 | has_protectables = 1 | |
295 | text0,text = text,lsplit |
|
295 | text0,text = text,lsplit | |
296 | else: |
|
296 | else: | |
297 | has_protectables = 0 |
|
297 | has_protectables = 0 | |
298 | text = os.path.expanduser(text) |
|
298 | text = os.path.expanduser(text) | |
299 |
|
299 | |||
300 | if text == "": |
|
300 | if text == "": | |
301 | return [protect_filename(f) for f in self.glob("*")] |
|
301 | return [protect_filename(f) for f in self.glob("*")] | |
302 |
|
302 | |||
303 | m0 = self.clean_glob(text.replace('\\','')) |
|
303 | m0 = self.clean_glob(text.replace('\\','')) | |
304 | if has_protectables: |
|
304 | if has_protectables: | |
305 | # If we had protectables, we need to revert our changes to the |
|
305 | # If we had protectables, we need to revert our changes to the | |
306 | # beginning of filename so that we don't double-write the part |
|
306 | # beginning of filename so that we don't double-write the part | |
307 | # of the filename we have so far |
|
307 | # of the filename we have so far | |
308 | len_lsplit = len(lsplit) |
|
308 | len_lsplit = len(lsplit) | |
309 | matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0] |
|
309 | matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0] | |
310 | else: |
|
310 | else: | |
311 | if open_quotes: |
|
311 | if open_quotes: | |
312 | # if we have a string with an open quote, we don't need to |
|
312 | # if we have a string with an open quote, we don't need to | |
313 | # protect the names at all (and we _shouldn't_, as it |
|
313 | # protect the names at all (and we _shouldn't_, as it | |
314 | # would cause bugs when the filesystem call is made). |
|
314 | # would cause bugs when the filesystem call is made). | |
315 | matches = m0 |
|
315 | matches = m0 | |
316 | else: |
|
316 | else: | |
317 | matches = [protect_filename(f) for f in m0] |
|
317 | matches = [protect_filename(f) for f in m0] | |
318 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
318 | if len(matches) == 1 and os.path.isdir(matches[0]): | |
319 | # Takes care of links to directories also. Use '/' |
|
319 | # Takes care of links to directories also. Use '/' | |
320 | # explicitly, even under Windows, so that name completions |
|
320 | # explicitly, even under Windows, so that name completions | |
321 | # don't end up escaped. |
|
321 | # don't end up escaped. | |
322 | matches[0] += '/' |
|
322 | matches[0] += '/' | |
323 | return matches |
|
323 | return matches | |
324 |
|
324 | |||
325 | def alias_matches(self, text): |
|
325 | def alias_matches(self, text): | |
326 | """Match internal system aliases""" |
|
326 | """Match internal system aliases""" | |
327 | #print 'Completer->alias_matches:',text # dbg |
|
327 | #print 'Completer->alias_matches:',text # dbg | |
328 | text = os.path.expanduser(text) |
|
328 | text = os.path.expanduser(text) | |
329 | aliases = self.alias_table.keys() |
|
329 | aliases = self.alias_table.keys() | |
330 | if text == "": |
|
330 | if text == "": | |
331 | return aliases |
|
331 | return aliases | |
332 | else: |
|
332 | else: | |
333 | return [alias for alias in aliases if alias.startswith(text)] |
|
333 | return [alias for alias in aliases if alias.startswith(text)] | |
334 |
|
334 | |||
335 | def python_matches(self,text): |
|
335 | def python_matches(self,text): | |
336 | """Match attributes or global python names""" |
|
336 | """Match attributes or global python names""" | |
337 | #print 'Completer->python_matches' # dbg |
|
337 | #print 'Completer->python_matches' # dbg | |
338 | if "." in text: |
|
338 | if "." in text: | |
339 | try: |
|
339 | try: | |
340 | matches = self.attr_matches(text) |
|
340 | matches = self.attr_matches(text) | |
341 | if text.endswith('.') and self.omit__names: |
|
341 | if text.endswith('.') and self.omit__names: | |
342 | if self.omit__names == 1: |
|
342 | if self.omit__names == 1: | |
343 | # true if txt is _not_ a __ name, false otherwise: |
|
343 | # true if txt is _not_ a __ name, false otherwise: | |
344 | no__name = (lambda txt: |
|
344 | no__name = (lambda txt: | |
345 | re.match(r'.*\.__.*?__',txt) is None) |
|
345 | re.match(r'.*\.__.*?__',txt) is None) | |
346 | else: |
|
346 | else: | |
347 | # true if txt is _not_ a _ name, false otherwise: |
|
347 | # true if txt is _not_ a _ name, false otherwise: | |
348 | no__name = (lambda txt: |
|
348 | no__name = (lambda txt: | |
349 | re.match(r'.*\._.*?',txt) is None) |
|
349 | re.match(r'.*\._.*?',txt) is None) | |
350 | matches = filter(no__name, matches) |
|
350 | matches = filter(no__name, matches) | |
351 | except NameError: |
|
351 | except NameError: | |
352 | # catches <undefined attributes>.<tab> |
|
352 | # catches <undefined attributes>.<tab> | |
353 | matches = [] |
|
353 | matches = [] | |
354 | else: |
|
354 | else: | |
355 | matches = self.global_matches(text) |
|
355 | matches = self.global_matches(text) | |
356 | # this is so completion finds magics when automagic is on: |
|
356 | # this is so completion finds magics when automagic is on: | |
357 | if matches == [] and not text.startswith(os.sep): |
|
357 | if matches == [] and not text.startswith(os.sep): | |
358 | matches = self.attr_matches(self.magic_prefix+text) |
|
358 | matches = self.attr_matches(self.magic_prefix+text) | |
359 | return matches |
|
359 | return matches | |
360 |
|
360 | |||
361 | def _default_arguments(self, obj): |
|
361 | def _default_arguments(self, obj): | |
362 | """Return the list of default arguments of obj if it is callable, |
|
362 | """Return the list of default arguments of obj if it is callable, | |
363 | or empty list otherwise.""" |
|
363 | or empty list otherwise.""" | |
364 |
|
364 | |||
365 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
365 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
366 | # for classes, check for __init__,__new__ |
|
366 | # for classes, check for __init__,__new__ | |
367 | if inspect.isclass(obj): |
|
367 | if inspect.isclass(obj): | |
368 | obj = (getattr(obj,'__init__',None) or |
|
368 | obj = (getattr(obj,'__init__',None) or | |
369 | getattr(obj,'__new__',None)) |
|
369 | getattr(obj,'__new__',None)) | |
370 | # for all others, check if they are __call__able |
|
370 | # for all others, check if they are __call__able | |
371 | elif hasattr(obj, '__call__'): |
|
371 | elif hasattr(obj, '__call__'): | |
372 | obj = obj.__call__ |
|
372 | obj = obj.__call__ | |
373 | # XXX: is there a way to handle the builtins ? |
|
373 | # XXX: is there a way to handle the builtins ? | |
374 | try: |
|
374 | try: | |
375 | args,_,_1,defaults = inspect.getargspec(obj) |
|
375 | args,_,_1,defaults = inspect.getargspec(obj) | |
376 | if defaults: |
|
376 | if defaults: | |
377 | return args[-len(defaults):] |
|
377 | return args[-len(defaults):] | |
378 | except TypeError: pass |
|
378 | except TypeError: pass | |
379 | return [] |
|
379 | return [] | |
380 |
|
380 | |||
381 | def python_func_kw_matches(self,text): |
|
381 | def python_func_kw_matches(self,text): | |
382 | """Match named parameters (kwargs) of the last open function""" |
|
382 | """Match named parameters (kwargs) of the last open function""" | |
383 |
|
383 | |||
384 | if "." in text: # a parameter cannot be dotted |
|
384 | if "." in text: # a parameter cannot be dotted | |
385 | return [] |
|
385 | return [] | |
386 | try: regexp = self.__funcParamsRegex |
|
386 | try: regexp = self.__funcParamsRegex | |
387 | except AttributeError: |
|
387 | except AttributeError: | |
388 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
388 | regexp = self.__funcParamsRegex = re.compile(r''' | |
389 | '.*?' | # single quoted strings or |
|
389 | '.*?' | # single quoted strings or | |
390 | ".*?" | # double quoted strings or |
|
390 | ".*?" | # double quoted strings or | |
391 | \w+ | # identifier |
|
391 | \w+ | # identifier | |
392 | \S # other characters |
|
392 | \S # other characters | |
393 | ''', re.VERBOSE | re.DOTALL) |
|
393 | ''', re.VERBOSE | re.DOTALL) | |
394 | # 1. find the nearest identifier that comes before an unclosed |
|
394 | # 1. find the nearest identifier that comes before an unclosed | |
395 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
395 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" | |
396 | tokens = regexp.findall(self.get_line_buffer()) |
|
396 | tokens = regexp.findall(self.get_line_buffer()) | |
397 | tokens.reverse() |
|
397 | tokens.reverse() | |
398 | iterTokens = iter(tokens); openPar = 0 |
|
398 | iterTokens = iter(tokens); openPar = 0 | |
399 | for token in iterTokens: |
|
399 | for token in iterTokens: | |
400 | if token == ')': |
|
400 | if token == ')': | |
401 | openPar -= 1 |
|
401 | openPar -= 1 | |
402 | elif token == '(': |
|
402 | elif token == '(': | |
403 | openPar += 1 |
|
403 | openPar += 1 | |
404 | if openPar > 0: |
|
404 | if openPar > 0: | |
405 | # found the last unclosed parenthesis |
|
405 | # found the last unclosed parenthesis | |
406 | break |
|
406 | break | |
407 | else: |
|
407 | else: | |
408 | return [] |
|
408 | return [] | |
409 | # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" ) |
|
409 | # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" ) | |
410 | ids = [] |
|
410 | ids = [] | |
411 | isId = re.compile(r'\w+$').match |
|
411 | isId = re.compile(r'\w+$').match | |
412 | while True: |
|
412 | while True: | |
413 | try: |
|
413 | try: | |
414 | ids.append(iterTokens.next()) |
|
414 | ids.append(iterTokens.next()) | |
415 | if not isId(ids[-1]): |
|
415 | if not isId(ids[-1]): | |
416 | ids.pop(); break |
|
416 | ids.pop(); break | |
417 | if not iterTokens.next() == '.': |
|
417 | if not iterTokens.next() == '.': | |
418 | break |
|
418 | break | |
419 | except StopIteration: |
|
419 | except StopIteration: | |
420 | break |
|
420 | break | |
421 | # lookup the candidate callable matches either using global_matches |
|
421 | # lookup the candidate callable matches either using global_matches | |
422 | # or attr_matches for dotted names |
|
422 | # or attr_matches for dotted names | |
423 | if len(ids) == 1: |
|
423 | if len(ids) == 1: | |
424 | callableMatches = self.global_matches(ids[0]) |
|
424 | callableMatches = self.global_matches(ids[0]) | |
425 | else: |
|
425 | else: | |
426 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
426 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
427 | argMatches = [] |
|
427 | argMatches = [] | |
428 | for callableMatch in callableMatches: |
|
428 | for callableMatch in callableMatches: | |
429 | try: namedArgs = self._default_arguments(eval(callableMatch, |
|
429 | try: namedArgs = self._default_arguments(eval(callableMatch, | |
430 | self.namespace)) |
|
430 | self.namespace)) | |
431 | except: continue |
|
431 | except: continue | |
432 | for namedArg in namedArgs: |
|
432 | for namedArg in namedArgs: | |
433 | if namedArg.startswith(text): |
|
433 | if namedArg.startswith(text): | |
434 | argMatches.append("%s=" %namedArg) |
|
434 | argMatches.append("%s=" %namedArg) | |
435 | return argMatches |
|
435 | return argMatches | |
436 |
|
436 | |||
437 | def complete(self, text, state): |
|
437 | def complete(self, text, state): | |
438 | """Return the next possible completion for 'text'. |
|
438 | """Return the next possible completion for 'text'. | |
439 |
|
439 | |||
440 | This is called successively with state == 0, 1, 2, ... until it |
|
440 | This is called successively with state == 0, 1, 2, ... until it | |
441 | returns None. The completion should begin with 'text'. """ |
|
441 | returns None. The completion should begin with 'text'. """ | |
442 |
|
442 | |||
443 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
443 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg | |
444 | magic_escape = self.magic_escape |
|
444 | magic_escape = self.magic_escape | |
445 | magic_prefix = self.magic_prefix |
|
445 | magic_prefix = self.magic_prefix | |
446 |
|
446 | |||
447 | try: |
|
447 | try: | |
448 | if text.startswith(magic_escape): |
|
448 | if text.startswith(magic_escape): | |
449 | text = text.replace(magic_escape,magic_prefix) |
|
449 | text = text.replace(magic_escape,magic_prefix) | |
450 | elif text.startswith('~'): |
|
450 | elif text.startswith('~'): | |
451 | text = os.path.expanduser(text) |
|
451 | text = os.path.expanduser(text) | |
452 | if state == 0: |
|
452 | if state == 0: | |
453 | # Extend the list of completions with the results of each |
|
453 | # Extend the list of completions with the results of each | |
454 | # matcher, so we return results to the user from all |
|
454 | # matcher, so we return results to the user from all | |
455 | # namespaces. |
|
455 | # namespaces. | |
456 | if self.merge_completions: |
|
456 | if self.merge_completions: | |
457 | self.matches = [] |
|
457 | self.matches = [] | |
458 | for matcher in self.matchers: |
|
458 | for matcher in self.matchers: | |
459 | self.matches.extend(matcher(text)) |
|
459 | self.matches.extend(matcher(text)) | |
460 | else: |
|
460 | else: | |
461 | for matcher in self.matchers: |
|
461 | for matcher in self.matchers: | |
462 | self.matches = matcher(text) |
|
462 | self.matches = matcher(text) | |
463 | if self.matches: |
|
463 | if self.matches: | |
464 | break |
|
464 | break | |
465 |
|
465 | |||
466 | try: |
|
466 | try: | |
467 | return self.matches[state].replace(magic_prefix,magic_escape) |
|
467 | return self.matches[state].replace(magic_prefix,magic_escape) | |
468 | except IndexError: |
|
468 | except IndexError: | |
469 | return None |
|
469 | return None | |
470 | except: |
|
470 | except: | |
471 | # If completion fails, don't annoy the user. |
|
471 | # If completion fails, don't annoy the user. | |
472 | pass |
|
472 | pass | |
473 |
|
473 | |||
474 | except ImportError: |
|
474 | except ImportError: | |
475 | pass # no readline support |
|
475 | pass # no readline support | |
476 |
|
476 | |||
477 | except KeyError: |
|
477 | except KeyError: | |
478 | pass # Windows doesn't set TERM, it doesn't matter |
|
478 | pass # Windows doesn't set TERM, it doesn't matter | |
479 |
|
479 | |||
480 |
|
480 | |||
481 | class InputList(UserList.UserList): |
|
481 | class InputList(UserList.UserList): | |
482 | """Class to store user input. |
|
482 | """Class to store user input. | |
483 |
|
483 | |||
484 | It's basically a list, but slices return a string instead of a list, thus |
|
484 | It's basically a list, but slices return a string instead of a list, thus | |
485 | allowing things like (assuming 'In' is an instance): |
|
485 | allowing things like (assuming 'In' is an instance): | |
486 |
|
486 | |||
487 | exec In[4:7] |
|
487 | exec In[4:7] | |
488 |
|
488 | |||
489 | or |
|
489 | or | |
490 |
|
490 | |||
491 | exec In[5:9] + In[14] + In[21:25]""" |
|
491 | exec In[5:9] + In[14] + In[21:25]""" | |
492 |
|
492 | |||
493 | def __getslice__(self,i,j): |
|
493 | def __getslice__(self,i,j): | |
494 | return ''.join(UserList.UserList.__getslice__(self,i,j)) |
|
494 | return ''.join(UserList.UserList.__getslice__(self,i,j)) | |
495 |
|
495 | |||
496 | #**************************************************************************** |
|
496 | #**************************************************************************** | |
497 | # Local use exceptions |
|
497 | # Local use exceptions | |
498 | class SpaceInInput(exceptions.Exception): |
|
498 | class SpaceInInput(exceptions.Exception): | |
499 | pass |
|
499 | pass | |
500 |
|
500 | |||
501 | #**************************************************************************** |
|
501 | #**************************************************************************** | |
502 | # Main IPython class |
|
502 | # Main IPython class | |
503 |
|
503 | |||
504 | class InteractiveShell(code.InteractiveConsole, Logger, Magic): |
|
504 | class InteractiveShell(code.InteractiveConsole, Logger, Magic): | |
505 | """An enhanced console for Python.""" |
|
505 | """An enhanced console for Python.""" | |
506 |
|
506 | |||
507 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
507 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
508 | user_ns = None,banner2='', |
|
508 | user_ns = None,banner2='', | |
509 | custom_exceptions=((),None)): |
|
509 | custom_exceptions=((),None)): | |
510 |
|
510 | |||
511 | # Put a reference to self in builtins so that any form of embedded or |
|
511 | # Put a reference to self in builtins so that any form of embedded or | |
512 | # imported code can test for being inside IPython. |
|
512 | # imported code can test for being inside IPython. | |
513 | __builtin__.__IPYTHON__ = self |
|
513 | __builtin__.__IPYTHON__ = self | |
514 |
|
514 | |||
515 | # And load into builtins ipmagic/ipalias as well |
|
515 | # And load into builtins ipmagic/ipalias as well | |
516 | __builtin__.ipmagic = ipmagic |
|
516 | __builtin__.ipmagic = ipmagic | |
517 | __builtin__.ipalias = ipalias |
|
517 | __builtin__.ipalias = ipalias | |
518 |
|
518 | |||
519 | # Add to __builtin__ other parts of IPython's public API |
|
519 | # Add to __builtin__ other parts of IPython's public API | |
520 | __builtin__.ip_set_hook = self.set_hook |
|
520 | __builtin__.ip_set_hook = self.set_hook | |
521 |
|
521 | |||
522 | # Keep in the builtins a flag for when IPython is active. We set it |
|
522 | # Keep in the builtins a flag for when IPython is active. We set it | |
523 | # with setdefault so that multiple nested IPythons don't clobber one |
|
523 | # with setdefault so that multiple nested IPythons don't clobber one | |
524 | # another. Each will increase its value by one upon being activated, |
|
524 | # another. Each will increase its value by one upon being activated, | |
525 | # which also gives us a way to determine the nesting level. |
|
525 | # which also gives us a way to determine the nesting level. | |
526 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
526 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
527 |
|
527 | |||
528 | # Inform the user of ipython's fast exit magics. |
|
528 | # Inform the user of ipython's fast exit magics. | |
529 | _exit = ' Use %Exit or %Quit to exit without confirmation.' |
|
529 | _exit = ' Use %Exit or %Quit to exit without confirmation.' | |
530 | __builtin__.exit += _exit |
|
530 | __builtin__.exit += _exit | |
531 | __builtin__.quit += _exit |
|
531 | __builtin__.quit += _exit | |
532 |
|
532 | |||
533 | # Create the namespace where the user will operate: |
|
533 | # Create the namespace where the user will operate: | |
534 |
|
534 | |||
535 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
535 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
536 | # level as a dict instead of a module. This is a manual fix, but I |
|
536 | # level as a dict instead of a module. This is a manual fix, but I | |
537 | # should really track down where the problem is coming from. Alex |
|
537 | # should really track down where the problem is coming from. Alex | |
538 | # Schmolck reported this problem first. |
|
538 | # Schmolck reported this problem first. | |
539 |
|
539 | |||
540 | # A useful post by Alex Martelli on this topic: |
|
540 | # A useful post by Alex Martelli on this topic: | |
541 | # Re: inconsistent value from __builtins__ |
|
541 | # Re: inconsistent value from __builtins__ | |
542 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
542 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
543 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
543 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
544 | # Gruppen: comp.lang.python |
|
544 | # Gruppen: comp.lang.python | |
545 | # Referenzen: 1 |
|
545 | # Referenzen: 1 | |
546 |
|
546 | |||
547 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
547 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
548 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
548 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
549 | # > <type 'dict'> |
|
549 | # > <type 'dict'> | |
550 | # > >>> print type(__builtins__) |
|
550 | # > >>> print type(__builtins__) | |
551 | # > <type 'module'> |
|
551 | # > <type 'module'> | |
552 | # > Is this difference in return value intentional? |
|
552 | # > Is this difference in return value intentional? | |
553 |
|
553 | |||
554 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
554 | # Well, it's documented that '__builtins__' can be either a dictionary | |
555 | # or a module, and it's been that way for a long time. Whether it's |
|
555 | # or a module, and it's been that way for a long time. Whether it's | |
556 | # intentional (or sensible), I don't know. In any case, the idea is that |
|
556 | # intentional (or sensible), I don't know. In any case, the idea is that | |
557 | # if you need to access the built-in namespace directly, you should start |
|
557 | # if you need to access the built-in namespace directly, you should start | |
558 | # with "import __builtin__" (note, no 's') which will definitely give you |
|
558 | # with "import __builtin__" (note, no 's') which will definitely give you | |
559 | # a module. Yeah, it's somewhat confusing:-(. |
|
559 | # a module. Yeah, it's somewhat confusing:-(. | |
560 |
|
560 | |||
561 | if user_ns is None: |
|
561 | if user_ns is None: | |
562 | # Set __name__ to __main__ to better match the behavior of the |
|
562 | # Set __name__ to __main__ to better match the behavior of the | |
563 | # normal interpreter. |
|
563 | # normal interpreter. | |
564 | self.user_ns = {'__name__' :'__main__', |
|
564 | self.user_ns = {'__name__' :'__main__', | |
565 | '__builtins__' : __builtin__, |
|
565 | '__builtins__' : __builtin__, | |
566 | } |
|
566 | } | |
567 | else: |
|
567 | else: | |
568 | self.user_ns = user_ns |
|
568 | self.user_ns = user_ns | |
569 |
|
569 | |||
570 | # The user namespace MUST have a pointer to the shell itself. |
|
570 | # The user namespace MUST have a pointer to the shell itself. | |
571 | self.user_ns[name] = self |
|
571 | self.user_ns[name] = self | |
572 |
|
572 | |||
573 | # We need to insert into sys.modules something that looks like a |
|
573 | # We need to insert into sys.modules something that looks like a | |
574 | # module but which accesses the IPython namespace, for shelve and |
|
574 | # module but which accesses the IPython namespace, for shelve and | |
575 | # pickle to work interactively. Normally they rely on getting |
|
575 | # pickle to work interactively. Normally they rely on getting | |
576 | # everything out of __main__, but for embedding purposes each IPython |
|
576 | # everything out of __main__, but for embedding purposes each IPython | |
577 | # instance has its own private namespace, so we can't go shoving |
|
577 | # instance has its own private namespace, so we can't go shoving | |
578 | # everything into __main__. |
|
578 | # everything into __main__. | |
579 |
|
579 | |||
580 | try: |
|
580 | try: | |
581 | main_name = self.user_ns['__name__'] |
|
581 | main_name = self.user_ns['__name__'] | |
582 | except KeyError: |
|
582 | except KeyError: | |
583 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
583 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
584 | else: |
|
584 | else: | |
585 | #print "pickle hack in place" # dbg |
|
585 | #print "pickle hack in place" # dbg | |
586 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
586 | sys.modules[main_name] = FakeModule(self.user_ns) | |
587 |
|
587 | |||
588 | # List of input with multi-line handling. |
|
588 | # List of input with multi-line handling. | |
589 | # Fill its zero entry, user counter starts at 1 |
|
589 | # Fill its zero entry, user counter starts at 1 | |
590 | self.input_hist = InputList(['\n']) |
|
590 | self.input_hist = InputList(['\n']) | |
591 |
|
591 | |||
592 | # list of visited directories |
|
592 | # list of visited directories | |
593 | self.dir_hist = [os.getcwd()] |
|
593 | self.dir_hist = [os.getcwd()] | |
594 |
|
594 | |||
595 | # dict of output history |
|
595 | # dict of output history | |
596 | self.output_hist = {} |
|
596 | self.output_hist = {} | |
597 |
|
597 | |||
598 | # dict of names to be treated as system aliases. Each entry in the |
|
598 | # dict of names to be treated as system aliases. Each entry in the | |
599 | # alias table must be a 2-tuple of the form (N,name), where N is the |
|
599 | # alias table must be a 2-tuple of the form (N,name), where N is the | |
600 | # number of positional arguments of the alias. |
|
600 | # number of positional arguments of the alias. | |
601 | self.alias_table = {} |
|
601 | self.alias_table = {} | |
602 |
|
602 | |||
603 | # dict of things NOT to alias (keywords and builtins) |
|
603 | # dict of things NOT to alias (keywords and builtins) | |
604 | self.no_alias = {} |
|
604 | self.no_alias = {} | |
605 | for key in keyword.kwlist: |
|
605 | for key in keyword.kwlist: | |
606 | self.no_alias[key] = 1 |
|
606 | self.no_alias[key] = 1 | |
607 | self.no_alias.update(__builtin__.__dict__) |
|
607 | self.no_alias.update(__builtin__.__dict__) | |
608 |
|
608 | |||
609 | # make global variables for user access to these |
|
609 | # make global variables for user access to these | |
610 | self.user_ns['_ih'] = self.input_hist |
|
610 | self.user_ns['_ih'] = self.input_hist | |
611 | self.user_ns['_oh'] = self.output_hist |
|
611 | self.user_ns['_oh'] = self.output_hist | |
612 | self.user_ns['_dh'] = self.dir_hist |
|
612 | self.user_ns['_dh'] = self.dir_hist | |
613 |
|
613 | |||
614 | # user aliases to input and output histories |
|
614 | # user aliases to input and output histories | |
615 | self.user_ns['In'] = self.input_hist |
|
615 | self.user_ns['In'] = self.input_hist | |
616 | self.user_ns['Out'] = self.output_hist |
|
616 | self.user_ns['Out'] = self.output_hist | |
617 |
|
617 | |||
618 | # Store the actual shell's name |
|
618 | # Store the actual shell's name | |
619 | self.name = name |
|
619 | self.name = name | |
620 |
|
620 | |||
621 | # Object variable to store code object waiting execution. This is |
|
621 | # Object variable to store code object waiting execution. This is | |
622 | # used mainly by the multithreaded shells, but it can come in handy in |
|
622 | # used mainly by the multithreaded shells, but it can come in handy in | |
623 | # other situations. No need to use a Queue here, since it's a single |
|
623 | # other situations. No need to use a Queue here, since it's a single | |
624 | # item which gets cleared once run. |
|
624 | # item which gets cleared once run. | |
625 | self.code_to_run = None |
|
625 | self.code_to_run = None | |
626 |
|
626 | |||
627 | # Job manager (for jobs run as background threads) |
|
627 | # Job manager (for jobs run as background threads) | |
628 | self.jobs = BackgroundJobManager() |
|
628 | self.jobs = BackgroundJobManager() | |
629 | # Put the job manager into builtins so it's always there. |
|
629 | # Put the job manager into builtins so it's always there. | |
630 | __builtin__.jobs = self.jobs |
|
630 | __builtin__.jobs = self.jobs | |
631 |
|
631 | |||
632 | # escapes for automatic behavior on the command line |
|
632 | # escapes for automatic behavior on the command line | |
633 | self.ESC_SHELL = '!' |
|
633 | self.ESC_SHELL = '!' | |
634 | self.ESC_HELP = '?' |
|
634 | self.ESC_HELP = '?' | |
635 | self.ESC_MAGIC = '%' |
|
635 | self.ESC_MAGIC = '%' | |
636 | self.ESC_QUOTE = ',' |
|
636 | self.ESC_QUOTE = ',' | |
637 | self.ESC_QUOTE2 = ';' |
|
637 | self.ESC_QUOTE2 = ';' | |
638 | self.ESC_PAREN = '/' |
|
638 | self.ESC_PAREN = '/' | |
639 |
|
639 | |||
640 | # And their associated handlers |
|
640 | # And their associated handlers | |
641 | self.esc_handlers = {self.ESC_PAREN:self.handle_auto, |
|
641 | self.esc_handlers = {self.ESC_PAREN:self.handle_auto, | |
642 | self.ESC_QUOTE:self.handle_auto, |
|
642 | self.ESC_QUOTE:self.handle_auto, | |
643 | self.ESC_QUOTE2:self.handle_auto, |
|
643 | self.ESC_QUOTE2:self.handle_auto, | |
644 | self.ESC_MAGIC:self.handle_magic, |
|
644 | self.ESC_MAGIC:self.handle_magic, | |
645 | self.ESC_HELP:self.handle_help, |
|
645 | self.ESC_HELP:self.handle_help, | |
646 | self.ESC_SHELL:self.handle_shell_escape, |
|
646 | self.ESC_SHELL:self.handle_shell_escape, | |
647 | } |
|
647 | } | |
648 |
|
648 | |||
649 | # class initializations |
|
649 | # class initializations | |
650 | code.InteractiveConsole.__init__(self,locals = self.user_ns) |
|
650 | code.InteractiveConsole.__init__(self,locals = self.user_ns) | |
651 | Logger.__init__(self,log_ns = self.user_ns) |
|
651 | Logger.__init__(self,log_ns = self.user_ns) | |
652 | Magic.__init__(self,self) |
|
652 | Magic.__init__(self,self) | |
653 |
|
653 | |||
654 | # an ugly hack to get a pointer to the shell, so I can start writing |
|
654 | # an ugly hack to get a pointer to the shell, so I can start writing | |
655 | # magic code via this pointer instead of the current mixin salad. |
|
655 | # magic code via this pointer instead of the current mixin salad. | |
656 | Magic.set_shell(self,self) |
|
656 | Magic.set_shell(self,self) | |
657 |
|
657 | |||
658 | # hooks holds pointers used for user-side customizations |
|
658 | # hooks holds pointers used for user-side customizations | |
659 | self.hooks = Struct() |
|
659 | self.hooks = Struct() | |
660 |
|
660 | |||
661 | # Set all default hooks, defined in the IPython.hooks module. |
|
661 | # Set all default hooks, defined in the IPython.hooks module. | |
662 | hooks = IPython.hooks |
|
662 | hooks = IPython.hooks | |
663 | for hook_name in hooks.__all__: |
|
663 | for hook_name in hooks.__all__: | |
664 | self.set_hook(hook_name,getattr(hooks,hook_name)) |
|
664 | self.set_hook(hook_name,getattr(hooks,hook_name)) | |
665 |
|
665 | |||
666 | # Flag to mark unconditional exit |
|
666 | # Flag to mark unconditional exit | |
667 | self.exit_now = False |
|
667 | self.exit_now = False | |
668 |
|
668 | |||
669 | self.usage_min = """\ |
|
669 | self.usage_min = """\ | |
670 | An enhanced console for Python. |
|
670 | An enhanced console for Python. | |
671 | Some of its features are: |
|
671 | Some of its features are: | |
672 | - Readline support if the readline library is present. |
|
672 | - Readline support if the readline library is present. | |
673 | - Tab completion in the local namespace. |
|
673 | - Tab completion in the local namespace. | |
674 | - Logging of input, see command-line options. |
|
674 | - Logging of input, see command-line options. | |
675 | - System shell escape via ! , eg !ls. |
|
675 | - System shell escape via ! , eg !ls. | |
676 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
676 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
677 | - Keeps track of locally defined variables via %who, %whos. |
|
677 | - Keeps track of locally defined variables via %who, %whos. | |
678 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
678 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
679 | """ |
|
679 | """ | |
680 | if usage: self.usage = usage |
|
680 | if usage: self.usage = usage | |
681 | else: self.usage = self.usage_min |
|
681 | else: self.usage = self.usage_min | |
682 |
|
682 | |||
683 | # Storage |
|
683 | # Storage | |
684 | self.rc = rc # This will hold all configuration information |
|
684 | self.rc = rc # This will hold all configuration information | |
685 | self.inputcache = [] |
|
685 | self.inputcache = [] | |
686 | self._boundcache = [] |
|
686 | self._boundcache = [] | |
687 | self.pager = 'less' |
|
687 | self.pager = 'less' | |
688 | # temporary files used for various purposes. Deleted at exit. |
|
688 | # temporary files used for various purposes. Deleted at exit. | |
689 | self.tempfiles = [] |
|
689 | self.tempfiles = [] | |
690 |
|
690 | |||
691 | # Keep track of readline usage (later set by init_readline) |
|
691 | # Keep track of readline usage (later set by init_readline) | |
692 | self.has_readline = 0 |
|
692 | self.has_readline = 0 | |
693 |
|
693 | |||
694 | # for pushd/popd management |
|
694 | # for pushd/popd management | |
695 | try: |
|
695 | try: | |
696 | self.home_dir = get_home_dir() |
|
696 | self.home_dir = get_home_dir() | |
697 | except HomeDirError,msg: |
|
697 | except HomeDirError,msg: | |
698 | fatal(msg) |
|
698 | fatal(msg) | |
699 |
|
699 | |||
700 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] |
|
700 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] | |
701 |
|
701 | |||
702 | # Functions to call the underlying shell. |
|
702 | # Functions to call the underlying shell. | |
703 |
|
703 | |||
704 | # utility to expand user variables via Itpl |
|
704 | # utility to expand user variables via Itpl | |
705 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), |
|
705 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), | |
706 | self.user_ns)) |
|
706 | self.user_ns)) | |
707 | # The first is similar to os.system, but it doesn't return a value, |
|
707 | # The first is similar to os.system, but it doesn't return a value, | |
708 | # and it allows interpolation of variables in the user's namespace. |
|
708 | # and it allows interpolation of variables in the user's namespace. | |
709 | self.system = lambda cmd: shell(self.var_expand(cmd), |
|
709 | self.system = lambda cmd: shell(self.var_expand(cmd), | |
710 | header='IPython system call: ', |
|
710 | header='IPython system call: ', | |
711 | verbose=self.rc.system_verbose) |
|
711 | verbose=self.rc.system_verbose) | |
712 | # These are for getoutput and getoutputerror: |
|
712 | # These are for getoutput and getoutputerror: | |
713 | self.getoutput = lambda cmd: \ |
|
713 | self.getoutput = lambda cmd: \ | |
714 | getoutput(self.var_expand(cmd), |
|
714 | getoutput(self.var_expand(cmd), | |
715 | header='IPython system call: ', |
|
715 | header='IPython system call: ', | |
716 | verbose=self.rc.system_verbose) |
|
716 | verbose=self.rc.system_verbose) | |
717 | self.getoutputerror = lambda cmd: \ |
|
717 | self.getoutputerror = lambda cmd: \ | |
718 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), |
|
718 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), | |
719 | self.user_ns)), |
|
719 | self.user_ns)), | |
720 | header='IPython system call: ', |
|
720 | header='IPython system call: ', | |
721 | verbose=self.rc.system_verbose) |
|
721 | verbose=self.rc.system_verbose) | |
722 |
|
722 | |||
723 | # RegExp for splitting line contents into pre-char//first |
|
723 | # RegExp for splitting line contents into pre-char//first | |
724 | # word-method//rest. For clarity, each group in on one line. |
|
724 | # word-method//rest. For clarity, each group in on one line. | |
725 |
|
725 | |||
726 | # WARNING: update the regexp if the above escapes are changed, as they |
|
726 | # WARNING: update the regexp if the above escapes are changed, as they | |
727 | # are hardwired in. |
|
727 | # are hardwired in. | |
728 |
|
728 | |||
729 | # Don't get carried away with trying to make the autocalling catch too |
|
729 | # Don't get carried away with trying to make the autocalling catch too | |
730 | # much: it's better to be conservative rather than to trigger hidden |
|
730 | # much: it's better to be conservative rather than to trigger hidden | |
731 | # evals() somewhere and end up causing side effects. |
|
731 | # evals() somewhere and end up causing side effects. | |
732 |
|
732 | |||
733 | self.line_split = re.compile(r'^([\s*,;/])' |
|
733 | self.line_split = re.compile(r'^([\s*,;/])' | |
734 | r'([\?\w\.]+\w*\s*)' |
|
734 | r'([\?\w\.]+\w*\s*)' | |
735 | r'(\(?.*$)') |
|
735 | r'(\(?.*$)') | |
736 |
|
736 | |||
737 | # Original re, keep around for a while in case changes break something |
|
737 | # Original re, keep around for a while in case changes break something | |
738 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' |
|
738 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' | |
739 | # r'(\s*[\?\w\.]+\w*\s*)' |
|
739 | # r'(\s*[\?\w\.]+\w*\s*)' | |
740 | # r'(\(?.*$)') |
|
740 | # r'(\(?.*$)') | |
741 |
|
741 | |||
742 | # RegExp to identify potential function names |
|
742 | # RegExp to identify potential function names | |
743 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
743 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
744 | # RegExp to exclude strings with this start from autocalling |
|
744 | # RegExp to exclude strings with this start from autocalling | |
745 | self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ') |
|
745 | self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ') | |
746 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
746 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
747 | # (experimental). For this to work, the line_split regexp would need |
|
747 | # (experimental). For this to work, the line_split regexp would need | |
748 | # to be modified so it wouldn't break things at '['. That line is |
|
748 | # to be modified so it wouldn't break things at '['. That line is | |
749 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
749 | # nasty enough that I shouldn't change it until I can test it _well_. | |
750 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
750 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
751 |
|
751 | |||
752 | # keep track of where we started running (mainly for crash post-mortem) |
|
752 | # keep track of where we started running (mainly for crash post-mortem) | |
753 | self.starting_dir = os.getcwd() |
|
753 | self.starting_dir = os.getcwd() | |
754 |
|
754 | |||
755 | # Attributes for Logger mixin class, make defaults here |
|
755 | # Attributes for Logger mixin class, make defaults here | |
756 | self._dolog = 0 |
|
756 | self._dolog = 0 | |
757 | self.LOG = '' |
|
757 | self.LOG = '' | |
758 | self.LOGDEF = '.InteractiveShell.log' |
|
758 | self.LOGDEF = '.InteractiveShell.log' | |
759 | self.LOGMODE = 'over' |
|
759 | self.LOGMODE = 'over' | |
760 | self.LOGHEAD = Itpl( |
|
760 | self.LOGHEAD = Itpl( | |
761 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
761 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
762 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
762 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
763 | #log# opts = $self.rc.opts |
|
763 | #log# opts = $self.rc.opts | |
764 | #log# args = $self.rc.args |
|
764 | #log# args = $self.rc.args | |
765 | #log# It is safe to make manual edits below here. |
|
765 | #log# It is safe to make manual edits below here. | |
766 | #log#----------------------------------------------------------------------- |
|
766 | #log#----------------------------------------------------------------------- | |
767 | """) |
|
767 | """) | |
768 | # Various switches which can be set |
|
768 | # Various switches which can be set | |
769 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
769 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
770 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
770 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
771 | self.banner2 = banner2 |
|
771 | self.banner2 = banner2 | |
772 |
|
772 | |||
773 | # TraceBack handlers: |
|
773 | # TraceBack handlers: | |
774 | # Need two, one for syntax errors and one for other exceptions. |
|
774 | # Need two, one for syntax errors and one for other exceptions. | |
775 | self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor') |
|
775 | self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor') | |
776 | # This one is initialized with an offset, meaning we always want to |
|
776 | # This one is initialized with an offset, meaning we always want to | |
777 | # remove the topmost item in the traceback, which is our own internal |
|
777 | # remove the topmost item in the traceback, which is our own internal | |
778 | # code. Valid modes: ['Plain','Context','Verbose'] |
|
778 | # code. Valid modes: ['Plain','Context','Verbose'] | |
779 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
779 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
780 | color_scheme='NoColor', |
|
780 | color_scheme='NoColor', | |
781 | tb_offset = 1) |
|
781 | tb_offset = 1) | |
782 | # and add any custom exception handlers the user may have specified |
|
782 | # and add any custom exception handlers the user may have specified | |
783 | self.set_custom_exc(*custom_exceptions) |
|
783 | self.set_custom_exc(*custom_exceptions) | |
784 |
|
784 | |||
785 | # Object inspector |
|
785 | # Object inspector | |
786 | ins_colors = OInspect.InspectColors |
|
786 | ins_colors = OInspect.InspectColors | |
787 | code_colors = PyColorize.ANSICodeColors |
|
787 | code_colors = PyColorize.ANSICodeColors | |
788 | self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor') |
|
788 | self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor') | |
789 | self.autoindent = 0 |
|
789 | self.autoindent = 0 | |
790 |
|
790 | |||
791 | # Make some aliases automatically |
|
791 | # Make some aliases automatically | |
792 | # Prepare list of shell aliases to auto-define |
|
792 | # Prepare list of shell aliases to auto-define | |
793 | if os.name == 'posix': |
|
793 | if os.name == 'posix': | |
794 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
794 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
795 | 'mv mv -i','rm rm -i','cp cp -i', |
|
795 | 'mv mv -i','rm rm -i','cp cp -i', | |
796 | 'cat cat','less less','clear clear', |
|
796 | 'cat cat','less less','clear clear', | |
797 | # a better ls |
|
797 | # a better ls | |
798 | 'ls ls -F', |
|
798 | 'ls ls -F', | |
799 | # long ls |
|
799 | # long ls | |
800 | 'll ls -lF', |
|
800 | 'll ls -lF', | |
801 | # color ls |
|
801 | # color ls | |
802 | 'lc ls -F -o --color', |
|
802 | 'lc ls -F -o --color', | |
803 | # ls normal files only |
|
803 | # ls normal files only | |
804 | 'lf ls -F -o --color %l | grep ^-', |
|
804 | 'lf ls -F -o --color %l | grep ^-', | |
805 | # ls symbolic links |
|
805 | # ls symbolic links | |
806 | 'lk ls -F -o --color %l | grep ^l', |
|
806 | 'lk ls -F -o --color %l | grep ^l', | |
807 | # directories or links to directories, |
|
807 | # directories or links to directories, | |
808 | 'ldir ls -F -o --color %l | grep /$', |
|
808 | 'ldir ls -F -o --color %l | grep /$', | |
809 | # things which are executable |
|
809 | # things which are executable | |
810 | 'lx ls -F -o --color %l | grep ^-..x', |
|
810 | 'lx ls -F -o --color %l | grep ^-..x', | |
811 | ) |
|
811 | ) | |
812 | elif os.name in ['nt','dos']: |
|
812 | elif os.name in ['nt','dos']: | |
813 | auto_alias = ('dir dir /on', 'ls dir /on', |
|
813 | auto_alias = ('dir dir /on', 'ls dir /on', | |
814 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
814 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
815 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
815 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
816 | 'ren ren','cls cls','copy copy') |
|
816 | 'ren ren','cls cls','copy copy') | |
817 | else: |
|
817 | else: | |
818 | auto_alias = () |
|
818 | auto_alias = () | |
819 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) |
|
819 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) | |
820 | # Call the actual (public) initializer |
|
820 | # Call the actual (public) initializer | |
821 | self.init_auto_alias() |
|
821 | self.init_auto_alias() | |
822 | # end __init__ |
|
822 | # end __init__ | |
823 |
|
823 | |||
824 | def set_hook(self,name,hook): |
|
824 | def set_hook(self,name,hook): | |
825 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
825 | """set_hook(name,hook) -> sets an internal IPython hook. | |
826 |
|
826 | |||
827 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
827 | IPython exposes some of its internal API as user-modifiable hooks. By | |
828 | resetting one of these hooks, you can modify IPython's behavior to |
|
828 | resetting one of these hooks, you can modify IPython's behavior to | |
829 | call at runtime your own routines.""" |
|
829 | call at runtime your own routines.""" | |
830 |
|
830 | |||
831 | # At some point in the future, this should validate the hook before it |
|
831 | # At some point in the future, this should validate the hook before it | |
832 | # accepts it. Probably at least check that the hook takes the number |
|
832 | # accepts it. Probably at least check that the hook takes the number | |
833 | # of args it's supposed to. |
|
833 | # of args it's supposed to. | |
834 | setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
834 | setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
835 |
|
835 | |||
836 | def set_custom_exc(self,exc_tuple,handler): |
|
836 | def set_custom_exc(self,exc_tuple,handler): | |
837 | """set_custom_exc(exc_tuple,handler) |
|
837 | """set_custom_exc(exc_tuple,handler) | |
838 |
|
838 | |||
839 | Set a custom exception handler, which will be called if any of the |
|
839 | Set a custom exception handler, which will be called if any of the | |
840 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
840 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
841 | runcode() method. |
|
841 | runcode() method. | |
842 |
|
842 | |||
843 | Inputs: |
|
843 | Inputs: | |
844 |
|
844 | |||
845 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
845 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
846 | handler for. It is very important that you use a tuple, and NOT A |
|
846 | handler for. It is very important that you use a tuple, and NOT A | |
847 | LIST here, because of the way Python's except statement works. If |
|
847 | LIST here, because of the way Python's except statement works. If | |
848 | you only want to trap a single exception, use a singleton tuple: |
|
848 | you only want to trap a single exception, use a singleton tuple: | |
849 |
|
849 | |||
850 | exc_tuple == (MyCustomException,) |
|
850 | exc_tuple == (MyCustomException,) | |
851 |
|
851 | |||
852 | - handler: this must be defined as a function with the following |
|
852 | - handler: this must be defined as a function with the following | |
853 | basic interface: def my_handler(self,etype,value,tb). |
|
853 | basic interface: def my_handler(self,etype,value,tb). | |
854 |
|
854 | |||
855 | This will be made into an instance method (via new.instancemethod) |
|
855 | This will be made into an instance method (via new.instancemethod) | |
856 | of IPython itself, and it will be called if any of the exceptions |
|
856 | of IPython itself, and it will be called if any of the exceptions | |
857 | listed in the exc_tuple are caught. If the handler is None, an |
|
857 | listed in the exc_tuple are caught. If the handler is None, an | |
858 | internal basic one is used, which just prints basic info. |
|
858 | internal basic one is used, which just prints basic info. | |
859 |
|
859 | |||
860 | WARNING: by putting in your own exception handler into IPython's main |
|
860 | WARNING: by putting in your own exception handler into IPython's main | |
861 | execution loop, you run a very good chance of nasty crashes. This |
|
861 | execution loop, you run a very good chance of nasty crashes. This | |
862 | facility should only be used if you really know what you are doing.""" |
|
862 | facility should only be used if you really know what you are doing.""" | |
863 |
|
863 | |||
864 | assert type(exc_tuple)==type(()) , \ |
|
864 | assert type(exc_tuple)==type(()) , \ | |
865 | "The custom exceptions must be given AS A TUPLE." |
|
865 | "The custom exceptions must be given AS A TUPLE." | |
866 |
|
866 | |||
867 | def dummy_handler(self,etype,value,tb): |
|
867 | def dummy_handler(self,etype,value,tb): | |
868 | print '*** Simple custom exception handler ***' |
|
868 | print '*** Simple custom exception handler ***' | |
869 | print 'Exception type :',etype |
|
869 | print 'Exception type :',etype | |
870 | print 'Exception value:',value |
|
870 | print 'Exception value:',value | |
871 | print 'Traceback :',tb |
|
871 | print 'Traceback :',tb | |
872 | print 'Source code :','\n'.join(self.buffer) |
|
872 | print 'Source code :','\n'.join(self.buffer) | |
873 |
|
873 | |||
874 | if handler is None: handler = dummy_handler |
|
874 | if handler is None: handler = dummy_handler | |
875 |
|
875 | |||
876 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
876 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
877 | self.custom_exceptions = exc_tuple |
|
877 | self.custom_exceptions = exc_tuple | |
878 |
|
878 | |||
879 | def set_custom_completer(self,completer,pos=0): |
|
879 | def set_custom_completer(self,completer,pos=0): | |
880 | """set_custom_completer(completer,pos=0) |
|
880 | """set_custom_completer(completer,pos=0) | |
881 |
|
881 | |||
882 | Adds a new custom completer function. |
|
882 | Adds a new custom completer function. | |
883 |
|
883 | |||
884 | The position argument (defaults to 0) is the index in the completers |
|
884 | The position argument (defaults to 0) is the index in the completers | |
885 | list where you want the completer to be inserted.""" |
|
885 | list where you want the completer to be inserted.""" | |
886 |
|
886 | |||
887 | newcomp = new.instancemethod(completer,self.Completer, |
|
887 | newcomp = new.instancemethod(completer,self.Completer, | |
888 | self.Completer.__class__) |
|
888 | self.Completer.__class__) | |
889 | self.Completer.matchers.insert(pos,newcomp) |
|
889 | self.Completer.matchers.insert(pos,newcomp) | |
890 |
|
890 | |||
|
891 | def complete(self,text): | |||
|
892 | """Return a sorted list of all possible completions on text. | |||
|
893 | ||||
|
894 | Inputs: | |||
|
895 | ||||
|
896 | - text: a string of text to be completed on. | |||
|
897 | ||||
|
898 | This is a wrapper around the completion mechanism, similar to what | |||
|
899 | readline does at the command line when the TAB key is hit. By | |||
|
900 | exposing it as a method, it can be used by other non-readline | |||
|
901 | environments (such as GUIs) for text completion. | |||
|
902 | ||||
|
903 | Simple usage example: | |||
|
904 | ||||
|
905 | In [1]: x = 'hello' | |||
|
906 | ||||
|
907 | In [2]: __IP.complete('x.l') | |||
|
908 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" | |||
|
909 | ||||
|
910 | complete = self.Completer.complete | |||
|
911 | state = 0 | |||
|
912 | # use a dict so we get unique keys, since ipyhton's multiple | |||
|
913 | # completers can return duplicates. | |||
|
914 | comps = {} | |||
|
915 | while True: | |||
|
916 | newcomp = complete(text,state) | |||
|
917 | if newcomp is None: | |||
|
918 | break | |||
|
919 | comps[newcomp] = 1 | |||
|
920 | state += 1 | |||
|
921 | outcomps = comps.keys() | |||
|
922 | outcomps.sort() | |||
|
923 | return outcomps | |||
|
924 | ||||
891 | def post_config_initialization(self): |
|
925 | def post_config_initialization(self): | |
892 | """Post configuration init method |
|
926 | """Post configuration init method | |
893 |
|
927 | |||
894 | This is called after the configuration files have been processed to |
|
928 | This is called after the configuration files have been processed to | |
895 | 'finalize' the initialization.""" |
|
929 | 'finalize' the initialization.""" | |
896 |
|
930 | |||
897 | # dynamic data that survives through sessions |
|
931 | # dynamic data that survives through sessions | |
898 | # XXX make the filename a config option? |
|
932 | # XXX make the filename a config option? | |
899 | persist_base = 'persist' |
|
933 | persist_base = 'persist' | |
900 | if self.rc.profile: |
|
934 | if self.rc.profile: | |
901 | persist_base += '_%s' % self.rc.profile |
|
935 | persist_base += '_%s' % self.rc.profile | |
902 | self.persist_fname = os.path.join(self.rc.ipythondir,persist_base) |
|
936 | self.persist_fname = os.path.join(self.rc.ipythondir,persist_base) | |
903 |
|
937 | |||
904 | try: |
|
938 | try: | |
905 | self.persist = pickle.load(file(self.persist_fname)) |
|
939 | self.persist = pickle.load(file(self.persist_fname)) | |
906 | except: |
|
940 | except: | |
907 | self.persist = {} |
|
941 | self.persist = {} | |
908 |
|
942 | |||
909 | def init_auto_alias(self): |
|
943 | def init_auto_alias(self): | |
910 | """Define some aliases automatically. |
|
944 | """Define some aliases automatically. | |
911 |
|
945 | |||
912 | These are ALL parameter-less aliases""" |
|
946 | These are ALL parameter-less aliases""" | |
913 | for alias,cmd in self.auto_alias: |
|
947 | for alias,cmd in self.auto_alias: | |
914 | self.alias_table[alias] = (0,cmd) |
|
948 | self.alias_table[alias] = (0,cmd) | |
915 |
|
949 | |||
916 | def alias_table_validate(self,verbose=0): |
|
950 | def alias_table_validate(self,verbose=0): | |
917 | """Update information about the alias table. |
|
951 | """Update information about the alias table. | |
918 |
|
952 | |||
919 | In particular, make sure no Python keywords/builtins are in it.""" |
|
953 | In particular, make sure no Python keywords/builtins are in it.""" | |
920 |
|
954 | |||
921 | no_alias = self.no_alias |
|
955 | no_alias = self.no_alias | |
922 | for k in self.alias_table.keys(): |
|
956 | for k in self.alias_table.keys(): | |
923 | if k in no_alias: |
|
957 | if k in no_alias: | |
924 | del self.alias_table[k] |
|
958 | del self.alias_table[k] | |
925 | if verbose: |
|
959 | if verbose: | |
926 | print ("Deleting alias <%s>, it's a Python " |
|
960 | print ("Deleting alias <%s>, it's a Python " | |
927 | "keyword or builtin." % k) |
|
961 | "keyword or builtin." % k) | |
928 |
|
962 | |||
929 | def set_autoindent(self,value=None): |
|
963 | def set_autoindent(self,value=None): | |
930 | """Set the autoindent flag, checking for readline support. |
|
964 | """Set the autoindent flag, checking for readline support. | |
931 |
|
965 | |||
932 | If called with no arguments, it acts as a toggle.""" |
|
966 | If called with no arguments, it acts as a toggle.""" | |
933 |
|
967 | |||
934 | if not self.has_readline: |
|
968 | if not self.has_readline: | |
935 | if os.name == 'posix': |
|
969 | if os.name == 'posix': | |
936 | warn("The auto-indent feature requires the readline library") |
|
970 | warn("The auto-indent feature requires the readline library") | |
937 | self.autoindent = 0 |
|
971 | self.autoindent = 0 | |
938 | return |
|
972 | return | |
939 | if value is None: |
|
973 | if value is None: | |
940 | self.autoindent = not self.autoindent |
|
974 | self.autoindent = not self.autoindent | |
941 | else: |
|
975 | else: | |
942 | self.autoindent = value |
|
976 | self.autoindent = value | |
943 |
|
977 | |||
944 | def rc_set_toggle(self,rc_field,value=None): |
|
978 | def rc_set_toggle(self,rc_field,value=None): | |
945 | """Set or toggle a field in IPython's rc config. structure. |
|
979 | """Set or toggle a field in IPython's rc config. structure. | |
946 |
|
980 | |||
947 | If called with no arguments, it acts as a toggle. |
|
981 | If called with no arguments, it acts as a toggle. | |
948 |
|
982 | |||
949 | If called with a non-existent field, the resulting AttributeError |
|
983 | If called with a non-existent field, the resulting AttributeError | |
950 | exception will propagate out.""" |
|
984 | exception will propagate out.""" | |
951 |
|
985 | |||
952 | rc_val = getattr(self.rc,rc_field) |
|
986 | rc_val = getattr(self.rc,rc_field) | |
953 | if value is None: |
|
987 | if value is None: | |
954 | value = not rc_val |
|
988 | value = not rc_val | |
955 | setattr(self.rc,rc_field,value) |
|
989 | setattr(self.rc,rc_field,value) | |
956 |
|
990 | |||
957 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
991 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
958 | """Install the user configuration directory. |
|
992 | """Install the user configuration directory. | |
959 |
|
993 | |||
960 | Can be called when running for the first time or to upgrade the user's |
|
994 | Can be called when running for the first time or to upgrade the user's | |
961 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
995 | .ipython/ directory with the mode parameter. Valid modes are 'install' | |
962 | and 'upgrade'.""" |
|
996 | and 'upgrade'.""" | |
963 |
|
997 | |||
964 | def wait(): |
|
998 | def wait(): | |
965 | try: |
|
999 | try: | |
966 | raw_input("Please press <RETURN> to start IPython.") |
|
1000 | raw_input("Please press <RETURN> to start IPython.") | |
967 | except EOFError: |
|
1001 | except EOFError: | |
968 | print >> Term.cout |
|
1002 | print >> Term.cout | |
969 | print '*'*70 |
|
1003 | print '*'*70 | |
970 |
|
1004 | |||
971 | cwd = os.getcwd() # remember where we started |
|
1005 | cwd = os.getcwd() # remember where we started | |
972 | glb = glob.glob |
|
1006 | glb = glob.glob | |
973 | print '*'*70 |
|
1007 | print '*'*70 | |
974 | if mode == 'install': |
|
1008 | if mode == 'install': | |
975 | print \ |
|
1009 | print \ | |
976 | """Welcome to IPython. I will try to create a personal configuration directory |
|
1010 | """Welcome to IPython. I will try to create a personal configuration directory | |
977 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1011 | where you can customize many aspects of IPython's functionality in:\n""" | |
978 | else: |
|
1012 | else: | |
979 | print 'I am going to upgrade your configuration in:' |
|
1013 | print 'I am going to upgrade your configuration in:' | |
980 |
|
1014 | |||
981 | print ipythondir |
|
1015 | print ipythondir | |
982 |
|
1016 | |||
983 | rcdirend = os.path.join('IPython','UserConfig') |
|
1017 | rcdirend = os.path.join('IPython','UserConfig') | |
984 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1018 | cfg = lambda d: os.path.join(d,rcdirend) | |
985 | try: |
|
1019 | try: | |
986 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1020 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
987 | except IOError: |
|
1021 | except IOError: | |
988 | warning = """ |
|
1022 | warning = """ | |
989 | Installation error. IPython's directory was not found. |
|
1023 | Installation error. IPython's directory was not found. | |
990 |
|
1024 | |||
991 | Check the following: |
|
1025 | Check the following: | |
992 |
|
1026 | |||
993 | The ipython/IPython directory should be in a directory belonging to your |
|
1027 | The ipython/IPython directory should be in a directory belonging to your | |
994 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1028 | PYTHONPATH environment variable (that is, it should be in a directory | |
995 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1029 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
996 |
|
1030 | |||
997 | IPython will proceed with builtin defaults. |
|
1031 | IPython will proceed with builtin defaults. | |
998 | """ |
|
1032 | """ | |
999 | warn(warning) |
|
1033 | warn(warning) | |
1000 | wait() |
|
1034 | wait() | |
1001 | return |
|
1035 | return | |
1002 |
|
1036 | |||
1003 | if mode == 'install': |
|
1037 | if mode == 'install': | |
1004 | try: |
|
1038 | try: | |
1005 | shutil.copytree(rcdir,ipythondir) |
|
1039 | shutil.copytree(rcdir,ipythondir) | |
1006 | os.chdir(ipythondir) |
|
1040 | os.chdir(ipythondir) | |
1007 | rc_files = glb("ipythonrc*") |
|
1041 | rc_files = glb("ipythonrc*") | |
1008 | for rc_file in rc_files: |
|
1042 | for rc_file in rc_files: | |
1009 | os.rename(rc_file,rc_file+rc_suffix) |
|
1043 | os.rename(rc_file,rc_file+rc_suffix) | |
1010 | except: |
|
1044 | except: | |
1011 | warning = """ |
|
1045 | warning = """ | |
1012 |
|
1046 | |||
1013 | There was a problem with the installation: |
|
1047 | There was a problem with the installation: | |
1014 | %s |
|
1048 | %s | |
1015 | Try to correct it or contact the developers if you think it's a bug. |
|
1049 | Try to correct it or contact the developers if you think it's a bug. | |
1016 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1050 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
1017 | warn(warning) |
|
1051 | warn(warning) | |
1018 | wait() |
|
1052 | wait() | |
1019 | return |
|
1053 | return | |
1020 |
|
1054 | |||
1021 | elif mode == 'upgrade': |
|
1055 | elif mode == 'upgrade': | |
1022 | try: |
|
1056 | try: | |
1023 | os.chdir(ipythondir) |
|
1057 | os.chdir(ipythondir) | |
1024 | except: |
|
1058 | except: | |
1025 | print """ |
|
1059 | print """ | |
1026 | Can not upgrade: changing to directory %s failed. Details: |
|
1060 | Can not upgrade: changing to directory %s failed. Details: | |
1027 | %s |
|
1061 | %s | |
1028 | """ % (ipythondir,sys.exc_info()[1]) |
|
1062 | """ % (ipythondir,sys.exc_info()[1]) | |
1029 | wait() |
|
1063 | wait() | |
1030 | return |
|
1064 | return | |
1031 | else: |
|
1065 | else: | |
1032 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1066 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
1033 | for new_full_path in sources: |
|
1067 | for new_full_path in sources: | |
1034 | new_filename = os.path.basename(new_full_path) |
|
1068 | new_filename = os.path.basename(new_full_path) | |
1035 | if new_filename.startswith('ipythonrc'): |
|
1069 | if new_filename.startswith('ipythonrc'): | |
1036 | new_filename = new_filename + rc_suffix |
|
1070 | new_filename = new_filename + rc_suffix | |
1037 | # The config directory should only contain files, skip any |
|
1071 | # The config directory should only contain files, skip any | |
1038 | # directories which may be there (like CVS) |
|
1072 | # directories which may be there (like CVS) | |
1039 | if os.path.isdir(new_full_path): |
|
1073 | if os.path.isdir(new_full_path): | |
1040 | continue |
|
1074 | continue | |
1041 | if os.path.exists(new_filename): |
|
1075 | if os.path.exists(new_filename): | |
1042 | old_file = new_filename+'.old' |
|
1076 | old_file = new_filename+'.old' | |
1043 | if os.path.exists(old_file): |
|
1077 | if os.path.exists(old_file): | |
1044 | os.remove(old_file) |
|
1078 | os.remove(old_file) | |
1045 | os.rename(new_filename,old_file) |
|
1079 | os.rename(new_filename,old_file) | |
1046 | shutil.copy(new_full_path,new_filename) |
|
1080 | shutil.copy(new_full_path,new_filename) | |
1047 | else: |
|
1081 | else: | |
1048 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1082 | raise ValueError,'unrecognized mode for install:',`mode` | |
1049 |
|
1083 | |||
1050 | # Fix line-endings to those native to each platform in the config |
|
1084 | # Fix line-endings to those native to each platform in the config | |
1051 | # directory. |
|
1085 | # directory. | |
1052 | try: |
|
1086 | try: | |
1053 | os.chdir(ipythondir) |
|
1087 | os.chdir(ipythondir) | |
1054 | except: |
|
1088 | except: | |
1055 | print """ |
|
1089 | print """ | |
1056 | Problem: changing to directory %s failed. |
|
1090 | Problem: changing to directory %s failed. | |
1057 | Details: |
|
1091 | Details: | |
1058 | %s |
|
1092 | %s | |
1059 |
|
1093 | |||
1060 | Some configuration files may have incorrect line endings. This should not |
|
1094 | Some configuration files may have incorrect line endings. This should not | |
1061 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1095 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) | |
1062 | wait() |
|
1096 | wait() | |
1063 | else: |
|
1097 | else: | |
1064 | for fname in glb('ipythonrc*'): |
|
1098 | for fname in glb('ipythonrc*'): | |
1065 | try: |
|
1099 | try: | |
1066 | native_line_ends(fname,backup=0) |
|
1100 | native_line_ends(fname,backup=0) | |
1067 | except IOError: |
|
1101 | except IOError: | |
1068 | pass |
|
1102 | pass | |
1069 |
|
1103 | |||
1070 | if mode == 'install': |
|
1104 | if mode == 'install': | |
1071 | print """ |
|
1105 | print """ | |
1072 | Successful installation! |
|
1106 | Successful installation! | |
1073 |
|
1107 | |||
1074 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1108 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
1075 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1109 | IPython manual (there are both HTML and PDF versions supplied with the | |
1076 | distribution) to make sure that your system environment is properly configured |
|
1110 | distribution) to make sure that your system environment is properly configured | |
1077 | to take advantage of IPython's features.""" |
|
1111 | to take advantage of IPython's features.""" | |
1078 | else: |
|
1112 | else: | |
1079 | print """ |
|
1113 | print """ | |
1080 | Successful upgrade! |
|
1114 | Successful upgrade! | |
1081 |
|
1115 | |||
1082 | All files in your directory: |
|
1116 | All files in your directory: | |
1083 | %(ipythondir)s |
|
1117 | %(ipythondir)s | |
1084 | which would have been overwritten by the upgrade were backed up with a .old |
|
1118 | which would have been overwritten by the upgrade were backed up with a .old | |
1085 | extension. If you had made particular customizations in those files you may |
|
1119 | extension. If you had made particular customizations in those files you may | |
1086 | want to merge them back into the new files.""" % locals() |
|
1120 | want to merge them back into the new files.""" % locals() | |
1087 | wait() |
|
1121 | wait() | |
1088 | os.chdir(cwd) |
|
1122 | os.chdir(cwd) | |
1089 | # end user_setup() |
|
1123 | # end user_setup() | |
1090 |
|
1124 | |||
1091 | def atexit_operations(self): |
|
1125 | def atexit_operations(self): | |
1092 | """This will be executed at the time of exit. |
|
1126 | """This will be executed at the time of exit. | |
1093 |
|
1127 | |||
1094 | Saving of persistent data should be performed here. """ |
|
1128 | Saving of persistent data should be performed here. """ | |
1095 |
|
1129 | |||
1096 | # input history |
|
1130 | # input history | |
1097 | self.savehist() |
|
1131 | self.savehist() | |
1098 |
|
1132 | |||
1099 | # Cleanup all tempfiles left around |
|
1133 | # Cleanup all tempfiles left around | |
1100 | for tfile in self.tempfiles: |
|
1134 | for tfile in self.tempfiles: | |
1101 | try: |
|
1135 | try: | |
1102 | os.unlink(tfile) |
|
1136 | os.unlink(tfile) | |
1103 | except OSError: |
|
1137 | except OSError: | |
1104 | pass |
|
1138 | pass | |
1105 |
|
1139 | |||
1106 | # save the "persistent data" catch-all dictionary |
|
1140 | # save the "persistent data" catch-all dictionary | |
1107 | try: |
|
1141 | try: | |
1108 | pickle.dump(self.persist, open(self.persist_fname,"w")) |
|
1142 | pickle.dump(self.persist, open(self.persist_fname,"w")) | |
1109 | except: |
|
1143 | except: | |
1110 | print "*** ERROR *** persistent data saving failed." |
|
1144 | print "*** ERROR *** persistent data saving failed." | |
1111 |
|
1145 | |||
1112 | def savehist(self): |
|
1146 | def savehist(self): | |
1113 | """Save input history to a file (via readline library).""" |
|
1147 | """Save input history to a file (via readline library).""" | |
1114 | try: |
|
1148 | try: | |
1115 | self.readline.write_history_file(self.histfile) |
|
1149 | self.readline.write_history_file(self.histfile) | |
1116 | except: |
|
1150 | except: | |
1117 | print 'Unable to save IPython command history to file: ' + \ |
|
1151 | print 'Unable to save IPython command history to file: ' + \ | |
1118 | `self.histfile` |
|
1152 | `self.histfile` | |
1119 |
|
1153 | |||
1120 | def pre_readline(self): |
|
1154 | def pre_readline(self): | |
1121 | """readline hook to be used at the start of each line. |
|
1155 | """readline hook to be used at the start of each line. | |
1122 |
|
1156 | |||
1123 | Currently it handles auto-indent only.""" |
|
1157 | Currently it handles auto-indent only.""" | |
1124 |
|
1158 | |||
1125 | self.readline.insert_text(' '* self.readline_indent) |
|
1159 | self.readline.insert_text(' '* self.readline_indent) | |
1126 |
|
1160 | |||
1127 | def init_readline(self): |
|
1161 | def init_readline(self): | |
1128 | """Command history completion/saving/reloading.""" |
|
1162 | """Command history completion/saving/reloading.""" | |
1129 | try: |
|
1163 | try: | |
1130 | import readline |
|
1164 | import readline | |
1131 | self.Completer = MagicCompleter(self, |
|
1165 | self.Completer = MagicCompleter(self, | |
1132 | self.user_ns, |
|
1166 | self.user_ns, | |
1133 | self.rc.readline_omit__names, |
|
1167 | self.rc.readline_omit__names, | |
1134 | self.alias_table) |
|
1168 | self.alias_table) | |
1135 | except ImportError,NameError: |
|
1169 | except ImportError,NameError: | |
1136 | # If FlexCompleter failed to import, MagicCompleter won't be |
|
1170 | # If FlexCompleter failed to import, MagicCompleter won't be | |
1137 | # defined. This can happen because of a problem with readline |
|
1171 | # defined. This can happen because of a problem with readline | |
1138 | self.has_readline = 0 |
|
1172 | self.has_readline = 0 | |
1139 | # no point in bugging windows users with this every time: |
|
1173 | # no point in bugging windows users with this every time: | |
1140 | if os.name == 'posix': |
|
1174 | if os.name == 'posix': | |
1141 | warn('Readline services not available on this platform.') |
|
1175 | warn('Readline services not available on this platform.') | |
1142 | else: |
|
1176 | else: | |
1143 | import atexit |
|
1177 | import atexit | |
1144 |
|
1178 | |||
1145 | # Platform-specific configuration |
|
1179 | # Platform-specific configuration | |
1146 | if os.name == 'nt': |
|
1180 | if os.name == 'nt': | |
1147 | # readline under Windows modifies the default exit behavior |
|
1181 | # readline under Windows modifies the default exit behavior | |
1148 | # from being Ctrl-Z/Return to the Unix Ctrl-D one. |
|
1182 | # from being Ctrl-Z/Return to the Unix Ctrl-D one. | |
1149 | __builtin__.exit = __builtin__.quit = \ |
|
1183 | __builtin__.exit = __builtin__.quit = \ | |
1150 | ('Use Ctrl-D (i.e. EOF) to exit. ' |
|
1184 | ('Use Ctrl-D (i.e. EOF) to exit. ' | |
1151 | 'Use %Exit or %Quit to exit without confirmation.') |
|
1185 | 'Use %Exit or %Quit to exit without confirmation.') | |
1152 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1186 | self.readline_startup_hook = readline.set_pre_input_hook | |
1153 | else: |
|
1187 | else: | |
1154 | self.readline_startup_hook = readline.set_startup_hook |
|
1188 | self.readline_startup_hook = readline.set_startup_hook | |
1155 |
|
1189 | |||
1156 | # Load user's initrc file (readline config) |
|
1190 | # Load user's initrc file (readline config) | |
1157 | inputrc_name = os.environ.get('INPUTRC') |
|
1191 | inputrc_name = os.environ.get('INPUTRC') | |
1158 | if inputrc_name is None: |
|
1192 | if inputrc_name is None: | |
1159 | home_dir = get_home_dir() |
|
1193 | home_dir = get_home_dir() | |
1160 | if home_dir is not None: |
|
1194 | if home_dir is not None: | |
1161 | inputrc_name = os.path.join(home_dir,'.inputrc') |
|
1195 | inputrc_name = os.path.join(home_dir,'.inputrc') | |
1162 | if os.path.isfile(inputrc_name): |
|
1196 | if os.path.isfile(inputrc_name): | |
1163 | try: |
|
1197 | try: | |
1164 | readline.read_init_file(inputrc_name) |
|
1198 | readline.read_init_file(inputrc_name) | |
1165 | except: |
|
1199 | except: | |
1166 | warn('Problems reading readline initialization file <%s>' |
|
1200 | warn('Problems reading readline initialization file <%s>' | |
1167 | % inputrc_name) |
|
1201 | % inputrc_name) | |
1168 |
|
1202 | |||
1169 | self.has_readline = 1 |
|
1203 | self.has_readline = 1 | |
1170 | self.readline = readline |
|
1204 | self.readline = readline | |
1171 | self.readline_indent = 0 # for auto-indenting via readline |
|
1205 | self.readline_indent = 0 # for auto-indenting via readline | |
1172 | # save this in sys so embedded copies can restore it properly |
|
1206 | # save this in sys so embedded copies can restore it properly | |
1173 | sys.ipcompleter = self.Completer.complete |
|
1207 | sys.ipcompleter = self.Completer.complete | |
1174 | readline.set_completer(self.Completer.complete) |
|
1208 | readline.set_completer(self.Completer.complete) | |
1175 |
|
1209 | |||
1176 | # Configure readline according to user's prefs |
|
1210 | # Configure readline according to user's prefs | |
1177 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1211 | for rlcommand in self.rc.readline_parse_and_bind: | |
1178 | readline.parse_and_bind(rlcommand) |
|
1212 | readline.parse_and_bind(rlcommand) | |
1179 |
|
1213 | |||
1180 | # remove some chars from the delimiters list |
|
1214 | # remove some chars from the delimiters list | |
1181 | delims = readline.get_completer_delims() |
|
1215 | delims = readline.get_completer_delims() | |
1182 | delims = delims.translate(string._idmap, |
|
1216 | delims = delims.translate(string._idmap, | |
1183 | self.rc.readline_remove_delims) |
|
1217 | self.rc.readline_remove_delims) | |
1184 | readline.set_completer_delims(delims) |
|
1218 | readline.set_completer_delims(delims) | |
1185 | # otherwise we end up with a monster history after a while: |
|
1219 | # otherwise we end up with a monster history after a while: | |
1186 | readline.set_history_length(1000) |
|
1220 | readline.set_history_length(1000) | |
1187 | try: |
|
1221 | try: | |
1188 | #print '*** Reading readline history' # dbg |
|
1222 | #print '*** Reading readline history' # dbg | |
1189 | readline.read_history_file(self.histfile) |
|
1223 | readline.read_history_file(self.histfile) | |
1190 | except IOError: |
|
1224 | except IOError: | |
1191 | pass # It doesn't exist yet. |
|
1225 | pass # It doesn't exist yet. | |
1192 |
|
1226 | |||
1193 | atexit.register(self.atexit_operations) |
|
1227 | atexit.register(self.atexit_operations) | |
1194 | del atexit |
|
1228 | del atexit | |
1195 |
|
1229 | |||
1196 | # Configure auto-indent for all platforms |
|
1230 | # Configure auto-indent for all platforms | |
1197 | self.set_autoindent(self.rc.autoindent) |
|
1231 | self.set_autoindent(self.rc.autoindent) | |
1198 |
|
1232 | |||
1199 | def showsyntaxerror(self, filename=None): |
|
1233 | def showsyntaxerror(self, filename=None): | |
1200 | """Display the syntax error that just occurred. |
|
1234 | """Display the syntax error that just occurred. | |
1201 |
|
1235 | |||
1202 | This doesn't display a stack trace because there isn't one. |
|
1236 | This doesn't display a stack trace because there isn't one. | |
1203 |
|
1237 | |||
1204 | If a filename is given, it is stuffed in the exception instead |
|
1238 | If a filename is given, it is stuffed in the exception instead | |
1205 | of what was there before (because Python's parser always uses |
|
1239 | of what was there before (because Python's parser always uses | |
1206 | "<string>" when reading from a string). |
|
1240 | "<string>" when reading from a string). | |
1207 | """ |
|
1241 | """ | |
1208 | type, value, sys.last_traceback = sys.exc_info() |
|
1242 | type, value, sys.last_traceback = sys.exc_info() | |
1209 | sys.last_type = type |
|
1243 | sys.last_type = type | |
1210 | sys.last_value = value |
|
1244 | sys.last_value = value | |
1211 | if filename and type is SyntaxError: |
|
1245 | if filename and type is SyntaxError: | |
1212 | # Work hard to stuff the correct filename in the exception |
|
1246 | # Work hard to stuff the correct filename in the exception | |
1213 | try: |
|
1247 | try: | |
1214 | msg, (dummy_filename, lineno, offset, line) = value |
|
1248 | msg, (dummy_filename, lineno, offset, line) = value | |
1215 | except: |
|
1249 | except: | |
1216 | # Not the format we expect; leave it alone |
|
1250 | # Not the format we expect; leave it alone | |
1217 | pass |
|
1251 | pass | |
1218 | else: |
|
1252 | else: | |
1219 | # Stuff in the right filename |
|
1253 | # Stuff in the right filename | |
1220 | try: |
|
1254 | try: | |
1221 | # Assume SyntaxError is a class exception |
|
1255 | # Assume SyntaxError is a class exception | |
1222 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1256 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1223 | except: |
|
1257 | except: | |
1224 | # If that failed, assume SyntaxError is a string |
|
1258 | # If that failed, assume SyntaxError is a string | |
1225 | value = msg, (filename, lineno, offset, line) |
|
1259 | value = msg, (filename, lineno, offset, line) | |
1226 | self.SyntaxTB(type,value,[]) |
|
1260 | self.SyntaxTB(type,value,[]) | |
1227 |
|
1261 | |||
1228 | def debugger(self): |
|
1262 | def debugger(self): | |
1229 | """Call the pdb debugger.""" |
|
1263 | """Call the pdb debugger.""" | |
1230 |
|
1264 | |||
1231 | if not self.rc.pdb: |
|
1265 | if not self.rc.pdb: | |
1232 | return |
|
1266 | return | |
1233 | pdb.pm() |
|
1267 | pdb.pm() | |
1234 |
|
1268 | |||
1235 | def showtraceback(self,exc_tuple = None): |
|
1269 | def showtraceback(self,exc_tuple = None): | |
1236 | """Display the exception that just occurred.""" |
|
1270 | """Display the exception that just occurred.""" | |
1237 |
|
1271 | |||
1238 | # Though this won't be called by syntax errors in the input line, |
|
1272 | # Though this won't be called by syntax errors in the input line, | |
1239 | # there may be SyntaxError cases whith imported code. |
|
1273 | # there may be SyntaxError cases whith imported code. | |
1240 | if exc_tuple is None: |
|
1274 | if exc_tuple is None: | |
1241 | type, value, tb = sys.exc_info() |
|
1275 | type, value, tb = sys.exc_info() | |
1242 | else: |
|
1276 | else: | |
1243 | type, value, tb = exc_tuple |
|
1277 | type, value, tb = exc_tuple | |
1244 | if type is SyntaxError: |
|
1278 | if type is SyntaxError: | |
1245 | self.showsyntaxerror() |
|
1279 | self.showsyntaxerror() | |
1246 | else: |
|
1280 | else: | |
1247 | sys.last_type = type |
|
1281 | sys.last_type = type | |
1248 | sys.last_value = value |
|
1282 | sys.last_value = value | |
1249 | sys.last_traceback = tb |
|
1283 | sys.last_traceback = tb | |
1250 | self.InteractiveTB() |
|
1284 | self.InteractiveTB() | |
1251 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1285 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1252 | # pdb mucks up readline, fix it back |
|
1286 | # pdb mucks up readline, fix it back | |
1253 | self.readline.set_completer(self.Completer.complete) |
|
1287 | self.readline.set_completer(self.Completer.complete) | |
1254 |
|
1288 | |||
1255 | def update_cache(self, line): |
|
1289 | def update_cache(self, line): | |
1256 | """puts line into cache""" |
|
1290 | """puts line into cache""" | |
1257 | self.inputcache.insert(0, line) # This copies the cache every time ... :-( |
|
1291 | self.inputcache.insert(0, line) # This copies the cache every time ... :-( | |
1258 | if len(self.inputcache) >= self.CACHELENGTH: |
|
1292 | if len(self.inputcache) >= self.CACHELENGTH: | |
1259 | self.inputcache.pop() # This not :-) |
|
1293 | self.inputcache.pop() # This not :-) | |
1260 |
|
1294 | |||
1261 | def name_space_init(self): |
|
1295 | def name_space_init(self): | |
1262 | """Create local namespace.""" |
|
1296 | """Create local namespace.""" | |
1263 | # We want this to be a method to facilitate embedded initialization. |
|
1297 | # We want this to be a method to facilitate embedded initialization. | |
1264 | code.InteractiveConsole.__init__(self,self.user_ns) |
|
1298 | code.InteractiveConsole.__init__(self,self.user_ns) | |
1265 |
|
1299 | |||
1266 | def mainloop(self,banner=None): |
|
1300 | def mainloop(self,banner=None): | |
1267 | """Creates the local namespace and starts the mainloop. |
|
1301 | """Creates the local namespace and starts the mainloop. | |
1268 |
|
1302 | |||
1269 | If an optional banner argument is given, it will override the |
|
1303 | If an optional banner argument is given, it will override the | |
1270 | internally created default banner.""" |
|
1304 | internally created default banner.""" | |
1271 |
|
1305 | |||
1272 | self.name_space_init() |
|
1306 | self.name_space_init() | |
1273 | if self.rc.c: # Emulate Python's -c option |
|
1307 | if self.rc.c: # Emulate Python's -c option | |
1274 | self.exec_init_cmd() |
|
1308 | self.exec_init_cmd() | |
1275 | if banner is None: |
|
1309 | if banner is None: | |
1276 | if self.rc.banner: |
|
1310 | if self.rc.banner: | |
1277 | banner = self.BANNER+self.banner2 |
|
1311 | banner = self.BANNER+self.banner2 | |
1278 | else: |
|
1312 | else: | |
1279 | banner = '' |
|
1313 | banner = '' | |
1280 | self.interact(banner) |
|
1314 | self.interact(banner) | |
1281 |
|
1315 | |||
1282 | def exec_init_cmd(self): |
|
1316 | def exec_init_cmd(self): | |
1283 | """Execute a command given at the command line. |
|
1317 | """Execute a command given at the command line. | |
1284 |
|
1318 | |||
1285 | This emulates Python's -c option.""" |
|
1319 | This emulates Python's -c option.""" | |
1286 |
|
1320 | |||
1287 | sys.argv = ['-c'] |
|
1321 | sys.argv = ['-c'] | |
1288 | self.push(self.rc.c) |
|
1322 | self.push(self.rc.c) | |
1289 |
|
1323 | |||
1290 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1324 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1291 | """Embeds IPython into a running python program. |
|
1325 | """Embeds IPython into a running python program. | |
1292 |
|
1326 | |||
1293 | Input: |
|
1327 | Input: | |
1294 |
|
1328 | |||
1295 | - header: An optional header message can be specified. |
|
1329 | - header: An optional header message can be specified. | |
1296 |
|
1330 | |||
1297 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1331 | - local_ns, global_ns: working namespaces. If given as None, the | |
1298 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1332 | IPython-initialized one is updated with __main__.__dict__, so that | |
1299 | program variables become visible but user-specific configuration |
|
1333 | program variables become visible but user-specific configuration | |
1300 | remains possible. |
|
1334 | remains possible. | |
1301 |
|
1335 | |||
1302 | - stack_depth: specifies how many levels in the stack to go to |
|
1336 | - stack_depth: specifies how many levels in the stack to go to | |
1303 | looking for namespaces (when local_ns and global_ns are None). This |
|
1337 | looking for namespaces (when local_ns and global_ns are None). This | |
1304 | allows an intermediate caller to make sure that this function gets |
|
1338 | allows an intermediate caller to make sure that this function gets | |
1305 | the namespace from the intended level in the stack. By default (0) |
|
1339 | the namespace from the intended level in the stack. By default (0) | |
1306 | it will get its locals and globals from the immediate caller. |
|
1340 | it will get its locals and globals from the immediate caller. | |
1307 |
|
1341 | |||
1308 | Warning: it's possible to use this in a program which is being run by |
|
1342 | Warning: it's possible to use this in a program which is being run by | |
1309 | IPython itself (via %run), but some funny things will happen (a few |
|
1343 | IPython itself (via %run), but some funny things will happen (a few | |
1310 | globals get overwritten). In the future this will be cleaned up, as |
|
1344 | globals get overwritten). In the future this will be cleaned up, as | |
1311 | there is no fundamental reason why it can't work perfectly.""" |
|
1345 | there is no fundamental reason why it can't work perfectly.""" | |
1312 |
|
1346 | |||
1313 | # Patch for global embedding to make sure that things don't overwrite |
|
1347 | # Patch for global embedding to make sure that things don't overwrite | |
1314 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1348 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1315 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1349 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1316 | if local_ns is None and global_ns is None: |
|
1350 | if local_ns is None and global_ns is None: | |
1317 | self.user_ns.update(__main__.__dict__) |
|
1351 | self.user_ns.update(__main__.__dict__) | |
1318 |
|
1352 | |||
1319 | # Get locals and globals from caller |
|
1353 | # Get locals and globals from caller | |
1320 | if local_ns is None or global_ns is None: |
|
1354 | if local_ns is None or global_ns is None: | |
1321 | call_frame = sys._getframe(stack_depth).f_back |
|
1355 | call_frame = sys._getframe(stack_depth).f_back | |
1322 |
|
1356 | |||
1323 | if local_ns is None: |
|
1357 | if local_ns is None: | |
1324 | local_ns = call_frame.f_locals |
|
1358 | local_ns = call_frame.f_locals | |
1325 | if global_ns is None: |
|
1359 | if global_ns is None: | |
1326 | global_ns = call_frame.f_globals |
|
1360 | global_ns = call_frame.f_globals | |
1327 |
|
1361 | |||
1328 | # Update namespaces and fire up interpreter |
|
1362 | # Update namespaces and fire up interpreter | |
1329 | self.user_ns.update(local_ns) |
|
1363 | self.user_ns.update(local_ns) | |
1330 | self.interact(header) |
|
1364 | self.interact(header) | |
1331 |
|
1365 | |||
1332 | # Remove locals from namespace |
|
1366 | # Remove locals from namespace | |
1333 | for k in local_ns: |
|
1367 | for k in local_ns: | |
1334 | del self.user_ns[k] |
|
1368 | del self.user_ns[k] | |
1335 |
|
1369 | |||
1336 | def interact(self, banner=None): |
|
1370 | def interact(self, banner=None): | |
1337 | """Closely emulate the interactive Python console. |
|
1371 | """Closely emulate the interactive Python console. | |
1338 |
|
1372 | |||
1339 | The optional banner argument specify the banner to print |
|
1373 | The optional banner argument specify the banner to print | |
1340 | before the first interaction; by default it prints a banner |
|
1374 | before the first interaction; by default it prints a banner | |
1341 | similar to the one printed by the real Python interpreter, |
|
1375 | similar to the one printed by the real Python interpreter, | |
1342 | followed by the current class name in parentheses (so as not |
|
1376 | followed by the current class name in parentheses (so as not | |
1343 | to confuse this with the real interpreter -- since it's so |
|
1377 | to confuse this with the real interpreter -- since it's so | |
1344 | close!). |
|
1378 | close!). | |
1345 |
|
1379 | |||
1346 | """ |
|
1380 | """ | |
1347 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1381 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1348 | if banner is None: |
|
1382 | if banner is None: | |
1349 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1383 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1350 | (sys.version, sys.platform, cprt, |
|
1384 | (sys.version, sys.platform, cprt, | |
1351 | self.__class__.__name__)) |
|
1385 | self.__class__.__name__)) | |
1352 | else: |
|
1386 | else: | |
1353 | self.write(banner) |
|
1387 | self.write(banner) | |
1354 |
|
1388 | |||
1355 | more = 0 |
|
1389 | more = 0 | |
1356 |
|
1390 | |||
1357 | # Mark activity in the builtins |
|
1391 | # Mark activity in the builtins | |
1358 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1392 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1359 |
|
1393 | |||
1360 | # exit_now is set by a call to %Exit or %Quit |
|
1394 | # exit_now is set by a call to %Exit or %Quit | |
1361 | while not self.exit_now: |
|
1395 | while not self.exit_now: | |
1362 | try: |
|
1396 | try: | |
1363 | if more: |
|
1397 | if more: | |
1364 | prompt = self.outputcache.prompt2 |
|
1398 | prompt = self.outputcache.prompt2 | |
1365 | if self.autoindent: |
|
1399 | if self.autoindent: | |
1366 | self.readline_startup_hook(self.pre_readline) |
|
1400 | self.readline_startup_hook(self.pre_readline) | |
1367 | else: |
|
1401 | else: | |
1368 | prompt = self.outputcache.prompt1 |
|
1402 | prompt = self.outputcache.prompt1 | |
1369 | try: |
|
1403 | try: | |
1370 | line = self.raw_input(prompt) |
|
1404 | line = self.raw_input(prompt) | |
1371 | if self.autoindent: |
|
1405 | if self.autoindent: | |
1372 | self.readline_startup_hook(None) |
|
1406 | self.readline_startup_hook(None) | |
1373 | except EOFError: |
|
1407 | except EOFError: | |
1374 | if self.autoindent: |
|
1408 | if self.autoindent: | |
1375 | self.readline_startup_hook(None) |
|
1409 | self.readline_startup_hook(None) | |
1376 | self.write("\n") |
|
1410 | self.write("\n") | |
1377 | if self.rc.confirm_exit: |
|
1411 | if self.rc.confirm_exit: | |
1378 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
1412 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
1379 | break |
|
1413 | break | |
1380 | else: |
|
1414 | else: | |
1381 | break |
|
1415 | break | |
1382 | else: |
|
1416 | else: | |
1383 | more = self.push(line) |
|
1417 | more = self.push(line) | |
1384 | # Auto-indent management |
|
1418 | # Auto-indent management | |
1385 | if self.autoindent: |
|
1419 | if self.autoindent: | |
1386 | if line: |
|
1420 | if line: | |
1387 | ini_spaces = re.match('^(\s+)',line) |
|
1421 | ini_spaces = re.match('^(\s+)',line) | |
1388 | if ini_spaces: |
|
1422 | if ini_spaces: | |
1389 | nspaces = ini_spaces.end() |
|
1423 | nspaces = ini_spaces.end() | |
1390 | else: |
|
1424 | else: | |
1391 | nspaces = 0 |
|
1425 | nspaces = 0 | |
1392 | self.readline_indent = nspaces |
|
1426 | self.readline_indent = nspaces | |
1393 |
|
1427 | |||
1394 | if line[-1] == ':': |
|
1428 | if line[-1] == ':': | |
1395 | self.readline_indent += 4 |
|
1429 | self.readline_indent += 4 | |
1396 | elif re.match(r'^\s+raise|^\s+return',line): |
|
1430 | elif re.match(r'^\s+raise|^\s+return',line): | |
1397 | self.readline_indent -= 4 |
|
1431 | self.readline_indent -= 4 | |
1398 | else: |
|
1432 | else: | |
1399 | self.readline_indent = 0 |
|
1433 | self.readline_indent = 0 | |
1400 |
|
1434 | |||
1401 | except KeyboardInterrupt: |
|
1435 | except KeyboardInterrupt: | |
1402 | self.write("\nKeyboardInterrupt\n") |
|
1436 | self.write("\nKeyboardInterrupt\n") | |
1403 | self.resetbuffer() |
|
1437 | self.resetbuffer() | |
1404 | more = 0 |
|
1438 | more = 0 | |
1405 | # keep cache in sync with the prompt counter: |
|
1439 | # keep cache in sync with the prompt counter: | |
1406 | self.outputcache.prompt_count -= 1 |
|
1440 | self.outputcache.prompt_count -= 1 | |
1407 |
|
1441 | |||
1408 | if self.autoindent: |
|
1442 | if self.autoindent: | |
1409 | self.readline_indent = 0 |
|
1443 | self.readline_indent = 0 | |
1410 |
|
1444 | |||
1411 | except bdb.BdbQuit: |
|
1445 | except bdb.BdbQuit: | |
1412 | warn("The Python debugger has exited with a BdbQuit exception.\n" |
|
1446 | warn("The Python debugger has exited with a BdbQuit exception.\n" | |
1413 | "Because of how pdb handles the stack, it is impossible\n" |
|
1447 | "Because of how pdb handles the stack, it is impossible\n" | |
1414 | "for IPython to properly format this particular exception.\n" |
|
1448 | "for IPython to properly format this particular exception.\n" | |
1415 | "IPython will resume normal operation.") |
|
1449 | "IPython will resume normal operation.") | |
1416 |
|
1450 | |||
1417 | # We are off again... |
|
1451 | # We are off again... | |
1418 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1452 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1419 |
|
1453 | |||
1420 | def excepthook(self, type, value, tb): |
|
1454 | def excepthook(self, type, value, tb): | |
1421 | """One more defense for GUI apps that call sys.excepthook. |
|
1455 | """One more defense for GUI apps that call sys.excepthook. | |
1422 |
|
1456 | |||
1423 | GUI frameworks like wxPython trap exceptions and call |
|
1457 | GUI frameworks like wxPython trap exceptions and call | |
1424 | sys.excepthook themselves. I guess this is a feature that |
|
1458 | sys.excepthook themselves. I guess this is a feature that | |
1425 | enables them to keep running after exceptions that would |
|
1459 | enables them to keep running after exceptions that would | |
1426 | otherwise kill their mainloop. This is a bother for IPython |
|
1460 | otherwise kill their mainloop. This is a bother for IPython | |
1427 | which excepts to catch all of the program exceptions with a try: |
|
1461 | which excepts to catch all of the program exceptions with a try: | |
1428 | except: statement. |
|
1462 | except: statement. | |
1429 |
|
1463 | |||
1430 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1464 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1431 | any app directly invokes sys.excepthook, it will look to the user like |
|
1465 | any app directly invokes sys.excepthook, it will look to the user like | |
1432 | IPython crashed. In order to work around this, we can disable the |
|
1466 | IPython crashed. In order to work around this, we can disable the | |
1433 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1467 | CrashHandler and replace it with this excepthook instead, which prints a | |
1434 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1468 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1435 | call sys.excepthook will generate a regular-looking exception from |
|
1469 | call sys.excepthook will generate a regular-looking exception from | |
1436 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1470 | IPython, and the CrashHandler will only be triggered by real IPython | |
1437 | crashes. |
|
1471 | crashes. | |
1438 |
|
1472 | |||
1439 | This hook should be used sparingly, only in places which are not likely |
|
1473 | This hook should be used sparingly, only in places which are not likely | |
1440 | to be true IPython errors. |
|
1474 | to be true IPython errors. | |
1441 | """ |
|
1475 | """ | |
1442 |
|
1476 | |||
1443 | self.InteractiveTB(type, value, tb, tb_offset=0) |
|
1477 | self.InteractiveTB(type, value, tb, tb_offset=0) | |
1444 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1478 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1445 | self.readline.set_completer(self.Completer.complete) |
|
1479 | self.readline.set_completer(self.Completer.complete) | |
1446 |
|
1480 | |||
1447 | def call_alias(self,alias,rest=''): |
|
1481 | def call_alias(self,alias,rest=''): | |
1448 | """Call an alias given its name and the rest of the line. |
|
1482 | """Call an alias given its name and the rest of the line. | |
1449 |
|
1483 | |||
1450 | This function MUST be given a proper alias, because it doesn't make |
|
1484 | This function MUST be given a proper alias, because it doesn't make | |
1451 | any checks when looking up into the alias table. The caller is |
|
1485 | any checks when looking up into the alias table. The caller is | |
1452 | responsible for invoking it only with a valid alias.""" |
|
1486 | responsible for invoking it only with a valid alias.""" | |
1453 |
|
1487 | |||
1454 | #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg |
|
1488 | #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg | |
1455 | nargs,cmd = self.alias_table[alias] |
|
1489 | nargs,cmd = self.alias_table[alias] | |
1456 | # Expand the %l special to be the user's input line |
|
1490 | # Expand the %l special to be the user's input line | |
1457 | if cmd.find('%l') >= 0: |
|
1491 | if cmd.find('%l') >= 0: | |
1458 | cmd = cmd.replace('%l',rest) |
|
1492 | cmd = cmd.replace('%l',rest) | |
1459 | rest = '' |
|
1493 | rest = '' | |
1460 | if nargs==0: |
|
1494 | if nargs==0: | |
1461 | # Simple, argument-less aliases |
|
1495 | # Simple, argument-less aliases | |
1462 | cmd = '%s %s' % (cmd,rest) |
|
1496 | cmd = '%s %s' % (cmd,rest) | |
1463 | else: |
|
1497 | else: | |
1464 | # Handle aliases with positional arguments |
|
1498 | # Handle aliases with positional arguments | |
1465 | args = rest.split(None,nargs) |
|
1499 | args = rest.split(None,nargs) | |
1466 | if len(args)< nargs: |
|
1500 | if len(args)< nargs: | |
1467 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1501 | error('Alias <%s> requires %s arguments, %s given.' % | |
1468 | (alias,nargs,len(args))) |
|
1502 | (alias,nargs,len(args))) | |
1469 | return |
|
1503 | return | |
1470 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1504 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
1471 | # Now call the macro, evaluating in the user's namespace |
|
1505 | # Now call the macro, evaluating in the user's namespace | |
1472 | try: |
|
1506 | try: | |
1473 | self.system(cmd) |
|
1507 | self.system(cmd) | |
1474 | except: |
|
1508 | except: | |
1475 | self.showtraceback() |
|
1509 | self.showtraceback() | |
1476 |
|
1510 | |||
1477 | def runlines(self,lines): |
|
1511 | def runlines(self,lines): | |
1478 | """Run a string of one or more lines of source. |
|
1512 | """Run a string of one or more lines of source. | |
1479 |
|
1513 | |||
1480 | This method is capable of running a string containing multiple source |
|
1514 | This method is capable of running a string containing multiple source | |
1481 | lines, as if they had been entered at the IPython prompt. Since it |
|
1515 | lines, as if they had been entered at the IPython prompt. Since it | |
1482 | exposes IPython's processing machinery, the given strings can contain |
|
1516 | exposes IPython's processing machinery, the given strings can contain | |
1483 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1517 | magic calls (%magic), special shell access (!cmd), etc.""" | |
1484 |
|
1518 | |||
1485 | # We must start with a clean buffer, in case this is run from an |
|
1519 | # We must start with a clean buffer, in case this is run from an | |
1486 | # interactive IPython session (via a magic, for example). |
|
1520 | # interactive IPython session (via a magic, for example). | |
1487 | self.resetbuffer() |
|
1521 | self.resetbuffer() | |
1488 | lines = lines.split('\n') |
|
1522 | lines = lines.split('\n') | |
1489 | more = 0 |
|
1523 | more = 0 | |
1490 | for line in lines: |
|
1524 | for line in lines: | |
1491 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1525 | # skip blank lines so we don't mess up the prompt counter, but do | |
1492 | # NOT skip even a blank line if we are in a code block (more is |
|
1526 | # NOT skip even a blank line if we are in a code block (more is | |
1493 | # true) |
|
1527 | # true) | |
1494 | if line or more: |
|
1528 | if line or more: | |
1495 | more = self.push((self.prefilter(line,more))) |
|
1529 | more = self.push((self.prefilter(line,more))) | |
1496 | # IPython's runsource returns None if there was an error |
|
1530 | # IPython's runsource returns None if there was an error | |
1497 | # compiling the code. This allows us to stop processing right |
|
1531 | # compiling the code. This allows us to stop processing right | |
1498 | # away, so the user gets the error message at the right place. |
|
1532 | # away, so the user gets the error message at the right place. | |
1499 | if more is None: |
|
1533 | if more is None: | |
1500 | break |
|
1534 | break | |
1501 | # final newline in case the input didn't have it, so that the code |
|
1535 | # final newline in case the input didn't have it, so that the code | |
1502 | # actually does get executed |
|
1536 | # actually does get executed | |
1503 | if more: |
|
1537 | if more: | |
1504 | self.push('\n') |
|
1538 | self.push('\n') | |
1505 |
|
1539 | |||
1506 | def runsource(self, source, filename="<input>", symbol="single"): |
|
1540 | def runsource(self, source, filename="<input>", symbol="single"): | |
1507 | """Compile and run some source in the interpreter. |
|
1541 | """Compile and run some source in the interpreter. | |
1508 |
|
1542 | |||
1509 | Arguments are as for compile_command(). |
|
1543 | Arguments are as for compile_command(). | |
1510 |
|
1544 | |||
1511 | One several things can happen: |
|
1545 | One several things can happen: | |
1512 |
|
1546 | |||
1513 | 1) The input is incorrect; compile_command() raised an |
|
1547 | 1) The input is incorrect; compile_command() raised an | |
1514 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1548 | exception (SyntaxError or OverflowError). A syntax traceback | |
1515 | will be printed by calling the showsyntaxerror() method. |
|
1549 | will be printed by calling the showsyntaxerror() method. | |
1516 |
|
1550 | |||
1517 | 2) The input is incomplete, and more input is required; |
|
1551 | 2) The input is incomplete, and more input is required; | |
1518 | compile_command() returned None. Nothing happens. |
|
1552 | compile_command() returned None. Nothing happens. | |
1519 |
|
1553 | |||
1520 | 3) The input is complete; compile_command() returned a code |
|
1554 | 3) The input is complete; compile_command() returned a code | |
1521 | object. The code is executed by calling self.runcode() (which |
|
1555 | object. The code is executed by calling self.runcode() (which | |
1522 | also handles run-time exceptions, except for SystemExit). |
|
1556 | also handles run-time exceptions, except for SystemExit). | |
1523 |
|
1557 | |||
1524 | The return value is: |
|
1558 | The return value is: | |
1525 |
|
1559 | |||
1526 | - True in case 2 |
|
1560 | - True in case 2 | |
1527 |
|
1561 | |||
1528 | - False in the other cases, unless an exception is raised, where |
|
1562 | - False in the other cases, unless an exception is raised, where | |
1529 | None is returned instead. This can be used by external callers to |
|
1563 | None is returned instead. This can be used by external callers to | |
1530 | know whether to continue feeding input or not. |
|
1564 | know whether to continue feeding input or not. | |
1531 |
|
1565 | |||
1532 | The return value can be used to decide whether to use sys.ps1 or |
|
1566 | The return value can be used to decide whether to use sys.ps1 or | |
1533 | sys.ps2 to prompt the next line.""" |
|
1567 | sys.ps2 to prompt the next line.""" | |
1534 |
|
1568 | |||
1535 | try: |
|
1569 | try: | |
1536 | code = self.compile(source, filename, symbol) |
|
1570 | code = self.compile(source, filename, symbol) | |
1537 | except (OverflowError, SyntaxError, ValueError): |
|
1571 | except (OverflowError, SyntaxError, ValueError): | |
1538 | # Case 1 |
|
1572 | # Case 1 | |
1539 | self.showsyntaxerror(filename) |
|
1573 | self.showsyntaxerror(filename) | |
1540 | return None |
|
1574 | return None | |
1541 |
|
1575 | |||
1542 | if code is None: |
|
1576 | if code is None: | |
1543 | # Case 2 |
|
1577 | # Case 2 | |
1544 | return True |
|
1578 | return True | |
1545 |
|
1579 | |||
1546 | # Case 3 |
|
1580 | # Case 3 | |
1547 | # We store the code object so that threaded shells and |
|
1581 | # We store the code object so that threaded shells and | |
1548 | # custom exception handlers can access all this info if needed. |
|
1582 | # custom exception handlers can access all this info if needed. | |
1549 | # The source corresponding to this can be obtained from the |
|
1583 | # The source corresponding to this can be obtained from the | |
1550 | # buffer attribute as '\n'.join(self.buffer). |
|
1584 | # buffer attribute as '\n'.join(self.buffer). | |
1551 | self.code_to_run = code |
|
1585 | self.code_to_run = code | |
1552 | # now actually execute the code object |
|
1586 | # now actually execute the code object | |
1553 | if self.runcode(code) == 0: |
|
1587 | if self.runcode(code) == 0: | |
1554 | return False |
|
1588 | return False | |
1555 | else: |
|
1589 | else: | |
1556 | return None |
|
1590 | return None | |
1557 |
|
1591 | |||
1558 | def runcode(self,code_obj): |
|
1592 | def runcode(self,code_obj): | |
1559 | """Execute a code object. |
|
1593 | """Execute a code object. | |
1560 |
|
1594 | |||
1561 | When an exception occurs, self.showtraceback() is called to display a |
|
1595 | When an exception occurs, self.showtraceback() is called to display a | |
1562 | traceback. |
|
1596 | traceback. | |
1563 |
|
1597 | |||
1564 | Return value: a flag indicating whether the code to be run completed |
|
1598 | Return value: a flag indicating whether the code to be run completed | |
1565 | successfully: |
|
1599 | successfully: | |
1566 |
|
1600 | |||
1567 | - 0: successful execution. |
|
1601 | - 0: successful execution. | |
1568 | - 1: an error occurred. |
|
1602 | - 1: an error occurred. | |
1569 | """ |
|
1603 | """ | |
1570 |
|
1604 | |||
1571 | # Set our own excepthook in case the user code tries to call it |
|
1605 | # Set our own excepthook in case the user code tries to call it | |
1572 | # directly, so that the IPython crash handler doesn't get triggered |
|
1606 | # directly, so that the IPython crash handler doesn't get triggered | |
1573 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
1607 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
1574 | outflag = 1 # happens in more places, so it's easier as default |
|
1608 | outflag = 1 # happens in more places, so it's easier as default | |
1575 | try: |
|
1609 | try: | |
1576 | try: |
|
1610 | try: | |
1577 | exec code_obj in self.locals |
|
1611 | exec code_obj in self.locals | |
1578 | finally: |
|
1612 | finally: | |
1579 | # Reset our crash handler in place |
|
1613 | # Reset our crash handler in place | |
1580 | sys.excepthook = old_excepthook |
|
1614 | sys.excepthook = old_excepthook | |
1581 | except SystemExit: |
|
1615 | except SystemExit: | |
1582 | self.resetbuffer() |
|
1616 | self.resetbuffer() | |
1583 | self.showtraceback() |
|
1617 | self.showtraceback() | |
1584 | warn( __builtin__.exit,level=1) |
|
1618 | warn( __builtin__.exit,level=1) | |
1585 | except self.custom_exceptions: |
|
1619 | except self.custom_exceptions: | |
1586 | etype,value,tb = sys.exc_info() |
|
1620 | etype,value,tb = sys.exc_info() | |
1587 | self.CustomTB(etype,value,tb) |
|
1621 | self.CustomTB(etype,value,tb) | |
1588 | except: |
|
1622 | except: | |
1589 | self.showtraceback() |
|
1623 | self.showtraceback() | |
1590 | else: |
|
1624 | else: | |
1591 | outflag = 0 |
|
1625 | outflag = 0 | |
1592 | if code.softspace(sys.stdout, 0): |
|
1626 | if code.softspace(sys.stdout, 0): | |
1593 |
|
1627 | |||
1594 | # Flush out code object which has been run (and source) |
|
1628 | # Flush out code object which has been run (and source) | |
1595 | self.code_to_run = None |
|
1629 | self.code_to_run = None | |
1596 | return outflag |
|
1630 | return outflag | |
1597 |
|
1631 | |||
1598 | def raw_input(self, prompt=""): |
|
1632 | def raw_input(self, prompt=""): | |
1599 | """Write a prompt and read a line. |
|
1633 | """Write a prompt and read a line. | |
1600 |
|
1634 | |||
1601 | The returned line does not include the trailing newline. |
|
1635 | The returned line does not include the trailing newline. | |
1602 | When the user enters the EOF key sequence, EOFError is raised. |
|
1636 | When the user enters the EOF key sequence, EOFError is raised. | |
1603 |
|
1637 | |||
1604 | The base implementation uses the built-in function |
|
1638 | The base implementation uses the built-in function | |
1605 | raw_input(); a subclass may replace this with a different |
|
1639 | raw_input(); a subclass may replace this with a different | |
1606 | implementation. |
|
1640 | implementation. | |
1607 | """ |
|
1641 | """ | |
1608 | return self.prefilter(raw_input_original(prompt), |
|
1642 | return self.prefilter(raw_input_original(prompt), | |
1609 | prompt==self.outputcache.prompt2) |
|
1643 | prompt==self.outputcache.prompt2) | |
1610 |
|
1644 | |||
1611 | def split_user_input(self,line): |
|
1645 | def split_user_input(self,line): | |
1612 | """Split user input into pre-char, function part and rest.""" |
|
1646 | """Split user input into pre-char, function part and rest.""" | |
1613 |
|
1647 | |||
1614 | lsplit = self.line_split.match(line) |
|
1648 | lsplit = self.line_split.match(line) | |
1615 | if lsplit is None: # no regexp match returns None |
|
1649 | if lsplit is None: # no regexp match returns None | |
1616 | try: |
|
1650 | try: | |
1617 | iFun,theRest = line.split(None,1) |
|
1651 | iFun,theRest = line.split(None,1) | |
1618 | except ValueError: |
|
1652 | except ValueError: | |
1619 | iFun,theRest = line,'' |
|
1653 | iFun,theRest = line,'' | |
1620 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
1654 | pre = re.match('^(\s*)(.*)',line).groups()[0] | |
1621 | else: |
|
1655 | else: | |
1622 | pre,iFun,theRest = lsplit.groups() |
|
1656 | pre,iFun,theRest = lsplit.groups() | |
1623 |
|
1657 | |||
1624 | #print 'line:<%s>' % line # dbg |
|
1658 | #print 'line:<%s>' % line # dbg | |
1625 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
1659 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg | |
1626 | return pre,iFun.strip(),theRest |
|
1660 | return pre,iFun.strip(),theRest | |
1627 |
|
1661 | |||
1628 | def _prefilter(self, line, continue_prompt): |
|
1662 | def _prefilter(self, line, continue_prompt): | |
1629 | """Calls different preprocessors, depending on the form of line.""" |
|
1663 | """Calls different preprocessors, depending on the form of line.""" | |
1630 |
|
1664 | |||
1631 | # All handlers *must* return a value, even if it's blank (''). |
|
1665 | # All handlers *must* return a value, even if it's blank (''). | |
1632 |
|
1666 | |||
1633 | # Lines are NOT logged here. Handlers should process the line as |
|
1667 | # Lines are NOT logged here. Handlers should process the line as | |
1634 | # needed, update the cache AND log it (so that the input cache array |
|
1668 | # needed, update the cache AND log it (so that the input cache array | |
1635 | # stays synced). |
|
1669 | # stays synced). | |
1636 |
|
1670 | |||
1637 | # This function is _very_ delicate, and since it's also the one which |
|
1671 | # This function is _very_ delicate, and since it's also the one which | |
1638 | # determines IPython's response to user input, it must be as efficient |
|
1672 | # determines IPython's response to user input, it must be as efficient | |
1639 | # as possible. For this reason it has _many_ returns in it, trying |
|
1673 | # as possible. For this reason it has _many_ returns in it, trying | |
1640 | # always to exit as quickly as it can figure out what it needs to do. |
|
1674 | # always to exit as quickly as it can figure out what it needs to do. | |
1641 |
|
1675 | |||
1642 | # This function is the main responsible for maintaining IPython's |
|
1676 | # This function is the main responsible for maintaining IPython's | |
1643 | # behavior respectful of Python's semantics. So be _very_ careful if |
|
1677 | # behavior respectful of Python's semantics. So be _very_ careful if | |
1644 | # making changes to anything here. |
|
1678 | # making changes to anything here. | |
1645 |
|
1679 | |||
1646 | #..................................................................... |
|
1680 | #..................................................................... | |
1647 | # Code begins |
|
1681 | # Code begins | |
1648 |
|
1682 | |||
1649 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
1683 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
1650 |
|
1684 | |||
1651 | # save the line away in case we crash, so the post-mortem handler can |
|
1685 | # save the line away in case we crash, so the post-mortem handler can | |
1652 | # record it |
|
1686 | # record it | |
1653 | self._last_input_line = line |
|
1687 | self._last_input_line = line | |
1654 |
|
1688 | |||
1655 | #print '***line: <%s>' % line # dbg |
|
1689 | #print '***line: <%s>' % line # dbg | |
1656 |
|
1690 | |||
1657 | # the input history needs to track even empty lines |
|
1691 | # the input history needs to track even empty lines | |
1658 | if not line.strip(): |
|
1692 | if not line.strip(): | |
1659 | if not continue_prompt: |
|
1693 | if not continue_prompt: | |
1660 | self.outputcache.prompt_count -= 1 |
|
1694 | self.outputcache.prompt_count -= 1 | |
1661 | return self.handle_normal('',continue_prompt) |
|
1695 | return self.handle_normal('',continue_prompt) | |
1662 |
|
1696 | |||
1663 | # print '***cont',continue_prompt # dbg |
|
1697 | # print '***cont',continue_prompt # dbg | |
1664 | # special handlers are only allowed for single line statements |
|
1698 | # special handlers are only allowed for single line statements | |
1665 | if continue_prompt and not self.rc.multi_line_specials: |
|
1699 | if continue_prompt and not self.rc.multi_line_specials: | |
1666 | return self.handle_normal(line,continue_prompt) |
|
1700 | return self.handle_normal(line,continue_prompt) | |
1667 |
|
1701 | |||
1668 | # For the rest, we need the structure of the input |
|
1702 | # For the rest, we need the structure of the input | |
1669 | pre,iFun,theRest = self.split_user_input(line) |
|
1703 | pre,iFun,theRest = self.split_user_input(line) | |
1670 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1704 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
1671 |
|
1705 | |||
1672 | # First check for explicit escapes in the last/first character |
|
1706 | # First check for explicit escapes in the last/first character | |
1673 | handler = None |
|
1707 | handler = None | |
1674 | if line[-1] == self.ESC_HELP: |
|
1708 | if line[-1] == self.ESC_HELP: | |
1675 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end |
|
1709 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end | |
1676 | if handler is None: |
|
1710 | if handler is None: | |
1677 | # look at the first character of iFun, NOT of line, so we skip |
|
1711 | # look at the first character of iFun, NOT of line, so we skip | |
1678 | # leading whitespace in multiline input |
|
1712 | # leading whitespace in multiline input | |
1679 | handler = self.esc_handlers.get(iFun[0:1]) |
|
1713 | handler = self.esc_handlers.get(iFun[0:1]) | |
1680 | if handler is not None: |
|
1714 | if handler is not None: | |
1681 | return handler(line,continue_prompt,pre,iFun,theRest) |
|
1715 | return handler(line,continue_prompt,pre,iFun,theRest) | |
1682 | # Emacs ipython-mode tags certain input lines |
|
1716 | # Emacs ipython-mode tags certain input lines | |
1683 | if line.endswith('# PYTHON-MODE'): |
|
1717 | if line.endswith('# PYTHON-MODE'): | |
1684 | return self.handle_emacs(line,continue_prompt) |
|
1718 | return self.handle_emacs(line,continue_prompt) | |
1685 |
|
1719 | |||
1686 | # Next, check if we can automatically execute this thing |
|
1720 | # Next, check if we can automatically execute this thing | |
1687 |
|
1721 | |||
1688 | # Allow ! in multi-line statements if multi_line_specials is on: |
|
1722 | # Allow ! in multi-line statements if multi_line_specials is on: | |
1689 | if continue_prompt and self.rc.multi_line_specials and \ |
|
1723 | if continue_prompt and self.rc.multi_line_specials and \ | |
1690 | iFun.startswith(self.ESC_SHELL): |
|
1724 | iFun.startswith(self.ESC_SHELL): | |
1691 | return self.handle_shell_escape(line,continue_prompt, |
|
1725 | return self.handle_shell_escape(line,continue_prompt, | |
1692 | pre=pre,iFun=iFun, |
|
1726 | pre=pre,iFun=iFun, | |
1693 | theRest=theRest) |
|
1727 | theRest=theRest) | |
1694 |
|
1728 | |||
1695 | # Let's try to find if the input line is a magic fn |
|
1729 | # Let's try to find if the input line is a magic fn | |
1696 | oinfo = None |
|
1730 | oinfo = None | |
1697 | if hasattr(self,'magic_'+iFun): |
|
1731 | if hasattr(self,'magic_'+iFun): | |
1698 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1732 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
1699 | if oinfo['ismagic']: |
|
1733 | if oinfo['ismagic']: | |
1700 | # Be careful not to call magics when a variable assignment is |
|
1734 | # Be careful not to call magics when a variable assignment is | |
1701 | # being made (ls='hi', for example) |
|
1735 | # being made (ls='hi', for example) | |
1702 | if self.rc.automagic and \ |
|
1736 | if self.rc.automagic and \ | |
1703 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ |
|
1737 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ | |
1704 | (self.rc.multi_line_specials or not continue_prompt): |
|
1738 | (self.rc.multi_line_specials or not continue_prompt): | |
1705 | return self.handle_magic(line,continue_prompt, |
|
1739 | return self.handle_magic(line,continue_prompt, | |
1706 | pre,iFun,theRest) |
|
1740 | pre,iFun,theRest) | |
1707 | else: |
|
1741 | else: | |
1708 | return self.handle_normal(line,continue_prompt) |
|
1742 | return self.handle_normal(line,continue_prompt) | |
1709 |
|
1743 | |||
1710 | # If the rest of the line begins with an (in)equality, assginment or |
|
1744 | # If the rest of the line begins with an (in)equality, assginment or | |
1711 | # function call, we should not call _ofind but simply execute it. |
|
1745 | # function call, we should not call _ofind but simply execute it. | |
1712 | # This avoids spurious geattr() accesses on objects upon assignment. |
|
1746 | # This avoids spurious geattr() accesses on objects upon assignment. | |
1713 | # |
|
1747 | # | |
1714 | # It also allows users to assign to either alias or magic names true |
|
1748 | # It also allows users to assign to either alias or magic names true | |
1715 | # python variables (the magic/alias systems always take second seat to |
|
1749 | # python variables (the magic/alias systems always take second seat to | |
1716 | # true python code). |
|
1750 | # true python code). | |
1717 | if theRest and theRest[0] in '!=()': |
|
1751 | if theRest and theRest[0] in '!=()': | |
1718 | return self.handle_normal(line,continue_prompt) |
|
1752 | return self.handle_normal(line,continue_prompt) | |
1719 |
|
1753 | |||
1720 | if oinfo is None: |
|
1754 | if oinfo is None: | |
1721 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1755 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
1722 |
|
1756 | |||
1723 | if not oinfo['found']: |
|
1757 | if not oinfo['found']: | |
1724 | return self.handle_normal(line,continue_prompt) |
|
1758 | return self.handle_normal(line,continue_prompt) | |
1725 | else: |
|
1759 | else: | |
1726 | #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg |
|
1760 | #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg | |
1727 | if oinfo['isalias']: |
|
1761 | if oinfo['isalias']: | |
1728 | return self.handle_alias(line,continue_prompt, |
|
1762 | return self.handle_alias(line,continue_prompt, | |
1729 | pre,iFun,theRest) |
|
1763 | pre,iFun,theRest) | |
1730 |
|
1764 | |||
1731 | if self.rc.autocall and \ |
|
1765 | if self.rc.autocall and \ | |
1732 | not self.re_exclude_auto.match(theRest) and \ |
|
1766 | not self.re_exclude_auto.match(theRest) and \ | |
1733 | self.re_fun_name.match(iFun) and \ |
|
1767 | self.re_fun_name.match(iFun) and \ | |
1734 | callable(oinfo['obj']) : |
|
1768 | callable(oinfo['obj']) : | |
1735 | #print 'going auto' # dbg |
|
1769 | #print 'going auto' # dbg | |
1736 | return self.handle_auto(line,continue_prompt,pre,iFun,theRest) |
|
1770 | return self.handle_auto(line,continue_prompt,pre,iFun,theRest) | |
1737 | else: |
|
1771 | else: | |
1738 | #print 'was callable?', callable(oinfo['obj']) # dbg |
|
1772 | #print 'was callable?', callable(oinfo['obj']) # dbg | |
1739 | return self.handle_normal(line,continue_prompt) |
|
1773 | return self.handle_normal(line,continue_prompt) | |
1740 |
|
1774 | |||
1741 | # If we get here, we have a normal Python line. Log and return. |
|
1775 | # If we get here, we have a normal Python line. Log and return. | |
1742 | return self.handle_normal(line,continue_prompt) |
|
1776 | return self.handle_normal(line,continue_prompt) | |
1743 |
|
1777 | |||
1744 | def _prefilter_dumb(self, line, continue_prompt): |
|
1778 | def _prefilter_dumb(self, line, continue_prompt): | |
1745 | """simple prefilter function, for debugging""" |
|
1779 | """simple prefilter function, for debugging""" | |
1746 | return self.handle_normal(line,continue_prompt) |
|
1780 | return self.handle_normal(line,continue_prompt) | |
1747 |
|
1781 | |||
1748 | # Set the default prefilter() function (this can be user-overridden) |
|
1782 | # Set the default prefilter() function (this can be user-overridden) | |
1749 | prefilter = _prefilter |
|
1783 | prefilter = _prefilter | |
1750 |
|
1784 | |||
1751 | def handle_normal(self,line,continue_prompt=None, |
|
1785 | def handle_normal(self,line,continue_prompt=None, | |
1752 | pre=None,iFun=None,theRest=None): |
|
1786 | pre=None,iFun=None,theRest=None): | |
1753 | """Handle normal input lines. Use as a template for handlers.""" |
|
1787 | """Handle normal input lines. Use as a template for handlers.""" | |
1754 |
|
1788 | |||
1755 | self.log(line,continue_prompt) |
|
1789 | self.log(line,continue_prompt) | |
1756 | self.update_cache(line) |
|
1790 | self.update_cache(line) | |
1757 | return line |
|
1791 | return line | |
1758 |
|
1792 | |||
1759 | def handle_alias(self,line,continue_prompt=None, |
|
1793 | def handle_alias(self,line,continue_prompt=None, | |
1760 | pre=None,iFun=None,theRest=None): |
|
1794 | pre=None,iFun=None,theRest=None): | |
1761 | """Handle alias input lines. """ |
|
1795 | """Handle alias input lines. """ | |
1762 |
|
1796 | |||
1763 | theRest = esc_quotes(theRest) |
|
1797 | theRest = esc_quotes(theRest) | |
1764 | line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest) |
|
1798 | line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest) | |
1765 | self.log(line_out,continue_prompt) |
|
1799 | self.log(line_out,continue_prompt) | |
1766 | self.update_cache(line_out) |
|
1800 | self.update_cache(line_out) | |
1767 | return line_out |
|
1801 | return line_out | |
1768 |
|
1802 | |||
1769 | def handle_shell_escape(self, line, continue_prompt=None, |
|
1803 | def handle_shell_escape(self, line, continue_prompt=None, | |
1770 | pre=None,iFun=None,theRest=None): |
|
1804 | pre=None,iFun=None,theRest=None): | |
1771 | """Execute the line in a shell, empty return value""" |
|
1805 | """Execute the line in a shell, empty return value""" | |
1772 |
|
1806 | |||
1773 | #print 'line in :', `line` # dbg |
|
1807 | #print 'line in :', `line` # dbg | |
1774 | # Example of a special handler. Others follow a similar pattern. |
|
1808 | # Example of a special handler. Others follow a similar pattern. | |
1775 | if continue_prompt: # multi-line statements |
|
1809 | if continue_prompt: # multi-line statements | |
1776 | if iFun.startswith('!!'): |
|
1810 | if iFun.startswith('!!'): | |
1777 | print 'SyntaxError: !! is not allowed in multiline statements' |
|
1811 | print 'SyntaxError: !! is not allowed in multiline statements' | |
1778 | return pre |
|
1812 | return pre | |
1779 | else: |
|
1813 | else: | |
1780 | cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"') |
|
1814 | cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"') | |
1781 | line_out = '%s%s.system("%s")' % (pre,self.name,cmd) |
|
1815 | line_out = '%s%s.system("%s")' % (pre,self.name,cmd) | |
1782 | #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')' |
|
1816 | #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')' | |
1783 | else: # single-line input |
|
1817 | else: # single-line input | |
1784 | if line.startswith('!!'): |
|
1818 | if line.startswith('!!'): | |
1785 | # rewrite iFun/theRest to properly hold the call to %sx and |
|
1819 | # rewrite iFun/theRest to properly hold the call to %sx and | |
1786 | # the actual command to be executed, so handle_magic can work |
|
1820 | # the actual command to be executed, so handle_magic can work | |
1787 | # correctly |
|
1821 | # correctly | |
1788 | theRest = '%s %s' % (iFun[2:],theRest) |
|
1822 | theRest = '%s %s' % (iFun[2:],theRest) | |
1789 | iFun = 'sx' |
|
1823 | iFun = 'sx' | |
1790 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]), |
|
1824 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]), | |
1791 | continue_prompt,pre,iFun,theRest) |
|
1825 | continue_prompt,pre,iFun,theRest) | |
1792 | else: |
|
1826 | else: | |
1793 | cmd = esc_quotes(line[1:]) |
|
1827 | cmd = esc_quotes(line[1:]) | |
1794 | line_out = '%s.system("%s")' % (self.name,cmd) |
|
1828 | line_out = '%s.system("%s")' % (self.name,cmd) | |
1795 | #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')' |
|
1829 | #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')' | |
1796 | # update cache/log and return |
|
1830 | # update cache/log and return | |
1797 | self.log(line_out,continue_prompt) |
|
1831 | self.log(line_out,continue_prompt) | |
1798 | self.update_cache(line_out) # readline cache gets normal line |
|
1832 | self.update_cache(line_out) # readline cache gets normal line | |
1799 | #print 'line out r:', `line_out` # dbg |
|
1833 | #print 'line out r:', `line_out` # dbg | |
1800 | #print 'line out s:', line_out # dbg |
|
1834 | #print 'line out s:', line_out # dbg | |
1801 | return line_out |
|
1835 | return line_out | |
1802 |
|
1836 | |||
1803 | def handle_magic(self, line, continue_prompt=None, |
|
1837 | def handle_magic(self, line, continue_prompt=None, | |
1804 | pre=None,iFun=None,theRest=None): |
|
1838 | pre=None,iFun=None,theRest=None): | |
1805 | """Execute magic functions. |
|
1839 | """Execute magic functions. | |
1806 |
|
1840 | |||
1807 | Also log them with a prepended # so the log is clean Python.""" |
|
1841 | Also log them with a prepended # so the log is clean Python.""" | |
1808 |
|
1842 | |||
1809 | cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest))) |
|
1843 | cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest))) | |
1810 | self.log(cmd,continue_prompt) |
|
1844 | self.log(cmd,continue_prompt) | |
1811 | self.update_cache(line) |
|
1845 | self.update_cache(line) | |
1812 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
1846 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
1813 | return cmd |
|
1847 | return cmd | |
1814 |
|
1848 | |||
1815 | def handle_auto(self, line, continue_prompt=None, |
|
1849 | def handle_auto(self, line, continue_prompt=None, | |
1816 | pre=None,iFun=None,theRest=None): |
|
1850 | pre=None,iFun=None,theRest=None): | |
1817 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
1851 | """Hande lines which can be auto-executed, quoting if requested.""" | |
1818 |
|
1852 | |||
1819 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1853 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
1820 |
|
1854 | |||
1821 | # This should only be active for single-line input! |
|
1855 | # This should only be active for single-line input! | |
1822 | if continue_prompt: |
|
1856 | if continue_prompt: | |
1823 | return line |
|
1857 | return line | |
1824 |
|
1858 | |||
1825 | if pre == self.ESC_QUOTE: |
|
1859 | if pre == self.ESC_QUOTE: | |
1826 | # Auto-quote splitting on whitespace |
|
1860 | # Auto-quote splitting on whitespace | |
1827 | newcmd = '%s("%s")\n' % (iFun,'", "'.join(theRest.split()) ) |
|
1861 | newcmd = '%s("%s")\n' % (iFun,'", "'.join(theRest.split()) ) | |
1828 | elif pre == self.ESC_QUOTE2: |
|
1862 | elif pre == self.ESC_QUOTE2: | |
1829 | # Auto-quote whole string |
|
1863 | # Auto-quote whole string | |
1830 | newcmd = '%s("%s")\n' % (iFun,theRest) |
|
1864 | newcmd = '%s("%s")\n' % (iFun,theRest) | |
1831 | else: |
|
1865 | else: | |
1832 | # Auto-paren |
|
1866 | # Auto-paren | |
1833 | if theRest[0:1] in ('=','['): |
|
1867 | if theRest[0:1] in ('=','['): | |
1834 | # Don't autocall in these cases. They can be either |
|
1868 | # Don't autocall in these cases. They can be either | |
1835 | # rebindings of an existing callable's name, or item access |
|
1869 | # rebindings of an existing callable's name, or item access | |
1836 | # for an object which is BOTH callable and implements |
|
1870 | # for an object which is BOTH callable and implements | |
1837 | # __getitem__. |
|
1871 | # __getitem__. | |
1838 | return '%s %s\n' % (iFun,theRest) |
|
1872 | return '%s %s\n' % (iFun,theRest) | |
1839 | if theRest.endswith(';'): |
|
1873 | if theRest.endswith(';'): | |
1840 | newcmd = '%s(%s);\n' % (iFun.rstrip(),theRest[:-1]) |
|
1874 | newcmd = '%s(%s);\n' % (iFun.rstrip(),theRest[:-1]) | |
1841 | else: |
|
1875 | else: | |
1842 | newcmd = '%s(%s)\n' % (iFun.rstrip(),theRest) |
|
1876 | newcmd = '%s(%s)\n' % (iFun.rstrip(),theRest) | |
1843 |
|
1877 | |||
1844 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd, |
|
1878 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd, | |
1845 | # log what is now valid Python, not the actual user input (without the |
|
1879 | # log what is now valid Python, not the actual user input (without the | |
1846 | # final newline) |
|
1880 | # final newline) | |
1847 | self.log(newcmd.strip(),continue_prompt) |
|
1881 | self.log(newcmd.strip(),continue_prompt) | |
1848 | return newcmd |
|
1882 | return newcmd | |
1849 |
|
1883 | |||
1850 | def handle_help(self, line, continue_prompt=None, |
|
1884 | def handle_help(self, line, continue_prompt=None, | |
1851 | pre=None,iFun=None,theRest=None): |
|
1885 | pre=None,iFun=None,theRest=None): | |
1852 | """Try to get some help for the object. |
|
1886 | """Try to get some help for the object. | |
1853 |
|
1887 | |||
1854 | obj? or ?obj -> basic information. |
|
1888 | obj? or ?obj -> basic information. | |
1855 | obj?? or ??obj -> more details. |
|
1889 | obj?? or ??obj -> more details. | |
1856 | """ |
|
1890 | """ | |
1857 |
|
1891 | |||
1858 | # We need to make sure that we don't process lines which would be |
|
1892 | # We need to make sure that we don't process lines which would be | |
1859 | # otherwise valid python, such as "x=1 # what?" |
|
1893 | # otherwise valid python, such as "x=1 # what?" | |
1860 | try: |
|
1894 | try: | |
1861 | code.compile_command(line) |
|
1895 | code.compile_command(line) | |
1862 | except SyntaxError: |
|
1896 | except SyntaxError: | |
1863 | # We should only handle as help stuff which is NOT valid syntax |
|
1897 | # We should only handle as help stuff which is NOT valid syntax | |
1864 | if line[0]==self.ESC_HELP: |
|
1898 | if line[0]==self.ESC_HELP: | |
1865 | line = line[1:] |
|
1899 | line = line[1:] | |
1866 | elif line[-1]==self.ESC_HELP: |
|
1900 | elif line[-1]==self.ESC_HELP: | |
1867 | line = line[:-1] |
|
1901 | line = line[:-1] | |
1868 | self.log('#?'+line) |
|
1902 | self.log('#?'+line) | |
1869 | self.update_cache(line) |
|
1903 | self.update_cache(line) | |
1870 | if line: |
|
1904 | if line: | |
1871 | self.magic_pinfo(line) |
|
1905 | self.magic_pinfo(line) | |
1872 | else: |
|
1906 | else: | |
1873 | page(self.usage,screen_lines=self.rc.screen_length) |
|
1907 | page(self.usage,screen_lines=self.rc.screen_length) | |
1874 | return '' # Empty string is needed here! |
|
1908 | return '' # Empty string is needed here! | |
1875 | except: |
|
1909 | except: | |
1876 | # Pass any other exceptions through to the normal handler |
|
1910 | # Pass any other exceptions through to the normal handler | |
1877 | return self.handle_normal(line,continue_prompt) |
|
1911 | return self.handle_normal(line,continue_prompt) | |
1878 | else: |
|
1912 | else: | |
1879 | # If the code compiles ok, we should handle it normally |
|
1913 | # If the code compiles ok, we should handle it normally | |
1880 | return self.handle_normal(line,continue_prompt) |
|
1914 | return self.handle_normal(line,continue_prompt) | |
1881 |
|
1915 | |||
1882 | def handle_emacs(self,line,continue_prompt=None, |
|
1916 | def handle_emacs(self,line,continue_prompt=None, | |
1883 | pre=None,iFun=None,theRest=None): |
|
1917 | pre=None,iFun=None,theRest=None): | |
1884 | """Handle input lines marked by python-mode.""" |
|
1918 | """Handle input lines marked by python-mode.""" | |
1885 |
|
1919 | |||
1886 | # Currently, nothing is done. Later more functionality can be added |
|
1920 | # Currently, nothing is done. Later more functionality can be added | |
1887 | # here if needed. |
|
1921 | # here if needed. | |
1888 |
|
1922 | |||
1889 | # The input cache shouldn't be updated |
|
1923 | # The input cache shouldn't be updated | |
1890 |
|
1924 | |||
1891 | return line |
|
1925 | return line | |
1892 |
|
1926 | |||
1893 | def write(self,data): |
|
1927 | def write(self,data): | |
1894 | """Write a string to the default output""" |
|
1928 | """Write a string to the default output""" | |
1895 | Term.cout.write(data) |
|
1929 | Term.cout.write(data) | |
1896 |
|
1930 | |||
1897 | def write_err(self,data): |
|
1931 | def write_err(self,data): | |
1898 | """Write a string to the default error output""" |
|
1932 | """Write a string to the default error output""" | |
1899 | Term.cerr.write(data) |
|
1933 | Term.cerr.write(data) | |
1900 |
|
1934 | |||
1901 | def safe_execfile(self,fname,*where,**kw): |
|
1935 | def safe_execfile(self,fname,*where,**kw): | |
1902 | fname = os.path.expanduser(fname) |
|
1936 | fname = os.path.expanduser(fname) | |
1903 |
|
1937 | |||
1904 | # find things also in current directory |
|
1938 | # find things also in current directory | |
1905 | dname = os.path.dirname(fname) |
|
1939 | dname = os.path.dirname(fname) | |
1906 | if not sys.path.count(dname): |
|
1940 | if not sys.path.count(dname): | |
1907 | sys.path.append(dname) |
|
1941 | sys.path.append(dname) | |
1908 |
|
1942 | |||
1909 | try: |
|
1943 | try: | |
1910 | xfile = open(fname) |
|
1944 | xfile = open(fname) | |
1911 | except: |
|
1945 | except: | |
1912 | print >> Term.cerr, \ |
|
1946 | print >> Term.cerr, \ | |
1913 | 'Could not open file <%s> for safe execution.' % fname |
|
1947 | 'Could not open file <%s> for safe execution.' % fname | |
1914 | return None |
|
1948 | return None | |
1915 |
|
1949 | |||
1916 | kw.setdefault('islog',0) |
|
1950 | kw.setdefault('islog',0) | |
1917 | kw.setdefault('quiet',1) |
|
1951 | kw.setdefault('quiet',1) | |
1918 | kw.setdefault('exit_ignore',0) |
|
1952 | kw.setdefault('exit_ignore',0) | |
1919 | first = xfile.readline() |
|
1953 | first = xfile.readline() | |
1920 | _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip() |
|
1954 | _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip() | |
1921 | xfile.close() |
|
1955 | xfile.close() | |
1922 | # line by line execution |
|
1956 | # line by line execution | |
1923 | if first.startswith(_LOGHEAD) or kw['islog']: |
|
1957 | if first.startswith(_LOGHEAD) or kw['islog']: | |
1924 | print 'Loading log file <%s> one line at a time...' % fname |
|
1958 | print 'Loading log file <%s> one line at a time...' % fname | |
1925 | if kw['quiet']: |
|
1959 | if kw['quiet']: | |
1926 | stdout_save = sys.stdout |
|
1960 | stdout_save = sys.stdout | |
1927 | sys.stdout = StringIO.StringIO() |
|
1961 | sys.stdout = StringIO.StringIO() | |
1928 | try: |
|
1962 | try: | |
1929 | globs,locs = where[0:2] |
|
1963 | globs,locs = where[0:2] | |
1930 | except: |
|
1964 | except: | |
1931 | try: |
|
1965 | try: | |
1932 | globs = locs = where[0] |
|
1966 | globs = locs = where[0] | |
1933 | except: |
|
1967 | except: | |
1934 | globs = locs = globals() |
|
1968 | globs = locs = globals() | |
1935 | badblocks = [] |
|
1969 | badblocks = [] | |
1936 |
|
1970 | |||
1937 | # we also need to identify indented blocks of code when replaying |
|
1971 | # we also need to identify indented blocks of code when replaying | |
1938 | # logs and put them together before passing them to an exec |
|
1972 | # logs and put them together before passing them to an exec | |
1939 | # statement. This takes a bit of regexp and look-ahead work in the |
|
1973 | # statement. This takes a bit of regexp and look-ahead work in the | |
1940 | # file. It's easiest if we swallow the whole thing in memory |
|
1974 | # file. It's easiest if we swallow the whole thing in memory | |
1941 | # first, and manually walk through the lines list moving the |
|
1975 | # first, and manually walk through the lines list moving the | |
1942 | # counter ourselves. |
|
1976 | # counter ourselves. | |
1943 | indent_re = re.compile('\s+\S') |
|
1977 | indent_re = re.compile('\s+\S') | |
1944 | xfile = open(fname) |
|
1978 | xfile = open(fname) | |
1945 | filelines = xfile.readlines() |
|
1979 | filelines = xfile.readlines() | |
1946 | xfile.close() |
|
1980 | xfile.close() | |
1947 | nlines = len(filelines) |
|
1981 | nlines = len(filelines) | |
1948 | lnum = 0 |
|
1982 | lnum = 0 | |
1949 | while lnum < nlines: |
|
1983 | while lnum < nlines: | |
1950 | line = filelines[lnum] |
|
1984 | line = filelines[lnum] | |
1951 | lnum += 1 |
|
1985 | lnum += 1 | |
1952 | # don't re-insert logger status info into cache |
|
1986 | # don't re-insert logger status info into cache | |
1953 | if line.startswith('#log#'): |
|
1987 | if line.startswith('#log#'): | |
1954 | continue |
|
1988 | continue | |
1955 | elif line.startswith('#%s'% self.ESC_MAGIC): |
|
1989 | elif line.startswith('#%s'% self.ESC_MAGIC): | |
1956 | self.update_cache(line[1:]) |
|
1990 | self.update_cache(line[1:]) | |
1957 | line = magic2python(line) |
|
1991 | line = magic2python(line) | |
1958 | elif line.startswith('#!'): |
|
1992 | elif line.startswith('#!'): | |
1959 | self.update_cache(line[1:]) |
|
1993 | self.update_cache(line[1:]) | |
1960 | else: |
|
1994 | else: | |
1961 | # build a block of code (maybe a single line) for execution |
|
1995 | # build a block of code (maybe a single line) for execution | |
1962 | block = line |
|
1996 | block = line | |
1963 | try: |
|
1997 | try: | |
1964 | next = filelines[lnum] # lnum has already incremented |
|
1998 | next = filelines[lnum] # lnum has already incremented | |
1965 | except: |
|
1999 | except: | |
1966 | next = None |
|
2000 | next = None | |
1967 | while next and indent_re.match(next): |
|
2001 | while next and indent_re.match(next): | |
1968 | block += next |
|
2002 | block += next | |
1969 | lnum += 1 |
|
2003 | lnum += 1 | |
1970 | try: |
|
2004 | try: | |
1971 | next = filelines[lnum] |
|
2005 | next = filelines[lnum] | |
1972 | except: |
|
2006 | except: | |
1973 | next = None |
|
2007 | next = None | |
1974 | # now execute the block of one or more lines |
|
2008 | # now execute the block of one or more lines | |
1975 | try: |
|
2009 | try: | |
1976 | exec block in globs,locs |
|
2010 | exec block in globs,locs | |
1977 | self.update_cache(block.rstrip()) |
|
2011 | self.update_cache(block.rstrip()) | |
1978 | except SystemExit: |
|
2012 | except SystemExit: | |
1979 | pass |
|
2013 | pass | |
1980 | except: |
|
2014 | except: | |
1981 | badblocks.append(block.rstrip()) |
|
2015 | badblocks.append(block.rstrip()) | |
1982 | if kw['quiet']: # restore stdout |
|
2016 | if kw['quiet']: # restore stdout | |
1983 | sys.stdout.close() |
|
2017 | sys.stdout.close() | |
1984 | sys.stdout = stdout_save |
|
2018 | sys.stdout = stdout_save | |
1985 | print 'Finished replaying log file <%s>' % fname |
|
2019 | print 'Finished replaying log file <%s>' % fname | |
1986 | if badblocks: |
|
2020 | if badblocks: | |
1987 | print >> sys.stderr, \ |
|
2021 | print >> sys.stderr, \ | |
1988 | '\nThe following lines/blocks in file <%s> reported errors:' \ |
|
2022 | '\nThe following lines/blocks in file <%s> reported errors:' \ | |
1989 | % fname |
|
2023 | % fname | |
1990 | for badline in badblocks: |
|
2024 | for badline in badblocks: | |
1991 | print >> sys.stderr, badline |
|
2025 | print >> sys.stderr, badline | |
1992 | else: # regular file execution |
|
2026 | else: # regular file execution | |
1993 | try: |
|
2027 | try: | |
1994 | execfile(fname,*where) |
|
2028 | execfile(fname,*where) | |
1995 | except SyntaxError: |
|
2029 | except SyntaxError: | |
1996 | etype, evalue = sys.exc_info()[0:2] |
|
2030 | etype, evalue = sys.exc_info()[0:2] | |
1997 | self.SyntaxTB(etype,evalue,[]) |
|
2031 | self.SyntaxTB(etype,evalue,[]) | |
1998 | warn('Failure executing file: <%s>' % fname) |
|
2032 | warn('Failure executing file: <%s>' % fname) | |
1999 | except SystemExit,status: |
|
2033 | except SystemExit,status: | |
2000 | if not kw['exit_ignore']: |
|
2034 | if not kw['exit_ignore']: | |
2001 | self.InteractiveTB() |
|
2035 | self.InteractiveTB() | |
2002 | warn('Failure executing file: <%s>' % fname) |
|
2036 | warn('Failure executing file: <%s>' % fname) | |
2003 | except: |
|
2037 | except: | |
2004 | self.InteractiveTB() |
|
2038 | self.InteractiveTB() | |
2005 | warn('Failure executing file: <%s>' % fname) |
|
2039 | warn('Failure executing file: <%s>' % fname) | |
2006 |
|
2040 | |||
2007 | #************************* end of file <iplib.py> ***************************** |
|
2041 | #************************* 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