Show More
@@ -1,590 +1,593 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Subclass of InteractiveShell for terminal based frontends.""" |
|
2 | """Subclass of InteractiveShell for terminal based frontends.""" | |
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-2010 The IPython Development Team |
|
7 | # Copyright (C) 2008-2010 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 | import __builtin__ |
|
17 | import __builtin__ | |
18 | import bdb |
|
18 | import bdb | |
19 | from contextlib import nested |
|
19 | from contextlib import nested | |
20 | import os |
|
20 | import os | |
21 | import re |
|
21 | import re | |
22 | import sys |
|
22 | import sys | |
23 |
|
23 | |||
24 | from IPython.core.error import TryNext |
|
24 | from IPython.core.error import TryNext | |
25 | from IPython.core.usage import interactive_usage, default_banner |
|
25 | from IPython.core.usage import interactive_usage, default_banner | |
26 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC |
|
26 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC | |
27 | from IPython.lib.inputhook import enable_gui |
|
27 | from IPython.lib.inputhook import enable_gui | |
28 | from IPython.lib.pylabtools import pylab_activate |
|
28 | from IPython.lib.pylabtools import pylab_activate | |
29 | from IPython.testing.skipdoctest import skip_doctest |
|
29 | from IPython.testing.skipdoctest import skip_doctest | |
30 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
30 | from IPython.utils.terminal import toggle_set_term_title, set_term_title | |
31 | from IPython.utils.process import abbrev_cwd |
|
31 | from IPython.utils.process import abbrev_cwd | |
32 | from IPython.utils.warn import warn |
|
32 | from IPython.utils.warn import warn | |
33 | from IPython.utils.text import num_ini_spaces |
|
33 | from IPython.utils.text import num_ini_spaces | |
34 | from IPython.utils.traitlets import Int, CBool, Unicode |
|
34 | from IPython.utils.traitlets import Int, CBool, Unicode | |
35 |
|
35 | |||
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 | # Utilities |
|
37 | # Utilities | |
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 |
|
39 | |||
40 | def get_default_editor(): |
|
40 | def get_default_editor(): | |
41 | try: |
|
41 | try: | |
42 | ed = os.environ['EDITOR'] |
|
42 | ed = os.environ['EDITOR'] | |
43 | except KeyError: |
|
43 | except KeyError: | |
44 | if os.name == 'posix': |
|
44 | if os.name == 'posix': | |
45 | ed = 'vi' # the only one guaranteed to be there! |
|
45 | ed = 'vi' # the only one guaranteed to be there! | |
46 | else: |
|
46 | else: | |
47 | ed = 'notepad' # same in Windows! |
|
47 | ed = 'notepad' # same in Windows! | |
48 | return ed |
|
48 | return ed | |
49 |
|
49 | |||
50 |
|
50 | |||
51 | # store the builtin raw_input globally, and use this always, in case user code |
|
51 | # store the builtin raw_input globally, and use this always, in case user code | |
52 | # overwrites it (like wx.py.PyShell does) |
|
52 | # overwrites it (like wx.py.PyShell does) | |
53 | raw_input_original = raw_input |
|
53 | raw_input_original = raw_input | |
54 |
|
54 | |||
55 | #----------------------------------------------------------------------------- |
|
55 | #----------------------------------------------------------------------------- | |
56 | # Main class |
|
56 | # Main class | |
57 | #----------------------------------------------------------------------------- |
|
57 | #----------------------------------------------------------------------------- | |
58 |
|
58 | |||
59 | class TerminalInteractiveShell(InteractiveShell): |
|
59 | class TerminalInteractiveShell(InteractiveShell): | |
60 |
|
60 | |||
61 | autoedit_syntax = CBool(False, config=True, |
|
61 | autoedit_syntax = CBool(False, config=True, | |
62 | help="auto editing of files with syntax errors.") |
|
62 | help="auto editing of files with syntax errors.") | |
63 | banner = Unicode('') |
|
63 | banner = Unicode('') | |
64 | banner1 = Unicode(default_banner, config=True, |
|
64 | banner1 = Unicode(default_banner, config=True, | |
65 | help="""The part of the banner to be printed before the profile""" |
|
65 | help="""The part of the banner to be printed before the profile""" | |
66 | ) |
|
66 | ) | |
67 | banner2 = Unicode('', config=True, |
|
67 | banner2 = Unicode('', config=True, | |
68 | help="""The part of the banner to be printed after the profile""" |
|
68 | help="""The part of the banner to be printed after the profile""" | |
69 | ) |
|
69 | ) | |
70 | confirm_exit = CBool(True, config=True, |
|
70 | confirm_exit = CBool(True, config=True, | |
71 | help=""" |
|
71 | help=""" | |
72 | Set to confirm when you try to exit IPython with an EOF (Control-D |
|
72 | Set to confirm when you try to exit IPython with an EOF (Control-D | |
73 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
73 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', | |
74 | you can force a direct exit without any confirmation.""", |
|
74 | you can force a direct exit without any confirmation.""", | |
75 | ) |
|
75 | ) | |
76 | # This display_banner only controls whether or not self.show_banner() |
|
76 | # This display_banner only controls whether or not self.show_banner() | |
77 | # is called when mainloop/interact are called. The default is False |
|
77 | # is called when mainloop/interact are called. The default is False | |
78 | # because for the terminal based application, the banner behavior |
|
78 | # because for the terminal based application, the banner behavior | |
79 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
79 | # is controlled by Global.display_banner, which IPythonApp looks at | |
80 | # to determine if *it* should call show_banner() by hand or not. |
|
80 | # to determine if *it* should call show_banner() by hand or not. | |
81 | display_banner = CBool(False) # This isn't configurable! |
|
81 | display_banner = CBool(False) # This isn't configurable! | |
82 | embedded = CBool(False) |
|
82 | embedded = CBool(False) | |
83 | embedded_active = CBool(False) |
|
83 | embedded_active = CBool(False) | |
84 | editor = Unicode(get_default_editor(), config=True, |
|
84 | editor = Unicode(get_default_editor(), config=True, | |
85 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." |
|
85 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." | |
86 | ) |
|
86 | ) | |
87 | pager = Unicode('less', config=True, |
|
87 | pager = Unicode('less', config=True, | |
88 | help="The shell program to be used for paging.") |
|
88 | help="The shell program to be used for paging.") | |
89 |
|
89 | |||
90 | screen_length = Int(0, config=True, |
|
90 | screen_length = Int(0, config=True, | |
91 | help= |
|
91 | help= | |
92 | """Number of lines of your screen, used to control printing of very |
|
92 | """Number of lines of your screen, used to control printing of very | |
93 | long strings. Strings longer than this number of lines will be sent |
|
93 | long strings. Strings longer than this number of lines will be sent | |
94 | through a pager instead of directly printed. The default value for |
|
94 | through a pager instead of directly printed. The default value for | |
95 | this is 0, which means IPython will auto-detect your screen size every |
|
95 | this is 0, which means IPython will auto-detect your screen size every | |
96 | time it needs to print certain potentially long strings (this doesn't |
|
96 | time it needs to print certain potentially long strings (this doesn't | |
97 | change the behavior of the 'print' keyword, it's only triggered |
|
97 | change the behavior of the 'print' keyword, it's only triggered | |
98 | internally). If for some reason this isn't working well (it needs |
|
98 | internally). If for some reason this isn't working well (it needs | |
99 | curses support), specify it yourself. Otherwise don't change the |
|
99 | curses support), specify it yourself. Otherwise don't change the | |
100 | default.""", |
|
100 | default.""", | |
101 | ) |
|
101 | ) | |
102 | term_title = CBool(False, config=True, |
|
102 | term_title = CBool(False, config=True, | |
103 | help="Enable auto setting the terminal title." |
|
103 | help="Enable auto setting the terminal title." | |
104 | ) |
|
104 | ) | |
105 |
|
105 | |||
106 | def __init__(self, config=None, ipython_dir=None, profile_dir=None, user_ns=None, |
|
106 | def __init__(self, config=None, ipython_dir=None, profile_dir=None, user_ns=None, | |
107 | user_global_ns=None, custom_exceptions=((),None), |
|
107 | user_global_ns=None, custom_exceptions=((),None), | |
108 | usage=None, banner1=None, banner2=None, |
|
108 | usage=None, banner1=None, banner2=None, | |
109 | display_banner=None): |
|
109 | display_banner=None): | |
110 |
|
110 | |||
111 | super(TerminalInteractiveShell, self).__init__( |
|
111 | super(TerminalInteractiveShell, self).__init__( | |
112 | config=config, profile_dir=profile_dir, user_ns=user_ns, |
|
112 | config=config, profile_dir=profile_dir, user_ns=user_ns, | |
113 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions |
|
113 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions | |
114 | ) |
|
114 | ) | |
115 | # use os.system instead of utils.process.system by default, except on Windows |
|
115 | # use os.system instead of utils.process.system by default, except on Windows | |
116 | if os.name == 'nt': |
|
116 | if os.name == 'nt': | |
117 | self.system = self.system_piped |
|
117 | self.system = self.system_piped | |
118 | else: |
|
118 | else: | |
119 | self.system = self.system_raw |
|
119 | self.system = self.system_raw | |
120 |
|
120 | |||
121 | self.init_term_title() |
|
121 | self.init_term_title() | |
122 | self.init_usage(usage) |
|
122 | self.init_usage(usage) | |
123 | self.init_banner(banner1, banner2, display_banner) |
|
123 | self.init_banner(banner1, banner2, display_banner) | |
124 |
|
124 | |||
125 | #------------------------------------------------------------------------- |
|
125 | #------------------------------------------------------------------------- | |
126 | # Things related to the terminal |
|
126 | # Things related to the terminal | |
127 | #------------------------------------------------------------------------- |
|
127 | #------------------------------------------------------------------------- | |
128 |
|
128 | |||
129 | @property |
|
129 | @property | |
130 | def usable_screen_length(self): |
|
130 | def usable_screen_length(self): | |
131 | if self.screen_length == 0: |
|
131 | if self.screen_length == 0: | |
132 | return 0 |
|
132 | return 0 | |
133 | else: |
|
133 | else: | |
134 | num_lines_bot = self.separate_in.count('\n')+1 |
|
134 | num_lines_bot = self.separate_in.count('\n')+1 | |
135 | return self.screen_length - num_lines_bot |
|
135 | return self.screen_length - num_lines_bot | |
136 |
|
136 | |||
137 | def init_term_title(self): |
|
137 | def init_term_title(self): | |
138 | # Enable or disable the terminal title. |
|
138 | # Enable or disable the terminal title. | |
139 | if self.term_title: |
|
139 | if self.term_title: | |
140 | toggle_set_term_title(True) |
|
140 | toggle_set_term_title(True) | |
141 | set_term_title('IPython: ' + abbrev_cwd()) |
|
141 | set_term_title('IPython: ' + abbrev_cwd()) | |
142 | else: |
|
142 | else: | |
143 | toggle_set_term_title(False) |
|
143 | toggle_set_term_title(False) | |
144 |
|
144 | |||
145 | #------------------------------------------------------------------------- |
|
145 | #------------------------------------------------------------------------- | |
146 | # Things related to aliases |
|
146 | # Things related to aliases | |
147 | #------------------------------------------------------------------------- |
|
147 | #------------------------------------------------------------------------- | |
148 |
|
148 | |||
149 | def init_alias(self): |
|
149 | def init_alias(self): | |
150 | # The parent class defines aliases that can be safely used with any |
|
150 | # The parent class defines aliases that can be safely used with any | |
151 | # frontend. |
|
151 | # frontend. | |
152 | super(TerminalInteractiveShell, self).init_alias() |
|
152 | super(TerminalInteractiveShell, self).init_alias() | |
153 |
|
153 | |||
154 | # Now define aliases that only make sense on the terminal, because they |
|
154 | # Now define aliases that only make sense on the terminal, because they | |
155 | # need direct access to the console in a way that we can't emulate in |
|
155 | # need direct access to the console in a way that we can't emulate in | |
156 | # GUI or web frontend |
|
156 | # GUI or web frontend | |
157 | if os.name == 'posix': |
|
157 | if os.name == 'posix': | |
158 | aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), |
|
158 | aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), | |
159 | ('man', 'man')] |
|
159 | ('man', 'man')] | |
160 | elif os.name == 'nt': |
|
160 | elif os.name == 'nt': | |
161 | aliases = [('cls', 'cls')] |
|
161 | aliases = [('cls', 'cls')] | |
162 |
|
162 | |||
163 |
|
163 | |||
164 | for name, cmd in aliases: |
|
164 | for name, cmd in aliases: | |
165 | self.alias_manager.define_alias(name, cmd) |
|
165 | self.alias_manager.define_alias(name, cmd) | |
166 |
|
166 | |||
167 | #------------------------------------------------------------------------- |
|
167 | #------------------------------------------------------------------------- | |
168 | # Things related to the banner and usage |
|
168 | # Things related to the banner and usage | |
169 | #------------------------------------------------------------------------- |
|
169 | #------------------------------------------------------------------------- | |
170 |
|
170 | |||
171 | def _banner1_changed(self): |
|
171 | def _banner1_changed(self): | |
172 | self.compute_banner() |
|
172 | self.compute_banner() | |
173 |
|
173 | |||
174 | def _banner2_changed(self): |
|
174 | def _banner2_changed(self): | |
175 | self.compute_banner() |
|
175 | self.compute_banner() | |
176 |
|
176 | |||
177 | def _term_title_changed(self, name, new_value): |
|
177 | def _term_title_changed(self, name, new_value): | |
178 | self.init_term_title() |
|
178 | self.init_term_title() | |
179 |
|
179 | |||
180 | def init_banner(self, banner1, banner2, display_banner): |
|
180 | def init_banner(self, banner1, banner2, display_banner): | |
181 | if banner1 is not None: |
|
181 | if banner1 is not None: | |
182 | self.banner1 = banner1 |
|
182 | self.banner1 = banner1 | |
183 | if banner2 is not None: |
|
183 | if banner2 is not None: | |
184 | self.banner2 = banner2 |
|
184 | self.banner2 = banner2 | |
185 | if display_banner is not None: |
|
185 | if display_banner is not None: | |
186 | self.display_banner = display_banner |
|
186 | self.display_banner = display_banner | |
187 | self.compute_banner() |
|
187 | self.compute_banner() | |
188 |
|
188 | |||
189 | def show_banner(self, banner=None): |
|
189 | def show_banner(self, banner=None): | |
190 | if banner is None: |
|
190 | if banner is None: | |
191 | banner = self.banner |
|
191 | banner = self.banner | |
192 | self.write(banner) |
|
192 | self.write(banner) | |
193 |
|
193 | |||
194 | def compute_banner(self): |
|
194 | def compute_banner(self): | |
195 | self.banner = self.banner1 |
|
195 | self.banner = self.banner1 | |
196 | if self.profile and self.profile != 'default': |
|
196 | if self.profile and self.profile != 'default': | |
197 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
197 | self.banner += '\nIPython profile: %s\n' % self.profile | |
198 | if self.banner2: |
|
198 | if self.banner2: | |
199 | self.banner += '\n' + self.banner2 |
|
199 | self.banner += '\n' + self.banner2 | |
200 |
|
200 | |||
201 | def init_usage(self, usage=None): |
|
201 | def init_usage(self, usage=None): | |
202 | if usage is None: |
|
202 | if usage is None: | |
203 | self.usage = interactive_usage |
|
203 | self.usage = interactive_usage | |
204 | else: |
|
204 | else: | |
205 | self.usage = usage |
|
205 | self.usage = usage | |
206 |
|
206 | |||
207 | #------------------------------------------------------------------------- |
|
207 | #------------------------------------------------------------------------- | |
208 | # Mainloop and code execution logic |
|
208 | # Mainloop and code execution logic | |
209 | #------------------------------------------------------------------------- |
|
209 | #------------------------------------------------------------------------- | |
210 |
|
210 | |||
211 | def mainloop(self, display_banner=None): |
|
211 | def mainloop(self, display_banner=None): | |
212 | """Start the mainloop. |
|
212 | """Start the mainloop. | |
213 |
|
213 | |||
214 | If an optional banner argument is given, it will override the |
|
214 | If an optional banner argument is given, it will override the | |
215 | internally created default banner. |
|
215 | internally created default banner. | |
216 | """ |
|
216 | """ | |
217 |
|
217 | |||
218 | with nested(self.builtin_trap, self.display_trap): |
|
218 | with nested(self.builtin_trap, self.display_trap): | |
219 |
|
219 | |||
220 | while 1: |
|
220 | while 1: | |
221 | try: |
|
221 | try: | |
222 | self.interact(display_banner=display_banner) |
|
222 | self.interact(display_banner=display_banner) | |
223 | #self.interact_with_readline() |
|
223 | #self.interact_with_readline() | |
224 | # XXX for testing of a readline-decoupled repl loop, call |
|
224 | # XXX for testing of a readline-decoupled repl loop, call | |
225 | # interact_with_readline above |
|
225 | # interact_with_readline above | |
226 | break |
|
226 | break | |
227 | except KeyboardInterrupt: |
|
227 | except KeyboardInterrupt: | |
228 | # this should not be necessary, but KeyboardInterrupt |
|
228 | # this should not be necessary, but KeyboardInterrupt | |
229 | # handling seems rather unpredictable... |
|
229 | # handling seems rather unpredictable... | |
230 | self.write("\nKeyboardInterrupt in interact()\n") |
|
230 | self.write("\nKeyboardInterrupt in interact()\n") | |
231 |
|
231 | |||
232 | def interact(self, display_banner=None): |
|
232 | def interact(self, display_banner=None): | |
233 | """Closely emulate the interactive Python console.""" |
|
233 | """Closely emulate the interactive Python console.""" | |
234 |
|
234 | |||
235 | # batch run -> do not interact |
|
235 | # batch run -> do not interact | |
236 | if self.exit_now: |
|
236 | if self.exit_now: | |
237 | return |
|
237 | return | |
238 |
|
238 | |||
239 | if display_banner is None: |
|
239 | if display_banner is None: | |
240 | display_banner = self.display_banner |
|
240 | display_banner = self.display_banner | |
241 | if display_banner: |
|
241 | ||
|
242 | if isinstance(display_banner, basestring): | |||
|
243 | self.show_banner(display_banner) | |||
|
244 | elif display_banner: | |||
242 | self.show_banner() |
|
245 | self.show_banner() | |
243 |
|
246 | |||
244 | more = False |
|
247 | more = False | |
245 |
|
248 | |||
246 | # Mark activity in the builtins |
|
249 | # Mark activity in the builtins | |
247 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
250 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
248 |
|
251 | |||
249 | if self.has_readline: |
|
252 | if self.has_readline: | |
250 | self.readline_startup_hook(self.pre_readline) |
|
253 | self.readline_startup_hook(self.pre_readline) | |
251 | # exit_now is set by a call to %Exit or %Quit, through the |
|
254 | # exit_now is set by a call to %Exit or %Quit, through the | |
252 | # ask_exit callback. |
|
255 | # ask_exit callback. | |
253 |
|
256 | |||
254 | while not self.exit_now: |
|
257 | while not self.exit_now: | |
255 | self.hooks.pre_prompt_hook() |
|
258 | self.hooks.pre_prompt_hook() | |
256 | if more: |
|
259 | if more: | |
257 | try: |
|
260 | try: | |
258 | prompt = self.hooks.generate_prompt(True) |
|
261 | prompt = self.hooks.generate_prompt(True) | |
259 | except: |
|
262 | except: | |
260 | self.showtraceback() |
|
263 | self.showtraceback() | |
261 | if self.autoindent: |
|
264 | if self.autoindent: | |
262 | self.rl_do_indent = True |
|
265 | self.rl_do_indent = True | |
263 |
|
266 | |||
264 | else: |
|
267 | else: | |
265 | try: |
|
268 | try: | |
266 | prompt = self.hooks.generate_prompt(False) |
|
269 | prompt = self.hooks.generate_prompt(False) | |
267 | except: |
|
270 | except: | |
268 | self.showtraceback() |
|
271 | self.showtraceback() | |
269 | try: |
|
272 | try: | |
270 | line = self.raw_input(prompt) |
|
273 | line = self.raw_input(prompt) | |
271 | if self.exit_now: |
|
274 | if self.exit_now: | |
272 | # quick exit on sys.std[in|out] close |
|
275 | # quick exit on sys.std[in|out] close | |
273 | break |
|
276 | break | |
274 | if self.autoindent: |
|
277 | if self.autoindent: | |
275 | self.rl_do_indent = False |
|
278 | self.rl_do_indent = False | |
276 |
|
279 | |||
277 | except KeyboardInterrupt: |
|
280 | except KeyboardInterrupt: | |
278 | #double-guard against keyboardinterrupts during kbdint handling |
|
281 | #double-guard against keyboardinterrupts during kbdint handling | |
279 | try: |
|
282 | try: | |
280 | self.write('\nKeyboardInterrupt\n') |
|
283 | self.write('\nKeyboardInterrupt\n') | |
281 | self.input_splitter.reset() |
|
284 | self.input_splitter.reset() | |
282 | more = False |
|
285 | more = False | |
283 | except KeyboardInterrupt: |
|
286 | except KeyboardInterrupt: | |
284 | pass |
|
287 | pass | |
285 | except EOFError: |
|
288 | except EOFError: | |
286 | if self.autoindent: |
|
289 | if self.autoindent: | |
287 | self.rl_do_indent = False |
|
290 | self.rl_do_indent = False | |
288 | if self.has_readline: |
|
291 | if self.has_readline: | |
289 | self.readline_startup_hook(None) |
|
292 | self.readline_startup_hook(None) | |
290 | self.write('\n') |
|
293 | self.write('\n') | |
291 | self.exit() |
|
294 | self.exit() | |
292 | except bdb.BdbQuit: |
|
295 | except bdb.BdbQuit: | |
293 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
296 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
294 | 'Because of how pdb handles the stack, it is impossible\n' |
|
297 | 'Because of how pdb handles the stack, it is impossible\n' | |
295 | 'for IPython to properly format this particular exception.\n' |
|
298 | 'for IPython to properly format this particular exception.\n' | |
296 | 'IPython will resume normal operation.') |
|
299 | 'IPython will resume normal operation.') | |
297 | except: |
|
300 | except: | |
298 | # exceptions here are VERY RARE, but they can be triggered |
|
301 | # exceptions here are VERY RARE, but they can be triggered | |
299 | # asynchronously by signal handlers, for example. |
|
302 | # asynchronously by signal handlers, for example. | |
300 | self.showtraceback() |
|
303 | self.showtraceback() | |
301 | else: |
|
304 | else: | |
302 | self.input_splitter.push(line) |
|
305 | self.input_splitter.push(line) | |
303 | more = self.input_splitter.push_accepts_more() |
|
306 | more = self.input_splitter.push_accepts_more() | |
304 | if (self.SyntaxTB.last_syntax_error and |
|
307 | if (self.SyntaxTB.last_syntax_error and | |
305 | self.autoedit_syntax): |
|
308 | self.autoedit_syntax): | |
306 | self.edit_syntax_error() |
|
309 | self.edit_syntax_error() | |
307 | if not more: |
|
310 | if not more: | |
308 | source_raw = self.input_splitter.source_raw_reset()[1] |
|
311 | source_raw = self.input_splitter.source_raw_reset()[1] | |
309 | self.run_cell(source_raw) |
|
312 | self.run_cell(source_raw) | |
310 |
|
313 | |||
311 | # We are off again... |
|
314 | # We are off again... | |
312 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
315 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
313 |
|
316 | |||
314 | # Turn off the exit flag, so the mainloop can be restarted if desired |
|
317 | # Turn off the exit flag, so the mainloop can be restarted if desired | |
315 | self.exit_now = False |
|
318 | self.exit_now = False | |
316 |
|
319 | |||
317 | def raw_input(self, prompt=''): |
|
320 | def raw_input(self, prompt=''): | |
318 | """Write a prompt and read a line. |
|
321 | """Write a prompt and read a line. | |
319 |
|
322 | |||
320 | The returned line does not include the trailing newline. |
|
323 | The returned line does not include the trailing newline. | |
321 | When the user enters the EOF key sequence, EOFError is raised. |
|
324 | When the user enters the EOF key sequence, EOFError is raised. | |
322 |
|
325 | |||
323 | Optional inputs: |
|
326 | Optional inputs: | |
324 |
|
327 | |||
325 | - prompt(''): a string to be printed to prompt the user. |
|
328 | - prompt(''): a string to be printed to prompt the user. | |
326 |
|
329 | |||
327 | - continue_prompt(False): whether this line is the first one or a |
|
330 | - continue_prompt(False): whether this line is the first one or a | |
328 | continuation in a sequence of inputs. |
|
331 | continuation in a sequence of inputs. | |
329 | """ |
|
332 | """ | |
330 | # Code run by the user may have modified the readline completer state. |
|
333 | # Code run by the user may have modified the readline completer state. | |
331 | # We must ensure that our completer is back in place. |
|
334 | # We must ensure that our completer is back in place. | |
332 |
|
335 | |||
333 | if self.has_readline: |
|
336 | if self.has_readline: | |
334 | self.set_readline_completer() |
|
337 | self.set_readline_completer() | |
335 |
|
338 | |||
336 | try: |
|
339 | try: | |
337 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
340 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
338 | except ValueError: |
|
341 | except ValueError: | |
339 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
342 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
340 | " or sys.stdout.close()!\nExiting IPython!") |
|
343 | " or sys.stdout.close()!\nExiting IPython!") | |
341 | self.ask_exit() |
|
344 | self.ask_exit() | |
342 | return "" |
|
345 | return "" | |
343 |
|
346 | |||
344 | # Try to be reasonably smart about not re-indenting pasted input more |
|
347 | # Try to be reasonably smart about not re-indenting pasted input more | |
345 | # than necessary. We do this by trimming out the auto-indent initial |
|
348 | # than necessary. We do this by trimming out the auto-indent initial | |
346 | # spaces, if the user's actual input started itself with whitespace. |
|
349 | # spaces, if the user's actual input started itself with whitespace. | |
347 | if self.autoindent: |
|
350 | if self.autoindent: | |
348 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
351 | if num_ini_spaces(line) > self.indent_current_nsp: | |
349 | line = line[self.indent_current_nsp:] |
|
352 | line = line[self.indent_current_nsp:] | |
350 | self.indent_current_nsp = 0 |
|
353 | self.indent_current_nsp = 0 | |
351 |
|
354 | |||
352 | return line |
|
355 | return line | |
353 |
|
356 | |||
354 | #------------------------------------------------------------------------- |
|
357 | #------------------------------------------------------------------------- | |
355 | # Methods to support auto-editing of SyntaxErrors. |
|
358 | # Methods to support auto-editing of SyntaxErrors. | |
356 | #------------------------------------------------------------------------- |
|
359 | #------------------------------------------------------------------------- | |
357 |
|
360 | |||
358 | def edit_syntax_error(self): |
|
361 | def edit_syntax_error(self): | |
359 | """The bottom half of the syntax error handler called in the main loop. |
|
362 | """The bottom half of the syntax error handler called in the main loop. | |
360 |
|
363 | |||
361 | Loop until syntax error is fixed or user cancels. |
|
364 | Loop until syntax error is fixed or user cancels. | |
362 | """ |
|
365 | """ | |
363 |
|
366 | |||
364 | while self.SyntaxTB.last_syntax_error: |
|
367 | while self.SyntaxTB.last_syntax_error: | |
365 | # copy and clear last_syntax_error |
|
368 | # copy and clear last_syntax_error | |
366 | err = self.SyntaxTB.clear_err_state() |
|
369 | err = self.SyntaxTB.clear_err_state() | |
367 | if not self._should_recompile(err): |
|
370 | if not self._should_recompile(err): | |
368 | return |
|
371 | return | |
369 | try: |
|
372 | try: | |
370 | # may set last_syntax_error again if a SyntaxError is raised |
|
373 | # may set last_syntax_error again if a SyntaxError is raised | |
371 | self.safe_execfile(err.filename,self.user_ns) |
|
374 | self.safe_execfile(err.filename,self.user_ns) | |
372 | except: |
|
375 | except: | |
373 | self.showtraceback() |
|
376 | self.showtraceback() | |
374 | else: |
|
377 | else: | |
375 | try: |
|
378 | try: | |
376 | f = file(err.filename) |
|
379 | f = file(err.filename) | |
377 | try: |
|
380 | try: | |
378 | # This should be inside a display_trap block and I |
|
381 | # This should be inside a display_trap block and I | |
379 | # think it is. |
|
382 | # think it is. | |
380 | sys.displayhook(f.read()) |
|
383 | sys.displayhook(f.read()) | |
381 | finally: |
|
384 | finally: | |
382 | f.close() |
|
385 | f.close() | |
383 | except: |
|
386 | except: | |
384 | self.showtraceback() |
|
387 | self.showtraceback() | |
385 |
|
388 | |||
386 | def _should_recompile(self,e): |
|
389 | def _should_recompile(self,e): | |
387 | """Utility routine for edit_syntax_error""" |
|
390 | """Utility routine for edit_syntax_error""" | |
388 |
|
391 | |||
389 | if e.filename in ('<ipython console>','<input>','<string>', |
|
392 | if e.filename in ('<ipython console>','<input>','<string>', | |
390 | '<console>','<BackgroundJob compilation>', |
|
393 | '<console>','<BackgroundJob compilation>', | |
391 | None): |
|
394 | None): | |
392 |
|
395 | |||
393 | return False |
|
396 | return False | |
394 | try: |
|
397 | try: | |
395 | if (self.autoedit_syntax and |
|
398 | if (self.autoedit_syntax and | |
396 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
399 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
397 | '[Y/n] ','y')): |
|
400 | '[Y/n] ','y')): | |
398 | return False |
|
401 | return False | |
399 | except EOFError: |
|
402 | except EOFError: | |
400 | return False |
|
403 | return False | |
401 |
|
404 | |||
402 | def int0(x): |
|
405 | def int0(x): | |
403 | try: |
|
406 | try: | |
404 | return int(x) |
|
407 | return int(x) | |
405 | except TypeError: |
|
408 | except TypeError: | |
406 | return 0 |
|
409 | return 0 | |
407 | # always pass integer line and offset values to editor hook |
|
410 | # always pass integer line and offset values to editor hook | |
408 | try: |
|
411 | try: | |
409 | self.hooks.fix_error_editor(e.filename, |
|
412 | self.hooks.fix_error_editor(e.filename, | |
410 | int0(e.lineno),int0(e.offset),e.msg) |
|
413 | int0(e.lineno),int0(e.offset),e.msg) | |
411 | except TryNext: |
|
414 | except TryNext: | |
412 | warn('Could not open editor') |
|
415 | warn('Could not open editor') | |
413 | return False |
|
416 | return False | |
414 | return True |
|
417 | return True | |
415 |
|
418 | |||
416 | #------------------------------------------------------------------------- |
|
419 | #------------------------------------------------------------------------- | |
417 | # Things related to GUI support and pylab |
|
420 | # Things related to GUI support and pylab | |
418 | #------------------------------------------------------------------------- |
|
421 | #------------------------------------------------------------------------- | |
419 |
|
422 | |||
420 | def enable_pylab(self, gui=None, import_all=True): |
|
423 | def enable_pylab(self, gui=None, import_all=True): | |
421 | """Activate pylab support at runtime. |
|
424 | """Activate pylab support at runtime. | |
422 |
|
425 | |||
423 | This turns on support for matplotlib, preloads into the interactive |
|
426 | This turns on support for matplotlib, preloads into the interactive | |
424 | namespace all of numpy and pylab, and configures IPython to correcdtly |
|
427 | namespace all of numpy and pylab, and configures IPython to correcdtly | |
425 | interact with the GUI event loop. The GUI backend to be used can be |
|
428 | interact with the GUI event loop. The GUI backend to be used can be | |
426 | optionally selected with the optional :param:`gui` argument. |
|
429 | optionally selected with the optional :param:`gui` argument. | |
427 |
|
430 | |||
428 | Parameters |
|
431 | Parameters | |
429 | ---------- |
|
432 | ---------- | |
430 | gui : optional, string |
|
433 | gui : optional, string | |
431 |
|
434 | |||
432 | If given, dictates the choice of matplotlib GUI backend to use |
|
435 | If given, dictates the choice of matplotlib GUI backend to use | |
433 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or |
|
436 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or | |
434 | 'gtk'), otherwise we use the default chosen by matplotlib (as |
|
437 | 'gtk'), otherwise we use the default chosen by matplotlib (as | |
435 | dictated by the matplotlib build-time options plus the user's |
|
438 | dictated by the matplotlib build-time options plus the user's | |
436 | matplotlibrc configuration file). |
|
439 | matplotlibrc configuration file). | |
437 | """ |
|
440 | """ | |
438 | # We want to prevent the loading of pylab to pollute the user's |
|
441 | # We want to prevent the loading of pylab to pollute the user's | |
439 | # namespace as shown by the %who* magics, so we execute the activation |
|
442 | # namespace as shown by the %who* magics, so we execute the activation | |
440 | # code in an empty namespace, and we update *both* user_ns and |
|
443 | # code in an empty namespace, and we update *both* user_ns and | |
441 | # user_ns_hidden with this information. |
|
444 | # user_ns_hidden with this information. | |
442 | ns = {} |
|
445 | ns = {} | |
443 | gui = pylab_activate(ns, gui, import_all) |
|
446 | gui = pylab_activate(ns, gui, import_all) | |
444 | self.user_ns.update(ns) |
|
447 | self.user_ns.update(ns) | |
445 | self.user_ns_hidden.update(ns) |
|
448 | self.user_ns_hidden.update(ns) | |
446 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
449 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
447 | # plot updates into account |
|
450 | # plot updates into account | |
448 | enable_gui(gui) |
|
451 | enable_gui(gui) | |
449 | self.magic_run = self._pylab_magic_run |
|
452 | self.magic_run = self._pylab_magic_run | |
450 |
|
453 | |||
451 | #------------------------------------------------------------------------- |
|
454 | #------------------------------------------------------------------------- | |
452 | # Things related to exiting |
|
455 | # Things related to exiting | |
453 | #------------------------------------------------------------------------- |
|
456 | #------------------------------------------------------------------------- | |
454 |
|
457 | |||
455 | def ask_exit(self): |
|
458 | def ask_exit(self): | |
456 | """ Ask the shell to exit. Can be overiden and used as a callback. """ |
|
459 | """ Ask the shell to exit. Can be overiden and used as a callback. """ | |
457 | self.exit_now = True |
|
460 | self.exit_now = True | |
458 |
|
461 | |||
459 | def exit(self): |
|
462 | def exit(self): | |
460 | """Handle interactive exit. |
|
463 | """Handle interactive exit. | |
461 |
|
464 | |||
462 | This method calls the ask_exit callback.""" |
|
465 | This method calls the ask_exit callback.""" | |
463 | if self.confirm_exit: |
|
466 | if self.confirm_exit: | |
464 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
467 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
465 | self.ask_exit() |
|
468 | self.ask_exit() | |
466 | else: |
|
469 | else: | |
467 | self.ask_exit() |
|
470 | self.ask_exit() | |
468 |
|
471 | |||
469 | #------------------------------------------------------------------------ |
|
472 | #------------------------------------------------------------------------ | |
470 | # Magic overrides |
|
473 | # Magic overrides | |
471 | #------------------------------------------------------------------------ |
|
474 | #------------------------------------------------------------------------ | |
472 | # Once the base class stops inheriting from magic, this code needs to be |
|
475 | # Once the base class stops inheriting from magic, this code needs to be | |
473 | # moved into a separate machinery as well. For now, at least isolate here |
|
476 | # moved into a separate machinery as well. For now, at least isolate here | |
474 | # the magics which this class needs to implement differently from the base |
|
477 | # the magics which this class needs to implement differently from the base | |
475 | # class, or that are unique to it. |
|
478 | # class, or that are unique to it. | |
476 |
|
479 | |||
477 | def magic_autoindent(self, parameter_s = ''): |
|
480 | def magic_autoindent(self, parameter_s = ''): | |
478 | """Toggle autoindent on/off (if available).""" |
|
481 | """Toggle autoindent on/off (if available).""" | |
479 |
|
482 | |||
480 | self.shell.set_autoindent() |
|
483 | self.shell.set_autoindent() | |
481 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
484 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
482 |
|
485 | |||
483 | @skip_doctest |
|
486 | @skip_doctest | |
484 | def magic_cpaste(self, parameter_s=''): |
|
487 | def magic_cpaste(self, parameter_s=''): | |
485 | """Paste & execute a pre-formatted code block from clipboard. |
|
488 | """Paste & execute a pre-formatted code block from clipboard. | |
486 |
|
489 | |||
487 | You must terminate the block with '--' (two minus-signs) alone on the |
|
490 | You must terminate the block with '--' (two minus-signs) alone on the | |
488 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
491 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
489 | is the new sentinel for this operation) |
|
492 | is the new sentinel for this operation) | |
490 |
|
493 | |||
491 | The block is dedented prior to execution to enable execution of method |
|
494 | The block is dedented prior to execution to enable execution of method | |
492 | definitions. '>' and '+' characters at the beginning of a line are |
|
495 | definitions. '>' and '+' characters at the beginning of a line are | |
493 | ignored, to allow pasting directly from e-mails, diff files and |
|
496 | ignored, to allow pasting directly from e-mails, diff files and | |
494 | doctests (the '...' continuation prompt is also stripped). The |
|
497 | doctests (the '...' continuation prompt is also stripped). The | |
495 | executed block is also assigned to variable named 'pasted_block' for |
|
498 | executed block is also assigned to variable named 'pasted_block' for | |
496 | later editing with '%edit pasted_block'. |
|
499 | later editing with '%edit pasted_block'. | |
497 |
|
500 | |||
498 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
501 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
499 | This assigns the pasted block to variable 'foo' as string, without |
|
502 | This assigns the pasted block to variable 'foo' as string, without | |
500 | dedenting or executing it (preceding >>> and + is still stripped) |
|
503 | dedenting or executing it (preceding >>> and + is still stripped) | |
501 |
|
504 | |||
502 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
505 | '%cpaste -r' re-executes the block previously entered by cpaste. | |
503 |
|
506 | |||
504 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
507 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
505 | Just press enter and type -- (and press enter again) and the block |
|
508 | Just press enter and type -- (and press enter again) and the block | |
506 | will be what was just pasted. |
|
509 | will be what was just pasted. | |
507 |
|
510 | |||
508 | IPython statements (magics, shell escapes) are not supported (yet). |
|
511 | IPython statements (magics, shell escapes) are not supported (yet). | |
509 |
|
512 | |||
510 | See also |
|
513 | See also | |
511 | -------- |
|
514 | -------- | |
512 | paste: automatically pull code from clipboard. |
|
515 | paste: automatically pull code from clipboard. | |
513 |
|
516 | |||
514 | Examples |
|
517 | Examples | |
515 | -------- |
|
518 | -------- | |
516 | :: |
|
519 | :: | |
517 |
|
520 | |||
518 | In [8]: %cpaste |
|
521 | In [8]: %cpaste | |
519 | Pasting code; enter '--' alone on the line to stop. |
|
522 | Pasting code; enter '--' alone on the line to stop. | |
520 | :>>> a = ["world!", "Hello"] |
|
523 | :>>> a = ["world!", "Hello"] | |
521 | :>>> print " ".join(sorted(a)) |
|
524 | :>>> print " ".join(sorted(a)) | |
522 | :-- |
|
525 | :-- | |
523 | Hello world! |
|
526 | Hello world! | |
524 | """ |
|
527 | """ | |
525 |
|
528 | |||
526 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
529 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') | |
527 | par = args.strip() |
|
530 | par = args.strip() | |
528 | if opts.has_key('r'): |
|
531 | if opts.has_key('r'): | |
529 | self._rerun_pasted() |
|
532 | self._rerun_pasted() | |
530 | return |
|
533 | return | |
531 |
|
534 | |||
532 | sentinel = opts.get('s','--') |
|
535 | sentinel = opts.get('s','--') | |
533 |
|
536 | |||
534 | block = self._strip_pasted_lines_for_code( |
|
537 | block = self._strip_pasted_lines_for_code( | |
535 | self._get_pasted_lines(sentinel)) |
|
538 | self._get_pasted_lines(sentinel)) | |
536 |
|
539 | |||
537 | self._execute_block(block, par) |
|
540 | self._execute_block(block, par) | |
538 |
|
541 | |||
539 | def magic_paste(self, parameter_s=''): |
|
542 | def magic_paste(self, parameter_s=''): | |
540 | """Paste & execute a pre-formatted code block from clipboard. |
|
543 | """Paste & execute a pre-formatted code block from clipboard. | |
541 |
|
544 | |||
542 | The text is pulled directly from the clipboard without user |
|
545 | The text is pulled directly from the clipboard without user | |
543 | intervention and printed back on the screen before execution (unless |
|
546 | intervention and printed back on the screen before execution (unless | |
544 | the -q flag is given to force quiet mode). |
|
547 | the -q flag is given to force quiet mode). | |
545 |
|
548 | |||
546 | The block is dedented prior to execution to enable execution of method |
|
549 | The block is dedented prior to execution to enable execution of method | |
547 | definitions. '>' and '+' characters at the beginning of a line are |
|
550 | definitions. '>' and '+' characters at the beginning of a line are | |
548 | ignored, to allow pasting directly from e-mails, diff files and |
|
551 | ignored, to allow pasting directly from e-mails, diff files and | |
549 | doctests (the '...' continuation prompt is also stripped). The |
|
552 | doctests (the '...' continuation prompt is also stripped). The | |
550 | executed block is also assigned to variable named 'pasted_block' for |
|
553 | executed block is also assigned to variable named 'pasted_block' for | |
551 | later editing with '%edit pasted_block'. |
|
554 | later editing with '%edit pasted_block'. | |
552 |
|
555 | |||
553 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
556 | You can also pass a variable name as an argument, e.g. '%paste foo'. | |
554 | This assigns the pasted block to variable 'foo' as string, without |
|
557 | This assigns the pasted block to variable 'foo' as string, without | |
555 | dedenting or executing it (preceding >>> and + is still stripped) |
|
558 | dedenting or executing it (preceding >>> and + is still stripped) | |
556 |
|
559 | |||
557 | Options |
|
560 | Options | |
558 | ------- |
|
561 | ------- | |
559 |
|
562 | |||
560 | -r: re-executes the block previously entered by cpaste. |
|
563 | -r: re-executes the block previously entered by cpaste. | |
561 |
|
564 | |||
562 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
565 | -q: quiet mode: do not echo the pasted text back to the terminal. | |
563 |
|
566 | |||
564 | IPython statements (magics, shell escapes) are not supported (yet). |
|
567 | IPython statements (magics, shell escapes) are not supported (yet). | |
565 |
|
568 | |||
566 | See also |
|
569 | See also | |
567 | -------- |
|
570 | -------- | |
568 | cpaste: manually paste code into terminal until you mark its end. |
|
571 | cpaste: manually paste code into terminal until you mark its end. | |
569 | """ |
|
572 | """ | |
570 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
573 | opts,args = self.parse_options(parameter_s,'rq',mode='string') | |
571 | par = args.strip() |
|
574 | par = args.strip() | |
572 | if opts.has_key('r'): |
|
575 | if opts.has_key('r'): | |
573 | self._rerun_pasted() |
|
576 | self._rerun_pasted() | |
574 | return |
|
577 | return | |
575 |
|
578 | |||
576 | text = self.shell.hooks.clipboard_get() |
|
579 | text = self.shell.hooks.clipboard_get() | |
577 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
580 | block = self._strip_pasted_lines_for_code(text.splitlines()) | |
578 |
|
581 | |||
579 | # By default, echo back to terminal unless quiet mode is requested |
|
582 | # By default, echo back to terminal unless quiet mode is requested | |
580 | if not opts.has_key('q'): |
|
583 | if not opts.has_key('q'): | |
581 | write = self.shell.write |
|
584 | write = self.shell.write | |
582 | write(self.shell.pycolorize(block)) |
|
585 | write(self.shell.pycolorize(block)) | |
583 | if not block.endswith('\n'): |
|
586 | if not block.endswith('\n'): | |
584 | write('\n') |
|
587 | write('\n') | |
585 | write("## -- End pasted text --\n") |
|
588 | write("## -- End pasted text --\n") | |
586 |
|
589 | |||
587 | self._execute_block(block, par) |
|
590 | self._execute_block(block, par) | |
588 |
|
591 | |||
589 |
|
592 | |||
590 | InteractiveShellABC.register(TerminalInteractiveShell) |
|
593 | InteractiveShellABC.register(TerminalInteractiveShell) |
General Comments 0
You need to be logged in to leave comments.
Login now