##// END OF EJS Templates
expand start_ipython / embed docstrings...
MinRK -
Show More
@@ -1,106 +1,114 b''
1 1 # encoding: utf-8
2 2 """
3 3 IPython: tools for interactive and parallel computing in Python.
4 4
5 5 http://ipython.org
6 6 """
7 7 #-----------------------------------------------------------------------------
8 8 # Copyright (c) 2008-2011, IPython Development Team.
9 9 # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
10 10 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
11 11 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
12 12 #
13 13 # Distributed under the terms of the Modified BSD License.
14 14 #
15 15 # The full license is in the file COPYING.txt, distributed with this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21 from __future__ import absolute_import
22 22
23 23 import os
24 24 import sys
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Setup everything
28 28 #-----------------------------------------------------------------------------
29 29
30 30 # Don't forget to also update setup.py when this changes!
31 31 if sys.version[0:3] < '2.6':
32 32 raise ImportError('Python Version 2.6 or above is required for IPython.')
33 33
34 34 # Make it easy to import extensions - they are always directly on pythonpath.
35 35 # Therefore, non-IPython modules can be added to extensions directory.
36 36 # This should probably be in ipapp.py.
37 37 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
38 38
39 39 #-----------------------------------------------------------------------------
40 40 # Setup the top level names
41 41 #-----------------------------------------------------------------------------
42 42
43 43 from .config.loader import Config
44 44 from .core.getipython import get_ipython
45 45 from .core import release
46 46 from .core.application import Application
47 47 from .terminal.embed import embed
48 48
49 49 from .core.error import TryNext
50 50 from .core.interactiveshell import InteractiveShell
51 51 from .testing import test
52 52 from .utils.sysinfo import sys_info
53 53 from .utils.frame import extract_module_locals
54 54
55 55 # Release data
56 56 __author__ = '%s <%s>' % (release.author, release.author_email)
57 57 __license__ = release.license
58 58 __version__ = release.version
59 59 version_info = release.version_info
60 60
61 61 def embed_kernel(module=None, local_ns=None, **kwargs):
62 62 """Embed and start an IPython kernel in a given scope.
63 63
64 64 Parameters
65 65 ----------
66 66 module : ModuleType, optional
67 67 The module to load into IPython globals (default: caller)
68 68 local_ns : dict, optional
69 69 The namespace to load into IPython user namespace (default: caller)
70 70
71 71 kwargs : various, optional
72 72 Further keyword args are relayed to the IPKernelApp constructor,
73 73 allowing configuration of the Kernel. Will only have an effect
74 74 on the first embed_kernel call for a given process.
75 75
76 76 """
77 77
78 78 (caller_module, caller_locals) = extract_module_locals(1)
79 79 if module is None:
80 80 module = caller_module
81 81 if local_ns is None:
82 82 local_ns = caller_locals
83 83
84 84 # Only import .zmq when we really need it
85 85 from IPython.kernel.zmq.embed import embed_kernel as real_embed_kernel
86 86 real_embed_kernel(module=module, local_ns=local_ns, **kwargs)
87 87
88 88 def start_ipython(argv=None, **kwargs):
89 """launch a normal IPython instance (as opposed to embedded)
89 """Launch a normal IPython instance (as opposed to embedded)
90 90
91 This is a public API method, and will survive implementation changes.
91 `IPython.embed()` puts a shell in a particular calling scope,
92 such as a function or method for debugging purposes,
93 which is often not desirable.
94
95 `start_ipython()` does full, regular IPython initialization,
96 including loading startup files, configuration, etc.
97 much of which is skipped by `embed()`.
92 98
99 This is a public API method, and will survive implementation changes.
93 100
94 101 Parameters
95 102 ----------
96 103
97 104 argv : list or None, optional
98 105 If unspecified or None, IPython will parse command-line options from sys.argv.
99 106 To prevent any command-line parsing, pass an empty list: `argv=[]`.
100
107 user_ns : dict, optional
108 specify this dictionary to initialize the IPython user namespace with particular values.
101 109 kwargs : various, optional
102 110 Any other kwargs will be passed to the Application constructor,
103 111 such as `config`.
104 112 """
105 113 from IPython.terminal.ipapp import launch_new_instance
106 114 return launch_new_instance(argv=argv, **kwargs)
@@ -1,296 +1,301 b''
1 1 # encoding: utf-8
2 2 """
3 3 An embedded IPython shell.
4 4
5 5 Authors:
6 6
7 7 * Brian Granger
8 8 * Fernando Perez
9 9
10 10 Notes
11 11 -----
12 12 """
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Copyright (C) 2008-2011 The IPython Development Team
16 16 #
17 17 # Distributed under the terms of the BSD License. The full license is in
18 18 # the file COPYING, distributed as part of this software.
19 19 #-----------------------------------------------------------------------------
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 24
25 25 from __future__ import with_statement
26 26
27 27 import sys
28 28 import warnings
29 29
30 30 # We need to use nested to support python 2.6, once we move to >=2.7, we can
31 31 # use the with keyword's new builtin support for nested managers
32 32 try:
33 33 from contextlib import nested
34 34 except:
35 35 from IPython.utils.nested_context import nested
36 36
37 37 from IPython.core import ultratb, compilerop
38 38 from IPython.core.magic import Magics, magics_class, line_magic
39 39 from IPython.terminal.interactiveshell import TerminalInteractiveShell
40 40 from IPython.terminal.ipapp import load_default_config
41 41
42 42 from IPython.utils.traitlets import Bool, CBool, Unicode
43 43 from IPython.utils.io import ask_yes_no
44 44
45 45
46 46 #-----------------------------------------------------------------------------
47 47 # Classes and functions
48 48 #-----------------------------------------------------------------------------
49 49
50 50 # This is an additional magic that is exposed in embedded shells.
51 51 @magics_class
52 52 class EmbeddedMagics(Magics):
53 53
54 54 @line_magic
55 55 def kill_embedded(self, parameter_s=''):
56 56 """%kill_embedded : deactivate for good the current embedded IPython.
57 57
58 58 This function (after asking for confirmation) sets an internal flag so
59 59 that an embedded IPython will never activate again. This is useful to
60 60 permanently disable a shell that is being called inside a loop: once
61 61 you've figured out what you needed from it, you may then kill it and
62 62 the program will then continue to run without the interactive shell
63 63 interfering again.
64 64 """
65 65
66 66 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
67 67 "(y/n)? [y/N] ",'n')
68 68 if kill:
69 69 self.shell.embedded_active = False
70 70 print ("This embedded IPython will not reactivate anymore "
71 71 "once you exit.")
72 72
73 73
74 74 class InteractiveShellEmbed(TerminalInteractiveShell):
75 75
76 76 dummy_mode = Bool(False)
77 77 exit_msg = Unicode('')
78 78 embedded = CBool(True)
79 79 embedded_active = CBool(True)
80 80 # Like the base class display_banner is not configurable, but here it
81 81 # is True by default.
82 82 display_banner = CBool(True)
83 83
84 84 def __init__(self, config=None, ipython_dir=None, user_ns=None,
85 85 user_module=None, custom_exceptions=((),None),
86 86 usage=None, banner1=None, banner2=None,
87 87 display_banner=None, exit_msg=u'', user_global_ns=None):
88 88
89 89 if user_global_ns is not None:
90 90 warnings.warn("user_global_ns has been replaced by user_module. The\
91 91 parameter will be ignored.", DeprecationWarning)
92 92
93 93 super(InteractiveShellEmbed,self).__init__(
94 94 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
95 95 user_module=user_module, custom_exceptions=custom_exceptions,
96 96 usage=usage, banner1=banner1, banner2=banner2,
97 97 display_banner=display_banner
98 98 )
99 99
100 100 self.exit_msg = exit_msg
101 101
102 102 # don't use the ipython crash handler so that user exceptions aren't
103 103 # trapped
104 104 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
105 105 mode=self.xmode,
106 106 call_pdb=self.pdb)
107 107
108 108 def init_sys_modules(self):
109 109 pass
110 110
111 111 def init_magics(self):
112 112 super(InteractiveShellEmbed, self).init_magics()
113 113 self.register_magics(EmbeddedMagics)
114 114
115 115 def __call__(self, header='', local_ns=None, module=None, dummy=None,
116 116 stack_depth=1, global_ns=None, compile_flags=None):
117 117 """Activate the interactive interpreter.
118 118
119 119 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
120 120 the interpreter shell with the given local and global namespaces, and
121 121 optionally print a header string at startup.
122 122
123 123 The shell can be globally activated/deactivated using the
124 124 dummy_mode attribute. This allows you to turn off a shell used
125 125 for debugging globally.
126 126
127 127 However, *each* time you call the shell you can override the current
128 128 state of dummy_mode with the optional keyword parameter 'dummy'. For
129 129 example, if you set dummy mode on with IPShell.dummy_mode = True, you
130 130 can still have a specific call work by making it as IPShell(dummy=False).
131 131 """
132 132
133 133 # If the user has turned it off, go away
134 134 if not self.embedded_active:
135 135 return
136 136
137 137 # Normal exits from interactive mode set this flag, so the shell can't
138 138 # re-enter (it checks this variable at the start of interactive mode).
139 139 self.exit_now = False
140 140
141 141 # Allow the dummy parameter to override the global __dummy_mode
142 142 if dummy or (dummy != 0 and self.dummy_mode):
143 143 return
144 144
145 145 if self.has_readline:
146 146 self.set_readline_completer()
147 147
148 148 # self.banner is auto computed
149 149 if header:
150 150 self.old_banner2 = self.banner2
151 151 self.banner2 = self.banner2 + '\n' + header + '\n'
152 152 else:
153 153 self.old_banner2 = ''
154 154
155 155 # Call the embedding code with a stack depth of 1 so it can skip over
156 156 # our call and get the original caller's namespaces.
157 157 self.mainloop(local_ns, module, stack_depth=stack_depth,
158 158 global_ns=global_ns, compile_flags=compile_flags)
159 159
160 160 self.banner2 = self.old_banner2
161 161
162 162 if self.exit_msg is not None:
163 163 print self.exit_msg
164 164
165 165 def mainloop(self, local_ns=None, module=None, stack_depth=0,
166 166 display_banner=None, global_ns=None, compile_flags=None):
167 167 """Embeds IPython into a running python program.
168 168
169 169 Input:
170 170
171 171 - header: An optional header message can be specified.
172 172
173 173 - local_ns, module: working local namespace (a dict) and module (a
174 174 module or similar object). If given as None, they are automatically
175 175 taken from the scope where the shell was called, so that
176 176 program variables become visible.
177 177
178 178 - stack_depth: specifies how many levels in the stack to go to
179 179 looking for namespaces (when local_ns or module is None). This
180 180 allows an intermediate caller to make sure that this function gets
181 181 the namespace from the intended level in the stack. By default (0)
182 182 it will get its locals and globals from the immediate caller.
183 183
184 184 - compile_flags: A bit field identifying the __future__ features
185 185 that are enabled, as passed to the builtin `compile` function. If
186 186 given as None, they are automatically taken from the scope where the
187 187 shell was called.
188 188
189 189 Warning: it's possible to use this in a program which is being run by
190 190 IPython itself (via %run), but some funny things will happen (a few
191 191 globals get overwritten). In the future this will be cleaned up, as
192 192 there is no fundamental reason why it can't work perfectly."""
193 193
194 194 if (global_ns is not None) and (module is None):
195 195 class DummyMod(object):
196 196 """A dummy module object for embedded IPython."""
197 197 pass
198 198 warnings.warn("global_ns is deprecated, use module instead.", DeprecationWarning)
199 199 module = DummyMod()
200 200 module.__dict__ = global_ns
201 201
202 202 # Get locals and globals from caller
203 203 if ((local_ns is None or module is None or compile_flags is None)
204 204 and self.default_user_namespaces):
205 205 call_frame = sys._getframe(stack_depth).f_back
206 206
207 207 if local_ns is None:
208 208 local_ns = call_frame.f_locals
209 209 if module is None:
210 210 global_ns = call_frame.f_globals
211 211 module = sys.modules[global_ns['__name__']]
212 212 if compile_flags is None:
213 213 compile_flags = (call_frame.f_code.co_flags &
214 214 compilerop.PyCF_MASK)
215 215
216 216 # Save original namespace and module so we can restore them after
217 217 # embedding; otherwise the shell doesn't shut down correctly.
218 218 orig_user_module = self.user_module
219 219 orig_user_ns = self.user_ns
220 220 orig_compile_flags = self.compile.flags
221 221
222 222 # Update namespaces and fire up interpreter
223 223
224 224 # The global one is easy, we can just throw it in
225 225 if module is not None:
226 226 self.user_module = module
227 227
228 228 # But the user/local one is tricky: ipython needs it to store internal
229 229 # data, but we also need the locals. We'll throw our hidden variables
230 230 # like _ih and get_ipython() into the local namespace, but delete them
231 231 # later.
232 232 if local_ns is not None:
233 233 self.user_ns = local_ns
234 234 self.init_user_ns()
235 235
236 236 # Compiler flags
237 237 if compile_flags is not None:
238 238 self.compile.flags = compile_flags
239 239
240 240 # Patch for global embedding to make sure that things don't overwrite
241 241 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
242 242 # FIXME. Test this a bit more carefully (the if.. is new)
243 243 # N.B. This can't now ever be called. Not sure what it was for.
244 244 # And now, since it wasn't called in the previous version, I'm
245 245 # commenting out these lines so they can't be called with my new changes
246 246 # --TK, 2011-12-10
247 247 #if local_ns is None and module is None:
248 248 # self.user_global_ns.update(__main__.__dict__)
249 249
250 250 # make sure the tab-completer has the correct frame information, so it
251 251 # actually completes using the frame's locals/globals
252 252 self.set_completer_frame()
253 253
254 254 with nested(self.builtin_trap, self.display_trap):
255 255 self.interact(display_banner=display_banner)
256 256
257 257 # now, purge out the local namespace of IPython's hidden variables.
258 258 if local_ns is not None:
259 259 for name in self.user_ns_hidden:
260 260 local_ns.pop(name, None)
261 261
262 262 # Restore original namespace so shell can shut down when we exit.
263 263 self.user_module = orig_user_module
264 264 self.user_ns = orig_user_ns
265 265 self.compile.flags = orig_compile_flags
266 266
267 267
268 268 def embed(**kwargs):
269 269 """Call this to embed IPython at the current point in your program.
270 270
271 271 The first invocation of this will create an :class:`InteractiveShellEmbed`
272 272 instance and then call it. Consecutive calls just call the already
273 273 created instance.
274 274
275 If you don't want the kernel to initialize the namespace
276 from the scope of the surrounding function,
277 and/or you want to load full IPython configuration,
278 you probably want `IPython.start_ipython()` instead.
279
275 280 Here is a simple example::
276 281
277 282 from IPython import embed
278 283 a = 10
279 284 b = 20
280 285 embed('First time')
281 286 c = 30
282 287 d = 40
283 288 embed
284 289
285 290 Full customization can be done by passing a :class:`Config` in as the
286 291 config argument.
287 292 """
288 293 config = kwargs.get('config')
289 294 header = kwargs.pop('header', u'')
290 295 compile_flags = kwargs.pop('compile_flags', None)
291 296 if config is None:
292 297 config = load_default_config()
293 298 config.InteractiveShellEmbed = config.TerminalInteractiveShell
294 299 kwargs['config'] = config
295 300 shell = InteractiveShellEmbed.instance(**kwargs)
296 301 shell(header=header, stack_depth=2, compile_flags=compile_flags)
General Comments 0
You need to be logged in to leave comments. Login now