##// END OF EJS Templates
Merge pull request #1640 from minrk/embedkernel...
Fernando Perez -
r6626:14dcd993 merge
parent child Browse files
Show More
@@ -0,0 +1,153
1 """test IPython.embed_kernel()"""
2
3 #-------------------------------------------------------------------------------
4 # Copyright (C) 2012 The IPython Development Team
5 #
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
8 #-------------------------------------------------------------------------------
9
10 #-------------------------------------------------------------------------------
11 # Imports
12 #-------------------------------------------------------------------------------
13
14 import os
15 import shutil
16 import sys
17 import tempfile
18 import time
19
20 from subprocess import Popen, PIPE
21
22 import nose.tools as nt
23
24 from IPython.zmq.blockingkernelmanager import BlockingKernelManager
25 from IPython.utils import path
26
27
28 #-------------------------------------------------------------------------------
29 # Tests
30 #-------------------------------------------------------------------------------
31
32 def setup():
33 """setup temporary IPYTHONDIR for tests"""
34 global IPYTHONDIR
35 global env
36 global save_get_ipython_dir
37
38 IPYTHONDIR = tempfile.mkdtemp()
39 env = dict(IPYTHONDIR=IPYTHONDIR)
40 save_get_ipython_dir = path.get_ipython_dir
41 path.get_ipython_dir = lambda : IPYTHONDIR
42
43
44 def teardown():
45 path.get_ipython_dir = save_get_ipython_dir
46
47 try:
48 shutil.rmtree(IPYTHONDIR)
49 except (OSError, IOError):
50 # no such file
51 pass
52
53
54 def _launch_kernel(cmd):
55 """start an embedded kernel in a subprocess, and wait for it to be ready
56
57 Returns
58 -------
59 kernel, kernel_manager: Popen instance and connected KernelManager
60 """
61 kernel = Popen([sys.executable, '-c', cmd], stdout=PIPE, stderr=PIPE, env=env)
62 connection_file = os.path.join(IPYTHONDIR,
63 'profile_default',
64 'security',
65 'kernel-%i.json' % kernel.pid
66 )
67 # wait for connection file to exist, timeout after 5s
68 tic = time.time()
69 while not os.path.exists(connection_file) and kernel.poll() is None and time.time() < tic + 5:
70 time.sleep(0.1)
71
72 if not os.path.exists(connection_file):
73 if kernel.poll() is None:
74 kernel.terminate()
75 raise IOError("Connection file %r never arrived" % connection_file)
76
77 if kernel.poll() is not None:
78 raise IOError("Kernel failed to start")
79
80 km = BlockingKernelManager(connection_file=connection_file)
81 km.load_connection_file()
82 km.start_channels()
83
84 return kernel, km
85
86 def test_embed_kernel_basic():
87 """IPython.embed_kernel() is basically functional"""
88 cmd = '\n'.join([
89 'from IPython import embed_kernel',
90 'def go():',
91 ' a=5',
92 ' b="hi there"',
93 ' embed_kernel()',
94 'go()',
95 '',
96 ])
97
98 kernel, km = _launch_kernel(cmd)
99 shell = km.shell_channel
100
101 # oinfo a (int)
102 msg_id = shell.object_info('a')
103 msg = shell.get_msg(block=True, timeout=2)
104 content = msg['content']
105 nt.assert_true(content['found'])
106
107 msg_id = shell.execute("c=a*2")
108 msg = shell.get_msg(block=True, timeout=2)
109 content = msg['content']
110 nt.assert_equals(content['status'], u'ok')
111
112 # oinfo c (should be 10)
113 msg_id = shell.object_info('c')
114 msg = shell.get_msg(block=True, timeout=2)
115 content = msg['content']
116 nt.assert_true(content['found'])
117 nt.assert_equals(content['string_form'], u'10')
118
119 def test_embed_kernel_namespace():
120 """IPython.embed_kernel() inherits calling namespace"""
121 cmd = '\n'.join([
122 'from IPython import embed_kernel',
123 'def go():',
124 ' a=5',
125 ' b="hi there"',
126 ' embed_kernel()',
127 'go()',
128 '',
129 ])
130
131 kernel, km = _launch_kernel(cmd)
132 shell = km.shell_channel
133
134 # oinfo a (int)
135 msg_id = shell.object_info('a')
136 msg = shell.get_msg(block=True, timeout=2)
137 content = msg['content']
138 nt.assert_true(content['found'])
139 nt.assert_equals(content['string_form'], u'5')
140
141 # oinfo b (str)
142 msg_id = shell.object_info('b')
143 msg = shell.get_msg(block=True, timeout=2)
144 content = msg['content']
145 nt.assert_true(content['found'])
146 nt.assert_equals(content['string_form'], u'hi there')
147
148 # oinfo c (undefined)
149 msg_id = shell.object_info('c')
150 msg = shell.get_msg(block=True, timeout=2)
151 content = msg['content']
152 nt.assert_false(content['found'])
153
@@ -1,57 +1,86
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 import release
45 45 from .core.application import Application
46 46 from .frontend.terminal.embed import embed
47
47 48 from .core.error import TryNext
48 49 from .core.interactiveshell import InteractiveShell
49 50 from .testing import test
50 51 from .utils.sysinfo import sys_info
52 from .utils.frame import extract_module_locals
51 53
52 54 # Release data
53 55 __author__ = ''
54 56 for author, email in release.authors.itervalues():
55 57 __author__ += author + ' <' + email + '>\n'
56 58 __license__ = release.license
57 59 __version__ = release.version
60
61 def embed_kernel(module=None, local_ns=None, **kwargs):
62 """Embed and start an IPython kernel in a given scope.
63
64 Parameters
65 ----------
66 module : ModuleType, optional
67 The module to load into IPython globals (default: caller)
68 local_ns : dict, optional
69 The namespace to load into IPython user namespace (default: caller)
70
71 kwargs : various, optional
72 Further keyword args are relayed to the KernelApp constructor,
73 allowing configuration of the Kernel. Will only have an effect
74 on the first embed_kernel call for a given process.
75
76 """
77
78 (caller_module, caller_locals) = extract_module_locals(1)
79 if module is None:
80 module = caller_module
81 if local_ns is None:
82 local_ns = caller_locals
83
84 # Only import .zmq when we really need it
85 from .zmq.ipkernel import embed_kernel as real_embed_kernel
86 real_embed_kernel(module=module, local_ns=local_ns, **kwargs)
@@ -1,87 +1,94
1 1 # encoding: utf-8
2 2 """
3 3 Utilities for working with stack frames.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 import sys
18 18 from IPython.utils import py3compat
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Code
22 22 #-----------------------------------------------------------------------------
23 23
24 24 @py3compat.doctest_refactor_print
25 25 def extract_vars(*names,**kw):
26 26 """Extract a set of variables by name from another frame.
27 27
28 28 :Parameters:
29 29 - `*names`: strings
30 30 One or more variable names which will be extracted from the caller's
31 31 frame.
32 32
33 33 :Keywords:
34 34 - `depth`: integer (0)
35 35 How many frames in the stack to walk when looking for your variables.
36 36
37 37
38 38 Examples:
39 39
40 40 In [2]: def func(x):
41 41 ...: y = 1
42 42 ...: print extract_vars('x','y')
43 43 ...:
44 44
45 45 In [3]: func('hello')
46 46 {'y': 1, 'x': 'hello'}
47 47 """
48 48
49 49 depth = kw.get('depth',0)
50 50
51 51 callerNS = sys._getframe(depth+1).f_locals
52 52 return dict((k,callerNS[k]) for k in names)
53 53
54 54
55 55 def extract_vars_above(*names):
56 56 """Extract a set of variables by name from another frame.
57 57
58 58 Similar to extractVars(), but with a specified depth of 1, so that names
59 59 are exctracted exactly from above the caller.
60 60
61 61 This is simply a convenience function so that the very common case (for us)
62 62 of skipping exactly 1 frame doesn't have to construct a special dict for
63 63 keyword passing."""
64 64
65 65 callerNS = sys._getframe(2).f_locals
66 66 return dict((k,callerNS[k]) for k in names)
67 67
68 68
69 69 def debugx(expr,pre_msg=''):
70 70 """Print the value of an expression from the caller's frame.
71 71
72 72 Takes an expression, evaluates it in the caller's frame and prints both
73 73 the given expression and the resulting value (as well as a debug mark
74 74 indicating the name of the calling function. The input must be of a form
75 75 suitable for eval().
76 76
77 77 An optional message can be passed, which will be prepended to the printed
78 78 expr->value pair."""
79 79
80 80 cf = sys._getframe(1)
81 81 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
82 82 eval(expr,cf.f_globals,cf.f_locals))
83 83
84 84
85 85 # deactivate it by uncommenting the following line, which makes it a no-op
86 86 #def debugx(expr,pre_msg=''): pass
87 87
88 def extract_module_locals(depth=0):
89 """Returns (module, locals) of the funciton `depth` frames away from the caller"""
90 f = sys._getframe(depth + 1)
91 global_ns = f.f_globals
92 module = sys.modules[global_ns['__name__']]
93 return (module, f.f_locals)
94
@@ -1,660 +1,709
1 1 #!/usr/bin/env python
2 2 """A simple interactive kernel that talks to a frontend over 0MQ.
3 3
4 4 Things to do:
5 5
6 6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 7 call set_parent on all the PUB objects with the message about to be executed.
8 8 * Implement random port and security key logic.
9 9 * Implement control messages.
10 10 * Implement event loop and poll version.
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Standard library imports.
19 19 import __builtin__
20 20 import atexit
21 21 import sys
22 22 import time
23 23 import traceback
24 24 import logging
25 25 from signal import (
26 26 signal, default_int_handler, SIGINT, SIG_IGN
27 27 )
28 28 # System library imports.
29 29 import zmq
30 30
31 31 # Local imports.
32 32 from IPython.core import pylabtools
33 33 from IPython.config.configurable import Configurable
34 34 from IPython.config.application import boolean_flag, catch_config_error
35 35 from IPython.core.application import ProfileDir
36 36 from IPython.core.error import StdinNotImplementedError
37 37 from IPython.core.shellapp import (
38 38 InteractiveShellApp, shell_flags, shell_aliases
39 39 )
40 40 from IPython.utils import io
41 41 from IPython.utils import py3compat
42 from IPython.utils.frame import extract_module_locals
42 43 from IPython.utils.jsonutil import json_clean
43 44 from IPython.utils.traitlets import (
44 45 Any, Instance, Float, Dict, CaselessStrEnum
45 46 )
46 47
47 48 from entry_point import base_launch_kernel
48 49 from kernelapp import KernelApp, kernel_flags, kernel_aliases
49 50 from session import Session, Message
50 51 from zmqshell import ZMQInteractiveShell
51 52
52 53
53 54 #-----------------------------------------------------------------------------
54 55 # Main kernel class
55 56 #-----------------------------------------------------------------------------
56 57
57 58 class Kernel(Configurable):
58 59
59 60 #---------------------------------------------------------------------------
60 61 # Kernel interface
61 62 #---------------------------------------------------------------------------
62 63
63 64 # attribute to override with a GUI
64 65 eventloop = Any(None)
65 66
66 67 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
67 68 session = Instance(Session)
68 69 profile_dir = Instance('IPython.core.profiledir.ProfileDir')
69 70 shell_socket = Instance('zmq.Socket')
70 71 iopub_socket = Instance('zmq.Socket')
71 72 stdin_socket = Instance('zmq.Socket')
72 73 log = Instance(logging.Logger)
73 74
75 user_module = Instance('types.ModuleType')
76 def _user_module_changed(self, name, old, new):
77 if self.shell is not None:
78 self.shell.user_module = new
79
80 user_ns = Dict(default_value=None)
81 def _user_ns_changed(self, name, old, new):
82 if self.shell is not None:
83 self.shell.user_ns = new
84 self.shell.init_user_ns()
85
74 86 # Private interface
75 87
76 88 # Time to sleep after flushing the stdout/err buffers in each execute
77 89 # cycle. While this introduces a hard limit on the minimal latency of the
78 90 # execute cycle, it helps prevent output synchronization problems for
79 91 # clients.
80 92 # Units are in seconds. The minimum zmq latency on local host is probably
81 93 # ~150 microseconds, set this to 500us for now. We may need to increase it
82 94 # a little if it's not enough after more interactive testing.
83 95 _execute_sleep = Float(0.0005, config=True)
84 96
85 97 # Frequency of the kernel's event loop.
86 98 # Units are in seconds, kernel subclasses for GUI toolkits may need to
87 99 # adapt to milliseconds.
88 100 _poll_interval = Float(0.05, config=True)
89 101
90 102 # If the shutdown was requested over the network, we leave here the
91 103 # necessary reply message so it can be sent by our registered atexit
92 104 # handler. This ensures that the reply is only sent to clients truly at
93 105 # the end of our shutdown process (which happens after the underlying
94 106 # IPython shell's own shutdown).
95 107 _shutdown_message = None
96 108
97 109 # This is a dict of port number that the kernel is listening on. It is set
98 110 # by record_ports and used by connect_request.
99 111 _recorded_ports = Dict()
100 112
101 113
102 114
103 115 def __init__(self, **kwargs):
104 116 super(Kernel, self).__init__(**kwargs)
105 117
106 118 # Before we even start up the shell, register *first* our exit handlers
107 119 # so they come before the shell's
108 120 atexit.register(self._at_shutdown)
109 121
110 122 # Initialize the InteractiveShell subclass
111 123 self.shell = ZMQInteractiveShell.instance(config=self.config,
112 124 profile_dir = self.profile_dir,
125 user_module = self.user_module,
126 user_ns = self.user_ns,
113 127 )
114 128 self.shell.displayhook.session = self.session
115 129 self.shell.displayhook.pub_socket = self.iopub_socket
116 130 self.shell.display_pub.session = self.session
117 131 self.shell.display_pub.pub_socket = self.iopub_socket
118 132
119 133 # TMP - hack while developing
120 134 self.shell._reply_content = None
121 135
122 136 # Build dict of handlers for message types
123 137 msg_types = [ 'execute_request', 'complete_request',
124 138 'object_info_request', 'history_request',
125 139 'connect_request', 'shutdown_request']
126 140 self.handlers = {}
127 141 for msg_type in msg_types:
128 142 self.handlers[msg_type] = getattr(self, msg_type)
129 143
130 144 def do_one_iteration(self):
131 145 """Do one iteration of the kernel's evaluation loop.
132 146 """
133 147 try:
134 148 ident,msg = self.session.recv(self.shell_socket, zmq.NOBLOCK)
135 149 except Exception:
136 150 self.log.warn("Invalid Message:", exc_info=True)
137 151 return
138 152 if msg is None:
139 153 return
140 154
141 155 msg_type = msg['header']['msg_type']
142 156
143 157 # This assert will raise in versions of zeromq 2.0.7 and lesser.
144 158 # We now require 2.0.8 or above, so we can uncomment for safety.
145 159 # print(ident,msg, file=sys.__stdout__)
146 160 assert ident is not None, "Missing message part."
147 161
148 162 # Print some info about this message and leave a '--->' marker, so it's
149 163 # easier to trace visually the message chain when debugging. Each
150 164 # handler prints its message at the end.
151 165 self.log.debug('\n*** MESSAGE TYPE:'+str(msg_type)+'***')
152 166 self.log.debug(' Content: '+str(msg['content'])+'\n --->\n ')
153 167
154 168 # Find and call actual handler for message
155 169 handler = self.handlers.get(msg_type, None)
156 170 if handler is None:
157 171 self.log.error("UNKNOWN MESSAGE TYPE:" +str(msg))
158 172 else:
159 173 handler(ident, msg)
160 174
161 175 # Check whether we should exit, in case the incoming message set the
162 176 # exit flag on
163 177 if self.shell.exit_now:
164 178 self.log.debug('\nExiting IPython kernel...')
165 179 # We do a normal, clean exit, which allows any actions registered
166 180 # via atexit (such as history saving) to take place.
167 181 sys.exit(0)
168 182
169 183
170 184 def start(self):
171 185 """ Start the kernel main loop.
172 186 """
173 187 # a KeyboardInterrupt (SIGINT) can occur on any python statement, so
174 188 # let's ignore (SIG_IGN) them until we're in a place to handle them properly
175 189 signal(SIGINT,SIG_IGN)
176 190 poller = zmq.Poller()
177 191 poller.register(self.shell_socket, zmq.POLLIN)
178 192 # loop while self.eventloop has not been overridden
179 193 while self.eventloop is None:
180 194 try:
181 195 # scale by extra factor of 10, because there is no
182 196 # reason for this to be anything less than ~ 0.1s
183 197 # since it is a real poller and will respond
184 198 # to events immediately
185 199
186 200 # double nested try/except, to properly catch KeyboardInterrupt
187 201 # due to pyzmq Issue #130
188 202 try:
189 203 poller.poll(10*1000*self._poll_interval)
190 204 # restore raising of KeyboardInterrupt
191 205 signal(SIGINT, default_int_handler)
192 206 self.do_one_iteration()
193 207 except:
194 208 raise
195 209 finally:
196 210 # prevent raising of KeyboardInterrupt
197 211 signal(SIGINT,SIG_IGN)
198 212 except KeyboardInterrupt:
199 213 # Ctrl-C shouldn't crash the kernel
200 214 io.raw_print("KeyboardInterrupt caught in kernel")
201 215 # stop ignoring sigint, now that we are out of our own loop,
202 216 # we don't want to prevent future code from handling it
203 217 signal(SIGINT, default_int_handler)
204 218 while self.eventloop is not None:
205 219 try:
206 220 self.eventloop(self)
207 221 except KeyboardInterrupt:
208 222 # Ctrl-C shouldn't crash the kernel
209 223 io.raw_print("KeyboardInterrupt caught in kernel")
210 224 continue
211 225 else:
212 226 # eventloop exited cleanly, this means we should stop (right?)
213 227 self.eventloop = None
214 228 break
215 229
216 230
217 231 def record_ports(self, ports):
218 232 """Record the ports that this kernel is using.
219 233
220 234 The creator of the Kernel instance must call this methods if they
221 235 want the :meth:`connect_request` method to return the port numbers.
222 236 """
223 237 self._recorded_ports = ports
224 238
225 239 #---------------------------------------------------------------------------
226 240 # Kernel request handlers
227 241 #---------------------------------------------------------------------------
228 242
229 243 def _publish_pyin(self, code, parent, execution_count):
230 244 """Publish the code request on the pyin stream."""
231 245
232 246 self.session.send(self.iopub_socket, u'pyin', {u'code':code,
233 247 u'execution_count': execution_count}, parent=parent)
234 248
235 249 def execute_request(self, ident, parent):
236 250
237 251 self.session.send(self.iopub_socket,
238 252 u'status',
239 253 {u'execution_state':u'busy'},
240 254 parent=parent )
241 255
242 256 try:
243 257 content = parent[u'content']
244 258 code = content[u'code']
245 259 silent = content[u'silent']
246 260 except:
247 261 self.log.error("Got bad msg: ")
248 262 self.log.error(str(Message(parent)))
249 263 return
250 264
251 265 shell = self.shell # we'll need this a lot here
252 266
253 267 # Replace raw_input. Note that is not sufficient to replace
254 268 # raw_input in the user namespace.
255 269 if content.get('allow_stdin', False):
256 270 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
257 271 else:
258 272 raw_input = lambda prompt='' : self._no_raw_input()
259 273
260 274 if py3compat.PY3:
261 275 __builtin__.input = raw_input
262 276 else:
263 277 __builtin__.raw_input = raw_input
264 278
265 279 # Set the parent message of the display hook and out streams.
266 280 shell.displayhook.set_parent(parent)
267 281 shell.display_pub.set_parent(parent)
268 282 sys.stdout.set_parent(parent)
269 283 sys.stderr.set_parent(parent)
270 284
271 285 # Re-broadcast our input for the benefit of listening clients, and
272 286 # start computing output
273 287 if not silent:
274 288 self._publish_pyin(code, parent, shell.execution_count)
275 289
276 290 reply_content = {}
277 291 try:
278 292 if silent:
279 293 # run_code uses 'exec' mode, so no displayhook will fire, and it
280 294 # doesn't call logging or history manipulations. Print
281 295 # statements in that code will obviously still execute.
282 296 shell.run_code(code)
283 297 else:
284 298 # FIXME: the shell calls the exception handler itself.
285 299 shell.run_cell(code, store_history=True)
286 300 except:
287 301 status = u'error'
288 302 # FIXME: this code right now isn't being used yet by default,
289 303 # because the run_cell() call above directly fires off exception
290 304 # reporting. This code, therefore, is only active in the scenario
291 305 # where runlines itself has an unhandled exception. We need to
292 306 # uniformize this, for all exception construction to come from a
293 307 # single location in the codbase.
294 308 etype, evalue, tb = sys.exc_info()
295 309 tb_list = traceback.format_exception(etype, evalue, tb)
296 310 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
297 311 else:
298 312 status = u'ok'
299 313
300 314 reply_content[u'status'] = status
301 315
302 316 # Return the execution counter so clients can display prompts
303 317 reply_content['execution_count'] = shell.execution_count -1
304 318
305 319 # FIXME - fish exception info out of shell, possibly left there by
306 320 # runlines. We'll need to clean up this logic later.
307 321 if shell._reply_content is not None:
308 322 reply_content.update(shell._reply_content)
309 323 # reset after use
310 324 shell._reply_content = None
311 325
312 326 # At this point, we can tell whether the main code execution succeeded
313 327 # or not. If it did, we proceed to evaluate user_variables/expressions
314 328 if reply_content['status'] == 'ok':
315 329 reply_content[u'user_variables'] = \
316 330 shell.user_variables(content[u'user_variables'])
317 331 reply_content[u'user_expressions'] = \
318 332 shell.user_expressions(content[u'user_expressions'])
319 333 else:
320 334 # If there was an error, don't even try to compute variables or
321 335 # expressions
322 336 reply_content[u'user_variables'] = {}
323 337 reply_content[u'user_expressions'] = {}
324 338
325 339 # Payloads should be retrieved regardless of outcome, so we can both
326 340 # recover partial output (that could have been generated early in a
327 341 # block, before an error) and clear the payload system always.
328 342 reply_content[u'payload'] = shell.payload_manager.read_payload()
329 343 # Be agressive about clearing the payload because we don't want
330 344 # it to sit in memory until the next execute_request comes in.
331 345 shell.payload_manager.clear_payload()
332 346
333 347 # Flush output before sending the reply.
334 348 sys.stdout.flush()
335 349 sys.stderr.flush()
336 350 # FIXME: on rare occasions, the flush doesn't seem to make it to the
337 351 # clients... This seems to mitigate the problem, but we definitely need
338 352 # to better understand what's going on.
339 353 if self._execute_sleep:
340 354 time.sleep(self._execute_sleep)
341 355
342 356 # Send the reply.
343 357 reply_content = json_clean(reply_content)
344 358 reply_msg = self.session.send(self.shell_socket, u'execute_reply',
345 359 reply_content, parent, ident=ident)
346 360 self.log.debug(str(reply_msg))
347 361
348 362 if reply_msg['content']['status'] == u'error':
349 363 self._abort_queue()
350 364
351 365 self.session.send(self.iopub_socket,
352 366 u'status',
353 367 {u'execution_state':u'idle'},
354 368 parent=parent )
355 369
356 370 def complete_request(self, ident, parent):
357 371 txt, matches = self._complete(parent)
358 372 matches = {'matches' : matches,
359 373 'matched_text' : txt,
360 374 'status' : 'ok'}
361 375 matches = json_clean(matches)
362 376 completion_msg = self.session.send(self.shell_socket, 'complete_reply',
363 377 matches, parent, ident)
364 378 self.log.debug(str(completion_msg))
365 379
366 380 def object_info_request(self, ident, parent):
367 381 content = parent['content']
368 382 object_info = self.shell.object_inspect(content['oname'],
369 383 detail_level = content.get('detail_level', 0)
370 384 )
371 385 # Before we send this object over, we scrub it for JSON usage
372 386 oinfo = json_clean(object_info)
373 387 msg = self.session.send(self.shell_socket, 'object_info_reply',
374 388 oinfo, parent, ident)
375 389 self.log.debug(msg)
376 390
377 391 def history_request(self, ident, parent):
378 392 # We need to pull these out, as passing **kwargs doesn't work with
379 393 # unicode keys before Python 2.6.5.
380 394 hist_access_type = parent['content']['hist_access_type']
381 395 raw = parent['content']['raw']
382 396 output = parent['content']['output']
383 397 if hist_access_type == 'tail':
384 398 n = parent['content']['n']
385 399 hist = self.shell.history_manager.get_tail(n, raw=raw, output=output,
386 400 include_latest=True)
387 401
388 402 elif hist_access_type == 'range':
389 403 session = parent['content']['session']
390 404 start = parent['content']['start']
391 405 stop = parent['content']['stop']
392 406 hist = self.shell.history_manager.get_range(session, start, stop,
393 407 raw=raw, output=output)
394 408
395 409 elif hist_access_type == 'search':
396 410 pattern = parent['content']['pattern']
397 411 hist = self.shell.history_manager.search(pattern, raw=raw,
398 412 output=output)
399 413
400 414 else:
401 415 hist = []
402 416 hist = list(hist)
403 417 content = {'history' : hist}
404 418 content = json_clean(content)
405 419 msg = self.session.send(self.shell_socket, 'history_reply',
406 420 content, parent, ident)
407 421 self.log.debug("Sending history reply with %i entries", len(hist))
408 422
409 423 def connect_request(self, ident, parent):
410 424 if self._recorded_ports is not None:
411 425 content = self._recorded_ports.copy()
412 426 else:
413 427 content = {}
414 428 msg = self.session.send(self.shell_socket, 'connect_reply',
415 429 content, parent, ident)
416 430 self.log.debug(msg)
417 431
418 432 def shutdown_request(self, ident, parent):
419 433 self.shell.exit_now = True
420 434 self._shutdown_message = self.session.msg(u'shutdown_reply',
421 435 parent['content'], parent)
422 436 sys.exit(0)
423 437
424 438 #---------------------------------------------------------------------------
425 439 # Protected interface
426 440 #---------------------------------------------------------------------------
427 441
428 442 def _abort_queue(self):
429 443 while True:
430 444 try:
431 445 ident,msg = self.session.recv(self.shell_socket, zmq.NOBLOCK)
432 446 except Exception:
433 447 self.log.warn("Invalid Message:", exc_info=True)
434 448 continue
435 449 if msg is None:
436 450 break
437 451 else:
438 452 assert ident is not None, \
439 453 "Unexpected missing message part."
440 454
441 455 self.log.debug("Aborting:\n"+str(Message(msg)))
442 456 msg_type = msg['header']['msg_type']
443 457 reply_type = msg_type.split('_')[0] + '_reply'
444 458 reply_msg = self.session.send(self.shell_socket, reply_type,
445 459 {'status' : 'aborted'}, msg, ident=ident)
446 460 self.log.debug(reply_msg)
447 461 # We need to wait a bit for requests to come in. This can probably
448 462 # be set shorter for true asynchronous clients.
449 463 time.sleep(0.1)
450 464
451 465 def _no_raw_input(self):
452 466 """Raise StdinNotImplentedError if active frontend doesn't support
453 467 stdin."""
454 468 raise StdinNotImplementedError("raw_input was called, but this "
455 469 "frontend does not support stdin.")
456 470
457 471 def _raw_input(self, prompt, ident, parent):
458 472 # Flush output before making the request.
459 473 sys.stderr.flush()
460 474 sys.stdout.flush()
461 475
462 476 # Send the input request.
463 477 content = json_clean(dict(prompt=prompt))
464 478 self.session.send(self.stdin_socket, u'input_request', content, parent,
465 479 ident=ident)
466 480
467 481 # Await a response.
468 482 while True:
469 483 try:
470 484 ident, reply = self.session.recv(self.stdin_socket, 0)
471 485 except Exception:
472 486 self.log.warn("Invalid Message:", exc_info=True)
473 487 else:
474 488 break
475 489 try:
476 490 value = reply['content']['value']
477 491 except:
478 492 self.log.error("Got bad raw_input reply: ")
479 493 self.log.error(str(Message(parent)))
480 494 value = ''
481 495 if value == '\x04':
482 496 # EOF
483 497 raise EOFError
484 498 return value
485 499
486 500 def _complete(self, msg):
487 501 c = msg['content']
488 502 try:
489 503 cpos = int(c['cursor_pos'])
490 504 except:
491 505 # If we don't get something that we can convert to an integer, at
492 506 # least attempt the completion guessing the cursor is at the end of
493 507 # the text, if there's any, and otherwise of the line
494 508 cpos = len(c['text'])
495 509 if cpos==0:
496 510 cpos = len(c['line'])
497 511 return self.shell.complete(c['text'], c['line'], cpos)
498 512
499 513 def _object_info(self, context):
500 514 symbol, leftover = self._symbol_from_context(context)
501 515 if symbol is not None and not leftover:
502 516 doc = getattr(symbol, '__doc__', '')
503 517 else:
504 518 doc = ''
505 519 object_info = dict(docstring = doc)
506 520 return object_info
507 521
508 522 def _symbol_from_context(self, context):
509 523 if not context:
510 524 return None, context
511 525
512 526 base_symbol_string = context[0]
513 527 symbol = self.shell.user_ns.get(base_symbol_string, None)
514 528 if symbol is None:
515 529 symbol = __builtin__.__dict__.get(base_symbol_string, None)
516 530 if symbol is None:
517 531 return None, context
518 532
519 533 context = context[1:]
520 534 for i, name in enumerate(context):
521 535 new_symbol = getattr(symbol, name, None)
522 536 if new_symbol is None:
523 537 return symbol, context[i:]
524 538 else:
525 539 symbol = new_symbol
526 540
527 541 return symbol, []
528 542
529 543 def _at_shutdown(self):
530 544 """Actions taken at shutdown by the kernel, called by python's atexit.
531 545 """
532 546 # io.rprint("Kernel at_shutdown") # dbg
533 547 if self._shutdown_message is not None:
534 548 self.session.send(self.shell_socket, self._shutdown_message)
535 549 self.session.send(self.iopub_socket, self._shutdown_message)
536 550 self.log.debug(str(self._shutdown_message))
537 551 # A very short sleep to give zmq time to flush its message buffers
538 552 # before Python truly shuts down.
539 553 time.sleep(0.01)
540 554
541 555 #-----------------------------------------------------------------------------
542 556 # Aliases and Flags for the IPKernelApp
543 557 #-----------------------------------------------------------------------------
544 558
545 559 flags = dict(kernel_flags)
546 560 flags.update(shell_flags)
547 561
548 562 addflag = lambda *args: flags.update(boolean_flag(*args))
549 563
550 564 flags['pylab'] = (
551 565 {'IPKernelApp' : {'pylab' : 'auto'}},
552 566 """Pre-load matplotlib and numpy for interactive use with
553 567 the default matplotlib backend."""
554 568 )
555 569
556 570 aliases = dict(kernel_aliases)
557 571 aliases.update(shell_aliases)
558 572
559 573 # it's possible we don't want short aliases for *all* of these:
560 574 aliases.update(dict(
561 575 pylab='IPKernelApp.pylab',
562 576 ))
563 577
564 578 #-----------------------------------------------------------------------------
565 579 # The IPKernelApp class
566 580 #-----------------------------------------------------------------------------
567 581
568 582 class IPKernelApp(KernelApp, InteractiveShellApp):
569 583 name = 'ipkernel'
570 584
571 585 aliases = Dict(aliases)
572 586 flags = Dict(flags)
573 587 classes = [Kernel, ZMQInteractiveShell, ProfileDir, Session]
588
574 589 # configurables
575 590 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'inline', 'auto'],
576 591 config=True,
577 592 help="""Pre-load matplotlib and numpy for interactive use,
578 593 selecting a particular matplotlib backend and loop integration.
579 594 """
580 595 )
581 596
582 597 @catch_config_error
583 598 def initialize(self, argv=None):
584 599 super(IPKernelApp, self).initialize(argv)
585 600 self.init_shell()
586 601 self.init_extensions()
587 602 self.init_code()
588 603
589 604 def init_kernel(self):
590 605
591 606 kernel = Kernel(config=self.config, session=self.session,
592 607 shell_socket=self.shell_socket,
593 608 iopub_socket=self.iopub_socket,
594 609 stdin_socket=self.stdin_socket,
595 610 log=self.log,
596 611 profile_dir=self.profile_dir,
597 612 )
598 613 self.kernel = kernel
599 614 kernel.record_ports(self.ports)
600 615 shell = kernel.shell
601 616 if self.pylab:
602 617 try:
603 618 gui, backend = pylabtools.find_gui_and_backend(self.pylab)
604 619 shell.enable_pylab(gui, import_all=self.pylab_import_all)
605 620 except Exception:
606 621 self.log.error("Pylab initialization failed", exc_info=True)
607 622 # print exception straight to stdout, because normally
608 623 # _showtraceback associates the reply with an execution,
609 624 # which means frontends will never draw it, as this exception
610 625 # is not associated with any execute request.
611 626
612 627 # replace pyerr-sending traceback with stdout
613 628 _showtraceback = shell._showtraceback
614 629 def print_tb(etype, evalue, stb):
615 630 print ("Error initializing pylab, pylab mode will not "
616 631 "be active", file=io.stderr)
617 632 print (shell.InteractiveTB.stb2text(stb), file=io.stdout)
618 633 shell._showtraceback = print_tb
619 634
620 635 # send the traceback over stdout
621 636 shell.showtraceback(tb_offset=0)
622 637
623 638 # restore proper _showtraceback method
624 639 shell._showtraceback = _showtraceback
625 640
626 641
627 642 def init_shell(self):
628 643 self.shell = self.kernel.shell
629 644 self.shell.configurables.append(self)
630 645
631 646
632 647 #-----------------------------------------------------------------------------
633 648 # Kernel main and launch functions
634 649 #-----------------------------------------------------------------------------
635 650
636 651 def launch_kernel(*args, **kwargs):
637 652 """Launches a localhost IPython kernel, binding to the specified ports.
638 653
639 654 This function simply calls entry_point.base_launch_kernel with the right
640 655 first command to start an ipkernel. See base_launch_kernel for arguments.
641 656
642 657 Returns
643 658 -------
644 659 A tuple of form:
645 660 (kernel_process, shell_port, iopub_port, stdin_port, hb_port)
646 661 where kernel_process is a Popen object and the ports are integers.
647 662 """
648 663 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
649 664 *args, **kwargs)
650 665
651 666
667 def embed_kernel(module=None, local_ns=None, **kwargs):
668 """Embed and start an IPython kernel in a given scope.
669
670 Parameters
671 ----------
672 module : ModuleType, optional
673 The module to load into IPython globals (default: caller)
674 local_ns : dict, optional
675 The namespace to load into IPython user namespace (default: caller)
676
677 kwargs : various, optional
678 Further keyword args are relayed to the KernelApp constructor,
679 allowing configuration of the Kernel. Will only have an effect
680 on the first embed_kernel call for a given process.
681
682 """
683 # get the app if it exists, or set it up if it doesn't
684 if IPKernelApp.initialized():
685 app = IPKernelApp.instance()
686 else:
687 app = IPKernelApp.instance(**kwargs)
688 app.initialize([])
689
690 # load the calling scope if not given
691 (caller_module, caller_locals) = extract_module_locals(1)
692 if module is None:
693 module = caller_module
694 if local_ns is None:
695 local_ns = caller_locals
696
697 app.kernel.user_module = module
698 app.kernel.user_ns = local_ns
699 app.start()
700
652 701 def main():
653 702 """Run an IPKernel as an application"""
654 703 app = IPKernelApp.instance()
655 704 app.initialize()
656 705 app.start()
657 706
658 707
659 708 if __name__ == '__main__':
660 709 main()
@@ -1,997 +1,1005
1 1 =================
2 2 IPython reference
3 3 =================
4 4
5 5 .. _command_line_options:
6 6
7 7 Command-line usage
8 8 ==================
9 9
10 10 You start IPython with the command::
11 11
12 12 $ ipython [options] files
13 13
14 14 .. note::
15 15
16 16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
17 17
18 18 If invoked with no options, it executes all the files listed in sequence
19 19 and drops you into the interpreter while still acknowledging any options
20 20 you may have set in your ipython_config.py. This behavior is different from
21 21 standard Python, which when called as python -i will only execute one
22 22 file and ignore your configuration setup.
23 23
24 24 Please note that some of the configuration options are not available at
25 25 the command line, simply because they are not practical here. Look into
26 26 your configuration files for details on those. There are separate configuration
27 27 files for each profile, and the files look like "ipython_config.py" or
28 28 "ipython_config_<frontendname>.py". Profile directories look like
29 29 "profile_profilename" and are typically installed in the IPYTHON_DIR directory.
30 30 For Linux users, this will be $HOME/.config/ipython, and for other users it
31 31 will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
32 32 Settings\\YourUserName in most instances.
33 33
34 34
35 35 Eventloop integration
36 36 ---------------------
37 37
38 38 Previously IPython had command line options for controlling GUI event loop
39 39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
40 40 version 0.11, these have been removed. Please see the new ``%gui``
41 41 magic command or :ref:`this section <gui_support>` for details on the new
42 42 interface, or specify the gui at the commandline::
43 43
44 44 $ ipython --gui=qt
45 45
46 46
47 47 Command-line Options
48 48 --------------------
49 49
50 50 To see the options IPython accepts, use ``ipython --help`` (and you probably
51 51 should run the output through a pager such as ``ipython --help | less`` for
52 52 more convenient reading). This shows all the options that have a single-word
53 53 alias to control them, but IPython lets you configure all of its objects from
54 54 the command-line by passing the full class name and a corresponding value; type
55 55 ``ipython --help-all`` to see this full list. For example::
56 56
57 57 ipython --pylab qt
58 58
59 59 is equivalent to::
60 60
61 61 ipython --TerminalIPythonApp.pylab='qt'
62 62
63 63 Note that in the second form, you *must* use the equal sign, as the expression
64 64 is evaluated as an actual Python assignment. While in the above example the
65 65 short form is more convenient, only the most common options have a short form,
66 66 while any configurable variable in IPython can be set at the command-line by
67 67 using the long form. This long form is the same syntax used in the
68 68 configuration files, if you want to set these options permanently.
69 69
70 70
71 71 Interactive use
72 72 ===============
73 73
74 74 IPython is meant to work as a drop-in replacement for the standard interactive
75 75 interpreter. As such, any code which is valid python should execute normally
76 76 under IPython (cases where this is not true should be reported as bugs). It
77 77 does, however, offer many features which are not available at a standard python
78 78 prompt. What follows is a list of these.
79 79
80 80
81 81 Caution for Windows users
82 82 -------------------------
83 83
84 84 Windows, unfortunately, uses the '\\' character as a path separator. This is a
85 85 terrible choice, because '\\' also represents the escape character in most
86 86 modern programming languages, including Python. For this reason, using '/'
87 87 character is recommended if you have problems with ``\``. However, in Windows
88 88 commands '/' flags options, so you can not use it for the root directory. This
89 89 means that paths beginning at the root must be typed in a contrived manner
90 90 like: ``%copy \opt/foo/bar.txt \tmp``
91 91
92 92 .. _magic:
93 93
94 94 Magic command system
95 95 --------------------
96 96
97 97 IPython will treat any line whose first character is a % as a special
98 98 call to a 'magic' function. These allow you to control the behavior of
99 99 IPython itself, plus a lot of system-type features. They are all
100 100 prefixed with a % character, but parameters are given without
101 101 parentheses or quotes.
102 102
103 103 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
104 104 exists.
105 105
106 106 If you have 'automagic' enabled (as it by default), you don't need
107 107 to type in the % explicitly. IPython will scan its internal list of
108 108 magic functions and call one if it exists. With automagic on you can
109 109 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
110 110 system has the lowest possible precedence in name searches, so defining
111 111 an identifier with the same name as an existing magic function will
112 112 shadow it for automagic use. You can still access the shadowed magic
113 113 function by explicitly using the % character at the beginning of the line.
114 114
115 115 An example (with automagic on) should clarify all this:
116 116
117 117 .. sourcecode:: ipython
118 118
119 119 In [1]: cd ipython # %cd is called by automagic
120 120 /home/fperez/ipython
121 121
122 122 In [2]: cd=1 # now cd is just a variable
123 123
124 124 In [3]: cd .. # and doesn't work as a function anymore
125 125 File "<ipython-input-3-9fedb3aff56c>", line 1
126 126 cd ..
127 127 ^
128 128 SyntaxError: invalid syntax
129 129
130 130
131 131 In [4]: %cd .. # but %cd always works
132 132 /home/fperez
133 133
134 134 In [5]: del cd # if you remove the cd variable, automagic works again
135 135
136 136 In [6]: cd ipython
137 137
138 138 /home/fperez/ipython
139 139
140 140 You can define your own magic functions to extend the system. The
141 141 following example defines a new magic command, %impall:
142 142
143 143 .. sourcecode:: python
144 144
145 145 ip = get_ipython()
146 146
147 147 def doimp(self, arg):
148 148 ip = self.api
149 149 ip.ex("import %s; reload(%s); from %s import *" % (arg,arg,arg) )
150 150
151 151 ip.define_magic('impall', doimp)
152 152
153 153 Type ``%magic`` for more information, including a list of all available magic
154 154 functions at any time and their docstrings. You can also type
155 155 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for information on
156 156 the '?' system) to get information about any particular magic function you are
157 157 interested in.
158 158
159 159 The API documentation for the :mod:`IPython.core.magic` module contains the full
160 160 docstrings of all currently available magic commands.
161 161
162 162
163 163 Access to the standard Python help
164 164 ----------------------------------
165 165
166 166 Simply type ``help()`` to access Python's standard help system. You can
167 167 also type ``help(object)`` for information about a given object, or
168 168 ``help('keyword')`` for information on a keyword. You may need to configure your
169 169 PYTHONDOCS environment variable for this feature to work correctly.
170 170
171 171 .. _dynamic_object_info:
172 172
173 173 Dynamic object information
174 174 --------------------------
175 175
176 176 Typing ``?word`` or ``word?`` prints detailed information about an object. If
177 177 certain strings in the object are too long (e.g. function signatures) they get
178 178 snipped in the center for brevity. This system gives access variable types and
179 179 values, docstrings, function prototypes and other useful information.
180 180
181 181 If the information will not fit in the terminal, it is displayed in a pager
182 182 (``less`` if available, otherwise a basic internal pager).
183 183
184 184 Typing ``??word`` or ``word??`` gives access to the full information, including
185 185 the source code where possible. Long strings are not snipped.
186 186
187 187 The following magic functions are particularly useful for gathering
188 188 information about your working environment. You can get more details by
189 189 typing ``%magic`` or querying them individually (``%function_name?``);
190 190 this is just a summary:
191 191
192 192 * **%pdoc <object>**: Print (or run through a pager if too long) the
193 193 docstring for an object. If the given object is a class, it will
194 194 print both the class and the constructor docstrings.
195 195 * **%pdef <object>**: Print the definition header for any callable
196 196 object. If the object is a class, print the constructor information.
197 197 * **%psource <object>**: Print (or run through a pager if too long)
198 198 the source code for an object.
199 199 * **%pfile <object>**: Show the entire source file where an object was
200 200 defined via a pager, opening it at the line where the object
201 201 definition begins.
202 202 * **%who/%whos**: These functions give information about identifiers
203 203 you have defined interactively (not things you loaded or defined
204 204 in your configuration files). %who just prints a list of
205 205 identifiers and %whos prints a table with some basic details about
206 206 each identifier.
207 207
208 208 Note that the dynamic object information functions (?/??, ``%pdoc``,
209 209 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
210 210 directly on variables. For example, after doing ``import os``, you can use
211 211 ``os.path.abspath??``.
212 212
213 213 .. _readline:
214 214
215 215 Readline-based features
216 216 -----------------------
217 217
218 218 These features require the GNU readline library, so they won't work if your
219 219 Python installation lacks readline support. We will first describe the default
220 220 behavior IPython uses, and then how to change it to suit your preferences.
221 221
222 222
223 223 Command line completion
224 224 +++++++++++++++++++++++
225 225
226 226 At any time, hitting TAB will complete any available python commands or
227 227 variable names, and show you a list of the possible completions if
228 228 there's no unambiguous one. It will also complete filenames in the
229 229 current directory if no python names match what you've typed so far.
230 230
231 231
232 232 Search command history
233 233 ++++++++++++++++++++++
234 234
235 235 IPython provides two ways for searching through previous input and thus
236 236 reduce the need for repetitive typing:
237 237
238 238 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
239 239 (next,down) to search through only the history items that match
240 240 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
241 241 prompt, they just behave like normal arrow keys.
242 242 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
243 243 searches your history for lines that contain what you've typed so
244 244 far, completing as much as it can.
245 245
246 246
247 247 Persistent command history across sessions
248 248 ++++++++++++++++++++++++++++++++++++++++++
249 249
250 250 IPython will save your input history when it leaves and reload it next
251 251 time you restart it. By default, the history file is named
252 252 $IPYTHON_DIR/profile_<name>/history.sqlite. This allows you to keep
253 253 separate histories related to various tasks: commands related to
254 254 numerical work will not be clobbered by a system shell history, for
255 255 example.
256 256
257 257
258 258 Autoindent
259 259 ++++++++++
260 260
261 261 IPython can recognize lines ending in ':' and indent the next line,
262 262 while also un-indenting automatically after 'raise' or 'return'.
263 263
264 264 This feature uses the readline library, so it will honor your
265 265 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
266 266 to). Adding the following lines to your :file:`.inputrc` file can make
267 267 indenting/unindenting more convenient (M-i indents, M-u unindents)::
268 268
269 269 $if Python
270 270 "\M-i": " "
271 271 "\M-u": "\d\d\d\d"
272 272 $endif
273 273
274 274 Note that there are 4 spaces between the quote marks after "M-i" above.
275 275
276 276 .. warning::
277 277
278 278 Setting the above indents will cause problems with unicode text entry in
279 279 the terminal.
280 280
281 281 .. warning::
282 282
283 283 Autoindent is ON by default, but it can cause problems with the pasting of
284 284 multi-line indented code (the pasted code gets re-indented on each line). A
285 285 magic function %autoindent allows you to toggle it on/off at runtime. You
286 286 can also disable it permanently on in your :file:`ipython_config.py` file
287 287 (set TerminalInteractiveShell.autoindent=False).
288 288
289 289 If you want to paste multiple lines in the terminal, it is recommended that
290 290 you use ``%paste``.
291 291
292 292
293 293 Customizing readline behavior
294 294 +++++++++++++++++++++++++++++
295 295
296 296 All these features are based on the GNU readline library, which has an
297 297 extremely customizable interface. Normally, readline is configured via a
298 298 file which defines the behavior of the library; the details of the
299 299 syntax for this can be found in the readline documentation available
300 300 with your system or on the Internet. IPython doesn't read this file (if
301 301 it exists) directly, but it does support passing to readline valid
302 302 options via a simple interface. In brief, you can customize readline by
303 303 setting the following options in your configuration file (note
304 304 that these options can not be specified at the command line):
305 305
306 306 * **readline_parse_and_bind**: this holds a list of strings to be executed
307 307 via a readline.parse_and_bind() command. The syntax for valid commands
308 308 of this kind can be found by reading the documentation for the GNU
309 309 readline library, as these commands are of the kind which readline
310 310 accepts in its configuration file.
311 311 * **readline_remove_delims**: a string of characters to be removed
312 312 from the default word-delimiters list used by readline, so that
313 313 completions may be performed on strings which contain them. Do not
314 314 change the default value unless you know what you're doing.
315 315
316 316 You will find the default values in your configuration file.
317 317
318 318
319 319 Session logging and restoring
320 320 -----------------------------
321 321
322 322 You can log all input from a session either by starting IPython with the
323 323 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
324 324 or by activating the logging at any moment with the magic function %logstart.
325 325
326 326 Log files can later be reloaded by running them as scripts and IPython
327 327 will attempt to 'replay' the log by executing all the lines in it, thus
328 328 restoring the state of a previous session. This feature is not quite
329 329 perfect, but can still be useful in many cases.
330 330
331 331 The log files can also be used as a way to have a permanent record of
332 332 any code you wrote while experimenting. Log files are regular text files
333 333 which you can later open in your favorite text editor to extract code or
334 334 to 'clean them up' before using them to replay a session.
335 335
336 336 The `%logstart` function for activating logging in mid-session is used as
337 337 follows::
338 338
339 339 %logstart [log_name [log_mode]]
340 340
341 341 If no name is given, it defaults to a file named 'ipython_log.py' in your
342 342 current working directory, in 'rotate' mode (see below).
343 343
344 344 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
345 345 history up to that point and then continues logging.
346 346
347 347 %logstart takes a second optional parameter: logging mode. This can be
348 348 one of (note that the modes are given unquoted):
349 349
350 350 * [over:] overwrite existing log_name.
351 351 * [backup:] rename (if exists) to log_name~ and start log_name.
352 352 * [append:] well, that says it.
353 353 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
354 354
355 355 The %logoff and %logon functions allow you to temporarily stop and
356 356 resume logging to a file which had previously been started with
357 357 %logstart. They will fail (with an explanation) if you try to use them
358 358 before logging has been started.
359 359
360 360 .. _system_shell_access:
361 361
362 362 System shell access
363 363 -------------------
364 364
365 365 Any input line beginning with a ! character is passed verbatim (minus
366 366 the !, of course) to the underlying operating system. For example,
367 367 typing ``!ls`` will run 'ls' in the current directory.
368 368
369 369 Manual capture of command output
370 370 --------------------------------
371 371
372 372 You can assign the result of a system command to a Python variable with the
373 373 syntax ``myfiles = !ls``. This gets machine readable output from stdout
374 374 (e.g. without colours), and splits on newlines. To explicitly get this sort of
375 375 output without assigning to a variable, use two exclamation marks (``!!ls``) or
376 376 the ``%sx`` magic command.
377 377
378 378 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
379 379 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
380 380 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
381 381 See :ref:`string_lists` for details.
382 382
383 383 IPython also allows you to expand the value of python variables when
384 384 making system calls. Wrap variables or expressions in {braces}::
385 385
386 386 In [1]: pyvar = 'Hello world'
387 387 In [2]: !echo "A python variable: {pyvar}"
388 388 A python variable: Hello world
389 389 In [3]: import math
390 390 In [4]: x = 8
391 391 In [5]: !echo {math.factorial(x)}
392 392 40320
393 393
394 394 For simple cases, you can alternatively prepend $ to a variable name::
395 395
396 396 In [6]: !echo $sys.argv
397 397 [/home/fperez/usr/bin/ipython]
398 398 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
399 399 A system variable: /home/fperez
400 400
401 401 System command aliases
402 402 ----------------------
403 403
404 404 The %alias magic function allows you to define magic functions which are in fact
405 405 system shell commands. These aliases can have parameters.
406 406
407 407 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
408 408
409 409 Then, typing ``alias_name params`` will execute the system command 'cmd
410 410 params' (from your underlying operating system).
411 411
412 412 You can also define aliases with parameters using %s specifiers (one per
413 413 parameter). The following example defines the parts function as an
414 414 alias to the command 'echo first %s second %s' where each %s will be
415 415 replaced by a positional parameter to the call to %parts::
416 416
417 417 In [1]: %alias parts echo first %s second %s
418 418 In [2]: parts A B
419 419 first A second B
420 420 In [3]: parts A
421 421 ERROR: Alias <parts> requires 2 arguments, 1 given.
422 422
423 423 If called with no parameters, %alias prints the table of currently
424 424 defined aliases.
425 425
426 426 The %rehashx magic allows you to load your entire $PATH as
427 427 ipython aliases. See its docstring for further details.
428 428
429 429
430 430 .. _dreload:
431 431
432 432 Recursive reload
433 433 ----------------
434 434
435 435 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
436 436 module: changes made to any of its dependencies will be reloaded without
437 437 having to exit. To start using it, do::
438 438
439 439 from IPython.lib.deepreload import reload as dreload
440 440
441 441
442 442 Verbose and colored exception traceback printouts
443 443 -------------------------------------------------
444 444
445 445 IPython provides the option to see very detailed exception tracebacks,
446 446 which can be especially useful when debugging large programs. You can
447 447 run any Python file with the %run function to benefit from these
448 448 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
449 449 be colored (if your terminal supports it) which makes them much easier
450 450 to parse visually.
451 451
452 452 See the magic xmode and colors functions for details (just type %magic).
453 453
454 454 These features are basically a terminal version of Ka-Ping Yee's cgitb
455 455 module, now part of the standard Python library.
456 456
457 457
458 458 .. _input_caching:
459 459
460 460 Input caching system
461 461 --------------------
462 462
463 463 IPython offers numbered prompts (In/Out) with input and output caching
464 464 (also referred to as 'input history'). All input is saved and can be
465 465 retrieved as variables (besides the usual arrow key recall), in
466 466 addition to the %rep magic command that brings a history entry
467 467 up for editing on the next command line.
468 468
469 469 The following GLOBAL variables always exist (so don't overwrite them!):
470 470
471 471 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
472 472 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
473 473 overwrite In with a variable of your own, you can remake the assignment to the
474 474 internal list with a simple ``In=_ih``.
475 475
476 476 Additionally, global variables named _i<n> are dynamically created (<n>
477 477 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
478 478
479 479 For example, what you typed at prompt 14 is available as _i14, _ih[14]
480 480 and In[14].
481 481
482 482 This allows you to easily cut and paste multi line interactive prompts
483 483 by printing them out: they print like a clean string, without prompt
484 484 characters. You can also manipulate them like regular variables (they
485 485 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
486 486 contents of input prompt 9.
487 487
488 488 You can also re-execute multiple lines of input easily by using the
489 489 magic %rerun or %macro functions. The macro system also allows you to re-execute
490 490 previous lines which include magic function calls (which require special
491 491 processing). Type %macro? for more details on the macro system.
492 492
493 493 A history function %hist allows you to see any part of your input
494 494 history by printing a range of the _i variables.
495 495
496 496 You can also search ('grep') through your history by typing
497 497 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
498 498 etc. You can bring history entries listed by '%hist -g' up for editing
499 499 with the %recall command, or run them immediately with %rerun.
500 500
501 501 .. _output_caching:
502 502
503 503 Output caching system
504 504 ---------------------
505 505
506 506 For output that is returned from actions, a system similar to the input
507 507 cache exists but using _ instead of _i. Only actions that produce a
508 508 result (NOT assignments, for example) are cached. If you are familiar
509 509 with Mathematica, IPython's _ variables behave exactly like
510 510 Mathematica's % variables.
511 511
512 512 The following GLOBAL variables always exist (so don't overwrite them!):
513 513
514 514 * [_] (a single underscore) : stores previous output, like Python's
515 515 default interpreter.
516 516 * [__] (two underscores): next previous.
517 517 * [___] (three underscores): next-next previous.
518 518
519 519 Additionally, global variables named _<n> are dynamically created (<n>
520 520 being the prompt counter), such that the result of output <n> is always
521 521 available as _<n> (don't use the angle brackets, just the number, e.g.
522 522 _21).
523 523
524 524 These variables are also stored in a global dictionary (not a
525 525 list, since it only has entries for lines which returned a result)
526 526 available under the names _oh and Out (similar to _ih and In). So the
527 527 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
528 528 accidentally overwrite the Out variable you can recover it by typing
529 529 'Out=_oh' at the prompt.
530 530
531 531 This system obviously can potentially put heavy memory demands on your
532 532 system, since it prevents Python's garbage collector from removing any
533 533 previously computed results. You can control how many results are kept
534 534 in memory with the option (at the command line or in your configuration
535 535 file) cache_size. If you set it to 0, the whole system is completely
536 536 disabled and the prompts revert to the classic '>>>' of normal Python.
537 537
538 538
539 539 Directory history
540 540 -----------------
541 541
542 542 Your history of visited directories is kept in the global list _dh, and
543 543 the magic %cd command can be used to go to any entry in that list. The
544 544 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
545 545 conveniently view the directory history.
546 546
547 547
548 548 Automatic parentheses and quotes
549 549 --------------------------------
550 550
551 551 These features were adapted from Nathan Gray's LazyPython. They are
552 552 meant to allow less typing for common situations.
553 553
554 554
555 555 Automatic parentheses
556 556 +++++++++++++++++++++
557 557
558 558 Callable objects (i.e. functions, methods, etc) can be invoked like this
559 559 (notice the commas between the arguments)::
560 560
561 561 In [1]: callable_ob arg1, arg2, arg3
562 562 ------> callable_ob(arg1, arg2, arg3)
563 563
564 564 You can force automatic parentheses by using '/' as the first character
565 565 of a line. For example::
566 566
567 567 In [2]: /globals # becomes 'globals()'
568 568
569 569 Note that the '/' MUST be the first character on the line! This won't work::
570 570
571 571 In [3]: print /globals # syntax error
572 572
573 573 In most cases the automatic algorithm should work, so you should rarely
574 574 need to explicitly invoke /. One notable exception is if you are trying
575 575 to call a function with a list of tuples as arguments (the parenthesis
576 576 will confuse IPython)::
577 577
578 578 In [4]: zip (1,2,3),(4,5,6) # won't work
579 579
580 580 but this will work::
581 581
582 582 In [5]: /zip (1,2,3),(4,5,6)
583 583 ------> zip ((1,2,3),(4,5,6))
584 584 Out[5]: [(1, 4), (2, 5), (3, 6)]
585 585
586 586 IPython tells you that it has altered your command line by displaying
587 587 the new command line preceded by ->. e.g.::
588 588
589 589 In [6]: callable list
590 590 ------> callable(list)
591 591
592 592
593 593 Automatic quoting
594 594 +++++++++++++++++
595 595
596 596 You can force automatic quoting of a function's arguments by using ','
597 597 or ';' as the first character of a line. For example::
598 598
599 599 In [1]: ,my_function /home/me # becomes my_function("/home/me")
600 600
601 601 If you use ';' the whole argument is quoted as a single string, while ',' splits
602 602 on whitespace::
603 603
604 604 In [2]: ,my_function a b c # becomes my_function("a","b","c")
605 605
606 606 In [3]: ;my_function a b c # becomes my_function("a b c")
607 607
608 608 Note that the ',' or ';' MUST be the first character on the line! This
609 609 won't work::
610 610
611 611 In [4]: x = ,my_function /home/me # syntax error
612 612
613 613 IPython as your default Python environment
614 614 ==========================================
615 615
616 616 Python honors the environment variable PYTHONSTARTUP and will execute at
617 617 startup the file referenced by this variable. If you put the following code at
618 618 the end of that file, then IPython will be your working environment anytime you
619 619 start Python::
620 620
621 621 from IPython.frontend.terminal.ipapp import launch_new_instance
622 622 launch_new_instance()
623 623 raise SystemExit
624 624
625 625 The ``raise SystemExit`` is needed to exit Python when
626 626 it finishes, otherwise you'll be back at the normal Python '>>>'
627 627 prompt.
628 628
629 629 This is probably useful to developers who manage multiple Python
630 630 versions and don't want to have correspondingly multiple IPython
631 631 versions. Note that in this mode, there is no way to pass IPython any
632 632 command-line options, as those are trapped first by Python itself.
633 633
634 634 .. _Embedding:
635 635
636 636 Embedding IPython
637 637 =================
638 638
639 639 It is possible to start an IPython instance inside your own Python
640 640 programs. This allows you to evaluate dynamically the state of your
641 641 code, operate with your variables, analyze them, etc. Note however that
642 642 any changes you make to values while in the shell do not propagate back
643 643 to the running code, so it is safe to modify your values because you
644 644 won't break your code in bizarre ways by doing so.
645 645
646 646 .. note::
647 647
648 648 At present, trying to embed IPython from inside IPython causes problems. Run
649 649 the code samples below outside IPython.
650 650
651 651 This feature allows you to easily have a fully functional python
652 652 environment for doing object introspection anywhere in your code with a
653 653 simple function call. In some cases a simple print statement is enough,
654 654 but if you need to do more detailed analysis of a code fragment this
655 655 feature can be very valuable.
656 656
657 657 It can also be useful in scientific computing situations where it is
658 658 common to need to do some automatic, computationally intensive part and
659 659 then stop to look at data, plots, etc.
660 660 Opening an IPython instance will give you full access to your data and
661 661 functions, and you can resume program execution once you are done with
662 662 the interactive part (perhaps to stop again later, as many times as
663 663 needed).
664 664
665 665 The following code snippet is the bare minimum you need to include in
666 666 your Python programs for this to work (detailed examples follow later)::
667 667
668 668 from IPython import embed
669 669
670 670 embed() # this call anywhere in your program will start IPython
671 671
672 .. note::
673
674 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
675 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
676 It should function just the same as regular embed, but you connect
677 an external frontend rather than IPython starting up in the local
678 terminal.
679
672 680 You can run embedded instances even in code which is itself being run at
673 681 the IPython interactive prompt with '%run <filename>'. Since it's easy
674 682 to get lost as to where you are (in your top-level IPython or in your
675 683 embedded one), it's a good idea in such cases to set the in/out prompts
676 684 to something different for the embedded instances. The code examples
677 685 below illustrate this.
678 686
679 687 You can also have multiple IPython instances in your program and open
680 688 them separately, for example with different options for data
681 689 presentation. If you close and open the same instance multiple times,
682 690 its prompt counters simply continue from each execution to the next.
683 691
684 692 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
685 693 module for more details on the use of this system.
686 694
687 695 The following sample file illustrating how to use the embedding
688 696 functionality is provided in the examples directory as example-embed.py.
689 697 It should be fairly self-explanatory:
690 698
691 699 .. literalinclude:: ../../examples/core/example-embed.py
692 700 :language: python
693 701
694 702 Once you understand how the system functions, you can use the following
695 703 code fragments in your programs which are ready for cut and paste:
696 704
697 705 .. literalinclude:: ../../examples/core/example-embed-short.py
698 706 :language: python
699 707
700 708 Using the Python debugger (pdb)
701 709 ===============================
702 710
703 711 Running entire programs via pdb
704 712 -------------------------------
705 713
706 714 pdb, the Python debugger, is a powerful interactive debugger which
707 715 allows you to step through code, set breakpoints, watch variables,
708 716 etc. IPython makes it very easy to start any script under the control
709 717 of pdb, regardless of whether you have wrapped it into a 'main()'
710 718 function or not. For this, simply type '%run -d myscript' at an
711 719 IPython prompt. See the %run command's documentation (via '%run?' or
712 720 in Sec. magic_ for more details, including how to control where pdb
713 721 will stop execution first.
714 722
715 723 For more information on the use of the pdb debugger, read the included
716 724 pdb.doc file (part of the standard Python distribution). On a stock
717 725 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
718 726 easiest way to read it is by using the help() function of the pdb module
719 727 as follows (in an IPython prompt)::
720 728
721 729 In [1]: import pdb
722 730 In [2]: pdb.help()
723 731
724 732 This will load the pdb.doc document in a file viewer for you automatically.
725 733
726 734
727 735 Automatic invocation of pdb on exceptions
728 736 -----------------------------------------
729 737
730 738 IPython, if started with the ``--pdb`` option (or if the option is set in
731 739 your config file) can call the Python pdb debugger every time your code
732 740 triggers an uncaught exception. This feature
733 741 can also be toggled at any time with the %pdb magic command. This can be
734 742 extremely useful in order to find the origin of subtle bugs, because pdb
735 743 opens up at the point in your code which triggered the exception, and
736 744 while your program is at this point 'dead', all the data is still
737 745 available and you can walk up and down the stack frame and understand
738 746 the origin of the problem.
739 747
740 748 Furthermore, you can use these debugging facilities both with the
741 749 embedded IPython mode and without IPython at all. For an embedded shell
742 750 (see sec. Embedding_), simply call the constructor with
743 751 ``--pdb`` in the argument string and pdb will automatically be called if an
744 752 uncaught exception is triggered by your code.
745 753
746 754 For stand-alone use of the feature in your programs which do not use
747 755 IPython at all, put the following lines toward the top of your 'main'
748 756 routine::
749 757
750 758 import sys
751 759 from IPython.core import ultratb
752 760 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
753 761 color_scheme='Linux', call_pdb=1)
754 762
755 763 The mode keyword can be either 'Verbose' or 'Plain', giving either very
756 764 detailed or normal tracebacks respectively. The color_scheme keyword can
757 765 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
758 766 options which can be set in IPython with ``--colors`` and ``--xmode``.
759 767
760 768 This will give any of your programs detailed, colored tracebacks with
761 769 automatic invocation of pdb.
762 770
763 771
764 772 Extensions for syntax processing
765 773 ================================
766 774
767 775 This isn't for the faint of heart, because the potential for breaking
768 776 things is quite high. But it can be a very powerful and useful feature.
769 777 In a nutshell, you can redefine the way IPython processes the user input
770 778 line to accept new, special extensions to the syntax without needing to
771 779 change any of IPython's own code.
772 780
773 781 In the IPython/extensions directory you will find some examples
774 782 supplied, which we will briefly describe now. These can be used 'as is'
775 783 (and both provide very useful functionality), or you can use them as a
776 784 starting point for writing your own extensions.
777 785
778 786 .. _pasting_with_prompts:
779 787
780 788 Pasting of code starting with Python or IPython prompts
781 789 -------------------------------------------------------
782 790
783 791 IPython is smart enough to filter out input prompts, be they plain Python ones
784 792 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and `` ...:``). You can
785 793 therefore copy and paste from existing interactive sessions without worry.
786 794
787 795 The following is a 'screenshot' of how things work, copying an example from the
788 796 standard Python tutorial::
789 797
790 798 In [1]: >>> # Fibonacci series:
791 799
792 800 In [2]: ... # the sum of two elements defines the next
793 801
794 802 In [3]: ... a, b = 0, 1
795 803
796 804 In [4]: >>> while b < 10:
797 805 ...: ... print b
798 806 ...: ... a, b = b, a+b
799 807 ...:
800 808 1
801 809 1
802 810 2
803 811 3
804 812 5
805 813 8
806 814
807 815 And pasting from IPython sessions works equally well::
808 816
809 817 In [1]: In [5]: def f(x):
810 818 ...: ...: "A simple function"
811 819 ...: ...: return x**2
812 820 ...: ...:
813 821
814 822 In [2]: f(3)
815 823 Out[2]: 9
816 824
817 825 .. _gui_support:
818 826
819 827 GUI event loop support
820 828 ======================
821 829
822 830 .. versionadded:: 0.11
823 831 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
824 832
825 833 IPython has excellent support for working interactively with Graphical User
826 834 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
827 835 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
828 836 is extremely robust compared to our previous thread-based version. The
829 837 advantages of this are:
830 838
831 839 * GUIs can be enabled and disabled dynamically at runtime.
832 840 * The active GUI can be switched dynamically at runtime.
833 841 * In some cases, multiple GUIs can run simultaneously with no problems.
834 842 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
835 843 all of these things.
836 844
837 845 For users, enabling GUI event loop integration is simple. You simple use the
838 846 ``%gui`` magic as follows::
839 847
840 848 %gui [GUINAME]
841 849
842 850 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
843 851 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
844 852
845 853 Thus, to use wxPython interactively and create a running :class:`wx.App`
846 854 object, do::
847 855
848 856 %gui wx
849 857
850 858 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
851 859 see :ref:`this section <matplotlib_support>`.
852 860
853 861 For developers that want to use IPython's GUI event loop integration in the
854 862 form of a library, these capabilities are exposed in library form in the
855 863 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
856 864 Interested developers should see the module docstrings for more information,
857 865 but there are a few points that should be mentioned here.
858 866
859 867 First, the ``PyOSInputHook`` approach only works in command line settings
860 868 where readline is activated. The integration with various eventloops
861 869 is handled somewhat differently (and more simply) when using the standalone
862 870 kernel, as in the qtconsole and notebook.
863 871
864 872 Second, when using the ``PyOSInputHook`` approach, a GUI application should
865 873 *not* start its event loop. Instead all of this is handled by the
866 874 ``PyOSInputHook``. This means that applications that are meant to be used both
867 875 in IPython and as standalone apps need to have special code to detects how the
868 876 application is being run. We highly recommend using IPython's support for this.
869 877 Since the details vary slightly between toolkits, we point you to the various
870 878 examples in our source directory :file:`docs/examples/lib` that demonstrate
871 879 these capabilities.
872 880
873 881 Third, unlike previous versions of IPython, we no longer "hijack" (replace
874 882 them with no-ops) the event loops. This is done to allow applications that
875 883 actually need to run the real event loops to do so. This is often needed to
876 884 process pending events at critical points.
877 885
878 886 Finally, we also have a number of examples in our source directory
879 887 :file:`docs/examples/lib` that demonstrate these capabilities.
880 888
881 889 PyQt and PySide
882 890 ---------------
883 891
884 892 .. attempt at explanation of the complete mess that is Qt support
885 893
886 894 When you use ``--gui=qt`` or ``--pylab=qt``, IPython can work with either
887 895 PyQt4 or PySide. There are three options for configuration here, because
888 896 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
889 897 Python 2, and the more natural v2, which is the only API supported by PySide.
890 898 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
891 899 uses v2, but you can still use any interface in your code, since the
892 900 Qt frontend is in a different process.
893 901
894 902 The default will be to import PyQt4 without configuration of the APIs, thus
895 903 matching what most applications would expect. It will fall back of PySide if
896 904 PyQt4 is unavailable.
897 905
898 906 If specified, IPython will respect the environment variable ``QT_API`` used
899 907 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
900 908 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
901 909 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
902 910 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
903 911
904 912 If you launch IPython in pylab mode with ``ipython --pylab=qt``, then IPython
905 913 will ask matplotlib which Qt library to use (only if QT_API is *not set*), via
906 914 the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or older, then
907 915 IPython will always use PyQt4 without setting the v2 APIs, since neither v2
908 916 PyQt nor PySide work.
909 917
910 918 .. warning::
911 919
912 920 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
913 921 to work with IPython's qt integration, because otherwise PyQt4 will be
914 922 loaded in an incompatible mode.
915 923
916 924 It also means that you must *not* have ``QT_API`` set if you want to
917 925 use ``--gui=qt`` with code that requires PyQt4 API v1.
918 926
919 927
920 928 .. _matplotlib_support:
921 929
922 930 Plotting with matplotlib
923 931 ========================
924 932
925 933 `Matplotlib`_ provides high quality 2D and 3D plotting for Python. Matplotlib
926 934 can produce plots on screen using a variety of GUI toolkits, including Tk,
927 935 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
928 936 scientific computing, all with a syntax compatible with that of the popular
929 937 Matlab program.
930 938
931 939 To start IPython with matplotlib support, use the ``--pylab`` switch. If no
932 940 arguments are given, IPython will automatically detect your choice of
933 941 matplotlib backend. You can also request a specific backend with ``--pylab
934 942 backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', 'gtk', 'osx'.
935 943 In the web notebook and Qt console, 'inline' is also a valid backend value,
936 944 which produces static figures inlined inside the application window instead of
937 945 matplotlib's interactive figures that live in separate windows.
938 946
939 947 .. _Matplotlib: http://matplotlib.sourceforge.net
940 948
941 949 .. _interactive_demos:
942 950
943 951 Interactive demos with IPython
944 952 ==============================
945 953
946 954 IPython ships with a basic system for running scripts interactively in
947 955 sections, useful when presenting code to audiences. A few tags embedded
948 956 in comments (so that the script remains valid Python code) divide a file
949 957 into separate blocks, and the demo can be run one block at a time, with
950 958 IPython printing (with syntax highlighting) the block before executing
951 959 it, and returning to the interactive prompt after each block. The
952 960 interactive namespace is updated after each block is run with the
953 961 contents of the demo's namespace.
954 962
955 963 This allows you to show a piece of code, run it and then execute
956 964 interactively commands based on the variables just created. Once you
957 965 want to continue, you simply execute the next block of the demo. The
958 966 following listing shows the markup necessary for dividing a script into
959 967 sections for execution as a demo:
960 968
961 969 .. literalinclude:: ../../examples/lib/example-demo.py
962 970 :language: python
963 971
964 972 In order to run a file as a demo, you must first make a Demo object out
965 973 of it. If the file is named myscript.py, the following code will make a
966 974 demo::
967 975
968 976 from IPython.lib.demo import Demo
969 977
970 978 mydemo = Demo('myscript.py')
971 979
972 980 This creates the mydemo object, whose blocks you run one at a time by
973 981 simply calling the object with no arguments. If you have autocall active
974 982 in IPython (the default), all you need to do is type::
975 983
976 984 mydemo
977 985
978 986 and IPython will call it, executing each block. Demo objects can be
979 987 restarted, you can move forward or back skipping blocks, re-execute the
980 988 last block, etc. Simply use the Tab key on a demo object to see its
981 989 methods, and call '?' on them to see their docstrings for more usage
982 990 details. In addition, the demo module itself contains a comprehensive
983 991 docstring, which you can access via::
984 992
985 993 from IPython.lib import demo
986 994
987 995 demo?
988 996
989 997 Limitations: It is important to note that these demos are limited to
990 998 fairly simple uses. In particular, you cannot break up sections within
991 999 indented code (loops, if statements, function definitions, etc.)
992 1000 Supporting something like this would basically require tracking the
993 1001 internal execution state of the Python interpreter, so only top-level
994 1002 divisions are allowed. If you want to be able to open an IPython
995 1003 instance at an arbitrary point in a program, you can use IPython's
996 1004 embedding facilities, see :func:`IPython.embed` for details.
997 1005
General Comments 0
You need to be logged in to leave comments. Login now