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