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