Show More
@@ -1,298 +1,299 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | An embedded IPython shell. |
|
4 | 4 | """ |
|
5 | 5 | # Copyright (c) IPython Development Team. |
|
6 | 6 | # Distributed under the terms of the Modified BSD License. |
|
7 | 7 | |
|
8 | 8 | from __future__ import with_statement |
|
9 | 9 | from __future__ import print_function |
|
10 | 10 | |
|
11 | 11 | import sys |
|
12 | 12 | import warnings |
|
13 | 13 | |
|
14 | 14 | from IPython.core import ultratb, compilerop |
|
15 | 15 | from IPython.core.magic import Magics, magics_class, line_magic |
|
16 | 16 | from IPython.core.interactiveshell import DummyMod |
|
17 | 17 | from IPython.core.interactiveshell import InteractiveShell |
|
18 | 18 | from IPython.terminal.interactiveshell import TerminalInteractiveShell |
|
19 | 19 | from IPython.terminal.ipapp import load_default_config |
|
20 | 20 | |
|
21 | 21 | from traitlets import Bool, CBool, Unicode |
|
22 | 22 | from IPython.utils.io import ask_yes_no |
|
23 | 23 | |
|
24 | 24 | class KillEmbeded(Exception):pass |
|
25 | 25 | |
|
26 | 26 | # This is an additional magic that is exposed in embedded shells. |
|
27 | 27 | @magics_class |
|
28 | 28 | class EmbeddedMagics(Magics): |
|
29 | 29 | |
|
30 | 30 | @line_magic |
|
31 | 31 | def kill_embedded(self, parameter_s=''): |
|
32 | 32 | """%kill_embedded : deactivate for good the current embedded IPython. |
|
33 | 33 | |
|
34 | 34 | This function (after asking for confirmation) sets an internal flag so |
|
35 | 35 | that an embedded IPython will never activate again. This is useful to |
|
36 | 36 | permanently disable a shell that is being called inside a loop: once |
|
37 | 37 | you've figured out what you needed from it, you may then kill it and |
|
38 | 38 | the program will then continue to run without the interactive shell |
|
39 | 39 | interfering again. |
|
40 | 40 | """ |
|
41 | 41 | |
|
42 | 42 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " |
|
43 | 43 | "(y/n)? [y/N] ",'n') |
|
44 | 44 | if kill: |
|
45 | 45 | self.shell.embedded_active = False |
|
46 | 46 | print ("This embedded IPython will not reactivate anymore " |
|
47 | 47 | "once you exit.") |
|
48 | 48 | |
|
49 | 49 | |
|
50 | 50 | @line_magic |
|
51 | 51 | def exit_raise(self, parameter_s=''): |
|
52 | 52 | """%exit_raise Make the current embedded kernel exit and raise and exception. |
|
53 | 53 | |
|
54 | 54 | This function sets an internal flag so that an embedded IPython will |
|
55 | 55 | raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is |
|
56 | 56 | useful to permanently exit a loop that create IPython embed instance. |
|
57 | 57 | """ |
|
58 | 58 | |
|
59 | 59 | self.shell.should_raise = True |
|
60 | 60 | self.shell.ask_exit() |
|
61 | 61 | |
|
62 | 62 | |
|
63 | 63 | |
|
64 | 64 | class InteractiveShellEmbed(TerminalInteractiveShell): |
|
65 | 65 | |
|
66 | 66 | dummy_mode = Bool(False) |
|
67 | 67 | exit_msg = Unicode('') |
|
68 | 68 | embedded = CBool(True) |
|
69 | 69 | embedded_active = CBool(True) |
|
70 | 70 | should_raise = CBool(False) |
|
71 | 71 | # Like the base class display_banner is not configurable, but here it |
|
72 | 72 | # is True by default. |
|
73 | 73 | display_banner = CBool(True) |
|
74 | 74 | exit_msg = Unicode() |
|
75 | 75 | |
|
76 | 76 | |
|
77 | 77 | def __init__(self, **kw): |
|
78 | 78 | |
|
79 | 79 | |
|
80 | 80 | if kw.get('user_global_ns', None) is not None: |
|
81 | 81 | warnings.warn("user_global_ns has been replaced by user_module. The\ |
|
82 | 82 | parameter will be ignored, and removed in IPython 5.0", DeprecationWarning) |
|
83 | 83 | |
|
84 | 84 | super(InteractiveShellEmbed,self).__init__(**kw) |
|
85 | 85 | |
|
86 | 86 | # don't use the ipython crash handler so that user exceptions aren't |
|
87 | 87 | # trapped |
|
88 | 88 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, |
|
89 | 89 | mode=self.xmode, |
|
90 | 90 | call_pdb=self.pdb) |
|
91 | 91 | |
|
92 | 92 | def init_sys_modules(self): |
|
93 | 93 | pass |
|
94 | 94 | |
|
95 | 95 | def init_magics(self): |
|
96 | 96 | super(InteractiveShellEmbed, self).init_magics() |
|
97 | 97 | self.register_magics(EmbeddedMagics) |
|
98 | 98 | |
|
99 | 99 | def __call__(self, header='', local_ns=None, module=None, dummy=None, |
|
100 | 100 | stack_depth=1, global_ns=None, compile_flags=None): |
|
101 | 101 | """Activate the interactive interpreter. |
|
102 | 102 | |
|
103 | 103 | __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start |
|
104 | 104 | the interpreter shell with the given local and global namespaces, and |
|
105 | 105 | optionally print a header string at startup. |
|
106 | 106 | |
|
107 | 107 | The shell can be globally activated/deactivated using the |
|
108 | 108 | dummy_mode attribute. This allows you to turn off a shell used |
|
109 | 109 | for debugging globally. |
|
110 | 110 | |
|
111 | 111 | However, *each* time you call the shell you can override the current |
|
112 | 112 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
113 | 113 | example, if you set dummy mode on with IPShell.dummy_mode = True, you |
|
114 | 114 | can still have a specific call work by making it as IPShell(dummy=False). |
|
115 | 115 | """ |
|
116 | 116 | |
|
117 | 117 | # If the user has turned it off, go away |
|
118 | 118 | if not self.embedded_active: |
|
119 | 119 | return |
|
120 | 120 | |
|
121 | 121 | # Normal exits from interactive mode set this flag, so the shell can't |
|
122 | 122 | # re-enter (it checks this variable at the start of interactive mode). |
|
123 | 123 | self.exit_now = False |
|
124 | 124 | |
|
125 | 125 | # Allow the dummy parameter to override the global __dummy_mode |
|
126 | 126 | if dummy or (dummy != 0 and self.dummy_mode): |
|
127 | 127 | return |
|
128 | 128 | |
|
129 | 129 | if self.has_readline: |
|
130 | 130 | self.set_readline_completer() |
|
131 | 131 | |
|
132 | 132 | # self.banner is auto computed |
|
133 | 133 | if header: |
|
134 | 134 | self.old_banner2 = self.banner2 |
|
135 | 135 | self.banner2 = self.banner2 + '\n' + header + '\n' |
|
136 | 136 | else: |
|
137 | 137 | self.old_banner2 = '' |
|
138 | 138 | |
|
139 | 139 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
140 | 140 | # our call and get the original caller's namespaces. |
|
141 | 141 | self.mainloop(local_ns, module, stack_depth=stack_depth, |
|
142 | 142 | global_ns=global_ns, compile_flags=compile_flags) |
|
143 | 143 | |
|
144 | 144 | self.banner2 = self.old_banner2 |
|
145 | 145 | |
|
146 | 146 | if self.exit_msg is not None: |
|
147 | 147 | print(self.exit_msg) |
|
148 | 148 | |
|
149 | 149 | if self.should_raise: |
|
150 | 150 | raise KillEmbeded('Embedded IPython raising error, as user requested.') |
|
151 | 151 | |
|
152 | 152 | |
|
153 | 153 | def mainloop(self, local_ns=None, module=None, stack_depth=0, |
|
154 | 154 | display_banner=None, global_ns=None, compile_flags=None): |
|
155 | 155 | """Embeds IPython into a running python program. |
|
156 | 156 | |
|
157 | 157 | Parameters |
|
158 | 158 | ---------- |
|
159 | 159 | |
|
160 | 160 | local_ns, module |
|
161 | 161 | Working local namespace (a dict) and module (a module or similar |
|
162 | 162 | object). If given as None, they are automatically taken from the scope |
|
163 | 163 | where the shell was called, so that program variables become visible. |
|
164 | 164 | |
|
165 | 165 | stack_depth : int |
|
166 | 166 | How many levels in the stack to go to looking for namespaces (when |
|
167 | 167 | local_ns or module is None). This allows an intermediate caller to |
|
168 | 168 | make sure that this function gets the namespace from the intended |
|
169 | 169 | level in the stack. By default (0) it will get its locals and globals |
|
170 | 170 | from the immediate caller. |
|
171 | 171 | |
|
172 | 172 | compile_flags |
|
173 | 173 | A bit field identifying the __future__ features |
|
174 | 174 | that are enabled, as passed to the builtin :func:`compile` function. |
|
175 | 175 | If given as None, they are automatically taken from the scope where |
|
176 | 176 | the shell was called. |
|
177 | 177 | |
|
178 | 178 | """ |
|
179 | 179 | |
|
180 | 180 | if (global_ns is not None) and (module is None): |
|
181 | 181 | warnings.warn("global_ns is deprecated, and will be removed in IPython 5.0 use module instead.", DeprecationWarning) |
|
182 | 182 | module = DummyMod() |
|
183 | 183 | module.__dict__ = global_ns |
|
184 | 184 | |
|
185 | 185 | # Get locals and globals from caller |
|
186 | 186 | if ((local_ns is None or module is None or compile_flags is None) |
|
187 | 187 | and self.default_user_namespaces): |
|
188 | 188 | call_frame = sys._getframe(stack_depth).f_back |
|
189 | 189 | |
|
190 | 190 | if local_ns is None: |
|
191 | 191 | local_ns = call_frame.f_locals |
|
192 | 192 | if module is None: |
|
193 | 193 | global_ns = call_frame.f_globals |
|
194 | 194 | module = sys.modules[global_ns['__name__']] |
|
195 | 195 | if compile_flags is None: |
|
196 | 196 | compile_flags = (call_frame.f_code.co_flags & |
|
197 | 197 | compilerop.PyCF_MASK) |
|
198 | 198 | |
|
199 | 199 | # Save original namespace and module so we can restore them after |
|
200 | 200 | # embedding; otherwise the shell doesn't shut down correctly. |
|
201 | 201 | orig_user_module = self.user_module |
|
202 | 202 | orig_user_ns = self.user_ns |
|
203 | 203 | orig_compile_flags = self.compile.flags |
|
204 | 204 | |
|
205 | 205 | # Update namespaces and fire up interpreter |
|
206 | 206 | |
|
207 | 207 | # The global one is easy, we can just throw it in |
|
208 | 208 | if module is not None: |
|
209 | 209 | self.user_module = module |
|
210 | 210 | |
|
211 | 211 | # But the user/local one is tricky: ipython needs it to store internal |
|
212 | 212 | # data, but we also need the locals. We'll throw our hidden variables |
|
213 | 213 | # like _ih and get_ipython() into the local namespace, but delete them |
|
214 | 214 | # later. |
|
215 | 215 | if local_ns is not None: |
|
216 | 216 | reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()} |
|
217 | 217 | self.user_ns = reentrant_local_ns |
|
218 | 218 | self.init_user_ns() |
|
219 | 219 | |
|
220 | 220 | # Compiler flags |
|
221 | 221 | if compile_flags is not None: |
|
222 | 222 | self.compile.flags = compile_flags |
|
223 | 223 | |
|
224 | 224 | # make sure the tab-completer has the correct frame information, so it |
|
225 | 225 | # actually completes using the frame's locals/globals |
|
226 | 226 | self.set_completer_frame() |
|
227 | 227 | |
|
228 | 228 | with self.builtin_trap, self.display_trap: |
|
229 | 229 | self.interact(display_banner=display_banner) |
|
230 | 230 | |
|
231 | 231 | # now, purge out the local namespace of IPython's hidden variables. |
|
232 | 232 | if local_ns is not None: |
|
233 | 233 | local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()}) |
|
234 | 234 | |
|
235 | 235 | |
|
236 | 236 | # Restore original namespace so shell can shut down when we exit. |
|
237 | 237 | self.user_module = orig_user_module |
|
238 | 238 | self.user_ns = orig_user_ns |
|
239 | 239 | self.compile.flags = orig_compile_flags |
|
240 | 240 | |
|
241 | 241 | |
|
242 | 242 | def embed(**kwargs): |
|
243 | 243 | """Call this to embed IPython at the current point in your program. |
|
244 | 244 | |
|
245 | 245 | The first invocation of this will create an :class:`InteractiveShellEmbed` |
|
246 | 246 | instance and then call it. Consecutive calls just call the already |
|
247 | 247 | created instance. |
|
248 | 248 | |
|
249 | 249 | If you don't want the kernel to initialize the namespace |
|
250 | 250 | from the scope of the surrounding function, |
|
251 | 251 | and/or you want to load full IPython configuration, |
|
252 | 252 | you probably want `IPython.start_ipython()` instead. |
|
253 | 253 | |
|
254 | 254 | Here is a simple example:: |
|
255 | 255 | |
|
256 | 256 | from IPython import embed |
|
257 | 257 | a = 10 |
|
258 | 258 | b = 20 |
|
259 | 259 | embed(header='First time') |
|
260 | 260 | c = 30 |
|
261 | 261 | d = 40 |
|
262 | 262 | embed() |
|
263 | 263 | |
|
264 | 264 | Full customization can be done by passing a :class:`Config` in as the |
|
265 | 265 | config argument. |
|
266 | 266 | """ |
|
267 | 267 | config = kwargs.get('config') |
|
268 | 268 | header = kwargs.pop('header', u'') |
|
269 | 269 | compile_flags = kwargs.pop('compile_flags', None) |
|
270 | 270 | if config is None: |
|
271 | 271 | config = load_default_config() |
|
272 | 272 | config.InteractiveShellEmbed = config.TerminalInteractiveShell |
|
273 | config.InteractiveShellEmbed.colors='nocolor' | |
|
273 | 274 | kwargs['config'] = config |
|
274 | 275 | #save ps1/ps2 if defined |
|
275 | 276 | ps1 = None |
|
276 | 277 | ps2 = None |
|
277 | 278 | try: |
|
278 | 279 | ps1 = sys.ps1 |
|
279 | 280 | ps2 = sys.ps2 |
|
280 | 281 | except AttributeError: |
|
281 | 282 | pass |
|
282 | 283 | #save previous instance |
|
283 | 284 | saved_shell_instance = InteractiveShell._instance |
|
284 | 285 | if saved_shell_instance is not None: |
|
285 | 286 | cls = type(saved_shell_instance) |
|
286 | 287 | cls.clear_instance() |
|
287 | 288 | shell = InteractiveShellEmbed.instance(**kwargs) |
|
288 | 289 | shell(header=header, stack_depth=2, compile_flags=compile_flags) |
|
289 | 290 | InteractiveShellEmbed.clear_instance() |
|
290 | 291 | #restore previous instance |
|
291 | 292 | if saved_shell_instance is not None: |
|
292 | 293 | cls = type(saved_shell_instance) |
|
293 | 294 | cls.clear_instance() |
|
294 | 295 | for subclass in cls._walk_mro(): |
|
295 | 296 | subclass._instance = saved_shell_instance |
|
296 | 297 | if ps1 is not None: |
|
297 | 298 | sys.ps1 = ps1 |
|
298 | 299 | sys.ps2 = ps2 |
@@ -1,125 +1,127 b'' | |||
|
1 | 1 | """Test embedding of IPython""" |
|
2 | 2 | |
|
3 | 3 | #----------------------------------------------------------------------------- |
|
4 | 4 | # Copyright (C) 2013 The IPython Development Team |
|
5 | 5 | # |
|
6 | 6 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | 7 | # the file COPYING, distributed as part of this software. |
|
8 | 8 | #----------------------------------------------------------------------------- |
|
9 | 9 | |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | # Imports |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | import os |
|
15 | 15 | import sys |
|
16 | 16 | import nose.tools as nt |
|
17 | 17 | from IPython.utils.process import process_handler |
|
18 | 18 | from IPython.utils.tempdir import NamedFileInTemporaryDirectory |
|
19 | 19 | from IPython.testing.decorators import skip_win32 |
|
20 | 20 | |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | # Tests |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | |
|
25 | 25 | |
|
26 | 26 | _sample_embed = b""" |
|
27 | 27 | from __future__ import print_function |
|
28 | 28 | import IPython |
|
29 | 29 | |
|
30 | 30 | a = 3 |
|
31 | 31 | b = 14 |
|
32 | 32 | print(a, '.', b) |
|
33 | 33 | |
|
34 | 34 | IPython.embed() |
|
35 | 35 | |
|
36 | 36 | print('bye!') |
|
37 | 37 | """ |
|
38 | 38 | |
|
39 | 39 | _exit = b"exit\r" |
|
40 | 40 | |
|
41 | 41 | def test_ipython_embed(): |
|
42 | 42 | """test that `IPython.embed()` works""" |
|
43 | 43 | with NamedFileInTemporaryDirectory('file_with_embed.py') as f: |
|
44 | 44 | f.write(_sample_embed) |
|
45 | 45 | f.flush() |
|
46 | 46 | f.close() # otherwise msft won't be able to read the file |
|
47 | 47 | |
|
48 | 48 | # run `python file_with_embed.py` |
|
49 | 49 | cmd = [sys.executable, f.name] |
|
50 | 50 | |
|
51 | 51 | out, p = process_handler(cmd, lambda p: (p.communicate(_exit), p)) |
|
52 | 52 | std = out[0].decode('UTF-8') |
|
53 | 53 | nt.assert_equal(p.returncode, 0) |
|
54 | 54 | nt.assert_in('3 . 14', std) |
|
55 | 55 | if os.name != 'nt': |
|
56 | 56 | # TODO: Fix up our different stdout references, see issue gh-14 |
|
57 | 57 | nt.assert_in('IPython', std) |
|
58 | 58 | nt.assert_in('bye!', std) |
|
59 | 59 | |
|
60 | 60 | @skip_win32 |
|
61 | 61 | def test_nest_embed(): |
|
62 | 62 | """test that `IPython.embed()` is nestable""" |
|
63 | 63 | import pexpect |
|
64 | 64 | ipy_prompt = r']:' #ansi color codes give problems matching beyond this |
|
65 | 65 | |
|
66 | 66 | |
|
67 | child = pexpect.spawn('%s -m IPython'%(sys.executable, )) | |
|
67 | child = pexpect.spawn('%s -m IPython --colors=nocolor'%(sys.executable, )) | |
|
68 | 68 | child.expect(ipy_prompt) |
|
69 | 69 | child.sendline("from __future__ import print_function") |
|
70 | 70 | child.expect(ipy_prompt) |
|
71 | 71 | child.sendline("import IPython") |
|
72 | 72 | child.expect(ipy_prompt) |
|
73 | 73 | child.sendline("ip0 = get_ipython()") |
|
74 | 74 | #enter first nested embed |
|
75 | 75 | child.sendline("IPython.embed()") |
|
76 | 76 | #skip the banner until we get to a prompt |
|
77 | 77 | try: |
|
78 | 78 | prompted = -1 |
|
79 | 79 | while prompted != 0: |
|
80 | 80 | prompted = child.expect([ipy_prompt, '\r\n']) |
|
81 | 81 | except pexpect.TIMEOUT as e: |
|
82 | 82 | print(e) |
|
83 | 83 | #child.interact() |
|
84 | 84 | child.sendline("embed1 = get_ipython()"); child.expect(ipy_prompt) |
|
85 | 85 | child.sendline("print('true' if embed1 is not ip0 else 'false')") |
|
86 | 86 | assert(child.expect(['true\r\n', 'false\r\n']) == 0) |
|
87 | 87 | child.expect(ipy_prompt) |
|
88 | 88 | child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')") |
|
89 | 89 | assert(child.expect(['true\r\n', 'false\r\n']) == 0) |
|
90 | 90 | child.expect(ipy_prompt) |
|
91 | 91 | #enter second nested embed |
|
92 | 92 | child.sendline("IPython.embed()") |
|
93 | 93 | #skip the banner until we get to a prompt |
|
94 | 94 | try: |
|
95 | 95 | prompted = -1 |
|
96 | 96 | while prompted != 0: |
|
97 | 97 | prompted = child.expect([ipy_prompt, '\r\n']) |
|
98 | 98 | except pexpect.TIMEOUT as e: |
|
99 | 99 | print(e) |
|
100 | 100 | #child.interact() |
|
101 | 101 | child.sendline("embed2 = get_ipython()"); child.expect(ipy_prompt) |
|
102 | 102 | child.sendline("print('true' if embed2 is not embed1 else 'false')") |
|
103 | 103 | assert(child.expect(['true\r\n', 'false\r\n']) == 0) |
|
104 | 104 | child.expect(ipy_prompt) |
|
105 | 105 | child.sendline("print('true' if embed2 is IPython.get_ipython() else 'false')") |
|
106 | 106 | assert(child.expect(['true\r\n', 'false\r\n']) == 0) |
|
107 | 107 | child.expect(ipy_prompt) |
|
108 | 108 | child.sendline('exit') |
|
109 | 109 | #back at first embed |
|
110 | 110 | child.expect(ipy_prompt) |
|
111 | 111 | child.sendline("print('true' if get_ipython() is embed1 else 'false')") |
|
112 | 112 | assert(child.expect(['true\r\n', 'false\r\n']) == 0) |
|
113 | 113 | child.expect(ipy_prompt) |
|
114 | 114 | child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')") |
|
115 | 115 | assert(child.expect(['true\r\n', 'false\r\n']) == 0) |
|
116 | 116 | child.expect(ipy_prompt) |
|
117 | 117 | child.sendline('exit') |
|
118 | 118 | #back at launching scope |
|
119 | 119 | child.expect(ipy_prompt) |
|
120 | 120 | child.sendline("print('true' if get_ipython() is ip0 else 'false')") |
|
121 | 121 | assert(child.expect(['true\r\n', 'false\r\n']) == 0) |
|
122 | 122 | child.expect(ipy_prompt) |
|
123 | 123 | child.sendline("print('true' if IPython.get_ipython() is ip0 else 'false')") |
|
124 | 124 | assert(child.expect(['true\r\n', 'false\r\n']) == 0) |
|
125 | 125 | child.expect(ipy_prompt) |
|
126 | child.sendline('exit') | |
|
127 | child.close() |
General Comments 0
You need to be logged in to leave comments.
Login now