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