Show More
@@ -1,2602 +1,2603 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Main IPython class.""" |
|
2 | """Main IPython class.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
7 | # Copyright (C) 2008-2011 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | from __future__ import with_statement |
|
17 | from __future__ import with_statement | |
18 | from __future__ import absolute_import |
|
18 | from __future__ import absolute_import | |
19 |
|
19 | |||
20 | import __builtin__ |
|
20 | import __builtin__ | |
21 | import __future__ |
|
21 | import __future__ | |
22 | import abc |
|
22 | import abc | |
23 | import ast |
|
23 | import ast | |
24 | import atexit |
|
24 | import atexit | |
25 | import codeop |
|
25 | import codeop | |
26 | import inspect |
|
26 | import inspect | |
27 | import os |
|
27 | import os | |
28 | import re |
|
28 | import re | |
29 | import sys |
|
29 | import sys | |
30 | import tempfile |
|
30 | import tempfile | |
31 | import types |
|
31 | import types | |
32 | from contextlib import nested |
|
32 | from contextlib import nested | |
33 |
|
33 | |||
34 | from IPython.config.configurable import Configurable |
|
34 | from IPython.config.configurable import Configurable | |
35 | from IPython.core import debugger, oinspect |
|
35 | from IPython.core import debugger, oinspect | |
36 | from IPython.core import history as ipcorehist |
|
36 | from IPython.core import history as ipcorehist | |
37 | from IPython.core import page |
|
37 | from IPython.core import page | |
38 | from IPython.core import prefilter |
|
38 | from IPython.core import prefilter | |
39 | from IPython.core import shadowns |
|
39 | from IPython.core import shadowns | |
40 | from IPython.core import ultratb |
|
40 | from IPython.core import ultratb | |
41 | from IPython.core.alias import AliasManager |
|
41 | from IPython.core.alias import AliasManager | |
42 | from IPython.core.builtin_trap import BuiltinTrap |
|
42 | from IPython.core.builtin_trap import BuiltinTrap | |
43 | from IPython.core.compilerop import CachingCompiler |
|
43 | from IPython.core.compilerop import CachingCompiler | |
44 | from IPython.core.display_trap import DisplayTrap |
|
44 | from IPython.core.display_trap import DisplayTrap | |
45 | from IPython.core.displayhook import DisplayHook |
|
45 | from IPython.core.displayhook import DisplayHook | |
46 | from IPython.core.displaypub import DisplayPublisher |
|
46 | from IPython.core.displaypub import DisplayPublisher | |
47 | from IPython.core.error import TryNext, UsageError |
|
47 | from IPython.core.error import TryNext, UsageError | |
48 | from IPython.core.extensions import ExtensionManager |
|
48 | from IPython.core.extensions import ExtensionManager | |
49 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
49 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
50 | from IPython.core.formatters import DisplayFormatter |
|
50 | from IPython.core.formatters import DisplayFormatter | |
51 | from IPython.core.history import HistoryManager |
|
51 | from IPython.core.history import HistoryManager | |
52 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
52 | from IPython.core.inputsplitter import IPythonInputSplitter | |
53 | from IPython.core.logger import Logger |
|
53 | from IPython.core.logger import Logger | |
54 | from IPython.core.macro import Macro |
|
54 | from IPython.core.macro import Macro | |
55 | from IPython.core.magic import Magic |
|
55 | from IPython.core.magic import Magic | |
56 | from IPython.core.payload import PayloadManager |
|
56 | from IPython.core.payload import PayloadManager | |
57 | from IPython.core.plugin import PluginManager |
|
57 | from IPython.core.plugin import PluginManager | |
58 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
58 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
59 | from IPython.external.Itpl import ItplNS |
|
59 | from IPython.external.Itpl import ItplNS | |
60 | from IPython.utils import PyColorize |
|
60 | from IPython.utils import PyColorize | |
61 | from IPython.utils import io |
|
61 | from IPython.utils import io | |
62 | from IPython.utils.doctestreload import doctest_reload |
|
62 | from IPython.utils.doctestreload import doctest_reload | |
63 | from IPython.utils.io import ask_yes_no, rprint |
|
63 | from IPython.utils.io import ask_yes_no, rprint | |
64 | from IPython.utils.ipstruct import Struct |
|
64 | from IPython.utils.ipstruct import Struct | |
65 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
65 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
66 | from IPython.utils.pickleshare import PickleShareDB |
|
66 | from IPython.utils.pickleshare import PickleShareDB | |
67 | from IPython.utils.process import system, getoutput |
|
67 | from IPython.utils.process import system, getoutput | |
68 | from IPython.utils.strdispatch import StrDispatch |
|
68 | from IPython.utils.strdispatch import StrDispatch | |
69 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
69 | from IPython.utils.syspathcontext import prepended_to_syspath | |
70 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList |
|
70 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList | |
71 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
71 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
72 | List, Unicode, Instance, Type) |
|
72 | List, Unicode, Instance, Type) | |
73 | from IPython.utils.warn import warn, error, fatal |
|
73 | from IPython.utils.warn import warn, error, fatal | |
74 | import IPython.core.hooks |
|
74 | import IPython.core.hooks | |
75 |
|
75 | |||
76 | #----------------------------------------------------------------------------- |
|
76 | #----------------------------------------------------------------------------- | |
77 | # Globals |
|
77 | # Globals | |
78 | #----------------------------------------------------------------------------- |
|
78 | #----------------------------------------------------------------------------- | |
79 |
|
79 | |||
80 | # compiled regexps for autoindent management |
|
80 | # compiled regexps for autoindent management | |
81 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
81 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
82 |
|
82 | |||
83 | #----------------------------------------------------------------------------- |
|
83 | #----------------------------------------------------------------------------- | |
84 | # Utilities |
|
84 | # Utilities | |
85 | #----------------------------------------------------------------------------- |
|
85 | #----------------------------------------------------------------------------- | |
86 |
|
86 | |||
87 | # store the builtin raw_input globally, and use this always, in case user code |
|
87 | # store the builtin raw_input globally, and use this always, in case user code | |
88 | # overwrites it (like wx.py.PyShell does) |
|
88 | # overwrites it (like wx.py.PyShell does) | |
89 | raw_input_original = raw_input |
|
89 | raw_input_original = raw_input | |
90 |
|
90 | |||
91 | def softspace(file, newvalue): |
|
91 | def softspace(file, newvalue): | |
92 | """Copied from code.py, to remove the dependency""" |
|
92 | """Copied from code.py, to remove the dependency""" | |
93 |
|
93 | |||
94 | oldvalue = 0 |
|
94 | oldvalue = 0 | |
95 | try: |
|
95 | try: | |
96 | oldvalue = file.softspace |
|
96 | oldvalue = file.softspace | |
97 | except AttributeError: |
|
97 | except AttributeError: | |
98 | pass |
|
98 | pass | |
99 | try: |
|
99 | try: | |
100 | file.softspace = newvalue |
|
100 | file.softspace = newvalue | |
101 | except (AttributeError, TypeError): |
|
101 | except (AttributeError, TypeError): | |
102 | # "attribute-less object" or "read-only attributes" |
|
102 | # "attribute-less object" or "read-only attributes" | |
103 | pass |
|
103 | pass | |
104 | return oldvalue |
|
104 | return oldvalue | |
105 |
|
105 | |||
106 |
|
106 | |||
107 | def no_op(*a, **kw): pass |
|
107 | def no_op(*a, **kw): pass | |
108 |
|
108 | |||
109 | class SpaceInInput(Exception): pass |
|
109 | class SpaceInInput(Exception): pass | |
110 |
|
110 | |||
111 | class Bunch: pass |
|
111 | class Bunch: pass | |
112 |
|
112 | |||
113 |
|
113 | |||
114 | def get_default_colors(): |
|
114 | def get_default_colors(): | |
115 | if sys.platform=='darwin': |
|
115 | if sys.platform=='darwin': | |
116 | return "LightBG" |
|
116 | return "LightBG" | |
117 | elif os.name=='nt': |
|
117 | elif os.name=='nt': | |
118 | return 'Linux' |
|
118 | return 'Linux' | |
119 | else: |
|
119 | else: | |
120 | return 'Linux' |
|
120 | return 'Linux' | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | class SeparateStr(Str): |
|
123 | class SeparateStr(Str): | |
124 | """A Str subclass to validate separate_in, separate_out, etc. |
|
124 | """A Str subclass to validate separate_in, separate_out, etc. | |
125 |
|
125 | |||
126 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
126 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
127 | """ |
|
127 | """ | |
128 |
|
128 | |||
129 | def validate(self, obj, value): |
|
129 | def validate(self, obj, value): | |
130 | if value == '0': value = '' |
|
130 | if value == '0': value = '' | |
131 | value = value.replace('\\n','\n') |
|
131 | value = value.replace('\\n','\n') | |
132 | return super(SeparateStr, self).validate(obj, value) |
|
132 | return super(SeparateStr, self).validate(obj, value) | |
133 |
|
133 | |||
134 | class MultipleInstanceError(Exception): |
|
134 | class MultipleInstanceError(Exception): | |
135 | pass |
|
135 | pass | |
136 |
|
136 | |||
137 | class ReadlineNoRecord(object): |
|
137 | class ReadlineNoRecord(object): | |
138 | """Context manager to execute some code, then reload readline history |
|
138 | """Context manager to execute some code, then reload readline history | |
139 | so that interactive input to the code doesn't appear when pressing up.""" |
|
139 | so that interactive input to the code doesn't appear when pressing up.""" | |
140 | def __init__(self, shell): |
|
140 | def __init__(self, shell): | |
141 | self.shell = shell |
|
141 | self.shell = shell | |
142 | self._nested_level = 0 |
|
142 | self._nested_level = 0 | |
143 |
|
143 | |||
144 | def __enter__(self): |
|
144 | def __enter__(self): | |
145 | if self._nested_level == 0: |
|
145 | if self._nested_level == 0: | |
146 | self.orig_length = self.current_length() |
|
146 | self.orig_length = self.current_length() | |
147 | self.readline_tail = self.get_readline_tail() |
|
147 | self.readline_tail = self.get_readline_tail() | |
148 | self._nested_level += 1 |
|
148 | self._nested_level += 1 | |
149 |
|
149 | |||
150 | def __exit__(self, type, value, traceback): |
|
150 | def __exit__(self, type, value, traceback): | |
151 | self._nested_level -= 1 |
|
151 | self._nested_level -= 1 | |
152 | if self._nested_level == 0: |
|
152 | if self._nested_level == 0: | |
153 | # Try clipping the end if it's got longer |
|
153 | # Try clipping the end if it's got longer | |
154 | e = self.current_length() - self.orig_length |
|
154 | e = self.current_length() - self.orig_length | |
155 | if e > 0: |
|
155 | if e > 0: | |
156 | for _ in range(e): |
|
156 | for _ in range(e): | |
157 | self.shell.readline.remove_history_item(self.orig_length) |
|
157 | self.shell.readline.remove_history_item(self.orig_length) | |
158 |
|
158 | |||
159 | # If it still doesn't match, just reload readline history. |
|
159 | # If it still doesn't match, just reload readline history. | |
160 | if self.current_length() != self.orig_length \ |
|
160 | if self.current_length() != self.orig_length \ | |
161 | or self.get_readline_tail() != self.readline_tail: |
|
161 | or self.get_readline_tail() != self.readline_tail: | |
162 | self.shell.refill_readline_hist() |
|
162 | self.shell.refill_readline_hist() | |
163 | # Returning False will cause exceptions to propagate |
|
163 | # Returning False will cause exceptions to propagate | |
164 | return False |
|
164 | return False | |
165 |
|
165 | |||
166 | def current_length(self): |
|
166 | def current_length(self): | |
167 | return self.shell.readline.get_current_history_length() |
|
167 | return self.shell.readline.get_current_history_length() | |
168 |
|
168 | |||
169 | def get_readline_tail(self, n=10): |
|
169 | def get_readline_tail(self, n=10): | |
170 | """Get the last n items in readline history.""" |
|
170 | """Get the last n items in readline history.""" | |
171 | end = self.shell.readline.get_current_history_length() + 1 |
|
171 | end = self.shell.readline.get_current_history_length() + 1 | |
172 | start = max(end-n, 1) |
|
172 | start = max(end-n, 1) | |
173 | ghi = self.shell.readline.get_history_item |
|
173 | ghi = self.shell.readline.get_history_item | |
174 | return [ghi(x) for x in range(start, end)] |
|
174 | return [ghi(x) for x in range(start, end)] | |
175 |
|
175 | |||
176 |
|
176 | |||
177 | #----------------------------------------------------------------------------- |
|
177 | #----------------------------------------------------------------------------- | |
178 | # Main IPython class |
|
178 | # Main IPython class | |
179 | #----------------------------------------------------------------------------- |
|
179 | #----------------------------------------------------------------------------- | |
180 |
|
180 | |||
181 | class InteractiveShell(Configurable, Magic): |
|
181 | class InteractiveShell(Configurable, Magic): | |
182 | """An enhanced, interactive shell for Python.""" |
|
182 | """An enhanced, interactive shell for Python.""" | |
183 |
|
183 | |||
184 | _instance = None |
|
184 | _instance = None | |
185 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
185 | autocall = Enum((0,1,2), default_value=1, config=True) | |
186 | # TODO: remove all autoindent logic and put into frontends. |
|
186 | # TODO: remove all autoindent logic and put into frontends. | |
187 | # We can't do this yet because even runlines uses the autoindent. |
|
187 | # We can't do this yet because even runlines uses the autoindent. | |
188 | autoindent = CBool(True, config=True) |
|
188 | autoindent = CBool(True, config=True) | |
189 | automagic = CBool(True, config=True) |
|
189 | automagic = CBool(True, config=True) | |
190 | cache_size = Int(1000, config=True) |
|
190 | cache_size = Int(1000, config=True) | |
191 | color_info = CBool(True, config=True) |
|
191 | color_info = CBool(True, config=True) | |
192 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
192 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
193 | default_value=get_default_colors(), config=True) |
|
193 | default_value=get_default_colors(), config=True) | |
194 | debug = CBool(False, config=True) |
|
194 | debug = CBool(False, config=True) | |
195 | deep_reload = CBool(False, config=True) |
|
195 | deep_reload = CBool(False, config=True) | |
196 | display_formatter = Instance(DisplayFormatter) |
|
196 | display_formatter = Instance(DisplayFormatter) | |
197 | displayhook_class = Type(DisplayHook) |
|
197 | displayhook_class = Type(DisplayHook) | |
198 | display_pub_class = Type(DisplayPublisher) |
|
198 | display_pub_class = Type(DisplayPublisher) | |
199 |
|
199 | |||
200 | exit_now = CBool(False) |
|
200 | exit_now = CBool(False) | |
201 | # Monotonically increasing execution counter |
|
201 | # Monotonically increasing execution counter | |
202 | execution_count = Int(1) |
|
202 | execution_count = Int(1) | |
203 | filename = Unicode("<ipython console>") |
|
203 | filename = Unicode("<ipython console>") | |
204 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
204 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
205 |
|
205 | |||
206 | # Input splitter, to split entire cells of input into either individual |
|
206 | # Input splitter, to split entire cells of input into either individual | |
207 | # interactive statements or whole blocks. |
|
207 | # interactive statements or whole blocks. | |
208 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
208 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
209 | (), {}) |
|
209 | (), {}) | |
210 | logstart = CBool(False, config=True) |
|
210 | logstart = CBool(False, config=True) | |
211 | logfile = Unicode('', config=True) |
|
211 | logfile = Unicode('', config=True) | |
212 | logappend = Unicode('', config=True) |
|
212 | logappend = Unicode('', config=True) | |
213 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
213 | object_info_string_level = Enum((0,1,2), default_value=0, | |
214 | config=True) |
|
214 | config=True) | |
215 | pdb = CBool(False, config=True) |
|
215 | pdb = CBool(False, config=True) | |
216 |
|
216 | |||
217 | profile = Unicode('', config=True) |
|
217 | profile = Unicode('', config=True) | |
218 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
218 | prompt_in1 = Str('In [\\#]: ', config=True) | |
219 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
219 | prompt_in2 = Str(' .\\D.: ', config=True) | |
220 | prompt_out = Str('Out[\\#]: ', config=True) |
|
220 | prompt_out = Str('Out[\\#]: ', config=True) | |
221 | prompts_pad_left = CBool(True, config=True) |
|
221 | prompts_pad_left = CBool(True, config=True) | |
222 | quiet = CBool(False, config=True) |
|
222 | quiet = CBool(False, config=True) | |
223 |
|
223 | |||
224 | history_length = Int(10000, config=True) |
|
224 | history_length = Int(10000, config=True) | |
225 |
|
225 | |||
226 | # The readline stuff will eventually be moved to the terminal subclass |
|
226 | # The readline stuff will eventually be moved to the terminal subclass | |
227 | # but for now, we can't do that as readline is welded in everywhere. |
|
227 | # but for now, we can't do that as readline is welded in everywhere. | |
228 | readline_use = CBool(True, config=True) |
|
228 | readline_use = CBool(True, config=True) | |
229 | readline_merge_completions = CBool(True, config=True) |
|
229 | readline_merge_completions = CBool(True, config=True) | |
230 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) |
|
230 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) | |
231 | readline_remove_delims = Str('-/~', config=True) |
|
231 | readline_remove_delims = Str('-/~', config=True) | |
232 | readline_parse_and_bind = List([ |
|
232 | readline_parse_and_bind = List([ | |
233 | 'tab: complete', |
|
233 | 'tab: complete', | |
234 | '"\C-l": clear-screen', |
|
234 | '"\C-l": clear-screen', | |
235 | 'set show-all-if-ambiguous on', |
|
235 | 'set show-all-if-ambiguous on', | |
236 | '"\C-o": tab-insert', |
|
236 | '"\C-o": tab-insert', | |
237 | # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff |
|
237 | # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff | |
238 | # crash IPython. |
|
238 | # crash IPython. | |
239 | '"\M-o": "\d\d\d\d"', |
|
239 | '"\M-o": "\d\d\d\d"', | |
240 | '"\M-I": "\d\d\d\d"', |
|
240 | '"\M-I": "\d\d\d\d"', | |
241 | '"\C-r": reverse-search-history', |
|
241 | '"\C-r": reverse-search-history', | |
242 | '"\C-s": forward-search-history', |
|
242 | '"\C-s": forward-search-history', | |
243 | '"\C-p": history-search-backward', |
|
243 | '"\C-p": history-search-backward', | |
244 | '"\C-n": history-search-forward', |
|
244 | '"\C-n": history-search-forward', | |
245 | '"\e[A": history-search-backward', |
|
245 | '"\e[A": history-search-backward', | |
246 | '"\e[B": history-search-forward', |
|
246 | '"\e[B": history-search-forward', | |
247 | '"\C-k": kill-line', |
|
247 | '"\C-k": kill-line', | |
248 | '"\C-u": unix-line-discard', |
|
248 | '"\C-u": unix-line-discard', | |
249 | ], allow_none=False, config=True) |
|
249 | ], allow_none=False, config=True) | |
250 |
|
250 | |||
251 | # TODO: this part of prompt management should be moved to the frontends. |
|
251 | # TODO: this part of prompt management should be moved to the frontends. | |
252 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
252 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
253 | separate_in = SeparateStr('\n', config=True) |
|
253 | separate_in = SeparateStr('\n', config=True) | |
254 | separate_out = SeparateStr('', config=True) |
|
254 | separate_out = SeparateStr('', config=True) | |
255 | separate_out2 = SeparateStr('', config=True) |
|
255 | separate_out2 = SeparateStr('', config=True) | |
256 | wildcards_case_sensitive = CBool(True, config=True) |
|
256 | wildcards_case_sensitive = CBool(True, config=True) | |
257 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
257 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
258 | default_value='Context', config=True) |
|
258 | default_value='Context', config=True) | |
259 |
|
259 | |||
260 | # Subcomponents of InteractiveShell |
|
260 | # Subcomponents of InteractiveShell | |
261 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
261 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
262 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
262 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
263 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
263 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
264 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
264 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
265 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
265 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
266 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
266 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
267 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
267 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
268 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
268 | history_manager = Instance('IPython.core.history.HistoryManager') | |
269 |
|
269 | |||
270 | # Private interface |
|
270 | # Private interface | |
271 | _post_execute = set() |
|
271 | _post_execute = set() | |
272 |
|
272 | |||
273 | def __init__(self, config=None, ipython_dir=None, |
|
273 | def __init__(self, config=None, ipython_dir=None, | |
274 | user_ns=None, user_global_ns=None, |
|
274 | user_ns=None, user_global_ns=None, | |
275 | custom_exceptions=((), None)): |
|
275 | custom_exceptions=((), None)): | |
276 |
|
276 | |||
277 | # This is where traits with a config_key argument are updated |
|
277 | # This is where traits with a config_key argument are updated | |
278 | # from the values on config. |
|
278 | # from the values on config. | |
279 | super(InteractiveShell, self).__init__(config=config) |
|
279 | super(InteractiveShell, self).__init__(config=config) | |
280 |
|
280 | |||
281 | # These are relatively independent and stateless |
|
281 | # These are relatively independent and stateless | |
282 | self.init_ipython_dir(ipython_dir) |
|
282 | self.init_ipython_dir(ipython_dir) | |
283 | self.init_instance_attrs() |
|
283 | self.init_instance_attrs() | |
284 | self.init_environment() |
|
284 | self.init_environment() | |
285 |
|
285 | |||
286 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
286 | # Create namespaces (user_ns, user_global_ns, etc.) | |
287 | self.init_create_namespaces(user_ns, user_global_ns) |
|
287 | self.init_create_namespaces(user_ns, user_global_ns) | |
288 | # This has to be done after init_create_namespaces because it uses |
|
288 | # This has to be done after init_create_namespaces because it uses | |
289 | # something in self.user_ns, but before init_sys_modules, which |
|
289 | # something in self.user_ns, but before init_sys_modules, which | |
290 | # is the first thing to modify sys. |
|
290 | # is the first thing to modify sys. | |
291 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
291 | # TODO: When we override sys.stdout and sys.stderr before this class | |
292 | # is created, we are saving the overridden ones here. Not sure if this |
|
292 | # is created, we are saving the overridden ones here. Not sure if this | |
293 | # is what we want to do. |
|
293 | # is what we want to do. | |
294 | self.save_sys_module_state() |
|
294 | self.save_sys_module_state() | |
295 | self.init_sys_modules() |
|
295 | self.init_sys_modules() | |
296 |
|
296 | |||
297 | # While we're trying to have each part of the code directly access what |
|
297 | # While we're trying to have each part of the code directly access what | |
298 | # it needs without keeping redundant references to objects, we have too |
|
298 | # it needs without keeping redundant references to objects, we have too | |
299 | # much legacy code that expects ip.db to exist. |
|
299 | # much legacy code that expects ip.db to exist. | |
300 | self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db')) |
|
300 | self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db')) | |
301 |
|
301 | |||
302 | self.init_history() |
|
302 | self.init_history() | |
303 | self.init_encoding() |
|
303 | self.init_encoding() | |
304 | self.init_prefilter() |
|
304 | self.init_prefilter() | |
305 |
|
305 | |||
306 | Magic.__init__(self, self) |
|
306 | Magic.__init__(self, self) | |
307 |
|
307 | |||
308 | self.init_syntax_highlighting() |
|
308 | self.init_syntax_highlighting() | |
309 | self.init_hooks() |
|
309 | self.init_hooks() | |
310 | self.init_pushd_popd_magic() |
|
310 | self.init_pushd_popd_magic() | |
311 | # self.init_traceback_handlers use to be here, but we moved it below |
|
311 | # self.init_traceback_handlers use to be here, but we moved it below | |
312 | # because it and init_io have to come after init_readline. |
|
312 | # because it and init_io have to come after init_readline. | |
313 | self.init_user_ns() |
|
313 | self.init_user_ns() | |
314 | self.init_logger() |
|
314 | self.init_logger() | |
315 | self.init_alias() |
|
315 | self.init_alias() | |
316 | self.init_builtins() |
|
316 | self.init_builtins() | |
317 |
|
317 | |||
318 | # pre_config_initialization |
|
318 | # pre_config_initialization | |
319 |
|
319 | |||
320 | # The next section should contain everything that was in ipmaker. |
|
320 | # The next section should contain everything that was in ipmaker. | |
321 | self.init_logstart() |
|
321 | self.init_logstart() | |
322 |
|
322 | |||
323 | # The following was in post_config_initialization |
|
323 | # The following was in post_config_initialization | |
324 | self.init_inspector() |
|
324 | self.init_inspector() | |
325 | # init_readline() must come before init_io(), because init_io uses |
|
325 | # init_readline() must come before init_io(), because init_io uses | |
326 | # readline related things. |
|
326 | # readline related things. | |
327 | self.init_readline() |
|
327 | self.init_readline() | |
328 | # init_completer must come after init_readline, because it needs to |
|
328 | # init_completer must come after init_readline, because it needs to | |
329 | # know whether readline is present or not system-wide to configure the |
|
329 | # know whether readline is present or not system-wide to configure the | |
330 | # completers, since the completion machinery can now operate |
|
330 | # completers, since the completion machinery can now operate | |
331 | # independently of readline (e.g. over the network) |
|
331 | # independently of readline (e.g. over the network) | |
332 | self.init_completer() |
|
332 | self.init_completer() | |
333 | # TODO: init_io() needs to happen before init_traceback handlers |
|
333 | # TODO: init_io() needs to happen before init_traceback handlers | |
334 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
334 | # because the traceback handlers hardcode the stdout/stderr streams. | |
335 | # This logic in in debugger.Pdb and should eventually be changed. |
|
335 | # This logic in in debugger.Pdb and should eventually be changed. | |
336 | self.init_io() |
|
336 | self.init_io() | |
337 | self.init_traceback_handlers(custom_exceptions) |
|
337 | self.init_traceback_handlers(custom_exceptions) | |
338 | self.init_prompts() |
|
338 | self.init_prompts() | |
339 | self.init_display_formatter() |
|
339 | self.init_display_formatter() | |
340 | self.init_display_pub() |
|
340 | self.init_display_pub() | |
341 | self.init_displayhook() |
|
341 | self.init_displayhook() | |
342 | self.init_reload_doctest() |
|
342 | self.init_reload_doctest() | |
343 | self.init_magics() |
|
343 | self.init_magics() | |
344 | self.init_pdb() |
|
344 | self.init_pdb() | |
345 | self.init_extension_manager() |
|
345 | self.init_extension_manager() | |
346 | self.init_plugin_manager() |
|
346 | self.init_plugin_manager() | |
347 | self.init_payload() |
|
347 | self.init_payload() | |
348 | self.hooks.late_startup_hook() |
|
348 | self.hooks.late_startup_hook() | |
349 | atexit.register(self.atexit_operations) |
|
349 | atexit.register(self.atexit_operations) | |
350 |
|
350 | |||
351 | @classmethod |
|
351 | @classmethod | |
352 | def instance(cls, *args, **kwargs): |
|
352 | def instance(cls, *args, **kwargs): | |
353 | """Returns a global InteractiveShell instance.""" |
|
353 | """Returns a global InteractiveShell instance.""" | |
354 | if cls._instance is None: |
|
354 | if cls._instance is None: | |
355 | inst = cls(*args, **kwargs) |
|
355 | inst = cls(*args, **kwargs) | |
356 | # Now make sure that the instance will also be returned by |
|
356 | # Now make sure that the instance will also be returned by | |
357 | # the subclasses instance attribute. |
|
357 | # the subclasses instance attribute. | |
358 | for subclass in cls.mro(): |
|
358 | for subclass in cls.mro(): | |
359 | if issubclass(cls, subclass) and \ |
|
359 | if issubclass(cls, subclass) and \ | |
360 | issubclass(subclass, InteractiveShell): |
|
360 | issubclass(subclass, InteractiveShell): | |
361 | subclass._instance = inst |
|
361 | subclass._instance = inst | |
362 | else: |
|
362 | else: | |
363 | break |
|
363 | break | |
364 | if isinstance(cls._instance, cls): |
|
364 | if isinstance(cls._instance, cls): | |
365 | return cls._instance |
|
365 | return cls._instance | |
366 | else: |
|
366 | else: | |
367 | raise MultipleInstanceError( |
|
367 | raise MultipleInstanceError( | |
368 | 'Multiple incompatible subclass instances of ' |
|
368 | 'Multiple incompatible subclass instances of ' | |
369 | 'InteractiveShell are being created.' |
|
369 | 'InteractiveShell are being created.' | |
370 | ) |
|
370 | ) | |
371 |
|
371 | |||
372 | @classmethod |
|
372 | @classmethod | |
373 | def initialized(cls): |
|
373 | def initialized(cls): | |
374 | return hasattr(cls, "_instance") |
|
374 | return hasattr(cls, "_instance") | |
375 |
|
375 | |||
376 | def get_ipython(self): |
|
376 | def get_ipython(self): | |
377 | """Return the currently running IPython instance.""" |
|
377 | """Return the currently running IPython instance.""" | |
378 | return self |
|
378 | return self | |
379 |
|
379 | |||
380 | #------------------------------------------------------------------------- |
|
380 | #------------------------------------------------------------------------- | |
381 | # Trait changed handlers |
|
381 | # Trait changed handlers | |
382 | #------------------------------------------------------------------------- |
|
382 | #------------------------------------------------------------------------- | |
383 |
|
383 | |||
384 | def _ipython_dir_changed(self, name, new): |
|
384 | def _ipython_dir_changed(self, name, new): | |
385 | if not os.path.isdir(new): |
|
385 | if not os.path.isdir(new): | |
386 | os.makedirs(new, mode = 0777) |
|
386 | os.makedirs(new, mode = 0777) | |
387 |
|
387 | |||
388 | def set_autoindent(self,value=None): |
|
388 | def set_autoindent(self,value=None): | |
389 | """Set the autoindent flag, checking for readline support. |
|
389 | """Set the autoindent flag, checking for readline support. | |
390 |
|
390 | |||
391 | If called with no arguments, it acts as a toggle.""" |
|
391 | If called with no arguments, it acts as a toggle.""" | |
392 |
|
392 | |||
393 | if not self.has_readline: |
|
393 | if not self.has_readline: | |
394 | if os.name == 'posix': |
|
394 | if os.name == 'posix': | |
395 | warn("The auto-indent feature requires the readline library") |
|
395 | warn("The auto-indent feature requires the readline library") | |
396 | self.autoindent = 0 |
|
396 | self.autoindent = 0 | |
397 | return |
|
397 | return | |
398 | if value is None: |
|
398 | if value is None: | |
399 | self.autoindent = not self.autoindent |
|
399 | self.autoindent = not self.autoindent | |
400 | else: |
|
400 | else: | |
401 | self.autoindent = value |
|
401 | self.autoindent = value | |
402 |
|
402 | |||
403 | #------------------------------------------------------------------------- |
|
403 | #------------------------------------------------------------------------- | |
404 | # init_* methods called by __init__ |
|
404 | # init_* methods called by __init__ | |
405 | #------------------------------------------------------------------------- |
|
405 | #------------------------------------------------------------------------- | |
406 |
|
406 | |||
407 | def init_ipython_dir(self, ipython_dir): |
|
407 | def init_ipython_dir(self, ipython_dir): | |
408 | if ipython_dir is not None: |
|
408 | if ipython_dir is not None: | |
409 | self.ipython_dir = ipython_dir |
|
409 | self.ipython_dir = ipython_dir | |
410 | self.config.Global.ipython_dir = self.ipython_dir |
|
410 | self.config.Global.ipython_dir = self.ipython_dir | |
411 | return |
|
411 | return | |
412 |
|
412 | |||
413 | if hasattr(self.config.Global, 'ipython_dir'): |
|
413 | if hasattr(self.config.Global, 'ipython_dir'): | |
414 | self.ipython_dir = self.config.Global.ipython_dir |
|
414 | self.ipython_dir = self.config.Global.ipython_dir | |
415 | else: |
|
415 | else: | |
416 | self.ipython_dir = get_ipython_dir() |
|
416 | self.ipython_dir = get_ipython_dir() | |
417 |
|
417 | |||
418 | # All children can just read this |
|
418 | # All children can just read this | |
419 | self.config.Global.ipython_dir = self.ipython_dir |
|
419 | self.config.Global.ipython_dir = self.ipython_dir | |
420 |
|
420 | |||
421 | def init_instance_attrs(self): |
|
421 | def init_instance_attrs(self): | |
422 | self.more = False |
|
422 | self.more = False | |
423 |
|
423 | |||
424 | # command compiler |
|
424 | # command compiler | |
425 | self.compile = CachingCompiler() |
|
425 | self.compile = CachingCompiler() | |
426 |
|
426 | |||
427 | # User input buffers |
|
427 | # User input buffers | |
428 | # NOTE: these variables are slated for full removal, once we are 100% |
|
428 | # NOTE: these variables are slated for full removal, once we are 100% | |
429 | # sure that the new execution logic is solid. We will delte runlines, |
|
429 | # sure that the new execution logic is solid. We will delte runlines, | |
430 | # push_line and these buffers, as all input will be managed by the |
|
430 | # push_line and these buffers, as all input will be managed by the | |
431 | # frontends via an inputsplitter instance. |
|
431 | # frontends via an inputsplitter instance. | |
432 | self.buffer = [] |
|
432 | self.buffer = [] | |
433 | self.buffer_raw = [] |
|
433 | self.buffer_raw = [] | |
434 |
|
434 | |||
435 | # Make an empty namespace, which extension writers can rely on both |
|
435 | # Make an empty namespace, which extension writers can rely on both | |
436 | # existing and NEVER being used by ipython itself. This gives them a |
|
436 | # existing and NEVER being used by ipython itself. This gives them a | |
437 | # convenient location for storing additional information and state |
|
437 | # convenient location for storing additional information and state | |
438 | # their extensions may require, without fear of collisions with other |
|
438 | # their extensions may require, without fear of collisions with other | |
439 | # ipython names that may develop later. |
|
439 | # ipython names that may develop later. | |
440 | self.meta = Struct() |
|
440 | self.meta = Struct() | |
441 |
|
441 | |||
442 | # Object variable to store code object waiting execution. This is |
|
442 | # Object variable to store code object waiting execution. This is | |
443 | # used mainly by the multithreaded shells, but it can come in handy in |
|
443 | # used mainly by the multithreaded shells, but it can come in handy in | |
444 | # other situations. No need to use a Queue here, since it's a single |
|
444 | # other situations. No need to use a Queue here, since it's a single | |
445 | # item which gets cleared once run. |
|
445 | # item which gets cleared once run. | |
446 | self.code_to_run = None |
|
446 | self.code_to_run = None | |
447 |
|
447 | |||
448 | # Temporary files used for various purposes. Deleted at exit. |
|
448 | # Temporary files used for various purposes. Deleted at exit. | |
449 | self.tempfiles = [] |
|
449 | self.tempfiles = [] | |
450 |
|
450 | |||
451 | # Keep track of readline usage (later set by init_readline) |
|
451 | # Keep track of readline usage (later set by init_readline) | |
452 | self.has_readline = False |
|
452 | self.has_readline = False | |
453 |
|
453 | |||
454 | # keep track of where we started running (mainly for crash post-mortem) |
|
454 | # keep track of where we started running (mainly for crash post-mortem) | |
455 | # This is not being used anywhere currently. |
|
455 | # This is not being used anywhere currently. | |
456 | self.starting_dir = os.getcwd() |
|
456 | self.starting_dir = os.getcwd() | |
457 |
|
457 | |||
458 | # Indentation management |
|
458 | # Indentation management | |
459 | self.indent_current_nsp = 0 |
|
459 | self.indent_current_nsp = 0 | |
460 |
|
460 | |||
461 | def init_environment(self): |
|
461 | def init_environment(self): | |
462 | """Any changes we need to make to the user's environment.""" |
|
462 | """Any changes we need to make to the user's environment.""" | |
463 | pass |
|
463 | pass | |
464 |
|
464 | |||
465 | def init_encoding(self): |
|
465 | def init_encoding(self): | |
466 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
466 | # Get system encoding at startup time. Certain terminals (like Emacs | |
467 | # under Win32 have it set to None, and we need to have a known valid |
|
467 | # under Win32 have it set to None, and we need to have a known valid | |
468 | # encoding to use in the raw_input() method |
|
468 | # encoding to use in the raw_input() method | |
469 | try: |
|
469 | try: | |
470 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
470 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
471 | except AttributeError: |
|
471 | except AttributeError: | |
472 | self.stdin_encoding = 'ascii' |
|
472 | self.stdin_encoding = 'ascii' | |
473 |
|
473 | |||
474 | def init_syntax_highlighting(self): |
|
474 | def init_syntax_highlighting(self): | |
475 | # Python source parser/formatter for syntax highlighting |
|
475 | # Python source parser/formatter for syntax highlighting | |
476 | pyformat = PyColorize.Parser().format |
|
476 | pyformat = PyColorize.Parser().format | |
477 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
477 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
478 |
|
478 | |||
479 | def init_pushd_popd_magic(self): |
|
479 | def init_pushd_popd_magic(self): | |
480 | # for pushd/popd management |
|
480 | # for pushd/popd management | |
481 | try: |
|
481 | try: | |
482 | self.home_dir = get_home_dir() |
|
482 | self.home_dir = get_home_dir() | |
483 | except HomeDirError, msg: |
|
483 | except HomeDirError, msg: | |
484 | fatal(msg) |
|
484 | fatal(msg) | |
485 |
|
485 | |||
486 | self.dir_stack = [] |
|
486 | self.dir_stack = [] | |
487 |
|
487 | |||
488 | def init_logger(self): |
|
488 | def init_logger(self): | |
489 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
489 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
490 | logmode='rotate') |
|
490 | logmode='rotate') | |
491 |
|
491 | |||
492 | def init_logstart(self): |
|
492 | def init_logstart(self): | |
493 | """Initialize logging in case it was requested at the command line. |
|
493 | """Initialize logging in case it was requested at the command line. | |
494 | """ |
|
494 | """ | |
495 | if self.logappend: |
|
495 | if self.logappend: | |
496 | self.magic_logstart(self.logappend + ' append') |
|
496 | self.magic_logstart(self.logappend + ' append') | |
497 | elif self.logfile: |
|
497 | elif self.logfile: | |
498 | self.magic_logstart(self.logfile) |
|
498 | self.magic_logstart(self.logfile) | |
499 | elif self.logstart: |
|
499 | elif self.logstart: | |
500 | self.magic_logstart() |
|
500 | self.magic_logstart() | |
501 |
|
501 | |||
502 | def init_builtins(self): |
|
502 | def init_builtins(self): | |
503 | self.builtin_trap = BuiltinTrap(shell=self) |
|
503 | self.builtin_trap = BuiltinTrap(shell=self) | |
504 |
|
504 | |||
505 | def init_inspector(self): |
|
505 | def init_inspector(self): | |
506 | # Object inspector |
|
506 | # Object inspector | |
507 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
507 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
508 | PyColorize.ANSICodeColors, |
|
508 | PyColorize.ANSICodeColors, | |
509 | 'NoColor', |
|
509 | 'NoColor', | |
510 | self.object_info_string_level) |
|
510 | self.object_info_string_level) | |
511 |
|
511 | |||
512 | def init_io(self): |
|
512 | def init_io(self): | |
513 | # This will just use sys.stdout and sys.stderr. If you want to |
|
513 | # This will just use sys.stdout and sys.stderr. If you want to | |
514 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
514 | # override sys.stdout and sys.stderr themselves, you need to do that | |
515 | # *before* instantiating this class, because Term holds onto |
|
515 | # *before* instantiating this class, because Term holds onto | |
516 | # references to the underlying streams. |
|
516 | # references to the underlying streams. | |
517 | if sys.platform == 'win32' and self.has_readline: |
|
517 | if sys.platform == 'win32' and self.has_readline: | |
518 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
518 | Term = io.IOTerm(cout=self.readline._outputfile, | |
519 | cerr=self.readline._outputfile) |
|
519 | cerr=self.readline._outputfile) | |
520 | else: |
|
520 | else: | |
521 | Term = io.IOTerm() |
|
521 | Term = io.IOTerm() | |
522 | io.Term = Term |
|
522 | io.Term = Term | |
523 |
|
523 | |||
524 | def init_prompts(self): |
|
524 | def init_prompts(self): | |
525 | # TODO: This is a pass for now because the prompts are managed inside |
|
525 | # TODO: This is a pass for now because the prompts are managed inside | |
526 | # the DisplayHook. Once there is a separate prompt manager, this |
|
526 | # the DisplayHook. Once there is a separate prompt manager, this | |
527 | # will initialize that object and all prompt related information. |
|
527 | # will initialize that object and all prompt related information. | |
528 | pass |
|
528 | pass | |
529 |
|
529 | |||
530 | def init_display_formatter(self): |
|
530 | def init_display_formatter(self): | |
531 | self.display_formatter = DisplayFormatter(config=self.config) |
|
531 | self.display_formatter = DisplayFormatter(config=self.config) | |
532 |
|
532 | |||
533 | def init_display_pub(self): |
|
533 | def init_display_pub(self): | |
534 | self.display_pub = self.display_pub_class(config=self.config) |
|
534 | self.display_pub = self.display_pub_class(config=self.config) | |
535 |
|
535 | |||
536 | def init_displayhook(self): |
|
536 | def init_displayhook(self): | |
537 | # Initialize displayhook, set in/out prompts and printing system |
|
537 | # Initialize displayhook, set in/out prompts and printing system | |
538 | self.displayhook = self.displayhook_class( |
|
538 | self.displayhook = self.displayhook_class( | |
539 | config=self.config, |
|
539 | config=self.config, | |
540 | shell=self, |
|
540 | shell=self, | |
541 | cache_size=self.cache_size, |
|
541 | cache_size=self.cache_size, | |
542 | input_sep = self.separate_in, |
|
542 | input_sep = self.separate_in, | |
543 | output_sep = self.separate_out, |
|
543 | output_sep = self.separate_out, | |
544 | output_sep2 = self.separate_out2, |
|
544 | output_sep2 = self.separate_out2, | |
545 | ps1 = self.prompt_in1, |
|
545 | ps1 = self.prompt_in1, | |
546 | ps2 = self.prompt_in2, |
|
546 | ps2 = self.prompt_in2, | |
547 | ps_out = self.prompt_out, |
|
547 | ps_out = self.prompt_out, | |
548 | pad_left = self.prompts_pad_left |
|
548 | pad_left = self.prompts_pad_left | |
549 | ) |
|
549 | ) | |
550 | # This is a context manager that installs/revmoes the displayhook at |
|
550 | # This is a context manager that installs/revmoes the displayhook at | |
551 | # the appropriate time. |
|
551 | # the appropriate time. | |
552 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
552 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
553 |
|
553 | |||
554 | def init_reload_doctest(self): |
|
554 | def init_reload_doctest(self): | |
555 | # Do a proper resetting of doctest, including the necessary displayhook |
|
555 | # Do a proper resetting of doctest, including the necessary displayhook | |
556 | # monkeypatching |
|
556 | # monkeypatching | |
557 | try: |
|
557 | try: | |
558 | doctest_reload() |
|
558 | doctest_reload() | |
559 | except ImportError: |
|
559 | except ImportError: | |
560 | warn("doctest module does not exist.") |
|
560 | warn("doctest module does not exist.") | |
561 |
|
561 | |||
562 | #------------------------------------------------------------------------- |
|
562 | #------------------------------------------------------------------------- | |
563 | # Things related to injections into the sys module |
|
563 | # Things related to injections into the sys module | |
564 | #------------------------------------------------------------------------- |
|
564 | #------------------------------------------------------------------------- | |
565 |
|
565 | |||
566 | def save_sys_module_state(self): |
|
566 | def save_sys_module_state(self): | |
567 | """Save the state of hooks in the sys module. |
|
567 | """Save the state of hooks in the sys module. | |
568 |
|
568 | |||
569 | This has to be called after self.user_ns is created. |
|
569 | This has to be called after self.user_ns is created. | |
570 | """ |
|
570 | """ | |
571 | self._orig_sys_module_state = {} |
|
571 | self._orig_sys_module_state = {} | |
572 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
572 | self._orig_sys_module_state['stdin'] = sys.stdin | |
573 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
573 | self._orig_sys_module_state['stdout'] = sys.stdout | |
574 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
574 | self._orig_sys_module_state['stderr'] = sys.stderr | |
575 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
575 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
576 | try: |
|
576 | try: | |
577 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
577 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
578 | except KeyError: |
|
578 | except KeyError: | |
579 | pass |
|
579 | pass | |
580 |
|
580 | |||
581 | def restore_sys_module_state(self): |
|
581 | def restore_sys_module_state(self): | |
582 | """Restore the state of the sys module.""" |
|
582 | """Restore the state of the sys module.""" | |
583 | try: |
|
583 | try: | |
584 | for k, v in self._orig_sys_module_state.iteritems(): |
|
584 | for k, v in self._orig_sys_module_state.iteritems(): | |
585 | setattr(sys, k, v) |
|
585 | setattr(sys, k, v) | |
586 | except AttributeError: |
|
586 | except AttributeError: | |
587 | pass |
|
587 | pass | |
588 | # Reset what what done in self.init_sys_modules |
|
588 | # Reset what what done in self.init_sys_modules | |
589 | try: |
|
589 | try: | |
590 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
590 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
591 | except (AttributeError, KeyError): |
|
591 | except (AttributeError, KeyError): | |
592 | pass |
|
592 | pass | |
593 |
|
593 | |||
594 | #------------------------------------------------------------------------- |
|
594 | #------------------------------------------------------------------------- | |
595 | # Things related to hooks |
|
595 | # Things related to hooks | |
596 | #------------------------------------------------------------------------- |
|
596 | #------------------------------------------------------------------------- | |
597 |
|
597 | |||
598 | def init_hooks(self): |
|
598 | def init_hooks(self): | |
599 | # hooks holds pointers used for user-side customizations |
|
599 | # hooks holds pointers used for user-side customizations | |
600 | self.hooks = Struct() |
|
600 | self.hooks = Struct() | |
601 |
|
601 | |||
602 | self.strdispatchers = {} |
|
602 | self.strdispatchers = {} | |
603 |
|
603 | |||
604 | # Set all default hooks, defined in the IPython.hooks module. |
|
604 | # Set all default hooks, defined in the IPython.hooks module. | |
605 | hooks = IPython.core.hooks |
|
605 | hooks = IPython.core.hooks | |
606 | for hook_name in hooks.__all__: |
|
606 | for hook_name in hooks.__all__: | |
607 | # default hooks have priority 100, i.e. low; user hooks should have |
|
607 | # default hooks have priority 100, i.e. low; user hooks should have | |
608 | # 0-100 priority |
|
608 | # 0-100 priority | |
609 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
609 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
610 |
|
610 | |||
611 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
611 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
612 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
612 | """set_hook(name,hook) -> sets an internal IPython hook. | |
613 |
|
613 | |||
614 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
614 | IPython exposes some of its internal API as user-modifiable hooks. By | |
615 | adding your function to one of these hooks, you can modify IPython's |
|
615 | adding your function to one of these hooks, you can modify IPython's | |
616 | behavior to call at runtime your own routines.""" |
|
616 | behavior to call at runtime your own routines.""" | |
617 |
|
617 | |||
618 | # At some point in the future, this should validate the hook before it |
|
618 | # At some point in the future, this should validate the hook before it | |
619 | # accepts it. Probably at least check that the hook takes the number |
|
619 | # accepts it. Probably at least check that the hook takes the number | |
620 | # of args it's supposed to. |
|
620 | # of args it's supposed to. | |
621 |
|
621 | |||
622 | f = types.MethodType(hook,self) |
|
622 | f = types.MethodType(hook,self) | |
623 |
|
623 | |||
624 | # check if the hook is for strdispatcher first |
|
624 | # check if the hook is for strdispatcher first | |
625 | if str_key is not None: |
|
625 | if str_key is not None: | |
626 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
626 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
627 | sdp.add_s(str_key, f, priority ) |
|
627 | sdp.add_s(str_key, f, priority ) | |
628 | self.strdispatchers[name] = sdp |
|
628 | self.strdispatchers[name] = sdp | |
629 | return |
|
629 | return | |
630 | if re_key is not None: |
|
630 | if re_key is not None: | |
631 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
631 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
632 | sdp.add_re(re.compile(re_key), f, priority ) |
|
632 | sdp.add_re(re.compile(re_key), f, priority ) | |
633 | self.strdispatchers[name] = sdp |
|
633 | self.strdispatchers[name] = sdp | |
634 | return |
|
634 | return | |
635 |
|
635 | |||
636 | dp = getattr(self.hooks, name, None) |
|
636 | dp = getattr(self.hooks, name, None) | |
637 | if name not in IPython.core.hooks.__all__: |
|
637 | if name not in IPython.core.hooks.__all__: | |
638 | print "Warning! Hook '%s' is not one of %s" % \ |
|
638 | print "Warning! Hook '%s' is not one of %s" % \ | |
639 | (name, IPython.core.hooks.__all__ ) |
|
639 | (name, IPython.core.hooks.__all__ ) | |
640 | if not dp: |
|
640 | if not dp: | |
641 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
641 | dp = IPython.core.hooks.CommandChainDispatcher() | |
642 |
|
642 | |||
643 | try: |
|
643 | try: | |
644 | dp.add(f,priority) |
|
644 | dp.add(f,priority) | |
645 | except AttributeError: |
|
645 | except AttributeError: | |
646 | # it was not commandchain, plain old func - replace |
|
646 | # it was not commandchain, plain old func - replace | |
647 | dp = f |
|
647 | dp = f | |
648 |
|
648 | |||
649 | setattr(self.hooks,name, dp) |
|
649 | setattr(self.hooks,name, dp) | |
650 |
|
650 | |||
651 | def register_post_execute(self, func): |
|
651 | def register_post_execute(self, func): | |
652 | """Register a function for calling after code execution. |
|
652 | """Register a function for calling after code execution. | |
653 | """ |
|
653 | """ | |
654 | if not callable(func): |
|
654 | if not callable(func): | |
655 | raise ValueError('argument %s must be callable' % func) |
|
655 | raise ValueError('argument %s must be callable' % func) | |
656 | self._post_execute.add(func) |
|
656 | self._post_execute.add(func) | |
657 |
|
657 | |||
658 | #------------------------------------------------------------------------- |
|
658 | #------------------------------------------------------------------------- | |
659 | # Things related to the "main" module |
|
659 | # Things related to the "main" module | |
660 | #------------------------------------------------------------------------- |
|
660 | #------------------------------------------------------------------------- | |
661 |
|
661 | |||
662 | def new_main_mod(self,ns=None): |
|
662 | def new_main_mod(self,ns=None): | |
663 | """Return a new 'main' module object for user code execution. |
|
663 | """Return a new 'main' module object for user code execution. | |
664 | """ |
|
664 | """ | |
665 | main_mod = self._user_main_module |
|
665 | main_mod = self._user_main_module | |
666 | init_fakemod_dict(main_mod,ns) |
|
666 | init_fakemod_dict(main_mod,ns) | |
667 | return main_mod |
|
667 | return main_mod | |
668 |
|
668 | |||
669 | def cache_main_mod(self,ns,fname): |
|
669 | def cache_main_mod(self,ns,fname): | |
670 | """Cache a main module's namespace. |
|
670 | """Cache a main module's namespace. | |
671 |
|
671 | |||
672 | When scripts are executed via %run, we must keep a reference to the |
|
672 | When scripts are executed via %run, we must keep a reference to the | |
673 | namespace of their __main__ module (a FakeModule instance) around so |
|
673 | namespace of their __main__ module (a FakeModule instance) around so | |
674 | that Python doesn't clear it, rendering objects defined therein |
|
674 | that Python doesn't clear it, rendering objects defined therein | |
675 | useless. |
|
675 | useless. | |
676 |
|
676 | |||
677 | This method keeps said reference in a private dict, keyed by the |
|
677 | This method keeps said reference in a private dict, keyed by the | |
678 | absolute path of the module object (which corresponds to the script |
|
678 | absolute path of the module object (which corresponds to the script | |
679 | path). This way, for multiple executions of the same script we only |
|
679 | path). This way, for multiple executions of the same script we only | |
680 | keep one copy of the namespace (the last one), thus preventing memory |
|
680 | keep one copy of the namespace (the last one), thus preventing memory | |
681 | leaks from old references while allowing the objects from the last |
|
681 | leaks from old references while allowing the objects from the last | |
682 | execution to be accessible. |
|
682 | execution to be accessible. | |
683 |
|
683 | |||
684 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
684 | Note: we can not allow the actual FakeModule instances to be deleted, | |
685 | because of how Python tears down modules (it hard-sets all their |
|
685 | because of how Python tears down modules (it hard-sets all their | |
686 | references to None without regard for reference counts). This method |
|
686 | references to None without regard for reference counts). This method | |
687 | must therefore make a *copy* of the given namespace, to allow the |
|
687 | must therefore make a *copy* of the given namespace, to allow the | |
688 | original module's __dict__ to be cleared and reused. |
|
688 | original module's __dict__ to be cleared and reused. | |
689 |
|
689 | |||
690 |
|
690 | |||
691 | Parameters |
|
691 | Parameters | |
692 | ---------- |
|
692 | ---------- | |
693 | ns : a namespace (a dict, typically) |
|
693 | ns : a namespace (a dict, typically) | |
694 |
|
694 | |||
695 | fname : str |
|
695 | fname : str | |
696 | Filename associated with the namespace. |
|
696 | Filename associated with the namespace. | |
697 |
|
697 | |||
698 | Examples |
|
698 | Examples | |
699 | -------- |
|
699 | -------- | |
700 |
|
700 | |||
701 | In [10]: import IPython |
|
701 | In [10]: import IPython | |
702 |
|
702 | |||
703 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
703 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
704 |
|
704 | |||
705 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
705 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
706 | Out[12]: True |
|
706 | Out[12]: True | |
707 | """ |
|
707 | """ | |
708 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
708 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
709 |
|
709 | |||
710 | def clear_main_mod_cache(self): |
|
710 | def clear_main_mod_cache(self): | |
711 | """Clear the cache of main modules. |
|
711 | """Clear the cache of main modules. | |
712 |
|
712 | |||
713 | Mainly for use by utilities like %reset. |
|
713 | Mainly for use by utilities like %reset. | |
714 |
|
714 | |||
715 | Examples |
|
715 | Examples | |
716 | -------- |
|
716 | -------- | |
717 |
|
717 | |||
718 | In [15]: import IPython |
|
718 | In [15]: import IPython | |
719 |
|
719 | |||
720 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
720 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
721 |
|
721 | |||
722 | In [17]: len(_ip._main_ns_cache) > 0 |
|
722 | In [17]: len(_ip._main_ns_cache) > 0 | |
723 | Out[17]: True |
|
723 | Out[17]: True | |
724 |
|
724 | |||
725 | In [18]: _ip.clear_main_mod_cache() |
|
725 | In [18]: _ip.clear_main_mod_cache() | |
726 |
|
726 | |||
727 | In [19]: len(_ip._main_ns_cache) == 0 |
|
727 | In [19]: len(_ip._main_ns_cache) == 0 | |
728 | Out[19]: True |
|
728 | Out[19]: True | |
729 | """ |
|
729 | """ | |
730 | self._main_ns_cache.clear() |
|
730 | self._main_ns_cache.clear() | |
731 |
|
731 | |||
732 | #------------------------------------------------------------------------- |
|
732 | #------------------------------------------------------------------------- | |
733 | # Things related to debugging |
|
733 | # Things related to debugging | |
734 | #------------------------------------------------------------------------- |
|
734 | #------------------------------------------------------------------------- | |
735 |
|
735 | |||
736 | def init_pdb(self): |
|
736 | def init_pdb(self): | |
737 | # Set calling of pdb on exceptions |
|
737 | # Set calling of pdb on exceptions | |
738 | # self.call_pdb is a property |
|
738 | # self.call_pdb is a property | |
739 | self.call_pdb = self.pdb |
|
739 | self.call_pdb = self.pdb | |
740 |
|
740 | |||
741 | def _get_call_pdb(self): |
|
741 | def _get_call_pdb(self): | |
742 | return self._call_pdb |
|
742 | return self._call_pdb | |
743 |
|
743 | |||
744 | def _set_call_pdb(self,val): |
|
744 | def _set_call_pdb(self,val): | |
745 |
|
745 | |||
746 | if val not in (0,1,False,True): |
|
746 | if val not in (0,1,False,True): | |
747 | raise ValueError,'new call_pdb value must be boolean' |
|
747 | raise ValueError,'new call_pdb value must be boolean' | |
748 |
|
748 | |||
749 | # store value in instance |
|
749 | # store value in instance | |
750 | self._call_pdb = val |
|
750 | self._call_pdb = val | |
751 |
|
751 | |||
752 | # notify the actual exception handlers |
|
752 | # notify the actual exception handlers | |
753 | self.InteractiveTB.call_pdb = val |
|
753 | self.InteractiveTB.call_pdb = val | |
754 |
|
754 | |||
755 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
755 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
756 | 'Control auto-activation of pdb at exceptions') |
|
756 | 'Control auto-activation of pdb at exceptions') | |
757 |
|
757 | |||
758 | def debugger(self,force=False): |
|
758 | def debugger(self,force=False): | |
759 | """Call the pydb/pdb debugger. |
|
759 | """Call the pydb/pdb debugger. | |
760 |
|
760 | |||
761 | Keywords: |
|
761 | Keywords: | |
762 |
|
762 | |||
763 | - force(False): by default, this routine checks the instance call_pdb |
|
763 | - force(False): by default, this routine checks the instance call_pdb | |
764 | flag and does not actually invoke the debugger if the flag is false. |
|
764 | flag and does not actually invoke the debugger if the flag is false. | |
765 | The 'force' option forces the debugger to activate even if the flag |
|
765 | The 'force' option forces the debugger to activate even if the flag | |
766 | is false. |
|
766 | is false. | |
767 | """ |
|
767 | """ | |
768 |
|
768 | |||
769 | if not (force or self.call_pdb): |
|
769 | if not (force or self.call_pdb): | |
770 | return |
|
770 | return | |
771 |
|
771 | |||
772 | if not hasattr(sys,'last_traceback'): |
|
772 | if not hasattr(sys,'last_traceback'): | |
773 | error('No traceback has been produced, nothing to debug.') |
|
773 | error('No traceback has been produced, nothing to debug.') | |
774 | return |
|
774 | return | |
775 |
|
775 | |||
776 | # use pydb if available |
|
776 | # use pydb if available | |
777 | if debugger.has_pydb: |
|
777 | if debugger.has_pydb: | |
778 | from pydb import pm |
|
778 | from pydb import pm | |
779 | else: |
|
779 | else: | |
780 | # fallback to our internal debugger |
|
780 | # fallback to our internal debugger | |
781 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
781 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
782 |
|
782 | |||
783 | with self.readline_no_record: |
|
783 | with self.readline_no_record: | |
784 | pm() |
|
784 | pm() | |
785 |
|
785 | |||
786 | #------------------------------------------------------------------------- |
|
786 | #------------------------------------------------------------------------- | |
787 | # Things related to IPython's various namespaces |
|
787 | # Things related to IPython's various namespaces | |
788 | #------------------------------------------------------------------------- |
|
788 | #------------------------------------------------------------------------- | |
789 |
|
789 | |||
790 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
790 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
791 | # Create the namespace where the user will operate. user_ns is |
|
791 | # Create the namespace where the user will operate. user_ns is | |
792 | # normally the only one used, and it is passed to the exec calls as |
|
792 | # normally the only one used, and it is passed to the exec calls as | |
793 | # the locals argument. But we do carry a user_global_ns namespace |
|
793 | # the locals argument. But we do carry a user_global_ns namespace | |
794 | # given as the exec 'globals' argument, This is useful in embedding |
|
794 | # given as the exec 'globals' argument, This is useful in embedding | |
795 | # situations where the ipython shell opens in a context where the |
|
795 | # situations where the ipython shell opens in a context where the | |
796 | # distinction between locals and globals is meaningful. For |
|
796 | # distinction between locals and globals is meaningful. For | |
797 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
797 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
798 |
|
798 | |||
799 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
799 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
800 | # level as a dict instead of a module. This is a manual fix, but I |
|
800 | # level as a dict instead of a module. This is a manual fix, but I | |
801 | # should really track down where the problem is coming from. Alex |
|
801 | # should really track down where the problem is coming from. Alex | |
802 | # Schmolck reported this problem first. |
|
802 | # Schmolck reported this problem first. | |
803 |
|
803 | |||
804 | # A useful post by Alex Martelli on this topic: |
|
804 | # A useful post by Alex Martelli on this topic: | |
805 | # Re: inconsistent value from __builtins__ |
|
805 | # Re: inconsistent value from __builtins__ | |
806 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
806 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
807 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
807 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
808 | # Gruppen: comp.lang.python |
|
808 | # Gruppen: comp.lang.python | |
809 |
|
809 | |||
810 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
810 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
811 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
811 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
812 | # > <type 'dict'> |
|
812 | # > <type 'dict'> | |
813 | # > >>> print type(__builtins__) |
|
813 | # > >>> print type(__builtins__) | |
814 | # > <type 'module'> |
|
814 | # > <type 'module'> | |
815 | # > Is this difference in return value intentional? |
|
815 | # > Is this difference in return value intentional? | |
816 |
|
816 | |||
817 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
817 | # Well, it's documented that '__builtins__' can be either a dictionary | |
818 | # or a module, and it's been that way for a long time. Whether it's |
|
818 | # or a module, and it's been that way for a long time. Whether it's | |
819 | # intentional (or sensible), I don't know. In any case, the idea is |
|
819 | # intentional (or sensible), I don't know. In any case, the idea is | |
820 | # that if you need to access the built-in namespace directly, you |
|
820 | # that if you need to access the built-in namespace directly, you | |
821 | # should start with "import __builtin__" (note, no 's') which will |
|
821 | # should start with "import __builtin__" (note, no 's') which will | |
822 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
822 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
823 |
|
823 | |||
824 | # These routines return properly built dicts as needed by the rest of |
|
824 | # These routines return properly built dicts as needed by the rest of | |
825 | # the code, and can also be used by extension writers to generate |
|
825 | # the code, and can also be used by extension writers to generate | |
826 | # properly initialized namespaces. |
|
826 | # properly initialized namespaces. | |
827 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
827 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
828 | user_global_ns) |
|
828 | user_global_ns) | |
829 |
|
829 | |||
830 | # Assign namespaces |
|
830 | # Assign namespaces | |
831 | # This is the namespace where all normal user variables live |
|
831 | # This is the namespace where all normal user variables live | |
832 | self.user_ns = user_ns |
|
832 | self.user_ns = user_ns | |
833 | self.user_global_ns = user_global_ns |
|
833 | self.user_global_ns = user_global_ns | |
834 |
|
834 | |||
835 | # An auxiliary namespace that checks what parts of the user_ns were |
|
835 | # An auxiliary namespace that checks what parts of the user_ns were | |
836 | # loaded at startup, so we can list later only variables defined in |
|
836 | # loaded at startup, so we can list later only variables defined in | |
837 | # actual interactive use. Since it is always a subset of user_ns, it |
|
837 | # actual interactive use. Since it is always a subset of user_ns, it | |
838 | # doesn't need to be separately tracked in the ns_table. |
|
838 | # doesn't need to be separately tracked in the ns_table. | |
839 | self.user_ns_hidden = {} |
|
839 | self.user_ns_hidden = {} | |
840 |
|
840 | |||
841 | # A namespace to keep track of internal data structures to prevent |
|
841 | # A namespace to keep track of internal data structures to prevent | |
842 | # them from cluttering user-visible stuff. Will be updated later |
|
842 | # them from cluttering user-visible stuff. Will be updated later | |
843 | self.internal_ns = {} |
|
843 | self.internal_ns = {} | |
844 |
|
844 | |||
845 | # Now that FakeModule produces a real module, we've run into a nasty |
|
845 | # Now that FakeModule produces a real module, we've run into a nasty | |
846 | # problem: after script execution (via %run), the module where the user |
|
846 | # problem: after script execution (via %run), the module where the user | |
847 | # code ran is deleted. Now that this object is a true module (needed |
|
847 | # code ran is deleted. Now that this object is a true module (needed | |
848 | # so docetst and other tools work correctly), the Python module |
|
848 | # so docetst and other tools work correctly), the Python module | |
849 | # teardown mechanism runs over it, and sets to None every variable |
|
849 | # teardown mechanism runs over it, and sets to None every variable | |
850 | # present in that module. Top-level references to objects from the |
|
850 | # present in that module. Top-level references to objects from the | |
851 | # script survive, because the user_ns is updated with them. However, |
|
851 | # script survive, because the user_ns is updated with them. However, | |
852 | # calling functions defined in the script that use other things from |
|
852 | # calling functions defined in the script that use other things from | |
853 | # the script will fail, because the function's closure had references |
|
853 | # the script will fail, because the function's closure had references | |
854 | # to the original objects, which are now all None. So we must protect |
|
854 | # to the original objects, which are now all None. So we must protect | |
855 | # these modules from deletion by keeping a cache. |
|
855 | # these modules from deletion by keeping a cache. | |
856 | # |
|
856 | # | |
857 | # To avoid keeping stale modules around (we only need the one from the |
|
857 | # To avoid keeping stale modules around (we only need the one from the | |
858 | # last run), we use a dict keyed with the full path to the script, so |
|
858 | # last run), we use a dict keyed with the full path to the script, so | |
859 | # only the last version of the module is held in the cache. Note, |
|
859 | # only the last version of the module is held in the cache. Note, | |
860 | # however, that we must cache the module *namespace contents* (their |
|
860 | # however, that we must cache the module *namespace contents* (their | |
861 | # __dict__). Because if we try to cache the actual modules, old ones |
|
861 | # __dict__). Because if we try to cache the actual modules, old ones | |
862 | # (uncached) could be destroyed while still holding references (such as |
|
862 | # (uncached) could be destroyed while still holding references (such as | |
863 | # those held by GUI objects that tend to be long-lived)> |
|
863 | # those held by GUI objects that tend to be long-lived)> | |
864 | # |
|
864 | # | |
865 | # The %reset command will flush this cache. See the cache_main_mod() |
|
865 | # The %reset command will flush this cache. See the cache_main_mod() | |
866 | # and clear_main_mod_cache() methods for details on use. |
|
866 | # and clear_main_mod_cache() methods for details on use. | |
867 |
|
867 | |||
868 | # This is the cache used for 'main' namespaces |
|
868 | # This is the cache used for 'main' namespaces | |
869 | self._main_ns_cache = {} |
|
869 | self._main_ns_cache = {} | |
870 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
870 | # And this is the single instance of FakeModule whose __dict__ we keep | |
871 | # copying and clearing for reuse on each %run |
|
871 | # copying and clearing for reuse on each %run | |
872 | self._user_main_module = FakeModule() |
|
872 | self._user_main_module = FakeModule() | |
873 |
|
873 | |||
874 | # A table holding all the namespaces IPython deals with, so that |
|
874 | # A table holding all the namespaces IPython deals with, so that | |
875 | # introspection facilities can search easily. |
|
875 | # introspection facilities can search easily. | |
876 | self.ns_table = {'user':user_ns, |
|
876 | self.ns_table = {'user':user_ns, | |
877 | 'user_global':user_global_ns, |
|
877 | 'user_global':user_global_ns, | |
878 | 'internal':self.internal_ns, |
|
878 | 'internal':self.internal_ns, | |
879 | 'builtin':__builtin__.__dict__ |
|
879 | 'builtin':__builtin__.__dict__ | |
880 | } |
|
880 | } | |
881 |
|
881 | |||
882 | # Similarly, track all namespaces where references can be held and that |
|
882 | # Similarly, track all namespaces where references can be held and that | |
883 | # we can safely clear (so it can NOT include builtin). This one can be |
|
883 | # we can safely clear (so it can NOT include builtin). This one can be | |
884 | # a simple list. Note that the main execution namespaces, user_ns and |
|
884 | # a simple list. Note that the main execution namespaces, user_ns and | |
885 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
885 | # user_global_ns, can NOT be listed here, as clearing them blindly | |
886 | # causes errors in object __del__ methods. Instead, the reset() method |
|
886 | # causes errors in object __del__ methods. Instead, the reset() method | |
887 | # clears them manually and carefully. |
|
887 | # clears them manually and carefully. | |
888 | self.ns_refs_table = [ self.user_ns_hidden, |
|
888 | self.ns_refs_table = [ self.user_ns_hidden, | |
889 | self.internal_ns, self._main_ns_cache ] |
|
889 | self.internal_ns, self._main_ns_cache ] | |
890 |
|
890 | |||
891 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
891 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
892 | """Return a valid local and global user interactive namespaces. |
|
892 | """Return a valid local and global user interactive namespaces. | |
893 |
|
893 | |||
894 | This builds a dict with the minimal information needed to operate as a |
|
894 | This builds a dict with the minimal information needed to operate as a | |
895 | valid IPython user namespace, which you can pass to the various |
|
895 | valid IPython user namespace, which you can pass to the various | |
896 | embedding classes in ipython. The default implementation returns the |
|
896 | embedding classes in ipython. The default implementation returns the | |
897 | same dict for both the locals and the globals to allow functions to |
|
897 | same dict for both the locals and the globals to allow functions to | |
898 | refer to variables in the namespace. Customized implementations can |
|
898 | refer to variables in the namespace. Customized implementations can | |
899 | return different dicts. The locals dictionary can actually be anything |
|
899 | return different dicts. The locals dictionary can actually be anything | |
900 | following the basic mapping protocol of a dict, but the globals dict |
|
900 | following the basic mapping protocol of a dict, but the globals dict | |
901 | must be a true dict, not even a subclass. It is recommended that any |
|
901 | must be a true dict, not even a subclass. It is recommended that any | |
902 | custom object for the locals namespace synchronize with the globals |
|
902 | custom object for the locals namespace synchronize with the globals | |
903 | dict somehow. |
|
903 | dict somehow. | |
904 |
|
904 | |||
905 | Raises TypeError if the provided globals namespace is not a true dict. |
|
905 | Raises TypeError if the provided globals namespace is not a true dict. | |
906 |
|
906 | |||
907 | Parameters |
|
907 | Parameters | |
908 | ---------- |
|
908 | ---------- | |
909 | user_ns : dict-like, optional |
|
909 | user_ns : dict-like, optional | |
910 | The current user namespace. The items in this namespace should |
|
910 | The current user namespace. The items in this namespace should | |
911 | be included in the output. If None, an appropriate blank |
|
911 | be included in the output. If None, an appropriate blank | |
912 | namespace should be created. |
|
912 | namespace should be created. | |
913 | user_global_ns : dict, optional |
|
913 | user_global_ns : dict, optional | |
914 | The current user global namespace. The items in this namespace |
|
914 | The current user global namespace. The items in this namespace | |
915 | should be included in the output. If None, an appropriate |
|
915 | should be included in the output. If None, an appropriate | |
916 | blank namespace should be created. |
|
916 | blank namespace should be created. | |
917 |
|
917 | |||
918 | Returns |
|
918 | Returns | |
919 | ------- |
|
919 | ------- | |
920 | A pair of dictionary-like object to be used as the local namespace |
|
920 | A pair of dictionary-like object to be used as the local namespace | |
921 | of the interpreter and a dict to be used as the global namespace. |
|
921 | of the interpreter and a dict to be used as the global namespace. | |
922 | """ |
|
922 | """ | |
923 |
|
923 | |||
924 |
|
924 | |||
925 | # We must ensure that __builtin__ (without the final 's') is always |
|
925 | # We must ensure that __builtin__ (without the final 's') is always | |
926 | # available and pointing to the __builtin__ *module*. For more details: |
|
926 | # available and pointing to the __builtin__ *module*. For more details: | |
927 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
927 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
928 |
|
928 | |||
929 | if user_ns is None: |
|
929 | if user_ns is None: | |
930 | # Set __name__ to __main__ to better match the behavior of the |
|
930 | # Set __name__ to __main__ to better match the behavior of the | |
931 | # normal interpreter. |
|
931 | # normal interpreter. | |
932 | user_ns = {'__name__' :'__main__', |
|
932 | user_ns = {'__name__' :'__main__', | |
933 | '__builtin__' : __builtin__, |
|
933 | '__builtin__' : __builtin__, | |
934 | '__builtins__' : __builtin__, |
|
934 | '__builtins__' : __builtin__, | |
935 | } |
|
935 | } | |
936 | else: |
|
936 | else: | |
937 | user_ns.setdefault('__name__','__main__') |
|
937 | user_ns.setdefault('__name__','__main__') | |
938 | user_ns.setdefault('__builtin__',__builtin__) |
|
938 | user_ns.setdefault('__builtin__',__builtin__) | |
939 | user_ns.setdefault('__builtins__',__builtin__) |
|
939 | user_ns.setdefault('__builtins__',__builtin__) | |
940 |
|
940 | |||
941 | if user_global_ns is None: |
|
941 | if user_global_ns is None: | |
942 | user_global_ns = user_ns |
|
942 | user_global_ns = user_ns | |
943 | if type(user_global_ns) is not dict: |
|
943 | if type(user_global_ns) is not dict: | |
944 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
944 | raise TypeError("user_global_ns must be a true dict; got %r" | |
945 | % type(user_global_ns)) |
|
945 | % type(user_global_ns)) | |
946 |
|
946 | |||
947 | return user_ns, user_global_ns |
|
947 | return user_ns, user_global_ns | |
948 |
|
948 | |||
949 | def init_sys_modules(self): |
|
949 | def init_sys_modules(self): | |
950 | # We need to insert into sys.modules something that looks like a |
|
950 | # We need to insert into sys.modules something that looks like a | |
951 | # module but which accesses the IPython namespace, for shelve and |
|
951 | # module but which accesses the IPython namespace, for shelve and | |
952 | # pickle to work interactively. Normally they rely on getting |
|
952 | # pickle to work interactively. Normally they rely on getting | |
953 | # everything out of __main__, but for embedding purposes each IPython |
|
953 | # everything out of __main__, but for embedding purposes each IPython | |
954 | # instance has its own private namespace, so we can't go shoving |
|
954 | # instance has its own private namespace, so we can't go shoving | |
955 | # everything into __main__. |
|
955 | # everything into __main__. | |
956 |
|
956 | |||
957 | # note, however, that we should only do this for non-embedded |
|
957 | # note, however, that we should only do this for non-embedded | |
958 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
958 | # ipythons, which really mimic the __main__.__dict__ with their own | |
959 | # namespace. Embedded instances, on the other hand, should not do |
|
959 | # namespace. Embedded instances, on the other hand, should not do | |
960 | # this because they need to manage the user local/global namespaces |
|
960 | # this because they need to manage the user local/global namespaces | |
961 | # only, but they live within a 'normal' __main__ (meaning, they |
|
961 | # only, but they live within a 'normal' __main__ (meaning, they | |
962 | # shouldn't overtake the execution environment of the script they're |
|
962 | # shouldn't overtake the execution environment of the script they're | |
963 | # embedded in). |
|
963 | # embedded in). | |
964 |
|
964 | |||
965 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
965 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
966 |
|
966 | |||
967 | try: |
|
967 | try: | |
968 | main_name = self.user_ns['__name__'] |
|
968 | main_name = self.user_ns['__name__'] | |
969 | except KeyError: |
|
969 | except KeyError: | |
970 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
970 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
971 | else: |
|
971 | else: | |
972 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
972 | sys.modules[main_name] = FakeModule(self.user_ns) | |
973 |
|
973 | |||
974 | def init_user_ns(self): |
|
974 | def init_user_ns(self): | |
975 | """Initialize all user-visible namespaces to their minimum defaults. |
|
975 | """Initialize all user-visible namespaces to their minimum defaults. | |
976 |
|
976 | |||
977 | Certain history lists are also initialized here, as they effectively |
|
977 | Certain history lists are also initialized here, as they effectively | |
978 | act as user namespaces. |
|
978 | act as user namespaces. | |
979 |
|
979 | |||
980 | Notes |
|
980 | Notes | |
981 | ----- |
|
981 | ----- | |
982 | All data structures here are only filled in, they are NOT reset by this |
|
982 | All data structures here are only filled in, they are NOT reset by this | |
983 | method. If they were not empty before, data will simply be added to |
|
983 | method. If they were not empty before, data will simply be added to | |
984 | therm. |
|
984 | therm. | |
985 | """ |
|
985 | """ | |
986 | # This function works in two parts: first we put a few things in |
|
986 | # This function works in two parts: first we put a few things in | |
987 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
987 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
988 | # initial variables aren't shown by %who. After the sync, we add the |
|
988 | # initial variables aren't shown by %who. After the sync, we add the | |
989 | # rest of what we *do* want the user to see with %who even on a new |
|
989 | # rest of what we *do* want the user to see with %who even on a new | |
990 | # session (probably nothing, so theye really only see their own stuff) |
|
990 | # session (probably nothing, so theye really only see their own stuff) | |
991 |
|
991 | |||
992 | # The user dict must *always* have a __builtin__ reference to the |
|
992 | # The user dict must *always* have a __builtin__ reference to the | |
993 | # Python standard __builtin__ namespace, which must be imported. |
|
993 | # Python standard __builtin__ namespace, which must be imported. | |
994 | # This is so that certain operations in prompt evaluation can be |
|
994 | # This is so that certain operations in prompt evaluation can be | |
995 | # reliably executed with builtins. Note that we can NOT use |
|
995 | # reliably executed with builtins. Note that we can NOT use | |
996 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
996 | # __builtins__ (note the 's'), because that can either be a dict or a | |
997 | # module, and can even mutate at runtime, depending on the context |
|
997 | # module, and can even mutate at runtime, depending on the context | |
998 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
998 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
999 | # always a module object, though it must be explicitly imported. |
|
999 | # always a module object, though it must be explicitly imported. | |
1000 |
|
1000 | |||
1001 | # For more details: |
|
1001 | # For more details: | |
1002 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1002 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1003 | ns = dict(__builtin__ = __builtin__) |
|
1003 | ns = dict(__builtin__ = __builtin__) | |
1004 |
|
1004 | |||
1005 | # Put 'help' in the user namespace |
|
1005 | # Put 'help' in the user namespace | |
1006 | try: |
|
1006 | try: | |
1007 | from site import _Helper |
|
1007 | from site import _Helper | |
1008 | ns['help'] = _Helper() |
|
1008 | ns['help'] = _Helper() | |
1009 | except ImportError: |
|
1009 | except ImportError: | |
1010 | warn('help() not available - check site.py') |
|
1010 | warn('help() not available - check site.py') | |
1011 |
|
1011 | |||
1012 | # make global variables for user access to the histories |
|
1012 | # make global variables for user access to the histories | |
1013 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1013 | ns['_ih'] = self.history_manager.input_hist_parsed | |
1014 | ns['_oh'] = self.history_manager.output_hist |
|
1014 | ns['_oh'] = self.history_manager.output_hist | |
1015 | ns['_dh'] = self.history_manager.dir_hist |
|
1015 | ns['_dh'] = self.history_manager.dir_hist | |
1016 |
|
1016 | |||
1017 | ns['_sh'] = shadowns |
|
1017 | ns['_sh'] = shadowns | |
1018 |
|
1018 | |||
1019 | # user aliases to input and output histories. These shouldn't show up |
|
1019 | # user aliases to input and output histories. These shouldn't show up | |
1020 | # in %who, as they can have very large reprs. |
|
1020 | # in %who, as they can have very large reprs. | |
1021 | ns['In'] = self.history_manager.input_hist_parsed |
|
1021 | ns['In'] = self.history_manager.input_hist_parsed | |
1022 | ns['Out'] = self.history_manager.output_hist |
|
1022 | ns['Out'] = self.history_manager.output_hist | |
1023 |
|
1023 | |||
1024 | # Store myself as the public api!!! |
|
1024 | # Store myself as the public api!!! | |
1025 | ns['get_ipython'] = self.get_ipython |
|
1025 | ns['get_ipython'] = self.get_ipython | |
1026 |
|
1026 | |||
1027 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1027 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
1028 | # by %who |
|
1028 | # by %who | |
1029 | self.user_ns_hidden.update(ns) |
|
1029 | self.user_ns_hidden.update(ns) | |
1030 |
|
1030 | |||
1031 | # Anything put into ns now would show up in %who. Think twice before |
|
1031 | # Anything put into ns now would show up in %who. Think twice before | |
1032 | # putting anything here, as we really want %who to show the user their |
|
1032 | # putting anything here, as we really want %who to show the user their | |
1033 | # stuff, not our variables. |
|
1033 | # stuff, not our variables. | |
1034 |
|
1034 | |||
1035 | # Finally, update the real user's namespace |
|
1035 | # Finally, update the real user's namespace | |
1036 | self.user_ns.update(ns) |
|
1036 | self.user_ns.update(ns) | |
1037 |
|
1037 | |||
1038 | def reset(self, new_session=True): |
|
1038 | def reset(self, new_session=True): | |
1039 | """Clear all internal namespaces. |
|
1039 | """Clear all internal namespaces. | |
1040 |
|
1040 | |||
1041 | Note that this is much more aggressive than %reset, since it clears |
|
1041 | Note that this is much more aggressive than %reset, since it clears | |
1042 | fully all namespaces, as well as all input/output lists. |
|
1042 | fully all namespaces, as well as all input/output lists. | |
1043 |
|
1043 | |||
1044 | If new_session is True, a new history session will be opened. |
|
1044 | If new_session is True, a new history session will be opened. | |
1045 | """ |
|
1045 | """ | |
1046 | # Clear histories |
|
1046 | # Clear histories | |
1047 | self.history_manager.reset(new_session) |
|
1047 | self.history_manager.reset(new_session) | |
1048 |
|
1048 | |||
1049 | # Flush cached output items |
|
1049 | # Flush cached output items | |
1050 | self.displayhook.flush() |
|
1050 | self.displayhook.flush() | |
1051 |
|
1051 | |||
1052 | # Reset counter used to index all histories |
|
1052 | # Reset counter used to index all histories | |
1053 | self.execution_count = 0 |
|
1053 | self.execution_count = 0 | |
1054 |
|
1054 | |||
1055 | # Restore the user namespaces to minimal usability |
|
1055 | # Restore the user namespaces to minimal usability | |
1056 | for ns in self.ns_refs_table: |
|
1056 | for ns in self.ns_refs_table: | |
1057 | ns.clear() |
|
1057 | ns.clear() | |
1058 |
|
1058 | |||
1059 | # The main execution namespaces must be cleared very carefully, |
|
1059 | # The main execution namespaces must be cleared very carefully, | |
1060 | # skipping the deletion of the builtin-related keys, because doing so |
|
1060 | # skipping the deletion of the builtin-related keys, because doing so | |
1061 | # would cause errors in many object's __del__ methods. |
|
1061 | # would cause errors in many object's __del__ methods. | |
1062 | for ns in [self.user_ns, self.user_global_ns]: |
|
1062 | for ns in [self.user_ns, self.user_global_ns]: | |
1063 | drop_keys = set(ns.keys()) |
|
1063 | drop_keys = set(ns.keys()) | |
1064 | drop_keys.discard('__builtin__') |
|
1064 | drop_keys.discard('__builtin__') | |
1065 | drop_keys.discard('__builtins__') |
|
1065 | drop_keys.discard('__builtins__') | |
1066 | for k in drop_keys: |
|
1066 | for k in drop_keys: | |
1067 | del ns[k] |
|
1067 | del ns[k] | |
1068 |
|
1068 | |||
1069 | # Restore the user namespaces to minimal usability |
|
1069 | # Restore the user namespaces to minimal usability | |
1070 | self.init_user_ns() |
|
1070 | self.init_user_ns() | |
1071 |
|
1071 | |||
1072 | # Restore the default and user aliases |
|
1072 | # Restore the default and user aliases | |
1073 | self.alias_manager.clear_aliases() |
|
1073 | self.alias_manager.clear_aliases() | |
1074 | self.alias_manager.init_aliases() |
|
1074 | self.alias_manager.init_aliases() | |
1075 |
|
1075 | |||
1076 | # Flush the private list of module references kept for script |
|
1076 | # Flush the private list of module references kept for script | |
1077 | # execution protection |
|
1077 | # execution protection | |
1078 | self.clear_main_mod_cache() |
|
1078 | self.clear_main_mod_cache() | |
1079 |
|
1079 | |||
1080 | def reset_selective(self, regex=None): |
|
1080 | def reset_selective(self, regex=None): | |
1081 | """Clear selective variables from internal namespaces based on a |
|
1081 | """Clear selective variables from internal namespaces based on a | |
1082 | specified regular expression. |
|
1082 | specified regular expression. | |
1083 |
|
1083 | |||
1084 | Parameters |
|
1084 | Parameters | |
1085 | ---------- |
|
1085 | ---------- | |
1086 | regex : string or compiled pattern, optional |
|
1086 | regex : string or compiled pattern, optional | |
1087 | A regular expression pattern that will be used in searching |
|
1087 | A regular expression pattern that will be used in searching | |
1088 | variable names in the users namespaces. |
|
1088 | variable names in the users namespaces. | |
1089 | """ |
|
1089 | """ | |
1090 | if regex is not None: |
|
1090 | if regex is not None: | |
1091 | try: |
|
1091 | try: | |
1092 | m = re.compile(regex) |
|
1092 | m = re.compile(regex) | |
1093 | except TypeError: |
|
1093 | except TypeError: | |
1094 | raise TypeError('regex must be a string or compiled pattern') |
|
1094 | raise TypeError('regex must be a string or compiled pattern') | |
1095 | # Search for keys in each namespace that match the given regex |
|
1095 | # Search for keys in each namespace that match the given regex | |
1096 | # If a match is found, delete the key/value pair. |
|
1096 | # If a match is found, delete the key/value pair. | |
1097 | for ns in self.ns_refs_table: |
|
1097 | for ns in self.ns_refs_table: | |
1098 | for var in ns: |
|
1098 | for var in ns: | |
1099 | if m.search(var): |
|
1099 | if m.search(var): | |
1100 | del ns[var] |
|
1100 | del ns[var] | |
1101 |
|
1101 | |||
1102 | def push(self, variables, interactive=True): |
|
1102 | def push(self, variables, interactive=True): | |
1103 | """Inject a group of variables into the IPython user namespace. |
|
1103 | """Inject a group of variables into the IPython user namespace. | |
1104 |
|
1104 | |||
1105 | Parameters |
|
1105 | Parameters | |
1106 | ---------- |
|
1106 | ---------- | |
1107 | variables : dict, str or list/tuple of str |
|
1107 | variables : dict, str or list/tuple of str | |
1108 | The variables to inject into the user's namespace. If a dict, a |
|
1108 | The variables to inject into the user's namespace. If a dict, a | |
1109 | simple update is done. If a str, the string is assumed to have |
|
1109 | simple update is done. If a str, the string is assumed to have | |
1110 | variable names separated by spaces. A list/tuple of str can also |
|
1110 | variable names separated by spaces. A list/tuple of str can also | |
1111 | be used to give the variable names. If just the variable names are |
|
1111 | be used to give the variable names. If just the variable names are | |
1112 | give (list/tuple/str) then the variable values looked up in the |
|
1112 | give (list/tuple/str) then the variable values looked up in the | |
1113 | callers frame. |
|
1113 | callers frame. | |
1114 | interactive : bool |
|
1114 | interactive : bool | |
1115 | If True (default), the variables will be listed with the ``who`` |
|
1115 | If True (default), the variables will be listed with the ``who`` | |
1116 | magic. |
|
1116 | magic. | |
1117 | """ |
|
1117 | """ | |
1118 | vdict = None |
|
1118 | vdict = None | |
1119 |
|
1119 | |||
1120 | # We need a dict of name/value pairs to do namespace updates. |
|
1120 | # We need a dict of name/value pairs to do namespace updates. | |
1121 | if isinstance(variables, dict): |
|
1121 | if isinstance(variables, dict): | |
1122 | vdict = variables |
|
1122 | vdict = variables | |
1123 | elif isinstance(variables, (basestring, list, tuple)): |
|
1123 | elif isinstance(variables, (basestring, list, tuple)): | |
1124 | if isinstance(variables, basestring): |
|
1124 | if isinstance(variables, basestring): | |
1125 | vlist = variables.split() |
|
1125 | vlist = variables.split() | |
1126 | else: |
|
1126 | else: | |
1127 | vlist = variables |
|
1127 | vlist = variables | |
1128 | vdict = {} |
|
1128 | vdict = {} | |
1129 | cf = sys._getframe(1) |
|
1129 | cf = sys._getframe(1) | |
1130 | for name in vlist: |
|
1130 | for name in vlist: | |
1131 | try: |
|
1131 | try: | |
1132 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1132 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1133 | except: |
|
1133 | except: | |
1134 | print ('Could not get variable %s from %s' % |
|
1134 | print ('Could not get variable %s from %s' % | |
1135 | (name,cf.f_code.co_name)) |
|
1135 | (name,cf.f_code.co_name)) | |
1136 | else: |
|
1136 | else: | |
1137 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1137 | raise ValueError('variables must be a dict/str/list/tuple') | |
1138 |
|
1138 | |||
1139 | # Propagate variables to user namespace |
|
1139 | # Propagate variables to user namespace | |
1140 | self.user_ns.update(vdict) |
|
1140 | self.user_ns.update(vdict) | |
1141 |
|
1141 | |||
1142 | # And configure interactive visibility |
|
1142 | # And configure interactive visibility | |
1143 | config_ns = self.user_ns_hidden |
|
1143 | config_ns = self.user_ns_hidden | |
1144 | if interactive: |
|
1144 | if interactive: | |
1145 | for name, val in vdict.iteritems(): |
|
1145 | for name, val in vdict.iteritems(): | |
1146 | config_ns.pop(name, None) |
|
1146 | config_ns.pop(name, None) | |
1147 | else: |
|
1147 | else: | |
1148 | for name,val in vdict.iteritems(): |
|
1148 | for name,val in vdict.iteritems(): | |
1149 | config_ns[name] = val |
|
1149 | config_ns[name] = val | |
1150 |
|
1150 | |||
1151 | #------------------------------------------------------------------------- |
|
1151 | #------------------------------------------------------------------------- | |
1152 | # Things related to object introspection |
|
1152 | # Things related to object introspection | |
1153 | #------------------------------------------------------------------------- |
|
1153 | #------------------------------------------------------------------------- | |
1154 |
|
1154 | |||
1155 | def _ofind(self, oname, namespaces=None): |
|
1155 | def _ofind(self, oname, namespaces=None): | |
1156 | """Find an object in the available namespaces. |
|
1156 | """Find an object in the available namespaces. | |
1157 |
|
1157 | |||
1158 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1158 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1159 |
|
1159 | |||
1160 | Has special code to detect magic functions. |
|
1160 | Has special code to detect magic functions. | |
1161 | """ |
|
1161 | """ | |
1162 | #oname = oname.strip() |
|
1162 | #oname = oname.strip() | |
1163 | #print '1- oname: <%r>' % oname # dbg |
|
1163 | #print '1- oname: <%r>' % oname # dbg | |
1164 | try: |
|
1164 | try: | |
1165 | oname = oname.strip().encode('ascii') |
|
1165 | oname = oname.strip().encode('ascii') | |
1166 | #print '2- oname: <%r>' % oname # dbg |
|
1166 | #print '2- oname: <%r>' % oname # dbg | |
1167 | except UnicodeEncodeError: |
|
1167 | except UnicodeEncodeError: | |
1168 | print 'Python identifiers can only contain ascii characters.' |
|
1168 | print 'Python identifiers can only contain ascii characters.' | |
1169 | return dict(found=False) |
|
1169 | return dict(found=False) | |
1170 |
|
1170 | |||
1171 | alias_ns = None |
|
1171 | alias_ns = None | |
1172 | if namespaces is None: |
|
1172 | if namespaces is None: | |
1173 | # Namespaces to search in: |
|
1173 | # Namespaces to search in: | |
1174 | # Put them in a list. The order is important so that we |
|
1174 | # Put them in a list. The order is important so that we | |
1175 | # find things in the same order that Python finds them. |
|
1175 | # find things in the same order that Python finds them. | |
1176 | namespaces = [ ('Interactive', self.user_ns), |
|
1176 | namespaces = [ ('Interactive', self.user_ns), | |
1177 | ('IPython internal', self.internal_ns), |
|
1177 | ('IPython internal', self.internal_ns), | |
1178 | ('Python builtin', __builtin__.__dict__), |
|
1178 | ('Python builtin', __builtin__.__dict__), | |
1179 | ('Alias', self.alias_manager.alias_table), |
|
1179 | ('Alias', self.alias_manager.alias_table), | |
1180 | ] |
|
1180 | ] | |
1181 | alias_ns = self.alias_manager.alias_table |
|
1181 | alias_ns = self.alias_manager.alias_table | |
1182 |
|
1182 | |||
1183 | # initialize results to 'null' |
|
1183 | # initialize results to 'null' | |
1184 | found = False; obj = None; ospace = None; ds = None; |
|
1184 | found = False; obj = None; ospace = None; ds = None; | |
1185 | ismagic = False; isalias = False; parent = None |
|
1185 | ismagic = False; isalias = False; parent = None | |
1186 |
|
1186 | |||
1187 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1187 | # We need to special-case 'print', which as of python2.6 registers as a | |
1188 | # function but should only be treated as one if print_function was |
|
1188 | # function but should only be treated as one if print_function was | |
1189 | # loaded with a future import. In this case, just bail. |
|
1189 | # loaded with a future import. In this case, just bail. | |
1190 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1190 | if (oname == 'print' and not (self.compile.compiler_flags & | |
1191 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1191 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1192 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1192 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1193 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1193 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1194 |
|
1194 | |||
1195 | # Look for the given name by splitting it in parts. If the head is |
|
1195 | # Look for the given name by splitting it in parts. If the head is | |
1196 | # found, then we look for all the remaining parts as members, and only |
|
1196 | # found, then we look for all the remaining parts as members, and only | |
1197 | # declare success if we can find them all. |
|
1197 | # declare success if we can find them all. | |
1198 | oname_parts = oname.split('.') |
|
1198 | oname_parts = oname.split('.') | |
1199 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1199 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1200 | for nsname,ns in namespaces: |
|
1200 | for nsname,ns in namespaces: | |
1201 | try: |
|
1201 | try: | |
1202 | obj = ns[oname_head] |
|
1202 | obj = ns[oname_head] | |
1203 | except KeyError: |
|
1203 | except KeyError: | |
1204 | continue |
|
1204 | continue | |
1205 | else: |
|
1205 | else: | |
1206 | #print 'oname_rest:', oname_rest # dbg |
|
1206 | #print 'oname_rest:', oname_rest # dbg | |
1207 | for part in oname_rest: |
|
1207 | for part in oname_rest: | |
1208 | try: |
|
1208 | try: | |
1209 | parent = obj |
|
1209 | parent = obj | |
1210 | obj = getattr(obj,part) |
|
1210 | obj = getattr(obj,part) | |
1211 | except: |
|
1211 | except: | |
1212 | # Blanket except b/c some badly implemented objects |
|
1212 | # Blanket except b/c some badly implemented objects | |
1213 | # allow __getattr__ to raise exceptions other than |
|
1213 | # allow __getattr__ to raise exceptions other than | |
1214 | # AttributeError, which then crashes IPython. |
|
1214 | # AttributeError, which then crashes IPython. | |
1215 | break |
|
1215 | break | |
1216 | else: |
|
1216 | else: | |
1217 | # If we finish the for loop (no break), we got all members |
|
1217 | # If we finish the for loop (no break), we got all members | |
1218 | found = True |
|
1218 | found = True | |
1219 | ospace = nsname |
|
1219 | ospace = nsname | |
1220 | if ns == alias_ns: |
|
1220 | if ns == alias_ns: | |
1221 | isalias = True |
|
1221 | isalias = True | |
1222 | break # namespace loop |
|
1222 | break # namespace loop | |
1223 |
|
1223 | |||
1224 | # Try to see if it's magic |
|
1224 | # Try to see if it's magic | |
1225 | if not found: |
|
1225 | if not found: | |
1226 | if oname.startswith(ESC_MAGIC): |
|
1226 | if oname.startswith(ESC_MAGIC): | |
1227 | oname = oname[1:] |
|
1227 | oname = oname[1:] | |
1228 | obj = getattr(self,'magic_'+oname,None) |
|
1228 | obj = getattr(self,'magic_'+oname,None) | |
1229 | if obj is not None: |
|
1229 | if obj is not None: | |
1230 | found = True |
|
1230 | found = True | |
1231 | ospace = 'IPython internal' |
|
1231 | ospace = 'IPython internal' | |
1232 | ismagic = True |
|
1232 | ismagic = True | |
1233 |
|
1233 | |||
1234 | # Last try: special-case some literals like '', [], {}, etc: |
|
1234 | # Last try: special-case some literals like '', [], {}, etc: | |
1235 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1235 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1236 | obj = eval(oname_head) |
|
1236 | obj = eval(oname_head) | |
1237 | found = True |
|
1237 | found = True | |
1238 | ospace = 'Interactive' |
|
1238 | ospace = 'Interactive' | |
1239 |
|
1239 | |||
1240 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1240 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1241 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1241 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1242 |
|
1242 | |||
1243 | def _ofind_property(self, oname, info): |
|
1243 | def _ofind_property(self, oname, info): | |
1244 | """Second part of object finding, to look for property details.""" |
|
1244 | """Second part of object finding, to look for property details.""" | |
1245 | if info.found: |
|
1245 | if info.found: | |
1246 | # Get the docstring of the class property if it exists. |
|
1246 | # Get the docstring of the class property if it exists. | |
1247 | path = oname.split('.') |
|
1247 | path = oname.split('.') | |
1248 | root = '.'.join(path[:-1]) |
|
1248 | root = '.'.join(path[:-1]) | |
1249 | if info.parent is not None: |
|
1249 | if info.parent is not None: | |
1250 | try: |
|
1250 | try: | |
1251 | target = getattr(info.parent, '__class__') |
|
1251 | target = getattr(info.parent, '__class__') | |
1252 | # The object belongs to a class instance. |
|
1252 | # The object belongs to a class instance. | |
1253 | try: |
|
1253 | try: | |
1254 | target = getattr(target, path[-1]) |
|
1254 | target = getattr(target, path[-1]) | |
1255 | # The class defines the object. |
|
1255 | # The class defines the object. | |
1256 | if isinstance(target, property): |
|
1256 | if isinstance(target, property): | |
1257 | oname = root + '.__class__.' + path[-1] |
|
1257 | oname = root + '.__class__.' + path[-1] | |
1258 | info = Struct(self._ofind(oname)) |
|
1258 | info = Struct(self._ofind(oname)) | |
1259 | except AttributeError: pass |
|
1259 | except AttributeError: pass | |
1260 | except AttributeError: pass |
|
1260 | except AttributeError: pass | |
1261 |
|
1261 | |||
1262 | # We return either the new info or the unmodified input if the object |
|
1262 | # We return either the new info or the unmodified input if the object | |
1263 | # hadn't been found |
|
1263 | # hadn't been found | |
1264 | return info |
|
1264 | return info | |
1265 |
|
1265 | |||
1266 | def _object_find(self, oname, namespaces=None): |
|
1266 | def _object_find(self, oname, namespaces=None): | |
1267 | """Find an object and return a struct with info about it.""" |
|
1267 | """Find an object and return a struct with info about it.""" | |
1268 | inf = Struct(self._ofind(oname, namespaces)) |
|
1268 | inf = Struct(self._ofind(oname, namespaces)) | |
1269 | return Struct(self._ofind_property(oname, inf)) |
|
1269 | return Struct(self._ofind_property(oname, inf)) | |
1270 |
|
1270 | |||
1271 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1271 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1272 | """Generic interface to the inspector system. |
|
1272 | """Generic interface to the inspector system. | |
1273 |
|
1273 | |||
1274 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1274 | This function is meant to be called by pdef, pdoc & friends.""" | |
1275 | info = self._object_find(oname) |
|
1275 | info = self._object_find(oname) | |
1276 | if info.found: |
|
1276 | if info.found: | |
1277 | pmethod = getattr(self.inspector, meth) |
|
1277 | pmethod = getattr(self.inspector, meth) | |
1278 | formatter = format_screen if info.ismagic else None |
|
1278 | formatter = format_screen if info.ismagic else None | |
1279 | if meth == 'pdoc': |
|
1279 | if meth == 'pdoc': | |
1280 | pmethod(info.obj, oname, formatter) |
|
1280 | pmethod(info.obj, oname, formatter) | |
1281 | elif meth == 'pinfo': |
|
1281 | elif meth == 'pinfo': | |
1282 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1282 | pmethod(info.obj, oname, formatter, info, **kw) | |
1283 | else: |
|
1283 | else: | |
1284 | pmethod(info.obj, oname) |
|
1284 | pmethod(info.obj, oname) | |
1285 | else: |
|
1285 | else: | |
1286 | print 'Object `%s` not found.' % oname |
|
1286 | print 'Object `%s` not found.' % oname | |
1287 | return 'not found' # so callers can take other action |
|
1287 | return 'not found' # so callers can take other action | |
1288 |
|
1288 | |||
1289 | def object_inspect(self, oname): |
|
1289 | def object_inspect(self, oname): | |
1290 | info = self._object_find(oname) |
|
1290 | with self.builtin_trap: | |
1291 | if info.found: |
|
1291 | info = self._object_find(oname) | |
1292 | return self.inspector.info(info.obj, oname, info=info) |
|
1292 | if info.found: | |
1293 | else: |
|
1293 | return self.inspector.info(info.obj, oname, info=info) | |
1294 | return oinspect.object_info(name=oname, found=False) |
|
1294 | else: | |
|
1295 | return oinspect.object_info(name=oname, found=False) | |||
1295 |
|
1296 | |||
1296 | #------------------------------------------------------------------------- |
|
1297 | #------------------------------------------------------------------------- | |
1297 | # Things related to history management |
|
1298 | # Things related to history management | |
1298 | #------------------------------------------------------------------------- |
|
1299 | #------------------------------------------------------------------------- | |
1299 |
|
1300 | |||
1300 | def init_history(self): |
|
1301 | def init_history(self): | |
1301 | """Sets up the command history, and starts regular autosaves.""" |
|
1302 | """Sets up the command history, and starts regular autosaves.""" | |
1302 | self.history_manager = HistoryManager(shell=self, config=self.config) |
|
1303 | self.history_manager = HistoryManager(shell=self, config=self.config) | |
1303 |
|
1304 | |||
1304 | #------------------------------------------------------------------------- |
|
1305 | #------------------------------------------------------------------------- | |
1305 | # Things related to exception handling and tracebacks (not debugging) |
|
1306 | # Things related to exception handling and tracebacks (not debugging) | |
1306 | #------------------------------------------------------------------------- |
|
1307 | #------------------------------------------------------------------------- | |
1307 |
|
1308 | |||
1308 | def init_traceback_handlers(self, custom_exceptions): |
|
1309 | def init_traceback_handlers(self, custom_exceptions): | |
1309 | # Syntax error handler. |
|
1310 | # Syntax error handler. | |
1310 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1311 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1311 |
|
1312 | |||
1312 | # The interactive one is initialized with an offset, meaning we always |
|
1313 | # The interactive one is initialized with an offset, meaning we always | |
1313 | # want to remove the topmost item in the traceback, which is our own |
|
1314 | # want to remove the topmost item in the traceback, which is our own | |
1314 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1315 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1315 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1316 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1316 | color_scheme='NoColor', |
|
1317 | color_scheme='NoColor', | |
1317 | tb_offset = 1, |
|
1318 | tb_offset = 1, | |
1318 | check_cache=self.compile.check_cache) |
|
1319 | check_cache=self.compile.check_cache) | |
1319 |
|
1320 | |||
1320 | # The instance will store a pointer to the system-wide exception hook, |
|
1321 | # The instance will store a pointer to the system-wide exception hook, | |
1321 | # so that runtime code (such as magics) can access it. This is because |
|
1322 | # so that runtime code (such as magics) can access it. This is because | |
1322 | # during the read-eval loop, it may get temporarily overwritten. |
|
1323 | # during the read-eval loop, it may get temporarily overwritten. | |
1323 | self.sys_excepthook = sys.excepthook |
|
1324 | self.sys_excepthook = sys.excepthook | |
1324 |
|
1325 | |||
1325 | # and add any custom exception handlers the user may have specified |
|
1326 | # and add any custom exception handlers the user may have specified | |
1326 | self.set_custom_exc(*custom_exceptions) |
|
1327 | self.set_custom_exc(*custom_exceptions) | |
1327 |
|
1328 | |||
1328 | # Set the exception mode |
|
1329 | # Set the exception mode | |
1329 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1330 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1330 |
|
1331 | |||
1331 | def set_custom_exc(self, exc_tuple, handler): |
|
1332 | def set_custom_exc(self, exc_tuple, handler): | |
1332 | """set_custom_exc(exc_tuple,handler) |
|
1333 | """set_custom_exc(exc_tuple,handler) | |
1333 |
|
1334 | |||
1334 | Set a custom exception handler, which will be called if any of the |
|
1335 | Set a custom exception handler, which will be called if any of the | |
1335 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1336 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1336 | run_code() method. |
|
1337 | run_code() method. | |
1337 |
|
1338 | |||
1338 | Inputs: |
|
1339 | Inputs: | |
1339 |
|
1340 | |||
1340 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1341 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1341 | handler for. It is very important that you use a tuple, and NOT A |
|
1342 | handler for. It is very important that you use a tuple, and NOT A | |
1342 | LIST here, because of the way Python's except statement works. If |
|
1343 | LIST here, because of the way Python's except statement works. If | |
1343 | you only want to trap a single exception, use a singleton tuple: |
|
1344 | you only want to trap a single exception, use a singleton tuple: | |
1344 |
|
1345 | |||
1345 | exc_tuple == (MyCustomException,) |
|
1346 | exc_tuple == (MyCustomException,) | |
1346 |
|
1347 | |||
1347 | - handler: this must be defined as a function with the following |
|
1348 | - handler: this must be defined as a function with the following | |
1348 | basic interface:: |
|
1349 | basic interface:: | |
1349 |
|
1350 | |||
1350 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1351 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1351 | ... |
|
1352 | ... | |
1352 | # The return value must be |
|
1353 | # The return value must be | |
1353 | return structured_traceback |
|
1354 | return structured_traceback | |
1354 |
|
1355 | |||
1355 | This will be made into an instance method (via types.MethodType) |
|
1356 | This will be made into an instance method (via types.MethodType) | |
1356 | of IPython itself, and it will be called if any of the exceptions |
|
1357 | of IPython itself, and it will be called if any of the exceptions | |
1357 | listed in the exc_tuple are caught. If the handler is None, an |
|
1358 | listed in the exc_tuple are caught. If the handler is None, an | |
1358 | internal basic one is used, which just prints basic info. |
|
1359 | internal basic one is used, which just prints basic info. | |
1359 |
|
1360 | |||
1360 | WARNING: by putting in your own exception handler into IPython's main |
|
1361 | WARNING: by putting in your own exception handler into IPython's main | |
1361 | execution loop, you run a very good chance of nasty crashes. This |
|
1362 | execution loop, you run a very good chance of nasty crashes. This | |
1362 | facility should only be used if you really know what you are doing.""" |
|
1363 | facility should only be used if you really know what you are doing.""" | |
1363 |
|
1364 | |||
1364 | assert type(exc_tuple)==type(()) , \ |
|
1365 | assert type(exc_tuple)==type(()) , \ | |
1365 | "The custom exceptions must be given AS A TUPLE." |
|
1366 | "The custom exceptions must be given AS A TUPLE." | |
1366 |
|
1367 | |||
1367 | def dummy_handler(self,etype,value,tb): |
|
1368 | def dummy_handler(self,etype,value,tb): | |
1368 | print '*** Simple custom exception handler ***' |
|
1369 | print '*** Simple custom exception handler ***' | |
1369 | print 'Exception type :',etype |
|
1370 | print 'Exception type :',etype | |
1370 | print 'Exception value:',value |
|
1371 | print 'Exception value:',value | |
1371 | print 'Traceback :',tb |
|
1372 | print 'Traceback :',tb | |
1372 | print 'Source code :','\n'.join(self.buffer) |
|
1373 | print 'Source code :','\n'.join(self.buffer) | |
1373 |
|
1374 | |||
1374 | if handler is None: handler = dummy_handler |
|
1375 | if handler is None: handler = dummy_handler | |
1375 |
|
1376 | |||
1376 | self.CustomTB = types.MethodType(handler,self) |
|
1377 | self.CustomTB = types.MethodType(handler,self) | |
1377 | self.custom_exceptions = exc_tuple |
|
1378 | self.custom_exceptions = exc_tuple | |
1378 |
|
1379 | |||
1379 | def excepthook(self, etype, value, tb): |
|
1380 | def excepthook(self, etype, value, tb): | |
1380 | """One more defense for GUI apps that call sys.excepthook. |
|
1381 | """One more defense for GUI apps that call sys.excepthook. | |
1381 |
|
1382 | |||
1382 | GUI frameworks like wxPython trap exceptions and call |
|
1383 | GUI frameworks like wxPython trap exceptions and call | |
1383 | sys.excepthook themselves. I guess this is a feature that |
|
1384 | sys.excepthook themselves. I guess this is a feature that | |
1384 | enables them to keep running after exceptions that would |
|
1385 | enables them to keep running after exceptions that would | |
1385 | otherwise kill their mainloop. This is a bother for IPython |
|
1386 | otherwise kill their mainloop. This is a bother for IPython | |
1386 | which excepts to catch all of the program exceptions with a try: |
|
1387 | which excepts to catch all of the program exceptions with a try: | |
1387 | except: statement. |
|
1388 | except: statement. | |
1388 |
|
1389 | |||
1389 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1390 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1390 | any app directly invokes sys.excepthook, it will look to the user like |
|
1391 | any app directly invokes sys.excepthook, it will look to the user like | |
1391 | IPython crashed. In order to work around this, we can disable the |
|
1392 | IPython crashed. In order to work around this, we can disable the | |
1392 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1393 | CrashHandler and replace it with this excepthook instead, which prints a | |
1393 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1394 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1394 | call sys.excepthook will generate a regular-looking exception from |
|
1395 | call sys.excepthook will generate a regular-looking exception from | |
1395 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1396 | IPython, and the CrashHandler will only be triggered by real IPython | |
1396 | crashes. |
|
1397 | crashes. | |
1397 |
|
1398 | |||
1398 | This hook should be used sparingly, only in places which are not likely |
|
1399 | This hook should be used sparingly, only in places which are not likely | |
1399 | to be true IPython errors. |
|
1400 | to be true IPython errors. | |
1400 | """ |
|
1401 | """ | |
1401 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1402 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1402 |
|
1403 | |||
1403 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1404 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1404 | exception_only=False): |
|
1405 | exception_only=False): | |
1405 | """Display the exception that just occurred. |
|
1406 | """Display the exception that just occurred. | |
1406 |
|
1407 | |||
1407 | If nothing is known about the exception, this is the method which |
|
1408 | If nothing is known about the exception, this is the method which | |
1408 | should be used throughout the code for presenting user tracebacks, |
|
1409 | should be used throughout the code for presenting user tracebacks, | |
1409 | rather than directly invoking the InteractiveTB object. |
|
1410 | rather than directly invoking the InteractiveTB object. | |
1410 |
|
1411 | |||
1411 | A specific showsyntaxerror() also exists, but this method can take |
|
1412 | A specific showsyntaxerror() also exists, but this method can take | |
1412 | care of calling it if needed, so unless you are explicitly catching a |
|
1413 | care of calling it if needed, so unless you are explicitly catching a | |
1413 | SyntaxError exception, don't try to analyze the stack manually and |
|
1414 | SyntaxError exception, don't try to analyze the stack manually and | |
1414 | simply call this method.""" |
|
1415 | simply call this method.""" | |
1415 |
|
1416 | |||
1416 | try: |
|
1417 | try: | |
1417 | if exc_tuple is None: |
|
1418 | if exc_tuple is None: | |
1418 | etype, value, tb = sys.exc_info() |
|
1419 | etype, value, tb = sys.exc_info() | |
1419 | else: |
|
1420 | else: | |
1420 | etype, value, tb = exc_tuple |
|
1421 | etype, value, tb = exc_tuple | |
1421 |
|
1422 | |||
1422 | if etype is None: |
|
1423 | if etype is None: | |
1423 | if hasattr(sys, 'last_type'): |
|
1424 | if hasattr(sys, 'last_type'): | |
1424 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1425 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1425 | sys.last_traceback |
|
1426 | sys.last_traceback | |
1426 | else: |
|
1427 | else: | |
1427 | self.write_err('No traceback available to show.\n') |
|
1428 | self.write_err('No traceback available to show.\n') | |
1428 | return |
|
1429 | return | |
1429 |
|
1430 | |||
1430 | if etype is SyntaxError: |
|
1431 | if etype is SyntaxError: | |
1431 | # Though this won't be called by syntax errors in the input |
|
1432 | # Though this won't be called by syntax errors in the input | |
1432 | # line, there may be SyntaxError cases whith imported code. |
|
1433 | # line, there may be SyntaxError cases whith imported code. | |
1433 | self.showsyntaxerror(filename) |
|
1434 | self.showsyntaxerror(filename) | |
1434 | elif etype is UsageError: |
|
1435 | elif etype is UsageError: | |
1435 | print "UsageError:", value |
|
1436 | print "UsageError:", value | |
1436 | else: |
|
1437 | else: | |
1437 | # WARNING: these variables are somewhat deprecated and not |
|
1438 | # WARNING: these variables are somewhat deprecated and not | |
1438 | # necessarily safe to use in a threaded environment, but tools |
|
1439 | # necessarily safe to use in a threaded environment, but tools | |
1439 | # like pdb depend on their existence, so let's set them. If we |
|
1440 | # like pdb depend on their existence, so let's set them. If we | |
1440 | # find problems in the field, we'll need to revisit their use. |
|
1441 | # find problems in the field, we'll need to revisit their use. | |
1441 | sys.last_type = etype |
|
1442 | sys.last_type = etype | |
1442 | sys.last_value = value |
|
1443 | sys.last_value = value | |
1443 | sys.last_traceback = tb |
|
1444 | sys.last_traceback = tb | |
1444 |
|
1445 | |||
1445 | if etype in self.custom_exceptions: |
|
1446 | if etype in self.custom_exceptions: | |
1446 | # FIXME: Old custom traceback objects may just return a |
|
1447 | # FIXME: Old custom traceback objects may just return a | |
1447 | # string, in that case we just put it into a list |
|
1448 | # string, in that case we just put it into a list | |
1448 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1449 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1449 | if isinstance(ctb, basestring): |
|
1450 | if isinstance(ctb, basestring): | |
1450 | stb = [stb] |
|
1451 | stb = [stb] | |
1451 | else: |
|
1452 | else: | |
1452 | if exception_only: |
|
1453 | if exception_only: | |
1453 | stb = ['An exception has occurred, use %tb to see ' |
|
1454 | stb = ['An exception has occurred, use %tb to see ' | |
1454 | 'the full traceback.\n'] |
|
1455 | 'the full traceback.\n'] | |
1455 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1456 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1456 | value)) |
|
1457 | value)) | |
1457 | else: |
|
1458 | else: | |
1458 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1459 | stb = self.InteractiveTB.structured_traceback(etype, | |
1459 | value, tb, tb_offset=tb_offset) |
|
1460 | value, tb, tb_offset=tb_offset) | |
1460 | # FIXME: the pdb calling should be done by us, not by |
|
1461 | # FIXME: the pdb calling should be done by us, not by | |
1461 | # the code computing the traceback. |
|
1462 | # the code computing the traceback. | |
1462 | if self.InteractiveTB.call_pdb: |
|
1463 | if self.InteractiveTB.call_pdb: | |
1463 | # pdb mucks up readline, fix it back |
|
1464 | # pdb mucks up readline, fix it back | |
1464 | self.set_readline_completer() |
|
1465 | self.set_readline_completer() | |
1465 |
|
1466 | |||
1466 | # Actually show the traceback |
|
1467 | # Actually show the traceback | |
1467 | self._showtraceback(etype, value, stb) |
|
1468 | self._showtraceback(etype, value, stb) | |
1468 |
|
1469 | |||
1469 | except KeyboardInterrupt: |
|
1470 | except KeyboardInterrupt: | |
1470 | self.write_err("\nKeyboardInterrupt\n") |
|
1471 | self.write_err("\nKeyboardInterrupt\n") | |
1471 |
|
1472 | |||
1472 | def _showtraceback(self, etype, evalue, stb): |
|
1473 | def _showtraceback(self, etype, evalue, stb): | |
1473 | """Actually show a traceback. |
|
1474 | """Actually show a traceback. | |
1474 |
|
1475 | |||
1475 | Subclasses may override this method to put the traceback on a different |
|
1476 | Subclasses may override this method to put the traceback on a different | |
1476 | place, like a side channel. |
|
1477 | place, like a side channel. | |
1477 | """ |
|
1478 | """ | |
1478 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1479 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) | |
1479 |
|
1480 | |||
1480 | def showsyntaxerror(self, filename=None): |
|
1481 | def showsyntaxerror(self, filename=None): | |
1481 | """Display the syntax error that just occurred. |
|
1482 | """Display the syntax error that just occurred. | |
1482 |
|
1483 | |||
1483 | This doesn't display a stack trace because there isn't one. |
|
1484 | This doesn't display a stack trace because there isn't one. | |
1484 |
|
1485 | |||
1485 | If a filename is given, it is stuffed in the exception instead |
|
1486 | If a filename is given, it is stuffed in the exception instead | |
1486 | of what was there before (because Python's parser always uses |
|
1487 | of what was there before (because Python's parser always uses | |
1487 | "<string>" when reading from a string). |
|
1488 | "<string>" when reading from a string). | |
1488 | """ |
|
1489 | """ | |
1489 | etype, value, last_traceback = sys.exc_info() |
|
1490 | etype, value, last_traceback = sys.exc_info() | |
1490 |
|
1491 | |||
1491 | # See note about these variables in showtraceback() above |
|
1492 | # See note about these variables in showtraceback() above | |
1492 | sys.last_type = etype |
|
1493 | sys.last_type = etype | |
1493 | sys.last_value = value |
|
1494 | sys.last_value = value | |
1494 | sys.last_traceback = last_traceback |
|
1495 | sys.last_traceback = last_traceback | |
1495 |
|
1496 | |||
1496 | if filename and etype is SyntaxError: |
|
1497 | if filename and etype is SyntaxError: | |
1497 | # Work hard to stuff the correct filename in the exception |
|
1498 | # Work hard to stuff the correct filename in the exception | |
1498 | try: |
|
1499 | try: | |
1499 | msg, (dummy_filename, lineno, offset, line) = value |
|
1500 | msg, (dummy_filename, lineno, offset, line) = value | |
1500 | except: |
|
1501 | except: | |
1501 | # Not the format we expect; leave it alone |
|
1502 | # Not the format we expect; leave it alone | |
1502 | pass |
|
1503 | pass | |
1503 | else: |
|
1504 | else: | |
1504 | # Stuff in the right filename |
|
1505 | # Stuff in the right filename | |
1505 | try: |
|
1506 | try: | |
1506 | # Assume SyntaxError is a class exception |
|
1507 | # Assume SyntaxError is a class exception | |
1507 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1508 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1508 | except: |
|
1509 | except: | |
1509 | # If that failed, assume SyntaxError is a string |
|
1510 | # If that failed, assume SyntaxError is a string | |
1510 | value = msg, (filename, lineno, offset, line) |
|
1511 | value = msg, (filename, lineno, offset, line) | |
1511 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1512 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1512 | self._showtraceback(etype, value, stb) |
|
1513 | self._showtraceback(etype, value, stb) | |
1513 |
|
1514 | |||
1514 | #------------------------------------------------------------------------- |
|
1515 | #------------------------------------------------------------------------- | |
1515 | # Things related to readline |
|
1516 | # Things related to readline | |
1516 | #------------------------------------------------------------------------- |
|
1517 | #------------------------------------------------------------------------- | |
1517 |
|
1518 | |||
1518 | def init_readline(self): |
|
1519 | def init_readline(self): | |
1519 | """Command history completion/saving/reloading.""" |
|
1520 | """Command history completion/saving/reloading.""" | |
1520 |
|
1521 | |||
1521 | if self.readline_use: |
|
1522 | if self.readline_use: | |
1522 | import IPython.utils.rlineimpl as readline |
|
1523 | import IPython.utils.rlineimpl as readline | |
1523 |
|
1524 | |||
1524 | self.rl_next_input = None |
|
1525 | self.rl_next_input = None | |
1525 | self.rl_do_indent = False |
|
1526 | self.rl_do_indent = False | |
1526 |
|
1527 | |||
1527 | if not self.readline_use or not readline.have_readline: |
|
1528 | if not self.readline_use or not readline.have_readline: | |
1528 | self.has_readline = False |
|
1529 | self.has_readline = False | |
1529 | self.readline = None |
|
1530 | self.readline = None | |
1530 | # Set a number of methods that depend on readline to be no-op |
|
1531 | # Set a number of methods that depend on readline to be no-op | |
1531 | self.set_readline_completer = no_op |
|
1532 | self.set_readline_completer = no_op | |
1532 | self.set_custom_completer = no_op |
|
1533 | self.set_custom_completer = no_op | |
1533 | self.set_completer_frame = no_op |
|
1534 | self.set_completer_frame = no_op | |
1534 | warn('Readline services not available or not loaded.') |
|
1535 | warn('Readline services not available or not loaded.') | |
1535 | else: |
|
1536 | else: | |
1536 | self.has_readline = True |
|
1537 | self.has_readline = True | |
1537 | self.readline = readline |
|
1538 | self.readline = readline | |
1538 | sys.modules['readline'] = readline |
|
1539 | sys.modules['readline'] = readline | |
1539 |
|
1540 | |||
1540 | # Platform-specific configuration |
|
1541 | # Platform-specific configuration | |
1541 | if os.name == 'nt': |
|
1542 | if os.name == 'nt': | |
1542 | # FIXME - check with Frederick to see if we can harmonize |
|
1543 | # FIXME - check with Frederick to see if we can harmonize | |
1543 | # naming conventions with pyreadline to avoid this |
|
1544 | # naming conventions with pyreadline to avoid this | |
1544 | # platform-dependent check |
|
1545 | # platform-dependent check | |
1545 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1546 | self.readline_startup_hook = readline.set_pre_input_hook | |
1546 | else: |
|
1547 | else: | |
1547 | self.readline_startup_hook = readline.set_startup_hook |
|
1548 | self.readline_startup_hook = readline.set_startup_hook | |
1548 |
|
1549 | |||
1549 | # Load user's initrc file (readline config) |
|
1550 | # Load user's initrc file (readline config) | |
1550 | # Or if libedit is used, load editrc. |
|
1551 | # Or if libedit is used, load editrc. | |
1551 | inputrc_name = os.environ.get('INPUTRC') |
|
1552 | inputrc_name = os.environ.get('INPUTRC') | |
1552 | if inputrc_name is None: |
|
1553 | if inputrc_name is None: | |
1553 | home_dir = get_home_dir() |
|
1554 | home_dir = get_home_dir() | |
1554 | if home_dir is not None: |
|
1555 | if home_dir is not None: | |
1555 | inputrc_name = '.inputrc' |
|
1556 | inputrc_name = '.inputrc' | |
1556 | if readline.uses_libedit: |
|
1557 | if readline.uses_libedit: | |
1557 | inputrc_name = '.editrc' |
|
1558 | inputrc_name = '.editrc' | |
1558 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1559 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1559 | if os.path.isfile(inputrc_name): |
|
1560 | if os.path.isfile(inputrc_name): | |
1560 | try: |
|
1561 | try: | |
1561 | readline.read_init_file(inputrc_name) |
|
1562 | readline.read_init_file(inputrc_name) | |
1562 | except: |
|
1563 | except: | |
1563 | warn('Problems reading readline initialization file <%s>' |
|
1564 | warn('Problems reading readline initialization file <%s>' | |
1564 | % inputrc_name) |
|
1565 | % inputrc_name) | |
1565 |
|
1566 | |||
1566 | # Configure readline according to user's prefs |
|
1567 | # Configure readline according to user's prefs | |
1567 | # This is only done if GNU readline is being used. If libedit |
|
1568 | # This is only done if GNU readline is being used. If libedit | |
1568 | # is being used (as on Leopard) the readline config is |
|
1569 | # is being used (as on Leopard) the readline config is | |
1569 | # not run as the syntax for libedit is different. |
|
1570 | # not run as the syntax for libedit is different. | |
1570 | if not readline.uses_libedit: |
|
1571 | if not readline.uses_libedit: | |
1571 | for rlcommand in self.readline_parse_and_bind: |
|
1572 | for rlcommand in self.readline_parse_and_bind: | |
1572 | #print "loading rl:",rlcommand # dbg |
|
1573 | #print "loading rl:",rlcommand # dbg | |
1573 | readline.parse_and_bind(rlcommand) |
|
1574 | readline.parse_and_bind(rlcommand) | |
1574 |
|
1575 | |||
1575 | # Remove some chars from the delimiters list. If we encounter |
|
1576 | # Remove some chars from the delimiters list. If we encounter | |
1576 | # unicode chars, discard them. |
|
1577 | # unicode chars, discard them. | |
1577 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1578 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1578 | delims = delims.translate(None, self.readline_remove_delims) |
|
1579 | delims = delims.translate(None, self.readline_remove_delims) | |
1579 | delims = delims.replace(ESC_MAGIC, '') |
|
1580 | delims = delims.replace(ESC_MAGIC, '') | |
1580 | readline.set_completer_delims(delims) |
|
1581 | readline.set_completer_delims(delims) | |
1581 | # otherwise we end up with a monster history after a while: |
|
1582 | # otherwise we end up with a monster history after a while: | |
1582 | readline.set_history_length(self.history_length) |
|
1583 | readline.set_history_length(self.history_length) | |
1583 |
|
1584 | |||
1584 | self.refill_readline_hist() |
|
1585 | self.refill_readline_hist() | |
1585 | self.readline_no_record = ReadlineNoRecord(self) |
|
1586 | self.readline_no_record = ReadlineNoRecord(self) | |
1586 |
|
1587 | |||
1587 | # Configure auto-indent for all platforms |
|
1588 | # Configure auto-indent for all platforms | |
1588 | self.set_autoindent(self.autoindent) |
|
1589 | self.set_autoindent(self.autoindent) | |
1589 |
|
1590 | |||
1590 | def refill_readline_hist(self): |
|
1591 | def refill_readline_hist(self): | |
1591 | # Load the last 1000 lines from history |
|
1592 | # Load the last 1000 lines from history | |
1592 | self.readline.clear_history() |
|
1593 | self.readline.clear_history() | |
1593 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1594 | stdin_encoding = sys.stdin.encoding or "utf-8" | |
1594 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1595 | for _, _, cell in self.history_manager.get_tail(1000, | |
1595 | include_latest=True): |
|
1596 | include_latest=True): | |
1596 | if cell.strip(): # Ignore blank lines |
|
1597 | if cell.strip(): # Ignore blank lines | |
1597 | for line in cell.splitlines(): |
|
1598 | for line in cell.splitlines(): | |
1598 | self.readline.add_history(line.encode(stdin_encoding)) |
|
1599 | self.readline.add_history(line.encode(stdin_encoding)) | |
1599 |
|
1600 | |||
1600 | def set_next_input(self, s): |
|
1601 | def set_next_input(self, s): | |
1601 | """ Sets the 'default' input string for the next command line. |
|
1602 | """ Sets the 'default' input string for the next command line. | |
1602 |
|
1603 | |||
1603 | Requires readline. |
|
1604 | Requires readline. | |
1604 |
|
1605 | |||
1605 | Example: |
|
1606 | Example: | |
1606 |
|
1607 | |||
1607 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1608 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1608 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1609 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1609 | """ |
|
1610 | """ | |
1610 |
|
1611 | |||
1611 | self.rl_next_input = s |
|
1612 | self.rl_next_input = s | |
1612 |
|
1613 | |||
1613 | # Maybe move this to the terminal subclass? |
|
1614 | # Maybe move this to the terminal subclass? | |
1614 | def pre_readline(self): |
|
1615 | def pre_readline(self): | |
1615 | """readline hook to be used at the start of each line. |
|
1616 | """readline hook to be used at the start of each line. | |
1616 |
|
1617 | |||
1617 | Currently it handles auto-indent only.""" |
|
1618 | Currently it handles auto-indent only.""" | |
1618 |
|
1619 | |||
1619 | if self.rl_do_indent: |
|
1620 | if self.rl_do_indent: | |
1620 | self.readline.insert_text(self._indent_current_str()) |
|
1621 | self.readline.insert_text(self._indent_current_str()) | |
1621 | if self.rl_next_input is not None: |
|
1622 | if self.rl_next_input is not None: | |
1622 | self.readline.insert_text(self.rl_next_input) |
|
1623 | self.readline.insert_text(self.rl_next_input) | |
1623 | self.rl_next_input = None |
|
1624 | self.rl_next_input = None | |
1624 |
|
1625 | |||
1625 | def _indent_current_str(self): |
|
1626 | def _indent_current_str(self): | |
1626 | """return the current level of indentation as a string""" |
|
1627 | """return the current level of indentation as a string""" | |
1627 | return self.input_splitter.indent_spaces * ' ' |
|
1628 | return self.input_splitter.indent_spaces * ' ' | |
1628 |
|
1629 | |||
1629 | #------------------------------------------------------------------------- |
|
1630 | #------------------------------------------------------------------------- | |
1630 | # Things related to text completion |
|
1631 | # Things related to text completion | |
1631 | #------------------------------------------------------------------------- |
|
1632 | #------------------------------------------------------------------------- | |
1632 |
|
1633 | |||
1633 | def init_completer(self): |
|
1634 | def init_completer(self): | |
1634 | """Initialize the completion machinery. |
|
1635 | """Initialize the completion machinery. | |
1635 |
|
1636 | |||
1636 | This creates completion machinery that can be used by client code, |
|
1637 | This creates completion machinery that can be used by client code, | |
1637 | either interactively in-process (typically triggered by the readline |
|
1638 | either interactively in-process (typically triggered by the readline | |
1638 | library), programatically (such as in test suites) or out-of-prcess |
|
1639 | library), programatically (such as in test suites) or out-of-prcess | |
1639 | (typically over the network by remote frontends). |
|
1640 | (typically over the network by remote frontends). | |
1640 | """ |
|
1641 | """ | |
1641 | from IPython.core.completer import IPCompleter |
|
1642 | from IPython.core.completer import IPCompleter | |
1642 | from IPython.core.completerlib import (module_completer, |
|
1643 | from IPython.core.completerlib import (module_completer, | |
1643 | magic_run_completer, cd_completer) |
|
1644 | magic_run_completer, cd_completer) | |
1644 |
|
1645 | |||
1645 | self.Completer = IPCompleter(self, |
|
1646 | self.Completer = IPCompleter(self, | |
1646 | self.user_ns, |
|
1647 | self.user_ns, | |
1647 | self.user_global_ns, |
|
1648 | self.user_global_ns, | |
1648 | self.readline_omit__names, |
|
1649 | self.readline_omit__names, | |
1649 | self.alias_manager.alias_table, |
|
1650 | self.alias_manager.alias_table, | |
1650 | self.has_readline) |
|
1651 | self.has_readline) | |
1651 |
|
1652 | |||
1652 | # Add custom completers to the basic ones built into IPCompleter |
|
1653 | # Add custom completers to the basic ones built into IPCompleter | |
1653 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1654 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1654 | self.strdispatchers['complete_command'] = sdisp |
|
1655 | self.strdispatchers['complete_command'] = sdisp | |
1655 | self.Completer.custom_completers = sdisp |
|
1656 | self.Completer.custom_completers = sdisp | |
1656 |
|
1657 | |||
1657 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1658 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1658 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1659 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1659 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1660 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1660 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1661 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1661 |
|
1662 | |||
1662 | # Only configure readline if we truly are using readline. IPython can |
|
1663 | # Only configure readline if we truly are using readline. IPython can | |
1663 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1664 | # do tab-completion over the network, in GUIs, etc, where readline | |
1664 | # itself may be absent |
|
1665 | # itself may be absent | |
1665 | if self.has_readline: |
|
1666 | if self.has_readline: | |
1666 | self.set_readline_completer() |
|
1667 | self.set_readline_completer() | |
1667 |
|
1668 | |||
1668 | def complete(self, text, line=None, cursor_pos=None): |
|
1669 | def complete(self, text, line=None, cursor_pos=None): | |
1669 | """Return the completed text and a list of completions. |
|
1670 | """Return the completed text and a list of completions. | |
1670 |
|
1671 | |||
1671 | Parameters |
|
1672 | Parameters | |
1672 | ---------- |
|
1673 | ---------- | |
1673 |
|
1674 | |||
1674 | text : string |
|
1675 | text : string | |
1675 | A string of text to be completed on. It can be given as empty and |
|
1676 | A string of text to be completed on. It can be given as empty and | |
1676 | instead a line/position pair are given. In this case, the |
|
1677 | instead a line/position pair are given. In this case, the | |
1677 | completer itself will split the line like readline does. |
|
1678 | completer itself will split the line like readline does. | |
1678 |
|
1679 | |||
1679 | line : string, optional |
|
1680 | line : string, optional | |
1680 | The complete line that text is part of. |
|
1681 | The complete line that text is part of. | |
1681 |
|
1682 | |||
1682 | cursor_pos : int, optional |
|
1683 | cursor_pos : int, optional | |
1683 | The position of the cursor on the input line. |
|
1684 | The position of the cursor on the input line. | |
1684 |
|
1685 | |||
1685 | Returns |
|
1686 | Returns | |
1686 | ------- |
|
1687 | ------- | |
1687 | text : string |
|
1688 | text : string | |
1688 | The actual text that was completed. |
|
1689 | The actual text that was completed. | |
1689 |
|
1690 | |||
1690 | matches : list |
|
1691 | matches : list | |
1691 | A sorted list with all possible completions. |
|
1692 | A sorted list with all possible completions. | |
1692 |
|
1693 | |||
1693 | The optional arguments allow the completion to take more context into |
|
1694 | The optional arguments allow the completion to take more context into | |
1694 | account, and are part of the low-level completion API. |
|
1695 | account, and are part of the low-level completion API. | |
1695 |
|
1696 | |||
1696 | This is a wrapper around the completion mechanism, similar to what |
|
1697 | This is a wrapper around the completion mechanism, similar to what | |
1697 | readline does at the command line when the TAB key is hit. By |
|
1698 | readline does at the command line when the TAB key is hit. By | |
1698 | exposing it as a method, it can be used by other non-readline |
|
1699 | exposing it as a method, it can be used by other non-readline | |
1699 | environments (such as GUIs) for text completion. |
|
1700 | environments (such as GUIs) for text completion. | |
1700 |
|
1701 | |||
1701 | Simple usage example: |
|
1702 | Simple usage example: | |
1702 |
|
1703 | |||
1703 | In [1]: x = 'hello' |
|
1704 | In [1]: x = 'hello' | |
1704 |
|
1705 | |||
1705 | In [2]: _ip.complete('x.l') |
|
1706 | In [2]: _ip.complete('x.l') | |
1706 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1707 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1707 | """ |
|
1708 | """ | |
1708 |
|
1709 | |||
1709 | # Inject names into __builtin__ so we can complete on the added names. |
|
1710 | # Inject names into __builtin__ so we can complete on the added names. | |
1710 | with self.builtin_trap: |
|
1711 | with self.builtin_trap: | |
1711 | return self.Completer.complete(text, line, cursor_pos) |
|
1712 | return self.Completer.complete(text, line, cursor_pos) | |
1712 |
|
1713 | |||
1713 | def set_custom_completer(self, completer, pos=0): |
|
1714 | def set_custom_completer(self, completer, pos=0): | |
1714 | """Adds a new custom completer function. |
|
1715 | """Adds a new custom completer function. | |
1715 |
|
1716 | |||
1716 | The position argument (defaults to 0) is the index in the completers |
|
1717 | The position argument (defaults to 0) is the index in the completers | |
1717 | list where you want the completer to be inserted.""" |
|
1718 | list where you want the completer to be inserted.""" | |
1718 |
|
1719 | |||
1719 | newcomp = types.MethodType(completer,self.Completer) |
|
1720 | newcomp = types.MethodType(completer,self.Completer) | |
1720 | self.Completer.matchers.insert(pos,newcomp) |
|
1721 | self.Completer.matchers.insert(pos,newcomp) | |
1721 |
|
1722 | |||
1722 | def set_readline_completer(self): |
|
1723 | def set_readline_completer(self): | |
1723 | """Reset readline's completer to be our own.""" |
|
1724 | """Reset readline's completer to be our own.""" | |
1724 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1725 | self.readline.set_completer(self.Completer.rlcomplete) | |
1725 |
|
1726 | |||
1726 | def set_completer_frame(self, frame=None): |
|
1727 | def set_completer_frame(self, frame=None): | |
1727 | """Set the frame of the completer.""" |
|
1728 | """Set the frame of the completer.""" | |
1728 | if frame: |
|
1729 | if frame: | |
1729 | self.Completer.namespace = frame.f_locals |
|
1730 | self.Completer.namespace = frame.f_locals | |
1730 | self.Completer.global_namespace = frame.f_globals |
|
1731 | self.Completer.global_namespace = frame.f_globals | |
1731 | else: |
|
1732 | else: | |
1732 | self.Completer.namespace = self.user_ns |
|
1733 | self.Completer.namespace = self.user_ns | |
1733 | self.Completer.global_namespace = self.user_global_ns |
|
1734 | self.Completer.global_namespace = self.user_global_ns | |
1734 |
|
1735 | |||
1735 | #------------------------------------------------------------------------- |
|
1736 | #------------------------------------------------------------------------- | |
1736 | # Things related to magics |
|
1737 | # Things related to magics | |
1737 | #------------------------------------------------------------------------- |
|
1738 | #------------------------------------------------------------------------- | |
1738 |
|
1739 | |||
1739 | def init_magics(self): |
|
1740 | def init_magics(self): | |
1740 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1741 | # FIXME: Move the color initialization to the DisplayHook, which | |
1741 | # should be split into a prompt manager and displayhook. We probably |
|
1742 | # should be split into a prompt manager and displayhook. We probably | |
1742 | # even need a centralize colors management object. |
|
1743 | # even need a centralize colors management object. | |
1743 | self.magic_colors(self.colors) |
|
1744 | self.magic_colors(self.colors) | |
1744 | # History was moved to a separate module |
|
1745 | # History was moved to a separate module | |
1745 | from . import history |
|
1746 | from . import history | |
1746 | history.init_ipython(self) |
|
1747 | history.init_ipython(self) | |
1747 |
|
1748 | |||
1748 | def magic(self,arg_s): |
|
1749 | def magic(self,arg_s): | |
1749 | """Call a magic function by name. |
|
1750 | """Call a magic function by name. | |
1750 |
|
1751 | |||
1751 | Input: a string containing the name of the magic function to call and |
|
1752 | Input: a string containing the name of the magic function to call and | |
1752 | any additional arguments to be passed to the magic. |
|
1753 | any additional arguments to be passed to the magic. | |
1753 |
|
1754 | |||
1754 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1755 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1755 | prompt: |
|
1756 | prompt: | |
1756 |
|
1757 | |||
1757 | In[1]: %name -opt foo bar |
|
1758 | In[1]: %name -opt foo bar | |
1758 |
|
1759 | |||
1759 | To call a magic without arguments, simply use magic('name'). |
|
1760 | To call a magic without arguments, simply use magic('name'). | |
1760 |
|
1761 | |||
1761 | This provides a proper Python function to call IPython's magics in any |
|
1762 | This provides a proper Python function to call IPython's magics in any | |
1762 | valid Python code you can type at the interpreter, including loops and |
|
1763 | valid Python code you can type at the interpreter, including loops and | |
1763 | compound statements. |
|
1764 | compound statements. | |
1764 | """ |
|
1765 | """ | |
1765 | args = arg_s.split(' ',1) |
|
1766 | args = arg_s.split(' ',1) | |
1766 | magic_name = args[0] |
|
1767 | magic_name = args[0] | |
1767 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1768 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1768 |
|
1769 | |||
1769 | try: |
|
1770 | try: | |
1770 | magic_args = args[1] |
|
1771 | magic_args = args[1] | |
1771 | except IndexError: |
|
1772 | except IndexError: | |
1772 | magic_args = '' |
|
1773 | magic_args = '' | |
1773 | fn = getattr(self,'magic_'+magic_name,None) |
|
1774 | fn = getattr(self,'magic_'+magic_name,None) | |
1774 | if fn is None: |
|
1775 | if fn is None: | |
1775 | error("Magic function `%s` not found." % magic_name) |
|
1776 | error("Magic function `%s` not found." % magic_name) | |
1776 | else: |
|
1777 | else: | |
1777 | magic_args = self.var_expand(magic_args,1) |
|
1778 | magic_args = self.var_expand(magic_args,1) | |
1778 | # Grab local namespace if we need it: |
|
1779 | # Grab local namespace if we need it: | |
1779 | if getattr(fn, "needs_local_scope", False): |
|
1780 | if getattr(fn, "needs_local_scope", False): | |
1780 | self._magic_locals = sys._getframe(1).f_locals |
|
1781 | self._magic_locals = sys._getframe(1).f_locals | |
1781 | with nested(self.builtin_trap,): |
|
1782 | with nested(self.builtin_trap,): | |
1782 | result = fn(magic_args) |
|
1783 | result = fn(magic_args) | |
1783 | # Ensure we're not keeping object references around: |
|
1784 | # Ensure we're not keeping object references around: | |
1784 | self._magic_locals = {} |
|
1785 | self._magic_locals = {} | |
1785 | return result |
|
1786 | return result | |
1786 |
|
1787 | |||
1787 | def define_magic(self, magicname, func): |
|
1788 | def define_magic(self, magicname, func): | |
1788 | """Expose own function as magic function for ipython |
|
1789 | """Expose own function as magic function for ipython | |
1789 |
|
1790 | |||
1790 | def foo_impl(self,parameter_s=''): |
|
1791 | def foo_impl(self,parameter_s=''): | |
1791 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1792 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1792 | print 'Magic function. Passed parameter is between < >:' |
|
1793 | print 'Magic function. Passed parameter is between < >:' | |
1793 | print '<%s>' % parameter_s |
|
1794 | print '<%s>' % parameter_s | |
1794 | print 'The self object is:',self |
|
1795 | print 'The self object is:',self | |
1795 |
|
1796 | |||
1796 | self.define_magic('foo',foo_impl) |
|
1797 | self.define_magic('foo',foo_impl) | |
1797 | """ |
|
1798 | """ | |
1798 |
|
1799 | |||
1799 | import new |
|
1800 | import new | |
1800 | im = types.MethodType(func,self) |
|
1801 | im = types.MethodType(func,self) | |
1801 | old = getattr(self, "magic_" + magicname, None) |
|
1802 | old = getattr(self, "magic_" + magicname, None) | |
1802 | setattr(self, "magic_" + magicname, im) |
|
1803 | setattr(self, "magic_" + magicname, im) | |
1803 | return old |
|
1804 | return old | |
1804 |
|
1805 | |||
1805 | #------------------------------------------------------------------------- |
|
1806 | #------------------------------------------------------------------------- | |
1806 | # Things related to macros |
|
1807 | # Things related to macros | |
1807 | #------------------------------------------------------------------------- |
|
1808 | #------------------------------------------------------------------------- | |
1808 |
|
1809 | |||
1809 | def define_macro(self, name, themacro): |
|
1810 | def define_macro(self, name, themacro): | |
1810 | """Define a new macro |
|
1811 | """Define a new macro | |
1811 |
|
1812 | |||
1812 | Parameters |
|
1813 | Parameters | |
1813 | ---------- |
|
1814 | ---------- | |
1814 | name : str |
|
1815 | name : str | |
1815 | The name of the macro. |
|
1816 | The name of the macro. | |
1816 | themacro : str or Macro |
|
1817 | themacro : str or Macro | |
1817 | The action to do upon invoking the macro. If a string, a new |
|
1818 | The action to do upon invoking the macro. If a string, a new | |
1818 | Macro object is created by passing the string to it. |
|
1819 | Macro object is created by passing the string to it. | |
1819 | """ |
|
1820 | """ | |
1820 |
|
1821 | |||
1821 | from IPython.core import macro |
|
1822 | from IPython.core import macro | |
1822 |
|
1823 | |||
1823 | if isinstance(themacro, basestring): |
|
1824 | if isinstance(themacro, basestring): | |
1824 | themacro = macro.Macro(themacro) |
|
1825 | themacro = macro.Macro(themacro) | |
1825 | if not isinstance(themacro, macro.Macro): |
|
1826 | if not isinstance(themacro, macro.Macro): | |
1826 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1827 | raise ValueError('A macro must be a string or a Macro instance.') | |
1827 | self.user_ns[name] = themacro |
|
1828 | self.user_ns[name] = themacro | |
1828 |
|
1829 | |||
1829 | #------------------------------------------------------------------------- |
|
1830 | #------------------------------------------------------------------------- | |
1830 | # Things related to the running of system commands |
|
1831 | # Things related to the running of system commands | |
1831 | #------------------------------------------------------------------------- |
|
1832 | #------------------------------------------------------------------------- | |
1832 |
|
1833 | |||
1833 | def system(self, cmd): |
|
1834 | def system(self, cmd): | |
1834 | """Call the given cmd in a subprocess. |
|
1835 | """Call the given cmd in a subprocess. | |
1835 |
|
1836 | |||
1836 | Parameters |
|
1837 | Parameters | |
1837 | ---------- |
|
1838 | ---------- | |
1838 | cmd : str |
|
1839 | cmd : str | |
1839 | Command to execute (can not end in '&', as bacground processes are |
|
1840 | Command to execute (can not end in '&', as bacground processes are | |
1840 | not supported. |
|
1841 | not supported. | |
1841 | """ |
|
1842 | """ | |
1842 | # We do not support backgrounding processes because we either use |
|
1843 | # We do not support backgrounding processes because we either use | |
1843 | # pexpect or pipes to read from. Users can always just call |
|
1844 | # pexpect or pipes to read from. Users can always just call | |
1844 | # os.system() if they really want a background process. |
|
1845 | # os.system() if they really want a background process. | |
1845 | if cmd.endswith('&'): |
|
1846 | if cmd.endswith('&'): | |
1846 | raise OSError("Background processes not supported.") |
|
1847 | raise OSError("Background processes not supported.") | |
1847 |
|
1848 | |||
1848 | return system(self.var_expand(cmd, depth=2)) |
|
1849 | return system(self.var_expand(cmd, depth=2)) | |
1849 |
|
1850 | |||
1850 | def getoutput(self, cmd, split=True): |
|
1851 | def getoutput(self, cmd, split=True): | |
1851 | """Get output (possibly including stderr) from a subprocess. |
|
1852 | """Get output (possibly including stderr) from a subprocess. | |
1852 |
|
1853 | |||
1853 | Parameters |
|
1854 | Parameters | |
1854 | ---------- |
|
1855 | ---------- | |
1855 | cmd : str |
|
1856 | cmd : str | |
1856 | Command to execute (can not end in '&', as background processes are |
|
1857 | Command to execute (can not end in '&', as background processes are | |
1857 | not supported. |
|
1858 | not supported. | |
1858 | split : bool, optional |
|
1859 | split : bool, optional | |
1859 |
|
1860 | |||
1860 | If True, split the output into an IPython SList. Otherwise, an |
|
1861 | If True, split the output into an IPython SList. Otherwise, an | |
1861 | IPython LSString is returned. These are objects similar to normal |
|
1862 | IPython LSString is returned. These are objects similar to normal | |
1862 | lists and strings, with a few convenience attributes for easier |
|
1863 | lists and strings, with a few convenience attributes for easier | |
1863 | manipulation of line-based output. You can use '?' on them for |
|
1864 | manipulation of line-based output. You can use '?' on them for | |
1864 | details. |
|
1865 | details. | |
1865 | """ |
|
1866 | """ | |
1866 | if cmd.endswith('&'): |
|
1867 | if cmd.endswith('&'): | |
1867 | raise OSError("Background processes not supported.") |
|
1868 | raise OSError("Background processes not supported.") | |
1868 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1869 | out = getoutput(self.var_expand(cmd, depth=2)) | |
1869 | if split: |
|
1870 | if split: | |
1870 | out = SList(out.splitlines()) |
|
1871 | out = SList(out.splitlines()) | |
1871 | else: |
|
1872 | else: | |
1872 | out = LSString(out) |
|
1873 | out = LSString(out) | |
1873 | return out |
|
1874 | return out | |
1874 |
|
1875 | |||
1875 | #------------------------------------------------------------------------- |
|
1876 | #------------------------------------------------------------------------- | |
1876 | # Things related to aliases |
|
1877 | # Things related to aliases | |
1877 | #------------------------------------------------------------------------- |
|
1878 | #------------------------------------------------------------------------- | |
1878 |
|
1879 | |||
1879 | def init_alias(self): |
|
1880 | def init_alias(self): | |
1880 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1881 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1881 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1882 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1882 |
|
1883 | |||
1883 | #------------------------------------------------------------------------- |
|
1884 | #------------------------------------------------------------------------- | |
1884 | # Things related to extensions and plugins |
|
1885 | # Things related to extensions and plugins | |
1885 | #------------------------------------------------------------------------- |
|
1886 | #------------------------------------------------------------------------- | |
1886 |
|
1887 | |||
1887 | def init_extension_manager(self): |
|
1888 | def init_extension_manager(self): | |
1888 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1889 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1889 |
|
1890 | |||
1890 | def init_plugin_manager(self): |
|
1891 | def init_plugin_manager(self): | |
1891 | self.plugin_manager = PluginManager(config=self.config) |
|
1892 | self.plugin_manager = PluginManager(config=self.config) | |
1892 |
|
1893 | |||
1893 | #------------------------------------------------------------------------- |
|
1894 | #------------------------------------------------------------------------- | |
1894 | # Things related to payloads |
|
1895 | # Things related to payloads | |
1895 | #------------------------------------------------------------------------- |
|
1896 | #------------------------------------------------------------------------- | |
1896 |
|
1897 | |||
1897 | def init_payload(self): |
|
1898 | def init_payload(self): | |
1898 | self.payload_manager = PayloadManager(config=self.config) |
|
1899 | self.payload_manager = PayloadManager(config=self.config) | |
1899 |
|
1900 | |||
1900 | #------------------------------------------------------------------------- |
|
1901 | #------------------------------------------------------------------------- | |
1901 | # Things related to the prefilter |
|
1902 | # Things related to the prefilter | |
1902 | #------------------------------------------------------------------------- |
|
1903 | #------------------------------------------------------------------------- | |
1903 |
|
1904 | |||
1904 | def init_prefilter(self): |
|
1905 | def init_prefilter(self): | |
1905 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1906 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1906 | # Ultimately this will be refactored in the new interpreter code, but |
|
1907 | # Ultimately this will be refactored in the new interpreter code, but | |
1907 | # for now, we should expose the main prefilter method (there's legacy |
|
1908 | # for now, we should expose the main prefilter method (there's legacy | |
1908 | # code out there that may rely on this). |
|
1909 | # code out there that may rely on this). | |
1909 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1910 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1910 |
|
1911 | |||
1911 | def auto_rewrite_input(self, cmd): |
|
1912 | def auto_rewrite_input(self, cmd): | |
1912 | """Print to the screen the rewritten form of the user's command. |
|
1913 | """Print to the screen the rewritten form of the user's command. | |
1913 |
|
1914 | |||
1914 | This shows visual feedback by rewriting input lines that cause |
|
1915 | This shows visual feedback by rewriting input lines that cause | |
1915 | automatic calling to kick in, like:: |
|
1916 | automatic calling to kick in, like:: | |
1916 |
|
1917 | |||
1917 | /f x |
|
1918 | /f x | |
1918 |
|
1919 | |||
1919 | into:: |
|
1920 | into:: | |
1920 |
|
1921 | |||
1921 | ------> f(x) |
|
1922 | ------> f(x) | |
1922 |
|
1923 | |||
1923 | after the user's input prompt. This helps the user understand that the |
|
1924 | after the user's input prompt. This helps the user understand that the | |
1924 | input line was transformed automatically by IPython. |
|
1925 | input line was transformed automatically by IPython. | |
1925 | """ |
|
1926 | """ | |
1926 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1927 | rw = self.displayhook.prompt1.auto_rewrite() + cmd | |
1927 |
|
1928 | |||
1928 | try: |
|
1929 | try: | |
1929 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1930 | # plain ascii works better w/ pyreadline, on some machines, so | |
1930 | # we use it and only print uncolored rewrite if we have unicode |
|
1931 | # we use it and only print uncolored rewrite if we have unicode | |
1931 | rw = str(rw) |
|
1932 | rw = str(rw) | |
1932 | print >> IPython.utils.io.Term.cout, rw |
|
1933 | print >> IPython.utils.io.Term.cout, rw | |
1933 | except UnicodeEncodeError: |
|
1934 | except UnicodeEncodeError: | |
1934 | print "------> " + cmd |
|
1935 | print "------> " + cmd | |
1935 |
|
1936 | |||
1936 | #------------------------------------------------------------------------- |
|
1937 | #------------------------------------------------------------------------- | |
1937 | # Things related to extracting values/expressions from kernel and user_ns |
|
1938 | # Things related to extracting values/expressions from kernel and user_ns | |
1938 | #------------------------------------------------------------------------- |
|
1939 | #------------------------------------------------------------------------- | |
1939 |
|
1940 | |||
1940 | def _simple_error(self): |
|
1941 | def _simple_error(self): | |
1941 | etype, value = sys.exc_info()[:2] |
|
1942 | etype, value = sys.exc_info()[:2] | |
1942 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1943 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1943 |
|
1944 | |||
1944 | def user_variables(self, names): |
|
1945 | def user_variables(self, names): | |
1945 | """Get a list of variable names from the user's namespace. |
|
1946 | """Get a list of variable names from the user's namespace. | |
1946 |
|
1947 | |||
1947 | Parameters |
|
1948 | Parameters | |
1948 | ---------- |
|
1949 | ---------- | |
1949 | names : list of strings |
|
1950 | names : list of strings | |
1950 | A list of names of variables to be read from the user namespace. |
|
1951 | A list of names of variables to be read from the user namespace. | |
1951 |
|
1952 | |||
1952 | Returns |
|
1953 | Returns | |
1953 | ------- |
|
1954 | ------- | |
1954 | A dict, keyed by the input names and with the repr() of each value. |
|
1955 | A dict, keyed by the input names and with the repr() of each value. | |
1955 | """ |
|
1956 | """ | |
1956 | out = {} |
|
1957 | out = {} | |
1957 | user_ns = self.user_ns |
|
1958 | user_ns = self.user_ns | |
1958 | for varname in names: |
|
1959 | for varname in names: | |
1959 | try: |
|
1960 | try: | |
1960 | value = repr(user_ns[varname]) |
|
1961 | value = repr(user_ns[varname]) | |
1961 | except: |
|
1962 | except: | |
1962 | value = self._simple_error() |
|
1963 | value = self._simple_error() | |
1963 | out[varname] = value |
|
1964 | out[varname] = value | |
1964 | return out |
|
1965 | return out | |
1965 |
|
1966 | |||
1966 | def user_expressions(self, expressions): |
|
1967 | def user_expressions(self, expressions): | |
1967 | """Evaluate a dict of expressions in the user's namespace. |
|
1968 | """Evaluate a dict of expressions in the user's namespace. | |
1968 |
|
1969 | |||
1969 | Parameters |
|
1970 | Parameters | |
1970 | ---------- |
|
1971 | ---------- | |
1971 | expressions : dict |
|
1972 | expressions : dict | |
1972 | A dict with string keys and string values. The expression values |
|
1973 | A dict with string keys and string values. The expression values | |
1973 | should be valid Python expressions, each of which will be evaluated |
|
1974 | should be valid Python expressions, each of which will be evaluated | |
1974 | in the user namespace. |
|
1975 | in the user namespace. | |
1975 |
|
1976 | |||
1976 | Returns |
|
1977 | Returns | |
1977 | ------- |
|
1978 | ------- | |
1978 | A dict, keyed like the input expressions dict, with the repr() of each |
|
1979 | A dict, keyed like the input expressions dict, with the repr() of each | |
1979 | value. |
|
1980 | value. | |
1980 | """ |
|
1981 | """ | |
1981 | out = {} |
|
1982 | out = {} | |
1982 | user_ns = self.user_ns |
|
1983 | user_ns = self.user_ns | |
1983 | global_ns = self.user_global_ns |
|
1984 | global_ns = self.user_global_ns | |
1984 | for key, expr in expressions.iteritems(): |
|
1985 | for key, expr in expressions.iteritems(): | |
1985 | try: |
|
1986 | try: | |
1986 | value = repr(eval(expr, global_ns, user_ns)) |
|
1987 | value = repr(eval(expr, global_ns, user_ns)) | |
1987 | except: |
|
1988 | except: | |
1988 | value = self._simple_error() |
|
1989 | value = self._simple_error() | |
1989 | out[key] = value |
|
1990 | out[key] = value | |
1990 | return out |
|
1991 | return out | |
1991 |
|
1992 | |||
1992 | #------------------------------------------------------------------------- |
|
1993 | #------------------------------------------------------------------------- | |
1993 | # Things related to the running of code |
|
1994 | # Things related to the running of code | |
1994 | #------------------------------------------------------------------------- |
|
1995 | #------------------------------------------------------------------------- | |
1995 |
|
1996 | |||
1996 | def ex(self, cmd): |
|
1997 | def ex(self, cmd): | |
1997 | """Execute a normal python statement in user namespace.""" |
|
1998 | """Execute a normal python statement in user namespace.""" | |
1998 | with nested(self.builtin_trap,): |
|
1999 | with nested(self.builtin_trap,): | |
1999 | exec cmd in self.user_global_ns, self.user_ns |
|
2000 | exec cmd in self.user_global_ns, self.user_ns | |
2000 |
|
2001 | |||
2001 | def ev(self, expr): |
|
2002 | def ev(self, expr): | |
2002 | """Evaluate python expression expr in user namespace. |
|
2003 | """Evaluate python expression expr in user namespace. | |
2003 |
|
2004 | |||
2004 | Returns the result of evaluation |
|
2005 | Returns the result of evaluation | |
2005 | """ |
|
2006 | """ | |
2006 | with nested(self.builtin_trap,): |
|
2007 | with nested(self.builtin_trap,): | |
2007 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2008 | return eval(expr, self.user_global_ns, self.user_ns) | |
2008 |
|
2009 | |||
2009 | def safe_execfile(self, fname, *where, **kw): |
|
2010 | def safe_execfile(self, fname, *where, **kw): | |
2010 | """A safe version of the builtin execfile(). |
|
2011 | """A safe version of the builtin execfile(). | |
2011 |
|
2012 | |||
2012 | This version will never throw an exception, but instead print |
|
2013 | This version will never throw an exception, but instead print | |
2013 | helpful error messages to the screen. This only works on pure |
|
2014 | helpful error messages to the screen. This only works on pure | |
2014 | Python files with the .py extension. |
|
2015 | Python files with the .py extension. | |
2015 |
|
2016 | |||
2016 | Parameters |
|
2017 | Parameters | |
2017 | ---------- |
|
2018 | ---------- | |
2018 | fname : string |
|
2019 | fname : string | |
2019 | The name of the file to be executed. |
|
2020 | The name of the file to be executed. | |
2020 | where : tuple |
|
2021 | where : tuple | |
2021 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2022 | One or two namespaces, passed to execfile() as (globals,locals). | |
2022 | If only one is given, it is passed as both. |
|
2023 | If only one is given, it is passed as both. | |
2023 | exit_ignore : bool (False) |
|
2024 | exit_ignore : bool (False) | |
2024 | If True, then silence SystemExit for non-zero status (it is always |
|
2025 | If True, then silence SystemExit for non-zero status (it is always | |
2025 | silenced for zero status, as it is so common). |
|
2026 | silenced for zero status, as it is so common). | |
2026 | """ |
|
2027 | """ | |
2027 | kw.setdefault('exit_ignore', False) |
|
2028 | kw.setdefault('exit_ignore', False) | |
2028 |
|
2029 | |||
2029 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2030 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2030 | # Make sure we have a .py file |
|
2031 | # Make sure we have a .py file | |
2031 | if not fname.endswith('.py'): |
|
2032 | if not fname.endswith('.py'): | |
2032 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2033 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2033 |
|
2034 | |||
2034 | # Make sure we can open the file |
|
2035 | # Make sure we can open the file | |
2035 | try: |
|
2036 | try: | |
2036 | with open(fname) as thefile: |
|
2037 | with open(fname) as thefile: | |
2037 | pass |
|
2038 | pass | |
2038 | except: |
|
2039 | except: | |
2039 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2040 | warn('Could not open file <%s> for safe execution.' % fname) | |
2040 | return |
|
2041 | return | |
2041 |
|
2042 | |||
2042 | # Find things also in current directory. This is needed to mimic the |
|
2043 | # Find things also in current directory. This is needed to mimic the | |
2043 | # behavior of running a script from the system command line, where |
|
2044 | # behavior of running a script from the system command line, where | |
2044 | # Python inserts the script's directory into sys.path |
|
2045 | # Python inserts the script's directory into sys.path | |
2045 | dname = os.path.dirname(fname) |
|
2046 | dname = os.path.dirname(fname) | |
2046 |
|
2047 | |||
2047 | if isinstance(fname, unicode): |
|
2048 | if isinstance(fname, unicode): | |
2048 | # execfile uses default encoding instead of filesystem encoding |
|
2049 | # execfile uses default encoding instead of filesystem encoding | |
2049 | # so unicode filenames will fail |
|
2050 | # so unicode filenames will fail | |
2050 | fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding()) |
|
2051 | fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding()) | |
2051 |
|
2052 | |||
2052 | with prepended_to_syspath(dname): |
|
2053 | with prepended_to_syspath(dname): | |
2053 | try: |
|
2054 | try: | |
2054 | execfile(fname,*where) |
|
2055 | execfile(fname,*where) | |
2055 | except SystemExit, status: |
|
2056 | except SystemExit, status: | |
2056 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2057 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2057 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2058 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2058 | # these are considered normal by the OS: |
|
2059 | # these are considered normal by the OS: | |
2059 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2060 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2060 | # 0 |
|
2061 | # 0 | |
2061 | # > python -c'import sys;sys.exit()'; echo $? |
|
2062 | # > python -c'import sys;sys.exit()'; echo $? | |
2062 | # 0 |
|
2063 | # 0 | |
2063 | # For other exit status, we show the exception unless |
|
2064 | # For other exit status, we show the exception unless | |
2064 | # explicitly silenced, but only in short form. |
|
2065 | # explicitly silenced, but only in short form. | |
2065 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2066 | if status.code not in (0, None) and not kw['exit_ignore']: | |
2066 | self.showtraceback(exception_only=True) |
|
2067 | self.showtraceback(exception_only=True) | |
2067 | except: |
|
2068 | except: | |
2068 | self.showtraceback() |
|
2069 | self.showtraceback() | |
2069 |
|
2070 | |||
2070 | def safe_execfile_ipy(self, fname): |
|
2071 | def safe_execfile_ipy(self, fname): | |
2071 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2072 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2072 |
|
2073 | |||
2073 | Parameters |
|
2074 | Parameters | |
2074 | ---------- |
|
2075 | ---------- | |
2075 | fname : str |
|
2076 | fname : str | |
2076 | The name of the file to execute. The filename must have a |
|
2077 | The name of the file to execute. The filename must have a | |
2077 | .ipy extension. |
|
2078 | .ipy extension. | |
2078 | """ |
|
2079 | """ | |
2079 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2080 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2080 |
|
2081 | |||
2081 | # Make sure we have a .py file |
|
2082 | # Make sure we have a .py file | |
2082 | if not fname.endswith('.ipy'): |
|
2083 | if not fname.endswith('.ipy'): | |
2083 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2084 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2084 |
|
2085 | |||
2085 | # Make sure we can open the file |
|
2086 | # Make sure we can open the file | |
2086 | try: |
|
2087 | try: | |
2087 | with open(fname) as thefile: |
|
2088 | with open(fname) as thefile: | |
2088 | pass |
|
2089 | pass | |
2089 | except: |
|
2090 | except: | |
2090 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2091 | warn('Could not open file <%s> for safe execution.' % fname) | |
2091 | return |
|
2092 | return | |
2092 |
|
2093 | |||
2093 | # Find things also in current directory. This is needed to mimic the |
|
2094 | # Find things also in current directory. This is needed to mimic the | |
2094 | # behavior of running a script from the system command line, where |
|
2095 | # behavior of running a script from the system command line, where | |
2095 | # Python inserts the script's directory into sys.path |
|
2096 | # Python inserts the script's directory into sys.path | |
2096 | dname = os.path.dirname(fname) |
|
2097 | dname = os.path.dirname(fname) | |
2097 |
|
2098 | |||
2098 | with prepended_to_syspath(dname): |
|
2099 | with prepended_to_syspath(dname): | |
2099 | try: |
|
2100 | try: | |
2100 | with open(fname) as thefile: |
|
2101 | with open(fname) as thefile: | |
2101 | # self.run_cell currently captures all exceptions |
|
2102 | # self.run_cell currently captures all exceptions | |
2102 | # raised in user code. It would be nice if there were |
|
2103 | # raised in user code. It would be nice if there were | |
2103 | # versions of runlines, execfile that did raise, so |
|
2104 | # versions of runlines, execfile that did raise, so | |
2104 | # we could catch the errors. |
|
2105 | # we could catch the errors. | |
2105 | self.run_cell(thefile.read(), store_history=False) |
|
2106 | self.run_cell(thefile.read(), store_history=False) | |
2106 | except: |
|
2107 | except: | |
2107 | self.showtraceback() |
|
2108 | self.showtraceback() | |
2108 | warn('Unknown failure executing file: <%s>' % fname) |
|
2109 | warn('Unknown failure executing file: <%s>' % fname) | |
2109 |
|
2110 | |||
2110 | def run_cell(self, cell, store_history=True): |
|
2111 | def run_cell(self, cell, store_history=True): | |
2111 | """Run a complete IPython cell. |
|
2112 | """Run a complete IPython cell. | |
2112 |
|
2113 | |||
2113 | Parameters |
|
2114 | Parameters | |
2114 | ---------- |
|
2115 | ---------- | |
2115 | cell : str |
|
2116 | cell : str | |
2116 | The code (including IPython code such as %magic functions) to run. |
|
2117 | The code (including IPython code such as %magic functions) to run. | |
2117 | store_history : bool |
|
2118 | store_history : bool | |
2118 | If True, the raw and translated cell will be stored in IPython's |
|
2119 | If True, the raw and translated cell will be stored in IPython's | |
2119 | history. For user code calling back into IPython's machinery, this |
|
2120 | history. For user code calling back into IPython's machinery, this | |
2120 | should be set to False. |
|
2121 | should be set to False. | |
2121 | """ |
|
2122 | """ | |
2122 | raw_cell = cell |
|
2123 | raw_cell = cell | |
2123 | with self.builtin_trap: |
|
2124 | with self.builtin_trap: | |
2124 | cell = self.prefilter_manager.prefilter_lines(cell) |
|
2125 | cell = self.prefilter_manager.prefilter_lines(cell) | |
2125 |
|
2126 | |||
2126 | # Store raw and processed history |
|
2127 | # Store raw and processed history | |
2127 | if store_history: |
|
2128 | if store_history: | |
2128 | self.history_manager.store_inputs(self.execution_count, |
|
2129 | self.history_manager.store_inputs(self.execution_count, | |
2129 | cell, raw_cell) |
|
2130 | cell, raw_cell) | |
2130 |
|
2131 | |||
2131 | self.logger.log(cell, raw_cell) |
|
2132 | self.logger.log(cell, raw_cell) | |
2132 |
|
2133 | |||
2133 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2134 | cell_name = self.compile.cache(cell, self.execution_count) | |
2134 |
|
2135 | |||
2135 | with self.display_trap: |
|
2136 | with self.display_trap: | |
2136 | try: |
|
2137 | try: | |
2137 | code_ast = ast.parse(cell, filename=cell_name) |
|
2138 | code_ast = ast.parse(cell, filename=cell_name) | |
2138 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2139 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2139 | # Case 1 |
|
2140 | # Case 1 | |
2140 | self.showsyntaxerror() |
|
2141 | self.showsyntaxerror() | |
2141 | self.execution_count += 1 |
|
2142 | self.execution_count += 1 | |
2142 | return None |
|
2143 | return None | |
2143 |
|
2144 | |||
2144 | interactivity = 'last' # Last node to be run interactive |
|
2145 | interactivity = 'last' # Last node to be run interactive | |
2145 | if len(cell.splitlines()) == 1: |
|
2146 | if len(cell.splitlines()) == 1: | |
2146 | interactivity = 'all' # Single line; run fully interactive |
|
2147 | interactivity = 'all' # Single line; run fully interactive | |
2147 |
|
2148 | |||
2148 | self.run_ast_nodes(code_ast.body, cell_name, interactivity) |
|
2149 | self.run_ast_nodes(code_ast.body, cell_name, interactivity) | |
2149 |
|
2150 | |||
2150 | if store_history: |
|
2151 | if store_history: | |
2151 | # Write output to the database. Does nothing unless |
|
2152 | # Write output to the database. Does nothing unless | |
2152 | # history output logging is enabled. |
|
2153 | # history output logging is enabled. | |
2153 | self.history_manager.store_output(self.execution_count) |
|
2154 | self.history_manager.store_output(self.execution_count) | |
2154 | # Each cell is a *single* input, regardless of how many lines it has |
|
2155 | # Each cell is a *single* input, regardless of how many lines it has | |
2155 | self.execution_count += 1 |
|
2156 | self.execution_count += 1 | |
2156 |
|
2157 | |||
2157 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last'): |
|
2158 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last'): | |
2158 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2159 | """Run a sequence of AST nodes. The execution mode depends on the | |
2159 | interactivity parameter. |
|
2160 | interactivity parameter. | |
2160 |
|
2161 | |||
2161 | Parameters |
|
2162 | Parameters | |
2162 | ---------- |
|
2163 | ---------- | |
2163 | nodelist : list |
|
2164 | nodelist : list | |
2164 | A sequence of AST nodes to run. |
|
2165 | A sequence of AST nodes to run. | |
2165 | cell_name : str |
|
2166 | cell_name : str | |
2166 | Will be passed to the compiler as the filename of the cell. Typically |
|
2167 | Will be passed to the compiler as the filename of the cell. Typically | |
2167 | the value returned by ip.compile.cache(cell). |
|
2168 | the value returned by ip.compile.cache(cell). | |
2168 | interactivity : str |
|
2169 | interactivity : str | |
2169 | 'all', 'last' or 'none', specifying which nodes should be run |
|
2170 | 'all', 'last' or 'none', specifying which nodes should be run | |
2170 | interactively (displaying output from expressions). Other values for |
|
2171 | interactively (displaying output from expressions). Other values for | |
2171 | this parameter will raise a ValueError. |
|
2172 | this parameter will raise a ValueError. | |
2172 | """ |
|
2173 | """ | |
2173 | if not nodelist: |
|
2174 | if not nodelist: | |
2174 | return |
|
2175 | return | |
2175 |
|
2176 | |||
2176 | if interactivity == 'none': |
|
2177 | if interactivity == 'none': | |
2177 | to_run_exec, to_run_interactive = nodelist, [] |
|
2178 | to_run_exec, to_run_interactive = nodelist, [] | |
2178 | elif interactivity == 'last': |
|
2179 | elif interactivity == 'last': | |
2179 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2180 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] | |
2180 | elif interactivity == 'all': |
|
2181 | elif interactivity == 'all': | |
2181 | to_run_exec, to_run_interactive = [], nodelist |
|
2182 | to_run_exec, to_run_interactive = [], nodelist | |
2182 | else: |
|
2183 | else: | |
2183 | raise ValueError("Interactivity was %r" % interactivity) |
|
2184 | raise ValueError("Interactivity was %r" % interactivity) | |
2184 |
|
2185 | |||
2185 | exec_count = self.execution_count |
|
2186 | exec_count = self.execution_count | |
2186 | if to_run_exec: |
|
2187 | if to_run_exec: | |
2187 | mod = ast.Module(to_run_exec) |
|
2188 | mod = ast.Module(to_run_exec) | |
2188 | self.code_to_run = code = self.compile(mod, cell_name, "exec") |
|
2189 | self.code_to_run = code = self.compile(mod, cell_name, "exec") | |
2189 | if self.run_code(code) == 1: |
|
2190 | if self.run_code(code) == 1: | |
2190 | return |
|
2191 | return | |
2191 |
|
2192 | |||
2192 | if to_run_interactive: |
|
2193 | if to_run_interactive: | |
2193 | mod = ast.Interactive(to_run_interactive) |
|
2194 | mod = ast.Interactive(to_run_interactive) | |
2194 | self.code_to_run = code = self.compile(mod, cell_name, "single") |
|
2195 | self.code_to_run = code = self.compile(mod, cell_name, "single") | |
2195 | return self.run_code(code) |
|
2196 | return self.run_code(code) | |
2196 |
|
2197 | |||
2197 |
|
2198 | |||
2198 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2199 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2199 | # input logic has been 100% moved to frontends and is stable. |
|
2200 | # input logic has been 100% moved to frontends and is stable. | |
2200 | def runlines(self, lines, clean=False): |
|
2201 | def runlines(self, lines, clean=False): | |
2201 | """Run a string of one or more lines of source. |
|
2202 | """Run a string of one or more lines of source. | |
2202 |
|
2203 | |||
2203 | This method is capable of running a string containing multiple source |
|
2204 | This method is capable of running a string containing multiple source | |
2204 | lines, as if they had been entered at the IPython prompt. Since it |
|
2205 | lines, as if they had been entered at the IPython prompt. Since it | |
2205 | exposes IPython's processing machinery, the given strings can contain |
|
2206 | exposes IPython's processing machinery, the given strings can contain | |
2206 | magic calls (%magic), special shell access (!cmd), etc. |
|
2207 | magic calls (%magic), special shell access (!cmd), etc. | |
2207 | """ |
|
2208 | """ | |
2208 |
|
2209 | |||
2209 | if not isinstance(lines, (list, tuple)): |
|
2210 | if not isinstance(lines, (list, tuple)): | |
2210 | lines = lines.splitlines() |
|
2211 | lines = lines.splitlines() | |
2211 |
|
2212 | |||
2212 | if clean: |
|
2213 | if clean: | |
2213 | lines = self._cleanup_ipy_script(lines) |
|
2214 | lines = self._cleanup_ipy_script(lines) | |
2214 |
|
2215 | |||
2215 | # We must start with a clean buffer, in case this is run from an |
|
2216 | # We must start with a clean buffer, in case this is run from an | |
2216 | # interactive IPython session (via a magic, for example). |
|
2217 | # interactive IPython session (via a magic, for example). | |
2217 | self.reset_buffer() |
|
2218 | self.reset_buffer() | |
2218 |
|
2219 | |||
2219 | # Since we will prefilter all lines, store the user's raw input too |
|
2220 | # Since we will prefilter all lines, store the user's raw input too | |
2220 | # before we apply any transformations |
|
2221 | # before we apply any transformations | |
2221 | self.buffer_raw[:] = [ l+'\n' for l in lines] |
|
2222 | self.buffer_raw[:] = [ l+'\n' for l in lines] | |
2222 |
|
2223 | |||
2223 | more = False |
|
2224 | more = False | |
2224 | prefilter_lines = self.prefilter_manager.prefilter_lines |
|
2225 | prefilter_lines = self.prefilter_manager.prefilter_lines | |
2225 | with nested(self.builtin_trap, self.display_trap): |
|
2226 | with nested(self.builtin_trap, self.display_trap): | |
2226 | for line in lines: |
|
2227 | for line in lines: | |
2227 | # skip blank lines so we don't mess up the prompt counter, but |
|
2228 | # skip blank lines so we don't mess up the prompt counter, but | |
2228 | # do NOT skip even a blank line if we are in a code block (more |
|
2229 | # do NOT skip even a blank line if we are in a code block (more | |
2229 | # is true) |
|
2230 | # is true) | |
2230 |
|
2231 | |||
2231 | if line or more: |
|
2232 | if line or more: | |
2232 | more = self.push_line(prefilter_lines(line, more)) |
|
2233 | more = self.push_line(prefilter_lines(line, more)) | |
2233 | # IPython's run_source returns None if there was an error |
|
2234 | # IPython's run_source returns None if there was an error | |
2234 | # compiling the code. This allows us to stop processing |
|
2235 | # compiling the code. This allows us to stop processing | |
2235 | # right away, so the user gets the error message at the |
|
2236 | # right away, so the user gets the error message at the | |
2236 | # right place. |
|
2237 | # right place. | |
2237 | if more is None: |
|
2238 | if more is None: | |
2238 | break |
|
2239 | break | |
2239 | # final newline in case the input didn't have it, so that the code |
|
2240 | # final newline in case the input didn't have it, so that the code | |
2240 | # actually does get executed |
|
2241 | # actually does get executed | |
2241 | if more: |
|
2242 | if more: | |
2242 | self.push_line('\n') |
|
2243 | self.push_line('\n') | |
2243 |
|
2244 | |||
2244 | def run_source(self, source, filename=None, |
|
2245 | def run_source(self, source, filename=None, | |
2245 | symbol='single', post_execute=True): |
|
2246 | symbol='single', post_execute=True): | |
2246 | """Compile and run some source in the interpreter. |
|
2247 | """Compile and run some source in the interpreter. | |
2247 |
|
2248 | |||
2248 | Arguments are as for compile_command(). |
|
2249 | Arguments are as for compile_command(). | |
2249 |
|
2250 | |||
2250 | One several things can happen: |
|
2251 | One several things can happen: | |
2251 |
|
2252 | |||
2252 | 1) The input is incorrect; compile_command() raised an |
|
2253 | 1) The input is incorrect; compile_command() raised an | |
2253 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2254 | exception (SyntaxError or OverflowError). A syntax traceback | |
2254 | will be printed by calling the showsyntaxerror() method. |
|
2255 | will be printed by calling the showsyntaxerror() method. | |
2255 |
|
2256 | |||
2256 | 2) The input is incomplete, and more input is required; |
|
2257 | 2) The input is incomplete, and more input is required; | |
2257 | compile_command() returned None. Nothing happens. |
|
2258 | compile_command() returned None. Nothing happens. | |
2258 |
|
2259 | |||
2259 | 3) The input is complete; compile_command() returned a code |
|
2260 | 3) The input is complete; compile_command() returned a code | |
2260 | object. The code is executed by calling self.run_code() (which |
|
2261 | object. The code is executed by calling self.run_code() (which | |
2261 | also handles run-time exceptions, except for SystemExit). |
|
2262 | also handles run-time exceptions, except for SystemExit). | |
2262 |
|
2263 | |||
2263 | The return value is: |
|
2264 | The return value is: | |
2264 |
|
2265 | |||
2265 | - True in case 2 |
|
2266 | - True in case 2 | |
2266 |
|
2267 | |||
2267 | - False in the other cases, unless an exception is raised, where |
|
2268 | - False in the other cases, unless an exception is raised, where | |
2268 | None is returned instead. This can be used by external callers to |
|
2269 | None is returned instead. This can be used by external callers to | |
2269 | know whether to continue feeding input or not. |
|
2270 | know whether to continue feeding input or not. | |
2270 |
|
2271 | |||
2271 | The return value can be used to decide whether to use sys.ps1 or |
|
2272 | The return value can be used to decide whether to use sys.ps1 or | |
2272 | sys.ps2 to prompt the next line.""" |
|
2273 | sys.ps2 to prompt the next line.""" | |
2273 |
|
2274 | |||
2274 | # We need to ensure that the source is unicode from here on. |
|
2275 | # We need to ensure that the source is unicode from here on. | |
2275 | if type(source)==str: |
|
2276 | if type(source)==str: | |
2276 | usource = source.decode(self.stdin_encoding) |
|
2277 | usource = source.decode(self.stdin_encoding) | |
2277 | else: |
|
2278 | else: | |
2278 | usource = source |
|
2279 | usource = source | |
2279 |
|
2280 | |||
2280 | if False: # dbg |
|
2281 | if False: # dbg | |
2281 | print 'Source:', repr(source) # dbg |
|
2282 | print 'Source:', repr(source) # dbg | |
2282 | print 'USource:', repr(usource) # dbg |
|
2283 | print 'USource:', repr(usource) # dbg | |
2283 | print 'type:', type(source) # dbg |
|
2284 | print 'type:', type(source) # dbg | |
2284 | print 'encoding', self.stdin_encoding # dbg |
|
2285 | print 'encoding', self.stdin_encoding # dbg | |
2285 |
|
2286 | |||
2286 | try: |
|
2287 | try: | |
2287 | code_name = self.compile.cache(usource, self.execution_count) |
|
2288 | code_name = self.compile.cache(usource, self.execution_count) | |
2288 | code = self.compile(usource, code_name, symbol) |
|
2289 | code = self.compile(usource, code_name, symbol) | |
2289 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2290 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2290 | # Case 1 |
|
2291 | # Case 1 | |
2291 | self.showsyntaxerror(filename) |
|
2292 | self.showsyntaxerror(filename) | |
2292 | return None |
|
2293 | return None | |
2293 |
|
2294 | |||
2294 | if code is None: |
|
2295 | if code is None: | |
2295 | # Case 2 |
|
2296 | # Case 2 | |
2296 | return True |
|
2297 | return True | |
2297 |
|
2298 | |||
2298 | # Case 3 |
|
2299 | # Case 3 | |
2299 | # We store the code object so that threaded shells and |
|
2300 | # We store the code object so that threaded shells and | |
2300 | # custom exception handlers can access all this info if needed. |
|
2301 | # custom exception handlers can access all this info if needed. | |
2301 | # The source corresponding to this can be obtained from the |
|
2302 | # The source corresponding to this can be obtained from the | |
2302 | # buffer attribute as '\n'.join(self.buffer). |
|
2303 | # buffer attribute as '\n'.join(self.buffer). | |
2303 | self.code_to_run = code |
|
2304 | self.code_to_run = code | |
2304 | # now actually execute the code object |
|
2305 | # now actually execute the code object | |
2305 | if self.run_code(code, post_execute) == 0: |
|
2306 | if self.run_code(code, post_execute) == 0: | |
2306 | return False |
|
2307 | return False | |
2307 | else: |
|
2308 | else: | |
2308 | return None |
|
2309 | return None | |
2309 |
|
2310 | |||
2310 | # For backwards compatibility |
|
2311 | # For backwards compatibility | |
2311 | runsource = run_source |
|
2312 | runsource = run_source | |
2312 |
|
2313 | |||
2313 | def run_code(self, code_obj, post_execute=True): |
|
2314 | def run_code(self, code_obj, post_execute=True): | |
2314 | """Execute a code object. |
|
2315 | """Execute a code object. | |
2315 |
|
2316 | |||
2316 | When an exception occurs, self.showtraceback() is called to display a |
|
2317 | When an exception occurs, self.showtraceback() is called to display a | |
2317 | traceback. |
|
2318 | traceback. | |
2318 |
|
2319 | |||
2319 | Return value: a flag indicating whether the code to be run completed |
|
2320 | Return value: a flag indicating whether the code to be run completed | |
2320 | successfully: |
|
2321 | successfully: | |
2321 |
|
2322 | |||
2322 | - 0: successful execution. |
|
2323 | - 0: successful execution. | |
2323 | - 1: an error occurred. |
|
2324 | - 1: an error occurred. | |
2324 | """ |
|
2325 | """ | |
2325 |
|
2326 | |||
2326 | # Set our own excepthook in case the user code tries to call it |
|
2327 | # Set our own excepthook in case the user code tries to call it | |
2327 | # directly, so that the IPython crash handler doesn't get triggered |
|
2328 | # directly, so that the IPython crash handler doesn't get triggered | |
2328 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2329 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2329 |
|
2330 | |||
2330 | # we save the original sys.excepthook in the instance, in case config |
|
2331 | # we save the original sys.excepthook in the instance, in case config | |
2331 | # code (such as magics) needs access to it. |
|
2332 | # code (such as magics) needs access to it. | |
2332 | self.sys_excepthook = old_excepthook |
|
2333 | self.sys_excepthook = old_excepthook | |
2333 | outflag = 1 # happens in more places, so it's easier as default |
|
2334 | outflag = 1 # happens in more places, so it's easier as default | |
2334 | try: |
|
2335 | try: | |
2335 | try: |
|
2336 | try: | |
2336 | self.hooks.pre_run_code_hook() |
|
2337 | self.hooks.pre_run_code_hook() | |
2337 | #rprint('Running code', repr(code_obj)) # dbg |
|
2338 | #rprint('Running code', repr(code_obj)) # dbg | |
2338 | exec code_obj in self.user_global_ns, self.user_ns |
|
2339 | exec code_obj in self.user_global_ns, self.user_ns | |
2339 | finally: |
|
2340 | finally: | |
2340 | # Reset our crash handler in place |
|
2341 | # Reset our crash handler in place | |
2341 | sys.excepthook = old_excepthook |
|
2342 | sys.excepthook = old_excepthook | |
2342 | except SystemExit: |
|
2343 | except SystemExit: | |
2343 | self.reset_buffer() |
|
2344 | self.reset_buffer() | |
2344 | self.showtraceback(exception_only=True) |
|
2345 | self.showtraceback(exception_only=True) | |
2345 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2346 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2346 | except self.custom_exceptions: |
|
2347 | except self.custom_exceptions: | |
2347 | etype,value,tb = sys.exc_info() |
|
2348 | etype,value,tb = sys.exc_info() | |
2348 | self.CustomTB(etype,value,tb) |
|
2349 | self.CustomTB(etype,value,tb) | |
2349 | except: |
|
2350 | except: | |
2350 | self.showtraceback() |
|
2351 | self.showtraceback() | |
2351 | else: |
|
2352 | else: | |
2352 | outflag = 0 |
|
2353 | outflag = 0 | |
2353 | if softspace(sys.stdout, 0): |
|
2354 | if softspace(sys.stdout, 0): | |
2354 |
|
2355 | |||
2355 |
|
2356 | |||
2356 | # Execute any registered post-execution functions. Here, any errors |
|
2357 | # Execute any registered post-execution functions. Here, any errors | |
2357 | # are reported only minimally and just on the terminal, because the |
|
2358 | # are reported only minimally and just on the terminal, because the | |
2358 | # main exception channel may be occupied with a user traceback. |
|
2359 | # main exception channel may be occupied with a user traceback. | |
2359 | # FIXME: we need to think this mechanism a little more carefully. |
|
2360 | # FIXME: we need to think this mechanism a little more carefully. | |
2360 | if post_execute: |
|
2361 | if post_execute: | |
2361 | for func in self._post_execute: |
|
2362 | for func in self._post_execute: | |
2362 | try: |
|
2363 | try: | |
2363 | func() |
|
2364 | func() | |
2364 | except: |
|
2365 | except: | |
2365 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ |
|
2366 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ | |
2366 | func |
|
2367 | func | |
2367 | print >> io.Term.cout, head |
|
2368 | print >> io.Term.cout, head | |
2368 | print >> io.Term.cout, self._simple_error() |
|
2369 | print >> io.Term.cout, self._simple_error() | |
2369 | print >> io.Term.cout, 'Removing from post_execute' |
|
2370 | print >> io.Term.cout, 'Removing from post_execute' | |
2370 | self._post_execute.remove(func) |
|
2371 | self._post_execute.remove(func) | |
2371 |
|
2372 | |||
2372 | # Flush out code object which has been run (and source) |
|
2373 | # Flush out code object which has been run (and source) | |
2373 | self.code_to_run = None |
|
2374 | self.code_to_run = None | |
2374 | return outflag |
|
2375 | return outflag | |
2375 |
|
2376 | |||
2376 | # For backwards compatibility |
|
2377 | # For backwards compatibility | |
2377 | runcode = run_code |
|
2378 | runcode = run_code | |
2378 |
|
2379 | |||
2379 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2380 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2380 | # input logic has been 100% moved to frontends and is stable. |
|
2381 | # input logic has been 100% moved to frontends and is stable. | |
2381 | def push_line(self, line): |
|
2382 | def push_line(self, line): | |
2382 | """Push a line to the interpreter. |
|
2383 | """Push a line to the interpreter. | |
2383 |
|
2384 | |||
2384 | The line should not have a trailing newline; it may have |
|
2385 | The line should not have a trailing newline; it may have | |
2385 | internal newlines. The line is appended to a buffer and the |
|
2386 | internal newlines. The line is appended to a buffer and the | |
2386 | interpreter's run_source() method is called with the |
|
2387 | interpreter's run_source() method is called with the | |
2387 | concatenated contents of the buffer as source. If this |
|
2388 | concatenated contents of the buffer as source. If this | |
2388 | indicates that the command was executed or invalid, the buffer |
|
2389 | indicates that the command was executed or invalid, the buffer | |
2389 | is reset; otherwise, the command is incomplete, and the buffer |
|
2390 | is reset; otherwise, the command is incomplete, and the buffer | |
2390 | is left as it was after the line was appended. The return |
|
2391 | is left as it was after the line was appended. The return | |
2391 | value is 1 if more input is required, 0 if the line was dealt |
|
2392 | value is 1 if more input is required, 0 if the line was dealt | |
2392 | with in some way (this is the same as run_source()). |
|
2393 | with in some way (this is the same as run_source()). | |
2393 | """ |
|
2394 | """ | |
2394 |
|
2395 | |||
2395 | # autoindent management should be done here, and not in the |
|
2396 | # autoindent management should be done here, and not in the | |
2396 | # interactive loop, since that one is only seen by keyboard input. We |
|
2397 | # interactive loop, since that one is only seen by keyboard input. We | |
2397 | # need this done correctly even for code run via runlines (which uses |
|
2398 | # need this done correctly even for code run via runlines (which uses | |
2398 | # push). |
|
2399 | # push). | |
2399 |
|
2400 | |||
2400 | #print 'push line: <%s>' % line # dbg |
|
2401 | #print 'push line: <%s>' % line # dbg | |
2401 | self.buffer.append(line) |
|
2402 | self.buffer.append(line) | |
2402 | full_source = '\n'.join(self.buffer) |
|
2403 | full_source = '\n'.join(self.buffer) | |
2403 | more = self.run_source(full_source, self.filename) |
|
2404 | more = self.run_source(full_source, self.filename) | |
2404 | if not more: |
|
2405 | if not more: | |
2405 | self.history_manager.store_inputs(self.execution_count, |
|
2406 | self.history_manager.store_inputs(self.execution_count, | |
2406 | '\n'.join(self.buffer_raw), full_source) |
|
2407 | '\n'.join(self.buffer_raw), full_source) | |
2407 | self.reset_buffer() |
|
2408 | self.reset_buffer() | |
2408 | self.execution_count += 1 |
|
2409 | self.execution_count += 1 | |
2409 | return more |
|
2410 | return more | |
2410 |
|
2411 | |||
2411 | def reset_buffer(self): |
|
2412 | def reset_buffer(self): | |
2412 | """Reset the input buffer.""" |
|
2413 | """Reset the input buffer.""" | |
2413 | self.buffer[:] = [] |
|
2414 | self.buffer[:] = [] | |
2414 | self.buffer_raw[:] = [] |
|
2415 | self.buffer_raw[:] = [] | |
2415 | self.input_splitter.reset() |
|
2416 | self.input_splitter.reset() | |
2416 |
|
2417 | |||
2417 | # For backwards compatibility |
|
2418 | # For backwards compatibility | |
2418 | resetbuffer = reset_buffer |
|
2419 | resetbuffer = reset_buffer | |
2419 |
|
2420 | |||
2420 | def _is_secondary_block_start(self, s): |
|
2421 | def _is_secondary_block_start(self, s): | |
2421 | if not s.endswith(':'): |
|
2422 | if not s.endswith(':'): | |
2422 | return False |
|
2423 | return False | |
2423 | if (s.startswith('elif') or |
|
2424 | if (s.startswith('elif') or | |
2424 | s.startswith('else') or |
|
2425 | s.startswith('else') or | |
2425 | s.startswith('except') or |
|
2426 | s.startswith('except') or | |
2426 | s.startswith('finally')): |
|
2427 | s.startswith('finally')): | |
2427 | return True |
|
2428 | return True | |
2428 |
|
2429 | |||
2429 | def _cleanup_ipy_script(self, script): |
|
2430 | def _cleanup_ipy_script(self, script): | |
2430 | """Make a script safe for self.runlines() |
|
2431 | """Make a script safe for self.runlines() | |
2431 |
|
2432 | |||
2432 | Currently, IPython is lines based, with blocks being detected by |
|
2433 | Currently, IPython is lines based, with blocks being detected by | |
2433 | empty lines. This is a problem for block based scripts that may |
|
2434 | empty lines. This is a problem for block based scripts that may | |
2434 | not have empty lines after blocks. This script adds those empty |
|
2435 | not have empty lines after blocks. This script adds those empty | |
2435 | lines to make scripts safe for running in the current line based |
|
2436 | lines to make scripts safe for running in the current line based | |
2436 | IPython. |
|
2437 | IPython. | |
2437 | """ |
|
2438 | """ | |
2438 | res = [] |
|
2439 | res = [] | |
2439 | lines = script.splitlines() |
|
2440 | lines = script.splitlines() | |
2440 | level = 0 |
|
2441 | level = 0 | |
2441 |
|
2442 | |||
2442 | for l in lines: |
|
2443 | for l in lines: | |
2443 | lstripped = l.lstrip() |
|
2444 | lstripped = l.lstrip() | |
2444 | stripped = l.strip() |
|
2445 | stripped = l.strip() | |
2445 | if not stripped: |
|
2446 | if not stripped: | |
2446 | continue |
|
2447 | continue | |
2447 | newlevel = len(l) - len(lstripped) |
|
2448 | newlevel = len(l) - len(lstripped) | |
2448 | if level > 0 and newlevel == 0 and \ |
|
2449 | if level > 0 and newlevel == 0 and \ | |
2449 | not self._is_secondary_block_start(stripped): |
|
2450 | not self._is_secondary_block_start(stripped): | |
2450 | # add empty line |
|
2451 | # add empty line | |
2451 | res.append('') |
|
2452 | res.append('') | |
2452 | res.append(l) |
|
2453 | res.append(l) | |
2453 | level = newlevel |
|
2454 | level = newlevel | |
2454 |
|
2455 | |||
2455 | return '\n'.join(res) + '\n' |
|
2456 | return '\n'.join(res) + '\n' | |
2456 |
|
2457 | |||
2457 | #------------------------------------------------------------------------- |
|
2458 | #------------------------------------------------------------------------- | |
2458 | # Things related to GUI support and pylab |
|
2459 | # Things related to GUI support and pylab | |
2459 | #------------------------------------------------------------------------- |
|
2460 | #------------------------------------------------------------------------- | |
2460 |
|
2461 | |||
2461 | def enable_pylab(self, gui=None): |
|
2462 | def enable_pylab(self, gui=None): | |
2462 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2463 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2463 |
|
2464 | |||
2464 | #------------------------------------------------------------------------- |
|
2465 | #------------------------------------------------------------------------- | |
2465 | # Utilities |
|
2466 | # Utilities | |
2466 | #------------------------------------------------------------------------- |
|
2467 | #------------------------------------------------------------------------- | |
2467 |
|
2468 | |||
2468 | def var_expand(self,cmd,depth=0): |
|
2469 | def var_expand(self,cmd,depth=0): | |
2469 | """Expand python variables in a string. |
|
2470 | """Expand python variables in a string. | |
2470 |
|
2471 | |||
2471 | The depth argument indicates how many frames above the caller should |
|
2472 | The depth argument indicates how many frames above the caller should | |
2472 | be walked to look for the local namespace where to expand variables. |
|
2473 | be walked to look for the local namespace where to expand variables. | |
2473 |
|
2474 | |||
2474 | The global namespace for expansion is always the user's interactive |
|
2475 | The global namespace for expansion is always the user's interactive | |
2475 | namespace. |
|
2476 | namespace. | |
2476 | """ |
|
2477 | """ | |
2477 | res = ItplNS(cmd, self.user_ns, # globals |
|
2478 | res = ItplNS(cmd, self.user_ns, # globals | |
2478 | # Skip our own frame in searching for locals: |
|
2479 | # Skip our own frame in searching for locals: | |
2479 | sys._getframe(depth+1).f_locals # locals |
|
2480 | sys._getframe(depth+1).f_locals # locals | |
2480 | ) |
|
2481 | ) | |
2481 | return str(res).decode(res.codec) |
|
2482 | return str(res).decode(res.codec) | |
2482 |
|
2483 | |||
2483 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2484 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2484 | """Make a new tempfile and return its filename. |
|
2485 | """Make a new tempfile and return its filename. | |
2485 |
|
2486 | |||
2486 | This makes a call to tempfile.mktemp, but it registers the created |
|
2487 | This makes a call to tempfile.mktemp, but it registers the created | |
2487 | filename internally so ipython cleans it up at exit time. |
|
2488 | filename internally so ipython cleans it up at exit time. | |
2488 |
|
2489 | |||
2489 | Optional inputs: |
|
2490 | Optional inputs: | |
2490 |
|
2491 | |||
2491 | - data(None): if data is given, it gets written out to the temp file |
|
2492 | - data(None): if data is given, it gets written out to the temp file | |
2492 | immediately, and the file is closed again.""" |
|
2493 | immediately, and the file is closed again.""" | |
2493 |
|
2494 | |||
2494 | filename = tempfile.mktemp('.py', prefix) |
|
2495 | filename = tempfile.mktemp('.py', prefix) | |
2495 | self.tempfiles.append(filename) |
|
2496 | self.tempfiles.append(filename) | |
2496 |
|
2497 | |||
2497 | if data: |
|
2498 | if data: | |
2498 | tmp_file = open(filename,'w') |
|
2499 | tmp_file = open(filename,'w') | |
2499 | tmp_file.write(data) |
|
2500 | tmp_file.write(data) | |
2500 | tmp_file.close() |
|
2501 | tmp_file.close() | |
2501 | return filename |
|
2502 | return filename | |
2502 |
|
2503 | |||
2503 | # TODO: This should be removed when Term is refactored. |
|
2504 | # TODO: This should be removed when Term is refactored. | |
2504 | def write(self,data): |
|
2505 | def write(self,data): | |
2505 | """Write a string to the default output""" |
|
2506 | """Write a string to the default output""" | |
2506 | io.Term.cout.write(data) |
|
2507 | io.Term.cout.write(data) | |
2507 |
|
2508 | |||
2508 | # TODO: This should be removed when Term is refactored. |
|
2509 | # TODO: This should be removed when Term is refactored. | |
2509 | def write_err(self,data): |
|
2510 | def write_err(self,data): | |
2510 | """Write a string to the default error output""" |
|
2511 | """Write a string to the default error output""" | |
2511 | io.Term.cerr.write(data) |
|
2512 | io.Term.cerr.write(data) | |
2512 |
|
2513 | |||
2513 | def ask_yes_no(self,prompt,default=True): |
|
2514 | def ask_yes_no(self,prompt,default=True): | |
2514 | if self.quiet: |
|
2515 | if self.quiet: | |
2515 | return True |
|
2516 | return True | |
2516 | return ask_yes_no(prompt,default) |
|
2517 | return ask_yes_no(prompt,default) | |
2517 |
|
2518 | |||
2518 | def show_usage(self): |
|
2519 | def show_usage(self): | |
2519 | """Show a usage message""" |
|
2520 | """Show a usage message""" | |
2520 | page.page(IPython.core.usage.interactive_usage) |
|
2521 | page.page(IPython.core.usage.interactive_usage) | |
2521 |
|
2522 | |||
2522 | def find_user_code(self, target, raw=True): |
|
2523 | def find_user_code(self, target, raw=True): | |
2523 | """Get a code string from history, file, or a string or macro. |
|
2524 | """Get a code string from history, file, or a string or macro. | |
2524 |
|
2525 | |||
2525 | This is mainly used by magic functions. |
|
2526 | This is mainly used by magic functions. | |
2526 |
|
2527 | |||
2527 | Parameters |
|
2528 | Parameters | |
2528 | ---------- |
|
2529 | ---------- | |
2529 | target : str |
|
2530 | target : str | |
2530 | A string specifying code to retrieve. This will be tried respectively |
|
2531 | A string specifying code to retrieve. This will be tried respectively | |
2531 | as: ranges of input history (see %history for syntax), a filename, or |
|
2532 | as: ranges of input history (see %history for syntax), a filename, or | |
2532 | an expression evaluating to a string or Macro in the user namespace. |
|
2533 | an expression evaluating to a string or Macro in the user namespace. | |
2533 | raw : bool |
|
2534 | raw : bool | |
2534 | If true (default), retrieve raw history. Has no effect on the other |
|
2535 | If true (default), retrieve raw history. Has no effect on the other | |
2535 | retrieval mechanisms. |
|
2536 | retrieval mechanisms. | |
2536 |
|
2537 | |||
2537 | Returns |
|
2538 | Returns | |
2538 | ------- |
|
2539 | ------- | |
2539 | A string of code. |
|
2540 | A string of code. | |
2540 |
|
2541 | |||
2541 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
2542 | ValueError is raised if nothing is found, and TypeError if it evaluates | |
2542 | to an object of another type. In each case, .args[0] is a printable |
|
2543 | to an object of another type. In each case, .args[0] is a printable | |
2543 | message. |
|
2544 | message. | |
2544 | """ |
|
2545 | """ | |
2545 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
2546 | code = self.extract_input_lines(target, raw=raw) # Grab history | |
2546 | if code: |
|
2547 | if code: | |
2547 | return code |
|
2548 | return code | |
2548 | if os.path.isfile(target): # Read file |
|
2549 | if os.path.isfile(target): # Read file | |
2549 | return open(target, "r").read() |
|
2550 | return open(target, "r").read() | |
2550 |
|
2551 | |||
2551 | try: # User namespace |
|
2552 | try: # User namespace | |
2552 | codeobj = eval(target, self.user_ns) |
|
2553 | codeobj = eval(target, self.user_ns) | |
2553 | except Exception: |
|
2554 | except Exception: | |
2554 | raise ValueError(("'%s' was not found in history, as a file, nor in" |
|
2555 | raise ValueError(("'%s' was not found in history, as a file, nor in" | |
2555 | " the user namespace.") % target) |
|
2556 | " the user namespace.") % target) | |
2556 | if isinstance(codeobj, basestring): |
|
2557 | if isinstance(codeobj, basestring): | |
2557 | return codeobj |
|
2558 | return codeobj | |
2558 | elif isinstance(codeobj, Macro): |
|
2559 | elif isinstance(codeobj, Macro): | |
2559 | return codeobj.value |
|
2560 | return codeobj.value | |
2560 |
|
2561 | |||
2561 | raise TypeError("%s is neither a string nor a macro." % target, |
|
2562 | raise TypeError("%s is neither a string nor a macro." % target, | |
2562 | codeobj) |
|
2563 | codeobj) | |
2563 |
|
2564 | |||
2564 | #------------------------------------------------------------------------- |
|
2565 | #------------------------------------------------------------------------- | |
2565 | # Things related to IPython exiting |
|
2566 | # Things related to IPython exiting | |
2566 | #------------------------------------------------------------------------- |
|
2567 | #------------------------------------------------------------------------- | |
2567 | def atexit_operations(self): |
|
2568 | def atexit_operations(self): | |
2568 | """This will be executed at the time of exit. |
|
2569 | """This will be executed at the time of exit. | |
2569 |
|
2570 | |||
2570 | Cleanup operations and saving of persistent data that is done |
|
2571 | Cleanup operations and saving of persistent data that is done | |
2571 | unconditionally by IPython should be performed here. |
|
2572 | unconditionally by IPython should be performed here. | |
2572 |
|
2573 | |||
2573 | For things that may depend on startup flags or platform specifics (such |
|
2574 | For things that may depend on startup flags or platform specifics (such | |
2574 | as having readline or not), register a separate atexit function in the |
|
2575 | as having readline or not), register a separate atexit function in the | |
2575 | code that has the appropriate information, rather than trying to |
|
2576 | code that has the appropriate information, rather than trying to | |
2576 | clutter |
|
2577 | clutter | |
2577 | """ |
|
2578 | """ | |
2578 | # Cleanup all tempfiles left around |
|
2579 | # Cleanup all tempfiles left around | |
2579 | for tfile in self.tempfiles: |
|
2580 | for tfile in self.tempfiles: | |
2580 | try: |
|
2581 | try: | |
2581 | os.unlink(tfile) |
|
2582 | os.unlink(tfile) | |
2582 | except OSError: |
|
2583 | except OSError: | |
2583 | pass |
|
2584 | pass | |
2584 |
|
2585 | |||
2585 | # Close the history session (this stores the end time and line count) |
|
2586 | # Close the history session (this stores the end time and line count) | |
2586 | self.history_manager.end_session() |
|
2587 | self.history_manager.end_session() | |
2587 |
|
2588 | |||
2588 | # Clear all user namespaces to release all references cleanly. |
|
2589 | # Clear all user namespaces to release all references cleanly. | |
2589 | self.reset(new_session=False) |
|
2590 | self.reset(new_session=False) | |
2590 |
|
2591 | |||
2591 | # Run user hooks |
|
2592 | # Run user hooks | |
2592 | self.hooks.shutdown_hook() |
|
2593 | self.hooks.shutdown_hook() | |
2593 |
|
2594 | |||
2594 | def cleanup(self): |
|
2595 | def cleanup(self): | |
2595 | self.restore_sys_module_state() |
|
2596 | self.restore_sys_module_state() | |
2596 |
|
2597 | |||
2597 |
|
2598 | |||
2598 | class InteractiveShellABC(object): |
|
2599 | class InteractiveShellABC(object): | |
2599 | """An abstract base class for InteractiveShell.""" |
|
2600 | """An abstract base class for InteractiveShell.""" | |
2600 | __metaclass__ = abc.ABCMeta |
|
2601 | __metaclass__ = abc.ABCMeta | |
2601 |
|
2602 | |||
2602 | InteractiveShellABC.register(InteractiveShell) |
|
2603 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,610 +1,616 b'' | |||||
1 | from __future__ import print_function |
|
1 | from __future__ import print_function | |
2 |
|
2 | |||
3 | # Standard library imports |
|
3 | # Standard library imports | |
4 | from collections import namedtuple |
|
4 | from collections import namedtuple | |
5 | import sys |
|
5 | import sys | |
6 | import time |
|
6 | import time | |
7 |
|
7 | |||
8 | # System library imports |
|
8 | # System library imports | |
9 | from pygments.lexers import PythonLexer |
|
9 | from pygments.lexers import PythonLexer | |
10 | from IPython.external.qt import QtCore, QtGui |
|
10 | from IPython.external.qt import QtCore, QtGui | |
11 |
|
11 | |||
12 | # Local imports |
|
12 | # Local imports | |
13 | from IPython.core.inputsplitter import InputSplitter, transform_classic_prompt |
|
13 | from IPython.core.inputsplitter import InputSplitter, transform_classic_prompt | |
14 | from IPython.core.oinspect import call_tip |
|
14 | from IPython.core.oinspect import call_tip | |
15 | from IPython.frontend.qt.base_frontend_mixin import BaseFrontendMixin |
|
15 | from IPython.frontend.qt.base_frontend_mixin import BaseFrontendMixin | |
16 | from IPython.utils.traitlets import Bool |
|
16 | from IPython.utils.traitlets import Bool | |
17 | from bracket_matcher import BracketMatcher |
|
17 | from bracket_matcher import BracketMatcher | |
18 | from call_tip_widget import CallTipWidget |
|
18 | from call_tip_widget import CallTipWidget | |
19 | from completion_lexer import CompletionLexer |
|
19 | from completion_lexer import CompletionLexer | |
20 | from history_console_widget import HistoryConsoleWidget |
|
20 | from history_console_widget import HistoryConsoleWidget | |
21 | from pygments_highlighter import PygmentsHighlighter |
|
21 | from pygments_highlighter import PygmentsHighlighter | |
22 |
|
22 | |||
23 |
|
23 | |||
24 | class FrontendHighlighter(PygmentsHighlighter): |
|
24 | class FrontendHighlighter(PygmentsHighlighter): | |
25 | """ A PygmentsHighlighter that can be turned on and off and that ignores |
|
25 | """ A PygmentsHighlighter that can be turned on and off and that ignores | |
26 | prompts. |
|
26 | prompts. | |
27 | """ |
|
27 | """ | |
28 |
|
28 | |||
29 | def __init__(self, frontend): |
|
29 | def __init__(self, frontend): | |
30 | super(FrontendHighlighter, self).__init__(frontend._control.document()) |
|
30 | super(FrontendHighlighter, self).__init__(frontend._control.document()) | |
31 | self._current_offset = 0 |
|
31 | self._current_offset = 0 | |
32 | self._frontend = frontend |
|
32 | self._frontend = frontend | |
33 | self.highlighting_on = False |
|
33 | self.highlighting_on = False | |
34 |
|
34 | |||
35 | def highlightBlock(self, string): |
|
35 | def highlightBlock(self, string): | |
36 | """ Highlight a block of text. Reimplemented to highlight selectively. |
|
36 | """ Highlight a block of text. Reimplemented to highlight selectively. | |
37 | """ |
|
37 | """ | |
38 | if not self.highlighting_on: |
|
38 | if not self.highlighting_on: | |
39 | return |
|
39 | return | |
40 |
|
40 | |||
41 | # The input to this function is a unicode string that may contain |
|
41 | # The input to this function is a unicode string that may contain | |
42 | # paragraph break characters, non-breaking spaces, etc. Here we acquire |
|
42 | # paragraph break characters, non-breaking spaces, etc. Here we acquire | |
43 | # the string as plain text so we can compare it. |
|
43 | # the string as plain text so we can compare it. | |
44 | current_block = self.currentBlock() |
|
44 | current_block = self.currentBlock() | |
45 | string = self._frontend._get_block_plain_text(current_block) |
|
45 | string = self._frontend._get_block_plain_text(current_block) | |
46 |
|
46 | |||
47 | # Decide whether to check for the regular or continuation prompt. |
|
47 | # Decide whether to check for the regular or continuation prompt. | |
48 | if current_block.contains(self._frontend._prompt_pos): |
|
48 | if current_block.contains(self._frontend._prompt_pos): | |
49 | prompt = self._frontend._prompt |
|
49 | prompt = self._frontend._prompt | |
50 | else: |
|
50 | else: | |
51 | prompt = self._frontend._continuation_prompt |
|
51 | prompt = self._frontend._continuation_prompt | |
52 |
|
52 | |||
53 | # Don't highlight the part of the string that contains the prompt. |
|
53 | # Don't highlight the part of the string that contains the prompt. | |
54 | if string.startswith(prompt): |
|
54 | if string.startswith(prompt): | |
55 | self._current_offset = len(prompt) |
|
55 | self._current_offset = len(prompt) | |
56 | string = string[len(prompt):] |
|
56 | string = string[len(prompt):] | |
57 | else: |
|
57 | else: | |
58 | self._current_offset = 0 |
|
58 | self._current_offset = 0 | |
59 |
|
59 | |||
60 | PygmentsHighlighter.highlightBlock(self, string) |
|
60 | PygmentsHighlighter.highlightBlock(self, string) | |
61 |
|
61 | |||
62 | def rehighlightBlock(self, block): |
|
62 | def rehighlightBlock(self, block): | |
63 | """ Reimplemented to temporarily enable highlighting if disabled. |
|
63 | """ Reimplemented to temporarily enable highlighting if disabled. | |
64 | """ |
|
64 | """ | |
65 | old = self.highlighting_on |
|
65 | old = self.highlighting_on | |
66 | self.highlighting_on = True |
|
66 | self.highlighting_on = True | |
67 | super(FrontendHighlighter, self).rehighlightBlock(block) |
|
67 | super(FrontendHighlighter, self).rehighlightBlock(block) | |
68 | self.highlighting_on = old |
|
68 | self.highlighting_on = old | |
69 |
|
69 | |||
70 | def setFormat(self, start, count, format): |
|
70 | def setFormat(self, start, count, format): | |
71 | """ Reimplemented to highlight selectively. |
|
71 | """ Reimplemented to highlight selectively. | |
72 | """ |
|
72 | """ | |
73 | start += self._current_offset |
|
73 | start += self._current_offset | |
74 | PygmentsHighlighter.setFormat(self, start, count, format) |
|
74 | PygmentsHighlighter.setFormat(self, start, count, format) | |
75 |
|
75 | |||
76 |
|
76 | |||
77 | class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin): |
|
77 | class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin): | |
78 | """ A Qt frontend for a generic Python kernel. |
|
78 | """ A Qt frontend for a generic Python kernel. | |
79 | """ |
|
79 | """ | |
80 |
|
80 | |||
81 | # An option and corresponding signal for overriding the default kernel |
|
81 | # An option and corresponding signal for overriding the default kernel | |
82 | # interrupt behavior. |
|
82 | # interrupt behavior. | |
83 | custom_interrupt = Bool(False) |
|
83 | custom_interrupt = Bool(False) | |
84 | custom_interrupt_requested = QtCore.Signal() |
|
84 | custom_interrupt_requested = QtCore.Signal() | |
85 |
|
85 | |||
86 | # An option and corresponding signals for overriding the default kernel |
|
86 | # An option and corresponding signals for overriding the default kernel | |
87 | # restart behavior. |
|
87 | # restart behavior. | |
88 | custom_restart = Bool(False) |
|
88 | custom_restart = Bool(False) | |
89 | custom_restart_kernel_died = QtCore.Signal(float) |
|
89 | custom_restart_kernel_died = QtCore.Signal(float) | |
90 | custom_restart_requested = QtCore.Signal() |
|
90 | custom_restart_requested = QtCore.Signal() | |
91 |
|
91 | |||
92 | # Emitted when a user visible 'execute_request' has been submitted to the |
|
92 | # Emitted when a user visible 'execute_request' has been submitted to the | |
93 | # kernel from the FrontendWidget. Contains the code to be executed. |
|
93 | # kernel from the FrontendWidget. Contains the code to be executed. | |
94 | executing = QtCore.Signal(object) |
|
94 | executing = QtCore.Signal(object) | |
95 |
|
95 | |||
96 | # Emitted when a user-visible 'execute_reply' has been received from the |
|
96 | # Emitted when a user-visible 'execute_reply' has been received from the | |
97 | # kernel and processed by the FrontendWidget. Contains the response message. |
|
97 | # kernel and processed by the FrontendWidget. Contains the response message. | |
98 | executed = QtCore.Signal(object) |
|
98 | executed = QtCore.Signal(object) | |
99 |
|
99 | |||
100 | # Emitted when an exit request has been received from the kernel. |
|
100 | # Emitted when an exit request has been received from the kernel. | |
101 | exit_requested = QtCore.Signal() |
|
101 | exit_requested = QtCore.Signal() | |
102 |
|
102 | |||
103 | # Protected class variables. |
|
103 | # Protected class variables. | |
104 | _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos']) |
|
104 | _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos']) | |
105 | _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos']) |
|
105 | _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos']) | |
106 | _ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind']) |
|
106 | _ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind']) | |
107 | _input_splitter_class = InputSplitter |
|
107 | _input_splitter_class = InputSplitter | |
108 | _local_kernel = False |
|
108 | _local_kernel = False | |
109 |
|
109 | |||
110 | #--------------------------------------------------------------------------- |
|
110 | #--------------------------------------------------------------------------- | |
111 | # 'object' interface |
|
111 | # 'object' interface | |
112 | #--------------------------------------------------------------------------- |
|
112 | #--------------------------------------------------------------------------- | |
113 |
|
113 | |||
114 | def __init__(self, *args, **kw): |
|
114 | def __init__(self, *args, **kw): | |
115 | super(FrontendWidget, self).__init__(*args, **kw) |
|
115 | super(FrontendWidget, self).__init__(*args, **kw) | |
116 |
|
116 | |||
117 | # FrontendWidget protected variables. |
|
117 | # FrontendWidget protected variables. | |
118 | self._bracket_matcher = BracketMatcher(self._control) |
|
118 | self._bracket_matcher = BracketMatcher(self._control) | |
119 | self._call_tip_widget = CallTipWidget(self._control) |
|
119 | self._call_tip_widget = CallTipWidget(self._control) | |
120 | self._completion_lexer = CompletionLexer(PythonLexer()) |
|
120 | self._completion_lexer = CompletionLexer(PythonLexer()) | |
121 | self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None) |
|
121 | self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None) | |
122 | self._hidden = False |
|
122 | self._hidden = False | |
123 | self._highlighter = FrontendHighlighter(self) |
|
123 | self._highlighter = FrontendHighlighter(self) | |
124 | self._input_splitter = self._input_splitter_class(input_mode='cell') |
|
124 | self._input_splitter = self._input_splitter_class(input_mode='cell') | |
125 | self._kernel_manager = None |
|
125 | self._kernel_manager = None | |
126 | self._request_info = {} |
|
126 | self._request_info = {} | |
127 |
|
127 | |||
128 | # Configure the ConsoleWidget. |
|
128 | # Configure the ConsoleWidget. | |
129 | self.tab_width = 4 |
|
129 | self.tab_width = 4 | |
130 | self._set_continuation_prompt('... ') |
|
130 | self._set_continuation_prompt('... ') | |
131 |
|
131 | |||
132 | # Configure the CallTipWidget. |
|
132 | # Configure the CallTipWidget. | |
133 | self._call_tip_widget.setFont(self.font) |
|
133 | self._call_tip_widget.setFont(self.font) | |
134 | self.font_changed.connect(self._call_tip_widget.setFont) |
|
134 | self.font_changed.connect(self._call_tip_widget.setFont) | |
135 |
|
135 | |||
136 | # Configure actions. |
|
136 | # Configure actions. | |
137 | action = self._copy_raw_action |
|
137 | action = self._copy_raw_action | |
138 | key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C |
|
138 | key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C | |
139 | action.setEnabled(False) |
|
139 | action.setEnabled(False) | |
140 | action.setShortcut(QtGui.QKeySequence(key)) |
|
140 | action.setShortcut(QtGui.QKeySequence(key)) | |
141 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) |
|
141 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) | |
142 | action.triggered.connect(self.copy_raw) |
|
142 | action.triggered.connect(self.copy_raw) | |
143 | self.copy_available.connect(action.setEnabled) |
|
143 | self.copy_available.connect(action.setEnabled) | |
144 | self.addAction(action) |
|
144 | self.addAction(action) | |
145 |
|
145 | |||
146 | # Connect signal handlers. |
|
146 | # Connect signal handlers. | |
147 | document = self._control.document() |
|
147 | document = self._control.document() | |
148 | document.contentsChange.connect(self._document_contents_change) |
|
148 | document.contentsChange.connect(self._document_contents_change) | |
149 |
|
149 | |||
150 | # Set flag for whether we are connected via localhost. |
|
150 | # Set flag for whether we are connected via localhost. | |
151 | self._local_kernel = kw.get('local_kernel', |
|
151 | self._local_kernel = kw.get('local_kernel', | |
152 | FrontendWidget._local_kernel) |
|
152 | FrontendWidget._local_kernel) | |
153 |
|
153 | |||
154 | #--------------------------------------------------------------------------- |
|
154 | #--------------------------------------------------------------------------- | |
155 | # 'ConsoleWidget' public interface |
|
155 | # 'ConsoleWidget' public interface | |
156 | #--------------------------------------------------------------------------- |
|
156 | #--------------------------------------------------------------------------- | |
157 |
|
157 | |||
158 | def copy(self): |
|
158 | def copy(self): | |
159 | """ Copy the currently selected text to the clipboard, removing prompts. |
|
159 | """ Copy the currently selected text to the clipboard, removing prompts. | |
160 | """ |
|
160 | """ | |
161 | text = self._control.textCursor().selection().toPlainText() |
|
161 | text = self._control.textCursor().selection().toPlainText() | |
162 | if text: |
|
162 | if text: | |
163 | lines = map(transform_classic_prompt, text.splitlines()) |
|
163 | lines = map(transform_classic_prompt, text.splitlines()) | |
164 | text = '\n'.join(lines) |
|
164 | text = '\n'.join(lines) | |
165 | QtGui.QApplication.clipboard().setText(text) |
|
165 | QtGui.QApplication.clipboard().setText(text) | |
166 |
|
166 | |||
167 | #--------------------------------------------------------------------------- |
|
167 | #--------------------------------------------------------------------------- | |
168 | # 'ConsoleWidget' abstract interface |
|
168 | # 'ConsoleWidget' abstract interface | |
169 | #--------------------------------------------------------------------------- |
|
169 | #--------------------------------------------------------------------------- | |
170 |
|
170 | |||
171 | def _is_complete(self, source, interactive): |
|
171 | def _is_complete(self, source, interactive): | |
172 | """ Returns whether 'source' can be completely processed and a new |
|
172 | """ Returns whether 'source' can be completely processed and a new | |
173 | prompt created. When triggered by an Enter/Return key press, |
|
173 | prompt created. When triggered by an Enter/Return key press, | |
174 | 'interactive' is True; otherwise, it is False. |
|
174 | 'interactive' is True; otherwise, it is False. | |
175 | """ |
|
175 | """ | |
176 | complete = self._input_splitter.push(source) |
|
176 | complete = self._input_splitter.push(source) | |
177 | if interactive: |
|
177 | if interactive: | |
178 | complete = not self._input_splitter.push_accepts_more() |
|
178 | complete = not self._input_splitter.push_accepts_more() | |
179 | return complete |
|
179 | return complete | |
180 |
|
180 | |||
181 | def _execute(self, source, hidden): |
|
181 | def _execute(self, source, hidden): | |
182 | """ Execute 'source'. If 'hidden', do not show any output. |
|
182 | """ Execute 'source'. If 'hidden', do not show any output. | |
183 |
|
183 | |||
184 | See parent class :meth:`execute` docstring for full details. |
|
184 | See parent class :meth:`execute` docstring for full details. | |
185 | """ |
|
185 | """ | |
186 | msg_id = self.kernel_manager.xreq_channel.execute(source, hidden) |
|
186 | msg_id = self.kernel_manager.xreq_channel.execute(source, hidden) | |
187 | self._request_info['execute'] = self._ExecutionRequest(msg_id, 'user') |
|
187 | self._request_info['execute'] = self._ExecutionRequest(msg_id, 'user') | |
188 | self._hidden = hidden |
|
188 | self._hidden = hidden | |
189 | if not hidden: |
|
189 | if not hidden: | |
190 | self.executing.emit(source) |
|
190 | self.executing.emit(source) | |
191 |
|
191 | |||
192 | def _prompt_started_hook(self): |
|
192 | def _prompt_started_hook(self): | |
193 | """ Called immediately after a new prompt is displayed. |
|
193 | """ Called immediately after a new prompt is displayed. | |
194 | """ |
|
194 | """ | |
195 | if not self._reading: |
|
195 | if not self._reading: | |
196 | self._highlighter.highlighting_on = True |
|
196 | self._highlighter.highlighting_on = True | |
197 |
|
197 | |||
198 | def _prompt_finished_hook(self): |
|
198 | def _prompt_finished_hook(self): | |
199 | """ Called immediately after a prompt is finished, i.e. when some input |
|
199 | """ Called immediately after a prompt is finished, i.e. when some input | |
200 | will be processed and a new prompt displayed. |
|
200 | will be processed and a new prompt displayed. | |
201 | """ |
|
201 | """ | |
202 | # Flush all state from the input splitter so the next round of |
|
202 | # Flush all state from the input splitter so the next round of | |
203 | # reading input starts with a clean buffer. |
|
203 | # reading input starts with a clean buffer. | |
204 | self._input_splitter.reset() |
|
204 | self._input_splitter.reset() | |
205 |
|
205 | |||
206 | if not self._reading: |
|
206 | if not self._reading: | |
207 | self._highlighter.highlighting_on = False |
|
207 | self._highlighter.highlighting_on = False | |
208 |
|
208 | |||
209 | def _tab_pressed(self): |
|
209 | def _tab_pressed(self): | |
210 | """ Called when the tab key is pressed. Returns whether to continue |
|
210 | """ Called when the tab key is pressed. Returns whether to continue | |
211 | processing the event. |
|
211 | processing the event. | |
212 | """ |
|
212 | """ | |
213 | # Perform tab completion if: |
|
213 | # Perform tab completion if: | |
214 | # 1) The cursor is in the input buffer. |
|
214 | # 1) The cursor is in the input buffer. | |
215 | # 2) There is a non-whitespace character before the cursor. |
|
215 | # 2) There is a non-whitespace character before the cursor. | |
216 | text = self._get_input_buffer_cursor_line() |
|
216 | text = self._get_input_buffer_cursor_line() | |
217 | if text is None: |
|
217 | if text is None: | |
218 | return False |
|
218 | return False | |
219 | complete = bool(text[:self._get_input_buffer_cursor_column()].strip()) |
|
219 | complete = bool(text[:self._get_input_buffer_cursor_column()].strip()) | |
220 | if complete: |
|
220 | if complete: | |
221 | self._complete() |
|
221 | self._complete() | |
222 | return not complete |
|
222 | return not complete | |
223 |
|
223 | |||
224 | #--------------------------------------------------------------------------- |
|
224 | #--------------------------------------------------------------------------- | |
225 | # 'ConsoleWidget' protected interface |
|
225 | # 'ConsoleWidget' protected interface | |
226 | #--------------------------------------------------------------------------- |
|
226 | #--------------------------------------------------------------------------- | |
227 |
|
227 | |||
228 | def _context_menu_make(self, pos): |
|
228 | def _context_menu_make(self, pos): | |
229 | """ Reimplemented to add an action for raw copy. |
|
229 | """ Reimplemented to add an action for raw copy. | |
230 | """ |
|
230 | """ | |
231 | menu = super(FrontendWidget, self)._context_menu_make(pos) |
|
231 | menu = super(FrontendWidget, self)._context_menu_make(pos) | |
232 | for before_action in menu.actions(): |
|
232 | for before_action in menu.actions(): | |
233 | if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ |
|
233 | if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ | |
234 | QtGui.QKeySequence.ExactMatch: |
|
234 | QtGui.QKeySequence.ExactMatch: | |
235 | menu.insertAction(before_action, self._copy_raw_action) |
|
235 | menu.insertAction(before_action, self._copy_raw_action) | |
236 | break |
|
236 | break | |
237 | return menu |
|
237 | return menu | |
238 |
|
238 | |||
239 | def _event_filter_console_keypress(self, event): |
|
239 | def _event_filter_console_keypress(self, event): | |
240 | """ Reimplemented for execution interruption and smart backspace. |
|
240 | """ Reimplemented for execution interruption and smart backspace. | |
241 | """ |
|
241 | """ | |
242 | key = event.key() |
|
242 | key = event.key() | |
243 | if self._control_key_down(event.modifiers(), include_command=False): |
|
243 | if self._control_key_down(event.modifiers(), include_command=False): | |
244 |
|
244 | |||
245 | if key == QtCore.Qt.Key_C and self._executing: |
|
245 | if key == QtCore.Qt.Key_C and self._executing: | |
246 | self.interrupt_kernel() |
|
246 | self.interrupt_kernel() | |
247 | return True |
|
247 | return True | |
248 |
|
248 | |||
249 | elif key == QtCore.Qt.Key_Period: |
|
249 | elif key == QtCore.Qt.Key_Period: | |
250 | message = 'Are you sure you want to restart the kernel?' |
|
250 | message = 'Are you sure you want to restart the kernel?' | |
251 | self.restart_kernel(message, now=False) |
|
251 | self.restart_kernel(message, now=False) | |
252 | return True |
|
252 | return True | |
253 |
|
253 | |||
254 | elif not event.modifiers() & QtCore.Qt.AltModifier: |
|
254 | elif not event.modifiers() & QtCore.Qt.AltModifier: | |
255 |
|
255 | |||
256 | # Smart backspace: remove four characters in one backspace if: |
|
256 | # Smart backspace: remove four characters in one backspace if: | |
257 | # 1) everything left of the cursor is whitespace |
|
257 | # 1) everything left of the cursor is whitespace | |
258 | # 2) the four characters immediately left of the cursor are spaces |
|
258 | # 2) the four characters immediately left of the cursor are spaces | |
259 | if key == QtCore.Qt.Key_Backspace: |
|
259 | if key == QtCore.Qt.Key_Backspace: | |
260 | col = self._get_input_buffer_cursor_column() |
|
260 | col = self._get_input_buffer_cursor_column() | |
261 | cursor = self._control.textCursor() |
|
261 | cursor = self._control.textCursor() | |
262 | if col > 3 and not cursor.hasSelection(): |
|
262 | if col > 3 and not cursor.hasSelection(): | |
263 | text = self._get_input_buffer_cursor_line()[:col] |
|
263 | text = self._get_input_buffer_cursor_line()[:col] | |
264 | if text.endswith(' ') and not text.strip(): |
|
264 | if text.endswith(' ') and not text.strip(): | |
265 | cursor.movePosition(QtGui.QTextCursor.Left, |
|
265 | cursor.movePosition(QtGui.QTextCursor.Left, | |
266 | QtGui.QTextCursor.KeepAnchor, 4) |
|
266 | QtGui.QTextCursor.KeepAnchor, 4) | |
267 | cursor.removeSelectedText() |
|
267 | cursor.removeSelectedText() | |
268 | return True |
|
268 | return True | |
269 |
|
269 | |||
270 | return super(FrontendWidget, self)._event_filter_console_keypress(event) |
|
270 | return super(FrontendWidget, self)._event_filter_console_keypress(event) | |
271 |
|
271 | |||
272 | def _insert_continuation_prompt(self, cursor): |
|
272 | def _insert_continuation_prompt(self, cursor): | |
273 | """ Reimplemented for auto-indentation. |
|
273 | """ Reimplemented for auto-indentation. | |
274 | """ |
|
274 | """ | |
275 | super(FrontendWidget, self)._insert_continuation_prompt(cursor) |
|
275 | super(FrontendWidget, self)._insert_continuation_prompt(cursor) | |
276 | cursor.insertText(' ' * self._input_splitter.indent_spaces) |
|
276 | cursor.insertText(' ' * self._input_splitter.indent_spaces) | |
277 |
|
277 | |||
278 | #--------------------------------------------------------------------------- |
|
278 | #--------------------------------------------------------------------------- | |
279 | # 'BaseFrontendMixin' abstract interface |
|
279 | # 'BaseFrontendMixin' abstract interface | |
280 | #--------------------------------------------------------------------------- |
|
280 | #--------------------------------------------------------------------------- | |
281 |
|
281 | |||
282 | def _handle_complete_reply(self, rep): |
|
282 | def _handle_complete_reply(self, rep): | |
283 | """ Handle replies for tab completion. |
|
283 | """ Handle replies for tab completion. | |
284 | """ |
|
284 | """ | |
285 | cursor = self._get_cursor() |
|
285 | cursor = self._get_cursor() | |
286 | info = self._request_info.get('complete') |
|
286 | info = self._request_info.get('complete') | |
287 | if info and info.id == rep['parent_header']['msg_id'] and \ |
|
287 | if info and info.id == rep['parent_header']['msg_id'] and \ | |
288 | info.pos == cursor.position(): |
|
288 | info.pos == cursor.position(): | |
289 | text = '.'.join(self._get_context()) |
|
289 | text = '.'.join(self._get_context()) | |
290 | cursor.movePosition(QtGui.QTextCursor.Left, n=len(text)) |
|
290 | cursor.movePosition(QtGui.QTextCursor.Left, n=len(text)) | |
291 | self._complete_with_items(cursor, rep['content']['matches']) |
|
291 | self._complete_with_items(cursor, rep['content']['matches']) | |
292 |
|
292 | |||
293 | def _handle_execute_reply(self, msg): |
|
293 | def _handle_execute_reply(self, msg): | |
294 | """ Handles replies for code execution. |
|
294 | """ Handles replies for code execution. | |
295 | """ |
|
295 | """ | |
296 | info = self._request_info.get('execute') |
|
296 | info = self._request_info.get('execute') | |
297 | if info and info.id == msg['parent_header']['msg_id'] and \ |
|
297 | if info and info.id == msg['parent_header']['msg_id'] and \ | |
298 | info.kind == 'user' and not self._hidden: |
|
298 | info.kind == 'user' and not self._hidden: | |
299 | # Make sure that all output from the SUB channel has been processed |
|
299 | # Make sure that all output from the SUB channel has been processed | |
300 | # before writing a new prompt. |
|
300 | # before writing a new prompt. | |
301 | self.kernel_manager.sub_channel.flush() |
|
301 | self.kernel_manager.sub_channel.flush() | |
302 |
|
302 | |||
303 | # Reset the ANSI style information to prevent bad text in stdout |
|
303 | # Reset the ANSI style information to prevent bad text in stdout | |
304 | # from messing up our colors. We're not a true terminal so we're |
|
304 | # from messing up our colors. We're not a true terminal so we're | |
305 | # allowed to do this. |
|
305 | # allowed to do this. | |
306 | if self.ansi_codes: |
|
306 | if self.ansi_codes: | |
307 | self._ansi_processor.reset_sgr() |
|
307 | self._ansi_processor.reset_sgr() | |
308 |
|
308 | |||
309 | content = msg['content'] |
|
309 | content = msg['content'] | |
310 | status = content['status'] |
|
310 | status = content['status'] | |
311 | if status == 'ok': |
|
311 | if status == 'ok': | |
312 | self._process_execute_ok(msg) |
|
312 | self._process_execute_ok(msg) | |
313 | elif status == 'error': |
|
313 | elif status == 'error': | |
314 | self._process_execute_error(msg) |
|
314 | self._process_execute_error(msg) | |
315 | elif status == 'abort': |
|
315 | elif status == 'abort': | |
316 | self._process_execute_abort(msg) |
|
316 | self._process_execute_abort(msg) | |
317 |
|
317 | |||
318 | self._show_interpreter_prompt_for_reply(msg) |
|
318 | self._show_interpreter_prompt_for_reply(msg) | |
319 | self.executed.emit(msg) |
|
319 | self.executed.emit(msg) | |
320 |
|
320 | |||
321 | def _handle_input_request(self, msg): |
|
321 | def _handle_input_request(self, msg): | |
322 | """ Handle requests for raw_input. |
|
322 | """ Handle requests for raw_input. | |
323 | """ |
|
323 | """ | |
324 | if self._hidden: |
|
324 | if self._hidden: | |
325 | raise RuntimeError('Request for raw input during hidden execution.') |
|
325 | raise RuntimeError('Request for raw input during hidden execution.') | |
326 |
|
326 | |||
327 | # Make sure that all output from the SUB channel has been processed |
|
327 | # Make sure that all output from the SUB channel has been processed | |
328 | # before entering readline mode. |
|
328 | # before entering readline mode. | |
329 | self.kernel_manager.sub_channel.flush() |
|
329 | self.kernel_manager.sub_channel.flush() | |
330 |
|
330 | |||
331 | def callback(line): |
|
331 | def callback(line): | |
332 | self.kernel_manager.rep_channel.input(line) |
|
332 | self.kernel_manager.rep_channel.input(line) | |
333 | self._readline(msg['content']['prompt'], callback=callback) |
|
333 | self._readline(msg['content']['prompt'], callback=callback) | |
334 |
|
334 | |||
335 | def _handle_kernel_died(self, since_last_heartbeat): |
|
335 | def _handle_kernel_died(self, since_last_heartbeat): | |
336 | """ Handle the kernel's death by asking if the user wants to restart. |
|
336 | """ Handle the kernel's death by asking if the user wants to restart. | |
337 | """ |
|
337 | """ | |
338 | if self.custom_restart: |
|
338 | if self.custom_restart: | |
339 | self.custom_restart_kernel_died.emit(since_last_heartbeat) |
|
339 | self.custom_restart_kernel_died.emit(since_last_heartbeat) | |
340 | else: |
|
340 | else: | |
341 | message = 'The kernel heartbeat has been inactive for %.2f ' \ |
|
341 | message = 'The kernel heartbeat has been inactive for %.2f ' \ | |
342 | 'seconds. Do you want to restart the kernel? You may ' \ |
|
342 | 'seconds. Do you want to restart the kernel? You may ' \ | |
343 | 'first want to check the network connection.' % \ |
|
343 | 'first want to check the network connection.' % \ | |
344 | since_last_heartbeat |
|
344 | since_last_heartbeat | |
345 | self.restart_kernel(message, now=True) |
|
345 | self.restart_kernel(message, now=True) | |
346 |
|
346 | |||
347 | def _handle_object_info_reply(self, rep): |
|
347 | def _handle_object_info_reply(self, rep): | |
348 | """ Handle replies for call tips. |
|
348 | """ Handle replies for call tips. | |
349 | """ |
|
349 | """ | |
350 | cursor = self._get_cursor() |
|
350 | cursor = self._get_cursor() | |
351 | info = self._request_info.get('call_tip') |
|
351 | info = self._request_info.get('call_tip') | |
352 | if info and info.id == rep['parent_header']['msg_id'] and \ |
|
352 | if info and info.id == rep['parent_header']['msg_id'] and \ | |
353 | info.pos == cursor.position(): |
|
353 | info.pos == cursor.position(): | |
354 | # Get the information for a call tip. For now we format the call |
|
354 | # Get the information for a call tip. For now we format the call | |
355 | # line as string, later we can pass False to format_call and |
|
355 | # line as string, later we can pass False to format_call and | |
356 | # syntax-highlight it ourselves for nicer formatting in the |
|
356 | # syntax-highlight it ourselves for nicer formatting in the | |
357 | # calltip. |
|
357 | # calltip. | |
358 | call_info, doc = call_tip(rep['content'], format_call=True) |
|
358 | if rep['content']['ismagic']: | |
|
359 | # Don't generate a call-tip for magics. Ideally, we should | |||
|
360 | # generate a tooltip, but not on ( like we do for actual | |||
|
361 | # callables. | |||
|
362 | call_info, doc = None, None | |||
|
363 | else: | |||
|
364 | call_info, doc = call_tip(rep['content'], format_call=True) | |||
359 | if call_info or doc: |
|
365 | if call_info or doc: | |
360 | self._call_tip_widget.show_call_info(call_info, doc) |
|
366 | self._call_tip_widget.show_call_info(call_info, doc) | |
361 |
|
367 | |||
362 | def _handle_pyout(self, msg): |
|
368 | def _handle_pyout(self, msg): | |
363 | """ Handle display hook output. |
|
369 | """ Handle display hook output. | |
364 | """ |
|
370 | """ | |
365 | if not self._hidden and self._is_from_this_session(msg): |
|
371 | if not self._hidden and self._is_from_this_session(msg): | |
366 | self._append_plain_text(msg['content']['data']['text/plain'] + '\n') |
|
372 | self._append_plain_text(msg['content']['data']['text/plain'] + '\n') | |
367 |
|
373 | |||
368 | def _handle_stream(self, msg): |
|
374 | def _handle_stream(self, msg): | |
369 | """ Handle stdout, stderr, and stdin. |
|
375 | """ Handle stdout, stderr, and stdin. | |
370 | """ |
|
376 | """ | |
371 | if not self._hidden and self._is_from_this_session(msg): |
|
377 | if not self._hidden and self._is_from_this_session(msg): | |
372 | # Most consoles treat tabs as being 8 space characters. Convert tabs |
|
378 | # Most consoles treat tabs as being 8 space characters. Convert tabs | |
373 | # to spaces so that output looks as expected regardless of this |
|
379 | # to spaces so that output looks as expected regardless of this | |
374 | # widget's tab width. |
|
380 | # widget's tab width. | |
375 | text = msg['content']['data'].expandtabs(8) |
|
381 | text = msg['content']['data'].expandtabs(8) | |
376 |
|
382 | |||
377 | self._append_plain_text(text) |
|
383 | self._append_plain_text(text) | |
378 | self._control.moveCursor(QtGui.QTextCursor.End) |
|
384 | self._control.moveCursor(QtGui.QTextCursor.End) | |
379 |
|
385 | |||
380 | def _handle_shutdown_reply(self, msg): |
|
386 | def _handle_shutdown_reply(self, msg): | |
381 | """ Handle shutdown signal, only if from other console. |
|
387 | """ Handle shutdown signal, only if from other console. | |
382 | """ |
|
388 | """ | |
383 | if not self._hidden and not self._is_from_this_session(msg): |
|
389 | if not self._hidden and not self._is_from_this_session(msg): | |
384 | if self._local_kernel: |
|
390 | if self._local_kernel: | |
385 | if not msg['content']['restart']: |
|
391 | if not msg['content']['restart']: | |
386 | sys.exit(0) |
|
392 | sys.exit(0) | |
387 | else: |
|
393 | else: | |
388 | # we just got notified of a restart! |
|
394 | # we just got notified of a restart! | |
389 | time.sleep(0.25) # wait 1/4 sec to reset |
|
395 | time.sleep(0.25) # wait 1/4 sec to reset | |
390 | # lest the request for a new prompt |
|
396 | # lest the request for a new prompt | |
391 | # goes to the old kernel |
|
397 | # goes to the old kernel | |
392 | self.reset() |
|
398 | self.reset() | |
393 | else: # remote kernel, prompt on Kernel shutdown/reset |
|
399 | else: # remote kernel, prompt on Kernel shutdown/reset | |
394 | title = self.window().windowTitle() |
|
400 | title = self.window().windowTitle() | |
395 | if not msg['content']['restart']: |
|
401 | if not msg['content']['restart']: | |
396 | reply = QtGui.QMessageBox.question(self, title, |
|
402 | reply = QtGui.QMessageBox.question(self, title, | |
397 | "Kernel has been shutdown permanently. " |
|
403 | "Kernel has been shutdown permanently. " | |
398 | "Close the Console?", |
|
404 | "Close the Console?", | |
399 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) |
|
405 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) | |
400 | if reply == QtGui.QMessageBox.Yes: |
|
406 | if reply == QtGui.QMessageBox.Yes: | |
401 | sys.exit(0) |
|
407 | sys.exit(0) | |
402 | else: |
|
408 | else: | |
403 | reply = QtGui.QMessageBox.question(self, title, |
|
409 | reply = QtGui.QMessageBox.question(self, title, | |
404 | "Kernel has been reset. Clear the Console?", |
|
410 | "Kernel has been reset. Clear the Console?", | |
405 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) |
|
411 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) | |
406 | if reply == QtGui.QMessageBox.Yes: |
|
412 | if reply == QtGui.QMessageBox.Yes: | |
407 | time.sleep(0.25) # wait 1/4 sec to reset |
|
413 | time.sleep(0.25) # wait 1/4 sec to reset | |
408 | # lest the request for a new prompt |
|
414 | # lest the request for a new prompt | |
409 | # goes to the old kernel |
|
415 | # goes to the old kernel | |
410 | self.reset() |
|
416 | self.reset() | |
411 |
|
417 | |||
412 | def _started_channels(self): |
|
418 | def _started_channels(self): | |
413 | """ Called when the KernelManager channels have started listening or |
|
419 | """ Called when the KernelManager channels have started listening or | |
414 | when the frontend is assigned an already listening KernelManager. |
|
420 | when the frontend is assigned an already listening KernelManager. | |
415 | """ |
|
421 | """ | |
416 | self.reset() |
|
422 | self.reset() | |
417 |
|
423 | |||
418 | #--------------------------------------------------------------------------- |
|
424 | #--------------------------------------------------------------------------- | |
419 | # 'FrontendWidget' public interface |
|
425 | # 'FrontendWidget' public interface | |
420 | #--------------------------------------------------------------------------- |
|
426 | #--------------------------------------------------------------------------- | |
421 |
|
427 | |||
422 | def copy_raw(self): |
|
428 | def copy_raw(self): | |
423 | """ Copy the currently selected text to the clipboard without attempting |
|
429 | """ Copy the currently selected text to the clipboard without attempting | |
424 | to remove prompts or otherwise alter the text. |
|
430 | to remove prompts or otherwise alter the text. | |
425 | """ |
|
431 | """ | |
426 | self._control.copy() |
|
432 | self._control.copy() | |
427 |
|
433 | |||
428 | def execute_file(self, path, hidden=False): |
|
434 | def execute_file(self, path, hidden=False): | |
429 | """ Attempts to execute file with 'path'. If 'hidden', no output is |
|
435 | """ Attempts to execute file with 'path'. If 'hidden', no output is | |
430 | shown. |
|
436 | shown. | |
431 | """ |
|
437 | """ | |
432 | self.execute('execfile("%s")' % path, hidden=hidden) |
|
438 | self.execute('execfile("%s")' % path, hidden=hidden) | |
433 |
|
439 | |||
434 | def interrupt_kernel(self): |
|
440 | def interrupt_kernel(self): | |
435 | """ Attempts to interrupt the running kernel. |
|
441 | """ Attempts to interrupt the running kernel. | |
436 | """ |
|
442 | """ | |
437 | if self.custom_interrupt: |
|
443 | if self.custom_interrupt: | |
438 | self.custom_interrupt_requested.emit() |
|
444 | self.custom_interrupt_requested.emit() | |
439 | elif self.kernel_manager.has_kernel: |
|
445 | elif self.kernel_manager.has_kernel: | |
440 | self.kernel_manager.interrupt_kernel() |
|
446 | self.kernel_manager.interrupt_kernel() | |
441 | else: |
|
447 | else: | |
442 | self._append_plain_text('Kernel process is either remote or ' |
|
448 | self._append_plain_text('Kernel process is either remote or ' | |
443 | 'unspecified. Cannot interrupt.\n') |
|
449 | 'unspecified. Cannot interrupt.\n') | |
444 |
|
450 | |||
445 | def reset(self): |
|
451 | def reset(self): | |
446 | """ Resets the widget to its initial state. Similar to ``clear``, but |
|
452 | """ Resets the widget to its initial state. Similar to ``clear``, but | |
447 | also re-writes the banner and aborts execution if necessary. |
|
453 | also re-writes the banner and aborts execution if necessary. | |
448 | """ |
|
454 | """ | |
449 | if self._executing: |
|
455 | if self._executing: | |
450 | self._executing = False |
|
456 | self._executing = False | |
451 | self._request_info['execute'] = None |
|
457 | self._request_info['execute'] = None | |
452 | self._reading = False |
|
458 | self._reading = False | |
453 | self._highlighter.highlighting_on = False |
|
459 | self._highlighter.highlighting_on = False | |
454 |
|
460 | |||
455 | self._control.clear() |
|
461 | self._control.clear() | |
456 | self._append_plain_text(self._get_banner()) |
|
462 | self._append_plain_text(self._get_banner()) | |
457 | self._show_interpreter_prompt() |
|
463 | self._show_interpreter_prompt() | |
458 |
|
464 | |||
459 | def restart_kernel(self, message, now=False): |
|
465 | def restart_kernel(self, message, now=False): | |
460 | """ Attempts to restart the running kernel. |
|
466 | """ Attempts to restart the running kernel. | |
461 | """ |
|
467 | """ | |
462 | # FIXME: now should be configurable via a checkbox in the dialog. Right |
|
468 | # FIXME: now should be configurable via a checkbox in the dialog. Right | |
463 | # now at least the heartbeat path sets it to True and the manual restart |
|
469 | # now at least the heartbeat path sets it to True and the manual restart | |
464 | # to False. But those should just be the pre-selected states of a |
|
470 | # to False. But those should just be the pre-selected states of a | |
465 | # checkbox that the user could override if so desired. But I don't know |
|
471 | # checkbox that the user could override if so desired. But I don't know | |
466 | # enough Qt to go implementing the checkbox now. |
|
472 | # enough Qt to go implementing the checkbox now. | |
467 |
|
473 | |||
468 | if self.custom_restart: |
|
474 | if self.custom_restart: | |
469 | self.custom_restart_requested.emit() |
|
475 | self.custom_restart_requested.emit() | |
470 |
|
476 | |||
471 | elif self.kernel_manager.has_kernel: |
|
477 | elif self.kernel_manager.has_kernel: | |
472 | # Pause the heart beat channel to prevent further warnings. |
|
478 | # Pause the heart beat channel to prevent further warnings. | |
473 | self.kernel_manager.hb_channel.pause() |
|
479 | self.kernel_manager.hb_channel.pause() | |
474 |
|
480 | |||
475 | # Prompt the user to restart the kernel. Un-pause the heartbeat if |
|
481 | # Prompt the user to restart the kernel. Un-pause the heartbeat if | |
476 | # they decline. (If they accept, the heartbeat will be un-paused |
|
482 | # they decline. (If they accept, the heartbeat will be un-paused | |
477 | # automatically when the kernel is restarted.) |
|
483 | # automatically when the kernel is restarted.) | |
478 | buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No |
|
484 | buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | |
479 | result = QtGui.QMessageBox.question(self, 'Restart kernel?', |
|
485 | result = QtGui.QMessageBox.question(self, 'Restart kernel?', | |
480 | message, buttons) |
|
486 | message, buttons) | |
481 | if result == QtGui.QMessageBox.Yes: |
|
487 | if result == QtGui.QMessageBox.Yes: | |
482 | try: |
|
488 | try: | |
483 | self.kernel_manager.restart_kernel(now=now) |
|
489 | self.kernel_manager.restart_kernel(now=now) | |
484 | except RuntimeError: |
|
490 | except RuntimeError: | |
485 | self._append_plain_text('Kernel started externally. ' |
|
491 | self._append_plain_text('Kernel started externally. ' | |
486 | 'Cannot restart.\n') |
|
492 | 'Cannot restart.\n') | |
487 | else: |
|
493 | else: | |
488 | self.reset() |
|
494 | self.reset() | |
489 | else: |
|
495 | else: | |
490 | self.kernel_manager.hb_channel.unpause() |
|
496 | self.kernel_manager.hb_channel.unpause() | |
491 |
|
497 | |||
492 | else: |
|
498 | else: | |
493 | self._append_plain_text('Kernel process is either remote or ' |
|
499 | self._append_plain_text('Kernel process is either remote or ' | |
494 | 'unspecified. Cannot restart.\n') |
|
500 | 'unspecified. Cannot restart.\n') | |
495 |
|
501 | |||
496 | #--------------------------------------------------------------------------- |
|
502 | #--------------------------------------------------------------------------- | |
497 | # 'FrontendWidget' protected interface |
|
503 | # 'FrontendWidget' protected interface | |
498 | #--------------------------------------------------------------------------- |
|
504 | #--------------------------------------------------------------------------- | |
499 |
|
505 | |||
500 | def _call_tip(self): |
|
506 | def _call_tip(self): | |
501 | """ Shows a call tip, if appropriate, at the current cursor location. |
|
507 | """ Shows a call tip, if appropriate, at the current cursor location. | |
502 | """ |
|
508 | """ | |
503 | # Decide if it makes sense to show a call tip |
|
509 | # Decide if it makes sense to show a call tip | |
504 | cursor = self._get_cursor() |
|
510 | cursor = self._get_cursor() | |
505 | cursor.movePosition(QtGui.QTextCursor.Left) |
|
511 | cursor.movePosition(QtGui.QTextCursor.Left) | |
506 | if cursor.document().characterAt(cursor.position()) != '(': |
|
512 | if cursor.document().characterAt(cursor.position()) != '(': | |
507 | return False |
|
513 | return False | |
508 | context = self._get_context(cursor) |
|
514 | context = self._get_context(cursor) | |
509 | if not context: |
|
515 | if not context: | |
510 | return False |
|
516 | return False | |
511 |
|
517 | |||
512 | # Send the metadata request to the kernel |
|
518 | # Send the metadata request to the kernel | |
513 | name = '.'.join(context) |
|
519 | name = '.'.join(context) | |
514 | msg_id = self.kernel_manager.xreq_channel.object_info(name) |
|
520 | msg_id = self.kernel_manager.xreq_channel.object_info(name) | |
515 | pos = self._get_cursor().position() |
|
521 | pos = self._get_cursor().position() | |
516 | self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos) |
|
522 | self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos) | |
517 | return True |
|
523 | return True | |
518 |
|
524 | |||
519 | def _complete(self): |
|
525 | def _complete(self): | |
520 | """ Performs completion at the current cursor location. |
|
526 | """ Performs completion at the current cursor location. | |
521 | """ |
|
527 | """ | |
522 | context = self._get_context() |
|
528 | context = self._get_context() | |
523 | if context: |
|
529 | if context: | |
524 | # Send the completion request to the kernel |
|
530 | # Send the completion request to the kernel | |
525 | msg_id = self.kernel_manager.xreq_channel.complete( |
|
531 | msg_id = self.kernel_manager.xreq_channel.complete( | |
526 | '.'.join(context), # text |
|
532 | '.'.join(context), # text | |
527 | self._get_input_buffer_cursor_line(), # line |
|
533 | self._get_input_buffer_cursor_line(), # line | |
528 | self._get_input_buffer_cursor_column(), # cursor_pos |
|
534 | self._get_input_buffer_cursor_column(), # cursor_pos | |
529 | self.input_buffer) # block |
|
535 | self.input_buffer) # block | |
530 | pos = self._get_cursor().position() |
|
536 | pos = self._get_cursor().position() | |
531 | info = self._CompletionRequest(msg_id, pos) |
|
537 | info = self._CompletionRequest(msg_id, pos) | |
532 | self._request_info['complete'] = info |
|
538 | self._request_info['complete'] = info | |
533 |
|
539 | |||
534 | def _get_banner(self): |
|
540 | def _get_banner(self): | |
535 | """ Gets a banner to display at the beginning of a session. |
|
541 | """ Gets a banner to display at the beginning of a session. | |
536 | """ |
|
542 | """ | |
537 | banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \ |
|
543 | banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \ | |
538 | '"license" for more information.' |
|
544 | '"license" for more information.' | |
539 | return banner % (sys.version, sys.platform) |
|
545 | return banner % (sys.version, sys.platform) | |
540 |
|
546 | |||
541 | def _get_context(self, cursor=None): |
|
547 | def _get_context(self, cursor=None): | |
542 | """ Gets the context for the specified cursor (or the current cursor |
|
548 | """ Gets the context for the specified cursor (or the current cursor | |
543 | if none is specified). |
|
549 | if none is specified). | |
544 | """ |
|
550 | """ | |
545 | if cursor is None: |
|
551 | if cursor is None: | |
546 | cursor = self._get_cursor() |
|
552 | cursor = self._get_cursor() | |
547 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, |
|
553 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, | |
548 | QtGui.QTextCursor.KeepAnchor) |
|
554 | QtGui.QTextCursor.KeepAnchor) | |
549 | text = cursor.selection().toPlainText() |
|
555 | text = cursor.selection().toPlainText() | |
550 | return self._completion_lexer.get_context(text) |
|
556 | return self._completion_lexer.get_context(text) | |
551 |
|
557 | |||
552 | def _process_execute_abort(self, msg): |
|
558 | def _process_execute_abort(self, msg): | |
553 | """ Process a reply for an aborted execution request. |
|
559 | """ Process a reply for an aborted execution request. | |
554 | """ |
|
560 | """ | |
555 | self._append_plain_text("ERROR: execution aborted\n") |
|
561 | self._append_plain_text("ERROR: execution aborted\n") | |
556 |
|
562 | |||
557 | def _process_execute_error(self, msg): |
|
563 | def _process_execute_error(self, msg): | |
558 | """ Process a reply for an execution request that resulted in an error. |
|
564 | """ Process a reply for an execution request that resulted in an error. | |
559 | """ |
|
565 | """ | |
560 | content = msg['content'] |
|
566 | content = msg['content'] | |
561 | # If a SystemExit is passed along, this means exit() was called - also |
|
567 | # If a SystemExit is passed along, this means exit() was called - also | |
562 | # all the ipython %exit magic syntax of '-k' to be used to keep |
|
568 | # all the ipython %exit magic syntax of '-k' to be used to keep | |
563 | # the kernel running |
|
569 | # the kernel running | |
564 | if content['ename']=='SystemExit': |
|
570 | if content['ename']=='SystemExit': | |
565 | keepkernel = content['evalue']=='-k' or content['evalue']=='True' |
|
571 | keepkernel = content['evalue']=='-k' or content['evalue']=='True' | |
566 | self._keep_kernel_on_exit = keepkernel |
|
572 | self._keep_kernel_on_exit = keepkernel | |
567 | self.exit_requested.emit() |
|
573 | self.exit_requested.emit() | |
568 | else: |
|
574 | else: | |
569 | traceback = ''.join(content['traceback']) |
|
575 | traceback = ''.join(content['traceback']) | |
570 | self._append_plain_text(traceback) |
|
576 | self._append_plain_text(traceback) | |
571 |
|
577 | |||
572 | def _process_execute_ok(self, msg): |
|
578 | def _process_execute_ok(self, msg): | |
573 | """ Process a reply for a successful execution equest. |
|
579 | """ Process a reply for a successful execution equest. | |
574 | """ |
|
580 | """ | |
575 | payload = msg['content']['payload'] |
|
581 | payload = msg['content']['payload'] | |
576 | for item in payload: |
|
582 | for item in payload: | |
577 | if not self._process_execute_payload(item): |
|
583 | if not self._process_execute_payload(item): | |
578 | warning = 'Warning: received unknown payload of type %s' |
|
584 | warning = 'Warning: received unknown payload of type %s' | |
579 | print(warning % repr(item['source'])) |
|
585 | print(warning % repr(item['source'])) | |
580 |
|
586 | |||
581 | def _process_execute_payload(self, item): |
|
587 | def _process_execute_payload(self, item): | |
582 | """ Process a single payload item from the list of payload items in an |
|
588 | """ Process a single payload item from the list of payload items in an | |
583 | execution reply. Returns whether the payload was handled. |
|
589 | execution reply. Returns whether the payload was handled. | |
584 | """ |
|
590 | """ | |
585 | # The basic FrontendWidget doesn't handle payloads, as they are a |
|
591 | # The basic FrontendWidget doesn't handle payloads, as they are a | |
586 | # mechanism for going beyond the standard Python interpreter model. |
|
592 | # mechanism for going beyond the standard Python interpreter model. | |
587 | return False |
|
593 | return False | |
588 |
|
594 | |||
589 | def _show_interpreter_prompt(self): |
|
595 | def _show_interpreter_prompt(self): | |
590 | """ Shows a prompt for the interpreter. |
|
596 | """ Shows a prompt for the interpreter. | |
591 | """ |
|
597 | """ | |
592 | self._show_prompt('>>> ') |
|
598 | self._show_prompt('>>> ') | |
593 |
|
599 | |||
594 | def _show_interpreter_prompt_for_reply(self, msg): |
|
600 | def _show_interpreter_prompt_for_reply(self, msg): | |
595 | """ Shows a prompt for the interpreter given an 'execute_reply' message. |
|
601 | """ Shows a prompt for the interpreter given an 'execute_reply' message. | |
596 | """ |
|
602 | """ | |
597 | self._show_interpreter_prompt() |
|
603 | self._show_interpreter_prompt() | |
598 |
|
604 | |||
599 | #------ Signal handlers ---------------------------------------------------- |
|
605 | #------ Signal handlers ---------------------------------------------------- | |
600 |
|
606 | |||
601 | def _document_contents_change(self, position, removed, added): |
|
607 | def _document_contents_change(self, position, removed, added): | |
602 | """ Called whenever the document's content changes. Display a call tip |
|
608 | """ Called whenever the document's content changes. Display a call tip | |
603 | if appropriate. |
|
609 | if appropriate. | |
604 | """ |
|
610 | """ | |
605 | # Calculate where the cursor should be *after* the change: |
|
611 | # Calculate where the cursor should be *after* the change: | |
606 | position += added |
|
612 | position += added | |
607 |
|
613 | |||
608 | document = self._control.document() |
|
614 | document = self._control.document() | |
609 | if position == self._get_cursor().position(): |
|
615 | if position == self._get_cursor().position(): | |
610 | self._call_tip() |
|
616 | self._call_tip() |
General Comments 0
You need to be logged in to leave comments.
Login now