##// END OF EJS Templates
Merge pull request #9276 from takluyver/test-embed-simple-prompt...
Kyle Kelley -
r22133:78b81f05 merge
parent child Browse files
Show More
@@ -1,274 +1,274 b''
1 """IPython terminal interface using prompt_toolkit in place of readline"""
1 """IPython terminal interface using prompt_toolkit in place of readline"""
2 from __future__ import print_function
2 from __future__ import print_function
3
3
4 import os
4 import os
5 import sys
5 import sys
6
6
7 from IPython.core.interactiveshell import InteractiveShell
7 from IPython.core.interactiveshell import InteractiveShell
8 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
8 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
9 from IPython.utils.terminal import toggle_set_term_title, set_term_title
9 from IPython.utils.terminal import toggle_set_term_title, set_term_title
10 from IPython.utils.process import abbrev_cwd
10 from IPython.utils.process import abbrev_cwd
11 from traitlets import Bool, Unicode, Dict
11 from traitlets import Bool, Unicode, Dict
12
12
13 from prompt_toolkit.completion import Completer, Completion
13 from prompt_toolkit.completion import Completer, Completion
14 from prompt_toolkit.enums import DEFAULT_BUFFER
14 from prompt_toolkit.enums import DEFAULT_BUFFER
15 from prompt_toolkit.filters import HasFocus, HasSelection
15 from prompt_toolkit.filters import HasFocus, HasSelection
16 from prompt_toolkit.history import InMemoryHistory
16 from prompt_toolkit.history import InMemoryHistory
17 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop
17 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop
18 from prompt_toolkit.interface import CommandLineInterface
18 from prompt_toolkit.interface import CommandLineInterface
19 from prompt_toolkit.key_binding.manager import KeyBindingManager
19 from prompt_toolkit.key_binding.manager import KeyBindingManager
20 from prompt_toolkit.key_binding.vi_state import InputMode
20 from prompt_toolkit.key_binding.vi_state import InputMode
21 from prompt_toolkit.key_binding.bindings.vi import ViStateFilter
21 from prompt_toolkit.key_binding.bindings.vi import ViStateFilter
22 from prompt_toolkit.keys import Keys
22 from prompt_toolkit.keys import Keys
23 from prompt_toolkit.layout.lexers import PygmentsLexer
23 from prompt_toolkit.layout.lexers import PygmentsLexer
24 from prompt_toolkit.styles import PygmentsStyle
24 from prompt_toolkit.styles import PygmentsStyle
25
25
26 from pygments.styles import get_style_by_name
26 from pygments.styles import get_style_by_name
27 from pygments.lexers import Python3Lexer, PythonLexer
27 from pygments.lexers import Python3Lexer, PythonLexer
28 from pygments.token import Token
28 from pygments.token import Token
29
29
30 from .pt_inputhooks import get_inputhook_func
30 from .pt_inputhooks import get_inputhook_func
31 from .interactiveshell import get_default_editor, TerminalMagics
31 from .interactiveshell import get_default_editor, TerminalMagics
32
32
33
33
34
34
35 class IPythonPTCompleter(Completer):
35 class IPythonPTCompleter(Completer):
36 """Adaptor to provide IPython completions to prompt_toolkit"""
36 """Adaptor to provide IPython completions to prompt_toolkit"""
37 def __init__(self, ipy_completer):
37 def __init__(self, ipy_completer):
38 self.ipy_completer = ipy_completer
38 self.ipy_completer = ipy_completer
39
39
40 def get_completions(self, document, complete_event):
40 def get_completions(self, document, complete_event):
41 if not document.current_line.strip():
41 if not document.current_line.strip():
42 return
42 return
43
43
44 used, matches = self.ipy_completer.complete(
44 used, matches = self.ipy_completer.complete(
45 line_buffer=document.current_line,
45 line_buffer=document.current_line,
46 cursor_pos=document.cursor_position_col
46 cursor_pos=document.cursor_position_col
47 )
47 )
48 start_pos = -len(used)
48 start_pos = -len(used)
49 for m in matches:
49 for m in matches:
50 yield Completion(m, start_position=start_pos)
50 yield Completion(m, start_position=start_pos)
51
51
52 class TerminalInteractiveShell(InteractiveShell):
52 class TerminalInteractiveShell(InteractiveShell):
53 colors_force = True
53 colors_force = True
54
54
55 pt_cli = None
55 pt_cli = None
56
56
57 vi_mode = Bool(False, config=True,
57 vi_mode = Bool(False, config=True,
58 help="Use vi style keybindings at the prompt",
58 help="Use vi style keybindings at the prompt",
59 )
59 )
60
60
61 mouse_support = Bool(False, config=True,
61 mouse_support = Bool(False, config=True,
62 help="Enable mouse support in the prompt"
62 help="Enable mouse support in the prompt"
63 )
63 )
64
64
65 highlighting_style = Unicode('', config=True,
65 highlighting_style = Unicode('', config=True,
66 help="The name of a Pygments style to use for syntax highlighting"
66 help="The name of a Pygments style to use for syntax highlighting"
67 )
67 )
68
68
69 highlighting_style_overrides = Dict(config=True,
69 highlighting_style_overrides = Dict(config=True,
70 help="Override highlighting format for specific tokens"
70 help="Override highlighting format for specific tokens"
71 )
71 )
72
72
73 editor = Unicode(get_default_editor(), config=True,
73 editor = Unicode(get_default_editor(), config=True,
74 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
74 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
75 )
75 )
76
76
77 term_title = Bool(True, config=True,
77 term_title = Bool(True, config=True,
78 help="Automatically set the terminal title"
78 help="Automatically set the terminal title"
79 )
79 )
80 def _term_title_changed(self, name, new_value):
80 def _term_title_changed(self, name, new_value):
81 self.init_term_title()
81 self.init_term_title()
82
82
83 def init_term_title(self):
83 def init_term_title(self):
84 # Enable or disable the terminal title.
84 # Enable or disable the terminal title.
85 if self.term_title:
85 if self.term_title:
86 toggle_set_term_title(True)
86 toggle_set_term_title(True)
87 set_term_title('IPython: ' + abbrev_cwd())
87 set_term_title('IPython: ' + abbrev_cwd())
88 else:
88 else:
89 toggle_set_term_title(False)
89 toggle_set_term_title(False)
90
90
91 def get_prompt_tokens(self, cli):
91 def get_prompt_tokens(self, cli):
92 return [
92 return [
93 (Token.Prompt, 'In ['),
93 (Token.Prompt, 'In ['),
94 (Token.PromptNum, str(self.execution_count)),
94 (Token.PromptNum, str(self.execution_count)),
95 (Token.Prompt, ']: '),
95 (Token.Prompt, ']: '),
96 ]
96 ]
97
97
98 def get_continuation_tokens(self, cli, width):
98 def get_continuation_tokens(self, cli, width):
99 return [
99 return [
100 (Token.Prompt, (' ' * (width - 5)) + '...: '),
100 (Token.Prompt, (' ' * (width - 5)) + '...: '),
101 ]
101 ]
102
102
103 def init_prompt_toolkit_cli(self):
103 def init_prompt_toolkit_cli(self):
104 if not sys.stdin.isatty():
104 if ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or not sys.stdin.isatty():
105 # Piped input - e.g. for tests. Fall back to plain non-interactive
105 # Fall back to plain non-interactive output for tests.
106 # output. This is very limited, and only accepts a single line.
106 # This is very limited, and only accepts a single line.
107 def prompt():
107 def prompt():
108 return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
108 return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
109 self.prompt_for_code = prompt
109 self.prompt_for_code = prompt
110 return
110 return
111
111
112 kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode)
112 kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode)
113 insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT)
113 insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT)
114 # Ctrl+J == Enter, seemingly
114 # Ctrl+J == Enter, seemingly
115 @kbmanager.registry.add_binding(Keys.ControlJ,
115 @kbmanager.registry.add_binding(Keys.ControlJ,
116 filter=(HasFocus(DEFAULT_BUFFER)
116 filter=(HasFocus(DEFAULT_BUFFER)
117 & ~HasSelection()
117 & ~HasSelection()
118 & insert_mode
118 & insert_mode
119 ))
119 ))
120 def _(event):
120 def _(event):
121 b = event.current_buffer
121 b = event.current_buffer
122 d = b.document
122 d = b.document
123 if not (d.on_last_line or d.cursor_position_row >= d.line_count
123 if not (d.on_last_line or d.cursor_position_row >= d.line_count
124 - d.empty_line_count_at_the_end()):
124 - d.empty_line_count_at_the_end()):
125 b.newline()
125 b.newline()
126 return
126 return
127
127
128 status, indent = self.input_splitter.check_complete(d.text)
128 status, indent = self.input_splitter.check_complete(d.text)
129
129
130 if (status != 'incomplete') and b.accept_action.is_returnable:
130 if (status != 'incomplete') and b.accept_action.is_returnable:
131 b.accept_action.validate_and_handle(event.cli, b)
131 b.accept_action.validate_and_handle(event.cli, b)
132 else:
132 else:
133 b.insert_text('\n' + (' ' * (indent or 0)))
133 b.insert_text('\n' + (' ' * (indent or 0)))
134
134
135 @kbmanager.registry.add_binding(Keys.ControlC)
135 @kbmanager.registry.add_binding(Keys.ControlC)
136 def _(event):
136 def _(event):
137 event.current_buffer.reset()
137 event.current_buffer.reset()
138
138
139 # Pre-populate history from IPython's history database
139 # Pre-populate history from IPython's history database
140 history = InMemoryHistory()
140 history = InMemoryHistory()
141 last_cell = u""
141 last_cell = u""
142 for _, _, cell in self.history_manager.get_tail(self.history_load_length,
142 for _, _, cell in self.history_manager.get_tail(self.history_load_length,
143 include_latest=True):
143 include_latest=True):
144 # Ignore blank lines and consecutive duplicates
144 # Ignore blank lines and consecutive duplicates
145 cell = cell.rstrip()
145 cell = cell.rstrip()
146 if cell and (cell != last_cell):
146 if cell and (cell != last_cell):
147 history.append(cell)
147 history.append(cell)
148
148
149 style_overrides = {
149 style_overrides = {
150 Token.Prompt: '#009900',
150 Token.Prompt: '#009900',
151 Token.PromptNum: '#00ff00 bold',
151 Token.PromptNum: '#00ff00 bold',
152 }
152 }
153 if self.highlighting_style:
153 if self.highlighting_style:
154 style_cls = get_style_by_name(self.highlighting_style)
154 style_cls = get_style_by_name(self.highlighting_style)
155 else:
155 else:
156 style_cls = get_style_by_name('default')
156 style_cls = get_style_by_name('default')
157 # The default theme needs to be visible on both a dark background
157 # The default theme needs to be visible on both a dark background
158 # and a light background, because we can't tell what the terminal
158 # and a light background, because we can't tell what the terminal
159 # looks like. These tweaks to the default theme help with that.
159 # looks like. These tweaks to the default theme help with that.
160 style_overrides.update({
160 style_overrides.update({
161 Token.Number: '#007700',
161 Token.Number: '#007700',
162 Token.Operator: 'noinherit',
162 Token.Operator: 'noinherit',
163 Token.String: '#BB6622',
163 Token.String: '#BB6622',
164 Token.Name.Function: '#2080D0',
164 Token.Name.Function: '#2080D0',
165 Token.Name.Class: 'bold #2080D0',
165 Token.Name.Class: 'bold #2080D0',
166 Token.Name.Namespace: 'bold #2080D0',
166 Token.Name.Namespace: 'bold #2080D0',
167 })
167 })
168 style_overrides.update(self.highlighting_style_overrides)
168 style_overrides.update(self.highlighting_style_overrides)
169 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
169 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
170 style_dict=style_overrides)
170 style_dict=style_overrides)
171
171
172 app = create_prompt_application(multiline=True,
172 app = create_prompt_application(multiline=True,
173 lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer),
173 lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer),
174 get_prompt_tokens=self.get_prompt_tokens,
174 get_prompt_tokens=self.get_prompt_tokens,
175 get_continuation_tokens=self.get_continuation_tokens,
175 get_continuation_tokens=self.get_continuation_tokens,
176 key_bindings_registry=kbmanager.registry,
176 key_bindings_registry=kbmanager.registry,
177 history=history,
177 history=history,
178 completer=IPythonPTCompleter(self.Completer),
178 completer=IPythonPTCompleter(self.Completer),
179 enable_history_search=True,
179 enable_history_search=True,
180 style=style,
180 style=style,
181 mouse_support=self.mouse_support,
181 mouse_support=self.mouse_support,
182 )
182 )
183
183
184 self.pt_cli = CommandLineInterface(app,
184 self.pt_cli = CommandLineInterface(app,
185 eventloop=create_eventloop(self.inputhook))
185 eventloop=create_eventloop(self.inputhook))
186
186
187 def prompt_for_code(self):
187 def prompt_for_code(self):
188 document = self.pt_cli.run(pre_run=self.pre_prompt)
188 document = self.pt_cli.run(pre_run=self.pre_prompt)
189 return document.text
189 return document.text
190
190
191 def init_io(self):
191 def init_io(self):
192 if sys.platform not in {'win32', 'cli'}:
192 if sys.platform not in {'win32', 'cli'}:
193 return
193 return
194
194
195 import colorama
195 import colorama
196 colorama.init()
196 colorama.init()
197
197
198 # For some reason we make these wrappers around stdout/stderr.
198 # For some reason we make these wrappers around stdout/stderr.
199 # For now, we need to reset them so all output gets coloured.
199 # For now, we need to reset them so all output gets coloured.
200 # https://github.com/ipython/ipython/issues/8669
200 # https://github.com/ipython/ipython/issues/8669
201 from IPython.utils import io
201 from IPython.utils import io
202 io.stdout = io.IOStream(sys.stdout)
202 io.stdout = io.IOStream(sys.stdout)
203 io.stderr = io.IOStream(sys.stderr)
203 io.stderr = io.IOStream(sys.stderr)
204
204
205 def init_magics(self):
205 def init_magics(self):
206 super(TerminalInteractiveShell, self).init_magics()
206 super(TerminalInteractiveShell, self).init_magics()
207 self.register_magics(TerminalMagics)
207 self.register_magics(TerminalMagics)
208
208
209 def init_alias(self):
209 def init_alias(self):
210 # The parent class defines aliases that can be safely used with any
210 # The parent class defines aliases that can be safely used with any
211 # frontend.
211 # frontend.
212 super(TerminalInteractiveShell, self).init_alias()
212 super(TerminalInteractiveShell, self).init_alias()
213
213
214 # Now define aliases that only make sense on the terminal, because they
214 # Now define aliases that only make sense on the terminal, because they
215 # need direct access to the console in a way that we can't emulate in
215 # need direct access to the console in a way that we can't emulate in
216 # GUI or web frontend
216 # GUI or web frontend
217 if os.name == 'posix':
217 if os.name == 'posix':
218 for cmd in ['clear', 'more', 'less', 'man']:
218 for cmd in ['clear', 'more', 'less', 'man']:
219 self.alias_manager.soft_define_alias(cmd, cmd)
219 self.alias_manager.soft_define_alias(cmd, cmd)
220
220
221
221
222 def __init__(self, *args, **kwargs):
222 def __init__(self, *args, **kwargs):
223 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
223 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
224 self.init_prompt_toolkit_cli()
224 self.init_prompt_toolkit_cli()
225 self.init_term_title()
225 self.init_term_title()
226 self.keep_running = True
226 self.keep_running = True
227
227
228 def ask_exit(self):
228 def ask_exit(self):
229 self.keep_running = False
229 self.keep_running = False
230
230
231 rl_next_input = None
231 rl_next_input = None
232
232
233 def pre_prompt(self):
233 def pre_prompt(self):
234 if self.rl_next_input:
234 if self.rl_next_input:
235 self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input)
235 self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input)
236 self.rl_next_input = None
236 self.rl_next_input = None
237
237
238 def interact(self):
238 def interact(self):
239 while self.keep_running:
239 while self.keep_running:
240 print(self.separate_in, end='')
240 print(self.separate_in, end='')
241
241
242 try:
242 try:
243 code = self.prompt_for_code()
243 code = self.prompt_for_code()
244 except EOFError:
244 except EOFError:
245 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
245 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
246 self.ask_exit()
246 self.ask_exit()
247
247
248 else:
248 else:
249 if code:
249 if code:
250 self.run_cell(code, store_history=True)
250 self.run_cell(code, store_history=True)
251
251
252 def mainloop(self):
252 def mainloop(self):
253 # An extra layer of protection in case someone mashing Ctrl-C breaks
253 # An extra layer of protection in case someone mashing Ctrl-C breaks
254 # out of our internal code.
254 # out of our internal code.
255 while True:
255 while True:
256 try:
256 try:
257 self.interact()
257 self.interact()
258 break
258 break
259 except KeyboardInterrupt:
259 except KeyboardInterrupt:
260 print("\nKeyboardInterrupt escaped interact()\n")
260 print("\nKeyboardInterrupt escaped interact()\n")
261
261
262 _inputhook = None
262 _inputhook = None
263 def inputhook(self, context):
263 def inputhook(self, context):
264 if self._inputhook is not None:
264 if self._inputhook is not None:
265 self._inputhook(context)
265 self._inputhook(context)
266
266
267 def enable_gui(self, gui=None):
267 def enable_gui(self, gui=None):
268 if gui:
268 if gui:
269 self._inputhook = get_inputhook_func(gui)
269 self._inputhook = get_inputhook_func(gui)
270 else:
270 else:
271 self._inputhook = None
271 self._inputhook = None
272
272
273 if __name__ == '__main__':
273 if __name__ == '__main__':
274 TerminalInteractiveShell.instance().interact()
274 TerminalInteractiveShell.instance().interact()
@@ -1,127 +1,135 b''
1 """Test embedding of IPython"""
1 """Test embedding of IPython"""
2
2
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (C) 2013 The IPython Development Team
4 # Copyright (C) 2013 The IPython Development Team
5 #
5 #
6 # Distributed under the terms of the BSD License. The full license is in
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
7 # the file COPYING, distributed as part of this software.
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 import os
14 import os
15 import subprocess
15 import sys
16 import sys
16 import nose.tools as nt
17 import nose.tools as nt
17 from IPython.utils.process import process_handler
18 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
18 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
19 from IPython.testing.decorators import skip_win32
19 from IPython.testing.decorators import skip_win32
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Tests
22 # Tests
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25
25
26 _sample_embed = b"""
26 _sample_embed = b"""
27 from __future__ import print_function
27 from __future__ import print_function
28 import IPython
28 import IPython
29
29
30 a = 3
30 a = 3
31 b = 14
31 b = 14
32 print(a, '.', b)
32 print(a, '.', b)
33
33
34 IPython.embed()
34 IPython.embed()
35
35
36 print('bye!')
36 print('bye!')
37 """
37 """
38
38
39 _exit = b"exit\r"
39 _exit = b"exit\r"
40
40
41 def test_ipython_embed():
41 def test_ipython_embed():
42 """test that `IPython.embed()` works"""
42 """test that `IPython.embed()` works"""
43 with NamedFileInTemporaryDirectory('file_with_embed.py') as f:
43 with NamedFileInTemporaryDirectory('file_with_embed.py') as f:
44 f.write(_sample_embed)
44 f.write(_sample_embed)
45 f.flush()
45 f.flush()
46 f.close() # otherwise msft won't be able to read the file
46 f.close() # otherwise msft won't be able to read the file
47
47
48 # run `python file_with_embed.py`
48 # run `python file_with_embed.py`
49 cmd = [sys.executable, f.name]
49 cmd = [sys.executable, f.name]
50 env = os.environ.copy()
51 env['IPY_TEST_SIMPLE_PROMPT'] = '1'
52
53 p = subprocess.Popen(cmd, env=env, stdin=subprocess.PIPE,
54 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
55 out, err = p.communicate(_exit)
56 std = out.decode('UTF-8')
50
57
51 out, p = process_handler(cmd, lambda p: (p.communicate(_exit), p))
52 std = out[0].decode('UTF-8')
53 nt.assert_equal(p.returncode, 0)
58 nt.assert_equal(p.returncode, 0)
54 nt.assert_in('3 . 14', std)
59 nt.assert_in('3 . 14', std)
55 if os.name != 'nt':
60 if os.name != 'nt':
56 # TODO: Fix up our different stdout references, see issue gh-14
61 # TODO: Fix up our different stdout references, see issue gh-14
57 nt.assert_in('IPython', std)
62 nt.assert_in('IPython', std)
58 nt.assert_in('bye!', std)
63 nt.assert_in('bye!', std)
59
64
60 @skip_win32
65 @skip_win32
61 def test_nest_embed():
66 def test_nest_embed():
62 """test that `IPython.embed()` is nestable"""
67 """test that `IPython.embed()` is nestable"""
63 import pexpect
68 import pexpect
64 ipy_prompt = r']:' #ansi color codes give problems matching beyond this
69 ipy_prompt = r']:' #ansi color codes give problems matching beyond this
70 env = os.environ.copy()
71 env['IPY_TEST_SIMPLE_PROMPT'] = '1'
65
72
66
73
67 child = pexpect.spawn('%s -m IPython --colors=nocolor'%(sys.executable, ))
74 child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor'],
75 env=env)
68 child.expect(ipy_prompt)
76 child.expect(ipy_prompt)
69 child.sendline("from __future__ import print_function")
77 child.sendline("from __future__ import print_function")
70 child.expect(ipy_prompt)
78 child.expect(ipy_prompt)
71 child.sendline("import IPython")
79 child.sendline("import IPython")
72 child.expect(ipy_prompt)
80 child.expect(ipy_prompt)
73 child.sendline("ip0 = get_ipython()")
81 child.sendline("ip0 = get_ipython()")
74 #enter first nested embed
82 #enter first nested embed
75 child.sendline("IPython.embed()")
83 child.sendline("IPython.embed()")
76 #skip the banner until we get to a prompt
84 #skip the banner until we get to a prompt
77 try:
85 try:
78 prompted = -1
86 prompted = -1
79 while prompted != 0:
87 while prompted != 0:
80 prompted = child.expect([ipy_prompt, '\r\n'])
88 prompted = child.expect([ipy_prompt, '\r\n'])
81 except pexpect.TIMEOUT as e:
89 except pexpect.TIMEOUT as e:
82 print(e)
90 print(e)
83 #child.interact()
91 #child.interact()
84 child.sendline("embed1 = get_ipython()"); child.expect(ipy_prompt)
92 child.sendline("embed1 = get_ipython()"); child.expect(ipy_prompt)
85 child.sendline("print('true' if embed1 is not ip0 else 'false')")
93 child.sendline("print('true' if embed1 is not ip0 else 'false')")
86 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
94 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
87 child.expect(ipy_prompt)
95 child.expect(ipy_prompt)
88 child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')")
96 child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')")
89 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
97 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
90 child.expect(ipy_prompt)
98 child.expect(ipy_prompt)
91 #enter second nested embed
99 #enter second nested embed
92 child.sendline("IPython.embed()")
100 child.sendline("IPython.embed()")
93 #skip the banner until we get to a prompt
101 #skip the banner until we get to a prompt
94 try:
102 try:
95 prompted = -1
103 prompted = -1
96 while prompted != 0:
104 while prompted != 0:
97 prompted = child.expect([ipy_prompt, '\r\n'])
105 prompted = child.expect([ipy_prompt, '\r\n'])
98 except pexpect.TIMEOUT as e:
106 except pexpect.TIMEOUT as e:
99 print(e)
107 print(e)
100 #child.interact()
108 #child.interact()
101 child.sendline("embed2 = get_ipython()"); child.expect(ipy_prompt)
109 child.sendline("embed2 = get_ipython()"); child.expect(ipy_prompt)
102 child.sendline("print('true' if embed2 is not embed1 else 'false')")
110 child.sendline("print('true' if embed2 is not embed1 else 'false')")
103 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
111 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
104 child.expect(ipy_prompt)
112 child.expect(ipy_prompt)
105 child.sendline("print('true' if embed2 is IPython.get_ipython() else 'false')")
113 child.sendline("print('true' if embed2 is IPython.get_ipython() else 'false')")
106 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
114 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
107 child.expect(ipy_prompt)
115 child.expect(ipy_prompt)
108 child.sendline('exit')
116 child.sendline('exit')
109 #back at first embed
117 #back at first embed
110 child.expect(ipy_prompt)
118 child.expect(ipy_prompt)
111 child.sendline("print('true' if get_ipython() is embed1 else 'false')")
119 child.sendline("print('true' if get_ipython() is embed1 else 'false')")
112 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
120 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
113 child.expect(ipy_prompt)
121 child.expect(ipy_prompt)
114 child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')")
122 child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')")
115 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
123 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
116 child.expect(ipy_prompt)
124 child.expect(ipy_prompt)
117 child.sendline('exit')
125 child.sendline('exit')
118 #back at launching scope
126 #back at launching scope
119 child.expect(ipy_prompt)
127 child.expect(ipy_prompt)
120 child.sendline("print('true' if get_ipython() is ip0 else 'false')")
128 child.sendline("print('true' if get_ipython() is ip0 else 'false')")
121 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
129 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
122 child.expect(ipy_prompt)
130 child.expect(ipy_prompt)
123 child.sendline("print('true' if IPython.get_ipython() is ip0 else 'false')")
131 child.sendline("print('true' if IPython.get_ipython() is ip0 else 'false')")
124 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
132 assert(child.expect(['true\r\n', 'false\r\n']) == 0)
125 child.expect(ipy_prompt)
133 child.expect(ipy_prompt)
126 child.sendline('exit')
134 child.sendline('exit')
127 child.close()
135 child.close()
General Comments 0
You need to be logged in to leave comments. Login now