##// END OF EJS Templates
Merging upstream changes from inputhook and config-refactor....
Brian Granger -
r2224:11a6689b merge
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -0,0 +1,35 b''
1 #!/usr/bin/env python
2 """Simple GTK example to manually test event loop integration.
3
4 This is meant to run tests manually in ipython as:
5
6 In [5]: %gui gtk
7
8 In [6]: %run gui-gtk.py
9 """
10
11
12 import pygtk
13 pygtk.require('2.0')
14 import gtk
15
16
17 def hello_world(wigdet, data=None):
18 print "Hello World"
19
20 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
21 button = gtk.Button("Hello World")
22 button.connect("clicked", hello_world, None)
23
24 window.add(self.button)
25 button.show()
26 window.show()
27
28 try:
29 from IPython.lib.inputhook import appstart_gtk
30 appstart_gtk()
31 except ImportError:
32 gtk.main()
33
34
35
@@ -0,0 +1,54 b''
1 """Test the new %gui command. Run this in ipython as
2
3 In [1]: %gui [backend]
4
5 In [2]: %run switchgui [backend]
6
7 where the optional backend can be one of: qt4, gtk, tk, wx.
8
9 Because of subtle difference in how Matplotlib handles the different GUI
10 toolkits (in things like draw and show), minor modifications to this script
11 have to be made for Tk to get it to work with the 0.99 and below releases
12 of Matplotlib. However, in the future, Matplotlib should be able to have
13 similar logic for all the toolkits, as they are all now using PyOS_InputHook.
14 """
15
16 import sys
17 import time
18
19 from IPython.lib import inputhook
20
21 gui = inputhook.current_gui()
22 if gui is None:
23 gui = 'qt4'
24 inputhook.enable_qt4(app=True)
25
26 backends = dict(wx='wxagg', qt4='qt4agg', gtk='gtkagg', tk='tkagg')
27
28 import matplotlib
29 matplotlib.use(backends[gui])
30 matplotlib.interactive(True)
31
32 import matplotlib
33 from matplotlib import pyplot as plt, mlab, pylab
34 import numpy as np
35
36 from numpy import *
37 from matplotlib.pyplot import *
38
39 x = np.linspace(0,pi,500)
40
41 print "A plot has been created"
42 line, = plot(x,sin(2*x))
43 inputhook.spin() # This has to be removed for Tk
44
45
46 print "Now, we will update the plot..."
47 print
48 for i in range(1,51):
49 print i,
50 sys.stdout.flush()
51 line.set_data(x,sin(x*i))
52 plt.title('i=%d' % i)
53 plt.draw()
54 inputhook.spin() # This has to be removed for Tk
@@ -0,0 +1,40 b''
1 #!/usr/bin/env python
2 """Simple Qt4 example to manually test event loop integration.
3
4 This is meant to run tests manually in ipython as:
5
6 In [5]: %gui qt
7
8 In [6]: %run gui-qt.py
9
10 Ref: Modified from http://zetcode.com/tutorials/pyqt4/firstprograms/
11 """
12
13 import sys
14 from PyQt4 import QtGui, QtCore
15
16 class SimpleWindow(QtGui.QWidget):
17 def __init__(self, parent=None):
18 QtGui.QWidget.__init__(self, parent)
19
20 self.setGeometry(300, 300, 200, 80)
21 self.setWindowTitle('Hello World')
22
23 quit = QtGui.QPushButton('Close', self)
24 quit.setGeometry(10, 10, 60, 35)
25
26 self.connect(quit, QtCore.SIGNAL('clicked()'),
27 self, QtCore.SLOT('close()'))
28
29 if __name__ == '__main__':
30 app = QtCore.QCoreApplication.instance()
31 if app is None:
32 app = QtGui.QApplication([])
33
34 sw = SimpleWindow()
35 sw.show()
36
37 try:
38 from IPython import appstart_qt4; appstart_qt4(app)
39 except ImportError:
40 app.exec_()
@@ -0,0 +1,32 b''
1 #!/usr/bin/env python
2 """Simple Tk example to manually test event loop integration.
3
4 This is meant to run tests manually in ipython as:
5
6 In [5]: %gui tk
7
8 In [6]: %run gui-tk.py
9 """
10
11 from Tkinter import *
12
13 class MyApp:
14
15 def __init__(self, root):
16 frame = Frame(root)
17 frame.pack()
18
19 self.button = Button(frame, text="Hello", command=self.hello_world)
20 self.button.pack(side=LEFT)
21
22 def hello_world(self):
23 print "Hello World!"
24
25 root = Tk()
26
27 app = MyApp(root)
28
29 try:
30 from IPython import appstart_tk; appstart_tk(root)
31 except ImportError:
32 root.mainloop()
@@ -0,0 +1,99 b''
1 """A Simple wx example to test IPython's event loop integration.
2
3 To run this do:
4
5 In [5]: %gui wx
6
7 In [6]: %run gui-wx.py
8
9 Ref: Modified from wxPython source code wxPython/samples/simple/simple.py
10
11 This example can only be run once in a given IPython session.
12 """
13
14 import wx
15
16
17 class MyFrame(wx.Frame):
18 """
19 This is MyFrame. It just shows a few controls on a wxPanel,
20 and has a simple menu.
21 """
22 def __init__(self, parent, title):
23 wx.Frame.__init__(self, parent, -1, title,
24 pos=(150, 150), size=(350, 200))
25
26 # Create the menubar
27 menuBar = wx.MenuBar()
28
29 # and a menu
30 menu = wx.Menu()
31
32 # add an item to the menu, using \tKeyName automatically
33 # creates an accelerator, the third param is some help text
34 # that will show up in the statusbar
35 menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")
36
37 # bind the menu event to an event handler
38 self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT)
39
40 # and put the menu on the menubar
41 menuBar.Append(menu, "&File")
42 self.SetMenuBar(menuBar)
43
44 self.CreateStatusBar()
45
46 # Now create the Panel to put the other controls on.
47 panel = wx.Panel(self)
48
49 # and a few controls
50 text = wx.StaticText(panel, -1, "Hello World!")
51 text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
52 text.SetSize(text.GetBestSize())
53 btn = wx.Button(panel, -1, "Close")
54 funbtn = wx.Button(panel, -1, "Just for fun...")
55
56 # bind the button events to handlers
57 self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, btn)
58 self.Bind(wx.EVT_BUTTON, self.OnFunButton, funbtn)
59
60 # Use a sizer to layout the controls, stacked vertically and with
61 # a 10 pixel border around each
62 sizer = wx.BoxSizer(wx.VERTICAL)
63 sizer.Add(text, 0, wx.ALL, 10)
64 sizer.Add(btn, 0, wx.ALL, 10)
65 sizer.Add(funbtn, 0, wx.ALL, 10)
66 panel.SetSizer(sizer)
67 panel.Layout()
68
69
70 def OnTimeToClose(self, evt):
71 """Event handler for the button click."""
72 print "See ya later!"
73 self.Close()
74
75 def OnFunButton(self, evt):
76 """Event handler for the button click."""
77 print "Having fun yet?"
78
79
80 class MyApp(wx.App):
81 def OnInit(self):
82 frame = MyFrame(None, "Simple wxPython App")
83 self.SetTopWindow(frame)
84
85 print "Print statements go to this stdout window by default."
86
87 frame.Show(True)
88 return True
89
90 app = wx.GetApp()
91 if app is None:
92 app = MyApp(redirect=False, clearSigInt=False)
93
94 try:
95 from IPython.lib.inputhook import appstart_wx
96 appstart_wx(app)
97 except ImportError:
98 app.MainLoop()
99
@@ -1,47 +1,62 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 IPython.
4 IPython.
5
5
6 IPython is a set of tools for interactive and exploratory computing in Python.
6 IPython is a set of tools for interactive and exploratory computing in Python.
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2009 The IPython Development Team
10 # Copyright (C) 2008-2009 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 import os
20 import os
21 import sys
21 import sys
22 from IPython.core import release
22 from IPython.core import release
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Setup everything
25 # Setup everything
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 if sys.version[0:3] < '2.4':
29 if sys.version[0:3] < '2.4':
30 raise ImportError('Python Version 2.4 or above is required for IPython.')
30 raise ImportError('Python Version 2.4 or above is required for IPython.')
31
31
32
32
33 # Make it easy to import extensions - they are always directly on pythonpath.
33 # Make it easy to import extensions - they are always directly on pythonpath.
34 # Therefore, non-IPython modules can be added to extensions directory
34 # Therefore, non-IPython modules can be added to extensions directory
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
36
36
37 from IPython.core import iplib
37 #-----------------------------------------------------------------------------
38 # Setup the top level names
39 #-----------------------------------------------------------------------------
38
40
41 from IPython.core.iplib import InteractiveShell
42 from IPython.core.error import TryNext
43
44 from IPython.lib import (
45 enable_wx, disable_wx,
46 enable_gtk, disable_gtk,
47 enable_qt4, disable_qt4,
48 enable_tk, disable_tk,
49 set_inputhook, clear_inputhook,
50 current_gui, spin,
51 appstart_qt4, appstart_wx,
52 appstart_gtk, appstart_tk
53 )
39
54
40 # Release data
55 # Release data
41 __author__ = ''
56 __author__ = ''
42 for author, email in release.authors.values():
57 for author, email in release.authors.values():
43 __author__ += author + ' <' + email + '>\n'
58 __author__ += author + ' <' + email + '>\n'
44 __license__ = release.license
59 __license__ = release.license
45 __version__ = release.version
60 __version__ = release.version
46 __revision__ = release.revision
61 __revision__ = release.revision
47
62
@@ -1,229 +1,233 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A lightweight component system for IPython.
4 A lightweight component system for IPython.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from copy import deepcopy
23 from copy import deepcopy
24 import datetime
24 import datetime
25 from weakref import WeakValueDictionary
25 from weakref import WeakValueDictionary
26
26
27 from IPython.utils.ipstruct import Struct
27 from IPython.utils.ipstruct import Struct
28 from IPython.utils.traitlets import (
28 from IPython.utils.traitlets import (
29 HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
29 HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
30 )
30 )
31
31
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Helper classes for Components
34 # Helper classes for Components
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37
37
38 class ComponentError(Exception):
38 class ComponentError(Exception):
39 pass
39 pass
40
40
41 class MetaComponentTracker(type):
41 class MetaComponentTracker(type):
42 """A metaclass that tracks instances of Components and its subclasses."""
42 """A metaclass that tracks instances of Components and its subclasses."""
43
43
44 def __init__(cls, name, bases, d):
44 def __init__(cls, name, bases, d):
45 super(MetaComponentTracker, cls).__init__(name, bases, d)
45 super(MetaComponentTracker, cls).__init__(name, bases, d)
46 cls.__instance_refs = WeakValueDictionary()
46 cls.__instance_refs = WeakValueDictionary()
47 cls.__numcreated = 0
47 cls.__numcreated = 0
48
48
49 def __call__(cls, *args, **kw):
49 def __call__(cls, *args, **kw):
50 """Called when *class* is called (instantiated)!!!
50 """Called when *class* is called (instantiated)!!!
51
51
52 When a Component or subclass is instantiated, this is called and
52 When a Component or subclass is instantiated, this is called and
53 the instance is saved in a WeakValueDictionary for tracking.
53 the instance is saved in a WeakValueDictionary for tracking.
54 """
54 """
55
55
56 instance = super(MetaComponentTracker, cls).__call__(*args, **kw)
56 instance = super(MetaComponentTracker, cls).__call__(*args, **kw)
57 for c in cls.__mro__:
57 for c in cls.__mro__:
58 if issubclass(cls, c) and issubclass(c, Component):
58 if issubclass(cls, c) and issubclass(c, Component):
59 c.__numcreated += 1
59 c.__numcreated += 1
60 c.__instance_refs[c.__numcreated] = instance
60 c.__instance_refs[c.__numcreated] = instance
61 return instance
61 return instance
62
62
63 def get_instances(cls, name=None, klass=None, root=None):
63 def get_instances(cls, name=None, root=None):
64 """Get all instances of cls and its subclasses.
64 """Get all instances of cls and its subclasses.
65
65
66 Parameters
66 Parameters
67 ----------
67 ----------
68 name : str
68 name : str
69 Limit to components with this name.
69 Limit to components with this name.
70 klass : class
71 Limit to components having isinstance(component, klass)
72 root : Component or subclass
70 root : Component or subclass
73 Limit to components having this root.
71 Limit to components having this root.
74 """
72 """
75 instances = cls.__instance_refs.values()
73 instances = cls.__instance_refs.values()
76 if name is not None:
74 if name is not None:
77 instances = [i for i in instances if i.name == name]
75 instances = [i for i in instances if i.name == name]
78 if klass is not None:
79 instances = [i for i in instances if isinstance(i, klass)]
80 if root is not None:
76 if root is not None:
81 instances = [i for i in instances if i.root == root]
77 instances = [i for i in instances if i.root == root]
82 return instances
78 return instances
83
79
84 def get_instances_by_condition(cls, call, name=None, klass=None, root=None):
80 def get_instances_by_condition(cls, call, name=None, root=None):
85 """Get all instances of cls, i such that call(i)==True.
81 """Get all instances of cls, i such that call(i)==True.
86
82
87 This also takes the ``name``, ``klass`` and ``root`` arguments of
83 This also takes the ``name`` and ``root`` arguments of
88 :meth:`get_instance`
84 :meth:`get_instance`
89 """
85 """
90 return [i for i in cls.get_instances(name,klass,root) if call(i)]
86 return [i for i in cls.get_instances(name, root) if call(i)]
91
87
92
88
93 class ComponentNameGenerator(object):
89 class ComponentNameGenerator(object):
94 """A Singleton to generate unique component names."""
90 """A Singleton to generate unique component names."""
95
91
96 def __init__(self, prefix):
92 def __init__(self, prefix):
97 self.prefix = prefix
93 self.prefix = prefix
98 self.i = 0
94 self.i = 0
99
95
100 def __call__(self):
96 def __call__(self):
101 count = self.i
97 count = self.i
102 self.i += 1
98 self.i += 1
103 return "%s%s" % (self.prefix, count)
99 return "%s%s" % (self.prefix, count)
104
100
105
101
106 ComponentNameGenerator = ComponentNameGenerator('ipython.component')
102 ComponentNameGenerator = ComponentNameGenerator('ipython.component')
107
103
108
104
109 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
105 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
110 pass
106 pass
111
107
112
108
113 #-----------------------------------------------------------------------------
109 #-----------------------------------------------------------------------------
114 # Component implementation
110 # Component implementation
115 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
116
112
117
113
118 class Component(HasTraitlets):
114 class Component(HasTraitlets):
119
115
120 __metaclass__ = MetaComponent
116 __metaclass__ = MetaComponent
121
117
122 # Traitlets are fun!
118 # Traitlets are fun!
123 config = Instance(Struct,(),{})
119 config = Instance(Struct,(),{})
124 parent = This()
120 parent = This()
125 root = This()
121 root = This()
126 created = None
122 created = None
127
123
128 def __init__(self, parent, name=None, config=None):
124 def __init__(self, parent, name=None, config=None):
129 """Create a component given a parent and possibly and name and config.
125 """Create a component given a parent and possibly and name and config.
130
126
131 Parameters
127 Parameters
132 ----------
128 ----------
133 parent : Component subclass
129 parent : Component subclass
134 The parent in the component graph. The parent is used
130 The parent in the component graph. The parent is used
135 to get the root of the component graph.
131 to get the root of the component graph.
136 name : str
132 name : str
137 The unique name of the component. If empty, then a unique
133 The unique name of the component. If empty, then a unique
138 one will be autogenerated.
134 one will be autogenerated.
139 config : Struct
135 config : Struct
140 If this is empty, self.config = parent.config, otherwise
136 If this is empty, self.config = parent.config, otherwise
141 self.config = config and root.config is ignored. This argument
137 self.config = config and root.config is ignored. This argument
142 should only be used to *override* the automatic inheritance of
138 should only be used to *override* the automatic inheritance of
143 parent.config. If a caller wants to modify parent.config
139 parent.config. If a caller wants to modify parent.config
144 (not override), the caller should make a copy and change
140 (not override), the caller should make a copy and change
145 attributes and then pass the copy to this argument.
141 attributes and then pass the copy to this argument.
146
142
147 Notes
143 Notes
148 -----
144 -----
149 Subclasses of Component must call the :meth:`__init__` method of
145 Subclasses of Component must call the :meth:`__init__` method of
150 :class:`Component` *before* doing anything else and using
146 :class:`Component` *before* doing anything else and using
151 :func:`super`::
147 :func:`super`::
152
148
153 class MyComponent(Component):
149 class MyComponent(Component):
154 def __init__(self, parent, name=None, config=None):
150 def __init__(self, parent, name=None, config=None):
155 super(MyComponent, self).__init__(parent, name, config)
151 super(MyComponent, self).__init__(parent, name, config)
156 # Then any other code you need to finish initialization.
152 # Then any other code you need to finish initialization.
157
153
158 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
154 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
159 attributes are handled properly.
155 attributes are handled properly.
160 """
156 """
161 super(Component, self).__init__()
157 super(Component, self).__init__()
162 self._children = []
158 self._children = []
163 if name is None:
159 if name is None:
164 self.name = ComponentNameGenerator()
160 self.name = ComponentNameGenerator()
165 else:
161 else:
166 self.name = name
162 self.name = name
167 self.root = self # This is the default, it is set when parent is set
163 self.root = self # This is the default, it is set when parent is set
168 self.parent = parent
164 self.parent = parent
169 if config is not None:
165 if config is not None:
170 self.config = deepcopy(config)
166 self.config = deepcopy(config)
171 else:
167 else:
172 if self.parent is not None:
168 if self.parent is not None:
173 self.config = deepcopy(self.parent.config)
169 self.config = deepcopy(self.parent.config)
174
170
175 self.created = datetime.datetime.now()
171 self.created = datetime.datetime.now()
176
172
177 #-------------------------------------------------------------------------
173 #-------------------------------------------------------------------------
178 # Static traitlet notifiations
174 # Static traitlet notifiations
179 #-------------------------------------------------------------------------
175 #-------------------------------------------------------------------------
180
176
181 def _parent_changed(self, name, old, new):
177 def _parent_changed(self, name, old, new):
182 if old is not None:
178 if old is not None:
183 old._remove_child(self)
179 old._remove_child(self)
184 if new is not None:
180 if new is not None:
185 new._add_child(self)
181 new._add_child(self)
186
182
187 if new is None:
183 if new is None:
188 self.root = self
184 self.root = self
189 else:
185 else:
190 self.root = new.root
186 self.root = new.root
191
187
192 def _root_changed(self, name, old, new):
188 def _root_changed(self, name, old, new):
193 if self.parent is None:
189 if self.parent is None:
194 if not (new is self):
190 if not (new is self):
195 raise ComponentError("Root not self, but parent is None.")
191 raise ComponentError("Root not self, but parent is None.")
196 else:
192 else:
197 if not self.parent.root is new:
193 if not self.parent.root is new:
198 raise ComponentError("Error in setting the root attribute: "
194 raise ComponentError("Error in setting the root attribute: "
199 "root != parent.root")
195 "root != parent.root")
200
196
201 def _config_changed(self, name, old, new):
197 def _config_changed(self, name, old, new):
198 """Update all the class traits having a config_key with the config.
199
200 For any class traitlet with a ``config_key`` metadata attribute, we
201 update the traitlet with the value of the corresponding config entry.
202
203 In the future, we might want to do a pop here so stale config info
204 is not passed onto children.
205 """
202 # Get all traitlets with a config_key metadata entry
206 # Get all traitlets with a config_key metadata entry
203 traitlets = self.traitlets('config_key')
207 traitlets = self.traitlets('config_key')
204 for k, v in traitlets.items():
208 for k, v in traitlets.items():
205 try:
209 try:
206 config_value = new[v.get_metadata('config_key')]
210 config_value = new[v.get_metadata('config_key')]
207 except KeyError:
211 except KeyError:
208 pass
212 pass
209 else:
213 else:
210 setattr(self, k, config_value)
214 setattr(self, k, config_value)
211
215
212 @property
216 @property
213 def children(self):
217 def children(self):
214 """A list of all my child components."""
218 """A list of all my child components."""
215 return self._children
219 return self._children
216
220
217 def _remove_child(self, child):
221 def _remove_child(self, child):
218 """A private method for removing children componenets."""
222 """A private method for removing children components."""
219 if child in self._children:
223 if child in self._children:
220 index = self._children.index(child)
224 index = self._children.index(child)
221 del self._children[index]
225 del self._children[index]
222
226
223 def _add_child(self, child):
227 def _add_child(self, child):
224 """A private method for adding children componenets."""
228 """A private method for adding children components."""
225 if child not in self._children:
229 if child not in self._children:
226 self._children.append(child)
230 self._children.append(child)
227
231
228 def __repr__(self):
232 def __repr__(self):
229 return "<Component('%s')>" % self.name
233 return "<Component('%s')>" % self.name
@@ -1,58 +1,59 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Oh my @#*%, where did ipapi go?
4 Oh my @#*%, where did ipapi go?
5
5
6 Originally, this module was designed to be a public api for IPython. It is
6 Originally, this module was designed to be a public api for IPython. It is
7 now deprecated and replaced by :class:`IPython.core.Interactive` shell.
7 now deprecated and replaced by :class:`IPython.core.Interactive` shell.
8 Almost all of the methods that were here are now there, but possibly renamed.
8 Almost all of the methods that were here are now there, but possibly renamed.
9
9
10 During our transition, we will keep this simple module with its :func:`get`
10 During our transition, we will keep this simple module with its :func:`get`
11 function. It too will eventually go away when the new component querying
11 function. It too will eventually go away when the new component querying
12 interface is fully used.
12 interface is fully used.
13
13
14 Authors:
14 Authors:
15
15
16 * Brian Granger
16 * Brian Granger
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2009 The IPython Development Team
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 from IPython.core.error import TryNext, UsageError
30 from IPython.core.error import TryNext, UsageError
31 from IPython.core.component import Component
31 from IPython.core.component import Component
32 from IPython.core.iplib import InteractiveShell
32
33
33 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
34 # Classes and functions
35 # Classes and functions
35 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
36
37
37 def get():
38 def get():
38 """Get the most recently created InteractiveShell instance."""
39 """Get the most recently created InteractiveShell instance."""
39 insts = Component.get_instances(name='__IP')
40 insts = InteractiveShell.get_instances()
40 most_recent = insts[0]
41 most_recent = insts[0]
41 for inst in insts[1:]:
42 for inst in insts[1:]:
42 if inst.created > most_recent.created:
43 if inst.created > most_recent.created:
43 most_recent = inst
44 most_recent = inst
44 return most_recent
45 return most_recent
45
46
46 def launch_new_instance():
47 def launch_new_instance():
47 """Create a run a full blown IPython instance"""
48 """Create a run a full blown IPython instance"""
48 from IPython.core.ipapp import IPythonApp
49 from IPython.core.ipapp import IPythonApp
49 app = IPythonApp()
50 app = IPythonApp()
50 app.start()
51 app.start()
51
52
52
53
53
54
54
55
55
56
56
57
57
58
58
59
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,194 +1,194 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Tests for IPython.core.component
4 Tests for IPython.core.component
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez (design help)
9 * Fernando Perez (design help)
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from unittest import TestCase
23 from unittest import TestCase
24
24
25 from IPython.core.component import Component, ComponentError
25 from IPython.core.component import Component, ComponentError
26 from IPython.utils.traitlets import (
26 from IPython.utils.traitlets import (
27 TraitletError, Int, Float, Str
27 TraitletError, Int, Float, Str
28 )
28 )
29 from IPython.utils.ipstruct import Struct
29 from IPython.utils.ipstruct import Struct
30
30
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Test cases
33 # Test cases
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36
36
37 class TestComponentMeta(TestCase):
37 class TestComponentMeta(TestCase):
38
38
39 def test_get_instances(self):
39 def test_get_instances(self):
40 class BaseComponent(Component):
40 class BaseComponent(Component):
41 pass
41 pass
42 c1 = BaseComponent(None)
42 c1 = BaseComponent(None)
43 c2 = BaseComponent(c1)
43 c2 = BaseComponent(c1)
44 self.assertEquals(BaseComponent.get_instances(),[c1,c2])
44 self.assertEquals(BaseComponent.get_instances(),[c1,c2])
45
45
46 def test_get_instances_subclass(self):
46 def test_get_instances_subclass(self):
47 class MyComponent(Component):
47 class MyComponent(Component):
48 pass
48 pass
49 class MyOtherComponent(MyComponent):
49 class MyOtherComponent(MyComponent):
50 pass
50 pass
51 c1 = MyComponent(None)
51 c1 = MyComponent(None)
52 c2 = MyOtherComponent(c1)
52 c2 = MyOtherComponent(c1)
53 c3 = MyOtherComponent(c2)
53 c3 = MyOtherComponent(c2)
54 self.assertEquals(MyComponent.get_instances(), [c1, c2, c3])
54 self.assertEquals(MyComponent.get_instances(), [c1, c2, c3])
55 self.assertEquals(MyComponent.get_instances(klass=MyOtherComponent), [c2, c3])
55 self.assertEquals(MyOtherComponent.get_instances(), [c2, c3])
56
56
57 def test_get_instances_root(self):
57 def test_get_instances_root(self):
58 class MyComponent(Component):
58 class MyComponent(Component):
59 pass
59 pass
60 class MyOtherComponent(MyComponent):
60 class MyOtherComponent(MyComponent):
61 pass
61 pass
62 c1 = MyComponent(None)
62 c1 = MyComponent(None)
63 c2 = MyOtherComponent(c1)
63 c2 = MyOtherComponent(c1)
64 c3 = MyOtherComponent(c2)
64 c3 = MyOtherComponent(c2)
65 c4 = MyComponent(None)
65 c4 = MyComponent(None)
66 c5 = MyComponent(c4)
66 c5 = MyComponent(c4)
67 self.assertEquals(MyComponent.get_instances(root=c1), [c1, c2, c3])
67 self.assertEquals(MyComponent.get_instances(root=c1), [c1, c2, c3])
68 self.assertEquals(MyComponent.get_instances(root=c4), [c4, c5])
68 self.assertEquals(MyComponent.get_instances(root=c4), [c4, c5])
69
69
70
70
71 class TestComponent(TestCase):
71 class TestComponent(TestCase):
72
72
73 def test_parent_child(self):
73 def test_parent_child(self):
74 c1 = Component(None)
74 c1 = Component(None)
75 c2 = Component(c1)
75 c2 = Component(c1)
76 c3 = Component(c1)
76 c3 = Component(c1)
77 c4 = Component(c3)
77 c4 = Component(c3)
78 self.assertEquals(c1.parent, None)
78 self.assertEquals(c1.parent, None)
79 self.assertEquals(c2.parent, c1)
79 self.assertEquals(c2.parent, c1)
80 self.assertEquals(c3.parent, c1)
80 self.assertEquals(c3.parent, c1)
81 self.assertEquals(c4.parent, c3)
81 self.assertEquals(c4.parent, c3)
82 self.assertEquals(c1.children, [c2, c3])
82 self.assertEquals(c1.children, [c2, c3])
83 self.assertEquals(c2.children, [])
83 self.assertEquals(c2.children, [])
84 self.assertEquals(c3.children, [c4])
84 self.assertEquals(c3.children, [c4])
85 self.assertEquals(c4.children, [])
85 self.assertEquals(c4.children, [])
86
86
87 def test_root(self):
87 def test_root(self):
88 c1 = Component(None)
88 c1 = Component(None)
89 c2 = Component(c1)
89 c2 = Component(c1)
90 c3 = Component(c1)
90 c3 = Component(c1)
91 c4 = Component(c3)
91 c4 = Component(c3)
92 self.assertEquals(c1.root, c1.root)
92 self.assertEquals(c1.root, c1.root)
93 self.assertEquals(c2.root, c1)
93 self.assertEquals(c2.root, c1)
94 self.assertEquals(c3.root, c1)
94 self.assertEquals(c3.root, c1)
95 self.assertEquals(c4.root, c1)
95 self.assertEquals(c4.root, c1)
96
96
97 def test_change_parent(self):
97 def test_change_parent(self):
98 c1 = Component(None)
98 c1 = Component(None)
99 c2 = Component(None)
99 c2 = Component(None)
100 c3 = Component(c1)
100 c3 = Component(c1)
101 self.assertEquals(c3.root, c1)
101 self.assertEquals(c3.root, c1)
102 self.assertEquals(c3.parent, c1)
102 self.assertEquals(c3.parent, c1)
103 self.assertEquals(c1.children,[c3])
103 self.assertEquals(c1.children,[c3])
104 c3.parent = c2
104 c3.parent = c2
105 self.assertEquals(c3.root, c2)
105 self.assertEquals(c3.root, c2)
106 self.assertEquals(c3.parent, c2)
106 self.assertEquals(c3.parent, c2)
107 self.assertEquals(c2.children,[c3])
107 self.assertEquals(c2.children,[c3])
108 self.assertEquals(c1.children,[])
108 self.assertEquals(c1.children,[])
109
109
110 def test_subclass_parent(self):
110 def test_subclass_parent(self):
111 c1 = Component(None)
111 c1 = Component(None)
112 self.assertRaises(TraitletError, setattr, c1, 'parent', 10)
112 self.assertRaises(TraitletError, setattr, c1, 'parent', 10)
113
113
114 class MyComponent(Component):
114 class MyComponent(Component):
115 pass
115 pass
116 c1 = Component(None)
116 c1 = Component(None)
117 c2 = MyComponent(c1)
117 c2 = MyComponent(c1)
118 self.assertEquals(MyComponent.parent.this_class, Component)
118 self.assertEquals(MyComponent.parent.this_class, Component)
119 self.assertEquals(c2.parent, c1)
119 self.assertEquals(c2.parent, c1)
120
120
121 def test_bad_root(self):
121 def test_bad_root(self):
122 c1 = Component(None)
122 c1 = Component(None)
123 c2 = Component(None)
123 c2 = Component(None)
124 c3 = Component(None)
124 c3 = Component(None)
125 self.assertRaises(ComponentError, setattr, c1, 'root', c2)
125 self.assertRaises(ComponentError, setattr, c1, 'root', c2)
126 c1.parent = c2
126 c1.parent = c2
127 self.assertEquals(c1.root, c2)
127 self.assertEquals(c1.root, c2)
128 self.assertRaises(ComponentError, setattr, c1, 'root', c3)
128 self.assertRaises(ComponentError, setattr, c1, 'root', c3)
129
129
130
130
131 class TestComponentConfig(TestCase):
131 class TestComponentConfig(TestCase):
132
132
133 def test_default(self):
133 def test_default(self):
134 c1 = Component(None)
134 c1 = Component(None)
135 c2 = Component(c1)
135 c2 = Component(c1)
136 c3 = Component(c2)
136 c3 = Component(c2)
137 self.assertEquals(c1.config, c2.config)
137 self.assertEquals(c1.config, c2.config)
138 self.assertEquals(c2.config, c3.config)
138 self.assertEquals(c2.config, c3.config)
139
139
140 def test_custom(self):
140 def test_custom(self):
141 config = Struct()
141 config = Struct()
142 config.FOO = 'foo'
142 config.FOO = 'foo'
143 config.BAR = 'bar'
143 config.BAR = 'bar'
144 c1 = Component(None, config=config)
144 c1 = Component(None, config=config)
145 c2 = Component(c1)
145 c2 = Component(c1)
146 c3 = Component(c2)
146 c3 = Component(c2)
147 self.assertEquals(c1.config, config)
147 self.assertEquals(c1.config, config)
148 self.assertEquals(c2.config, config)
148 self.assertEquals(c2.config, config)
149 self.assertEquals(c3.config, config)
149 self.assertEquals(c3.config, config)
150 # Test that we always make copies
150 # Test that we always make copies
151 self.assert_(c1.config is not config)
151 self.assert_(c1.config is not config)
152 self.assert_(c2.config is not config)
152 self.assert_(c2.config is not config)
153 self.assert_(c3.config is not config)
153 self.assert_(c3.config is not config)
154 self.assert_(c1.config is not c2.config)
154 self.assert_(c1.config is not c2.config)
155 self.assert_(c2.config is not c3.config)
155 self.assert_(c2.config is not c3.config)
156
156
157 def test_inheritance(self):
157 def test_inheritance(self):
158 class MyComponent(Component):
158 class MyComponent(Component):
159 a = Int(1, config_key='A')
159 a = Int(1, config_key='A')
160 b = Float(1.0, config_key='B')
160 b = Float(1.0, config_key='B')
161 c = Str('no config')
161 c = Str('no config')
162 config = Struct()
162 config = Struct()
163 config.A = 2
163 config.A = 2
164 config.B = 2.0
164 config.B = 2.0
165 c1 = MyComponent(None, config=config)
165 c1 = MyComponent(None, config=config)
166 c2 = MyComponent(c1)
166 c2 = MyComponent(c1)
167 self.assertEquals(c1.a, config.A)
167 self.assertEquals(c1.a, config.A)
168 self.assertEquals(c1.b, config.B)
168 self.assertEquals(c1.b, config.B)
169 self.assertEquals(c2.a, config.A)
169 self.assertEquals(c2.a, config.A)
170 self.assertEquals(c2.b, config.B)
170 self.assertEquals(c2.b, config.B)
171 c4 = MyComponent(c2, config=Struct())
171 c4 = MyComponent(c2, config=Struct())
172 self.assertEquals(c4.a, 1)
172 self.assertEquals(c4.a, 1)
173 self.assertEquals(c4.b, 1.0)
173 self.assertEquals(c4.b, 1.0)
174
174
175 class TestComponentName(TestCase):
175 class TestComponentName(TestCase):
176
176
177 def test_default(self):
177 def test_default(self):
178 class MyComponent(Component):
178 class MyComponent(Component):
179 pass
179 pass
180 c1 = Component(None)
180 c1 = Component(None)
181 c2 = MyComponent(None)
181 c2 = MyComponent(None)
182 c3 = Component(c2)
182 c3 = Component(c2)
183 self.assertNotEquals(c1.name, c2.name)
183 self.assertNotEquals(c1.name, c2.name)
184 self.assertNotEquals(c1.name, c3.name)
184 self.assertNotEquals(c1.name, c3.name)
185
185
186 def test_manual(self):
186 def test_manual(self):
187 class MyComponent(Component):
187 class MyComponent(Component):
188 pass
188 pass
189 c1 = Component(None, name='foo')
189 c1 = Component(None, name='foo')
190 c2 = MyComponent(None, name='bar')
190 c2 = MyComponent(None, name='bar')
191 c3 = Component(c2, name='bah')
191 c3 = Component(c2, name='bah')
192 self.assertEquals(c1.name, 'foo')
192 self.assertEquals(c1.name, 'foo')
193 self.assertEquals(c2.name, 'bar')
193 self.assertEquals(c2.name, 'bar')
194 self.assertEquals(c3.name, 'bah')
194 self.assertEquals(c3.name, 'bah')
@@ -1,28 +1,31 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Extra capabilities for IPython
4 Extra capabilities for IPython
5 """
5 """
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 from IPython.lib.inputhook import (
18 from IPython.lib.inputhook import (
19 enable_wx, disable_wx,
19 enable_wx, disable_wx,
20 enable_gtk, disable_gtk,
20 enable_gtk, disable_gtk,
21 enable_qt4, disable_qt4,
21 enable_qt4, disable_qt4,
22 enable_tk, disable_tk,
22 enable_tk, disable_tk,
23 set_inputhook, clear_inputhook
23 set_inputhook, clear_inputhook,
24 current_gui, spin,
25 appstart_qt4, appstart_wx,
26 appstart_gtk, appstart_tk
24 )
27 )
25
28
26 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
27 # Code
30 # Code
28 #----------------------------------------------------------------------------- No newline at end of file
31 #-----------------------------------------------------------------------------
@@ -1,226 +1,525 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Inputhook management for GUI event loop integration.
4 Inputhook management for GUI event loop integration.
5 """
5 """
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import ctypes
18 import ctypes
19 import sys
19 import sys
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Code
22 # Constants
23 #-----------------------------------------------------------------------------
24
25 # Constants for identifying the GUI toolkits.
26 GUI_WX = 'wx'
27 GUI_QT4 = 'qt4'
28 GUI_GTK = 'gtk'
29 GUI_TK = 'tk'
30
31 #-----------------------------------------------------------------------------
32 # Utility classes
33 #-----------------------------------------------------------------------------
34
35
36 class _DummyMainloop(object):
37 """A special manager to hijack GUI mainloops that is mostly a no-op.
38
39 We are not using this class currently as it breaks GUI code that calls
40 a mainloop function after the app has started to process pending events.
41 """
42 def __init__(self, ml, ihm, gui_type):
43 self.ml = ml
44 self.ihm = ihm
45 self.gui_type = gui_type
46
47 def __call__(self, *args, **kw):
48 if self.ihm.current_gui() == self.gui_type:
49 pass
50 else:
51 self.ml(*args, **kw)
52
53
54 #-----------------------------------------------------------------------------
55 # Appstart and spin functions
56 #-----------------------------------------------------------------------------
57
58
59 def appstart_qt4(app):
60 """Start the qt4 event loop in a way that plays with IPython.
61
62 When a qt4 app is run interactively in IPython, the event loop should
63 not be started. This function checks to see if IPython's qt4 integration
64 is activated and if so, it passes. If not, it will call the :meth:`exec_`
65 method of the main qt4 app.
66
67 This function should be used by users who want their qt4 scripts to work
68 both at the command line and in IPython. These users should put the
69 following logic at the bottom on their script, after they create a
70 :class:`QApplication` instance (called ``app`` here)::
71
72 try:
73 from IPython.lib.inputhook import appstart_qt4
74 appstart_qt4(app)
75 except ImportError:
76 app.exec_()
77 """
78 from PyQt4 import QtCore, QtGui
79
80 assert isinstance(app, QtCore.QCoreApplication)
81 if app is not None:
82 if current_gui() == GUI_QT4:
83 pass
84 else:
85 app.exec_()
86
87
88 def appstart_wx(app):
89 """Start the wx event loop in a way that plays with IPython.
90
91 When a wx app is run interactively in IPython, the event loop should
92 not be started. This function checks to see if IPython's wx integration
93 is activated and if so, it passes. If not, it will call the
94 :meth:`MainLoop` method of the main qt4 app.
95
96 This function should be used by users who want their wx scripts to work
97 both at the command line and in IPython. These users should put the
98 following logic at the bottom on their script, after they create a
99 :class:`App` instance (called ``app`` here)::
100
101 try:
102 from IPython.lib.inputhook import appstart_wx
103 appstart_wx(app)
104 except ImportError:
105 app.MainLoop()
106 """
107 import wx
108
109 assert isinstance(app, wx.App)
110 if app is not None:
111 if current_gui() == GUI_WX:
112 pass
113 else:
114 app.MainLoop()
115
116
117 def appstart_tk(app):
118 """Start the tk event loop in a way that plays with IPython.
119
120 When a tk app is run interactively in IPython, the event loop should
121 not be started. This function checks to see if IPython's tk integration
122 is activated and if so, it passes. If not, it will call the
123 :meth:`mainloop` method of the tk object passed to this method.
124
125 This function should be used by users who want their tk scripts to work
126 both at the command line and in IPython. These users should put the
127 following logic at the bottom on their script, after they create a
128 :class:`Tk` instance (called ``app`` here)::
129
130 try:
131 from IPython.lib.inputhook import appstart_tk
132 appstart_tk(app)
133 except ImportError:
134 app.mainloop()
135 """
136 if app is not None:
137 if current_gui() == GUI_TK:
138 pass
139 else:
140 app.mainloop()
141
142 def appstart_gtk():
143 """Start the gtk event loop in a way that plays with IPython.
144
145 When a gtk app is run interactively in IPython, the event loop should
146 not be started. This function checks to see if IPython's gtk integration
147 is activated and if so, it passes. If not, it will call
148 :func:`gtk.main`. Unlike the other appstart implementations, this does
149 not take an ``app`` argument.
150
151 This function should be used by users who want their gtk scripts to work
152 both at the command line and in IPython. These users should put the
153 following logic at the bottom on their script::
154
155 try:
156 from IPython.lib.inputhook import appstart_gtk
157 appstart_gtk()
158 except ImportError:
159 gtk.main()
160 """
161 import gtk
162 if current_gui() == GUI_GTK:
163 pass
164 else:
165 gtk.main()
166
167 #-----------------------------------------------------------------------------
168 # Main InputHookManager class
23 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
24
170
25
171
26 class InputHookManager(object):
172 class InputHookManager(object):
27 """Manage PyOS_InputHook for different GUI toolkits.
173 """Manage PyOS_InputHook for different GUI toolkits.
28
174
29 This class installs various hooks under ``PyOSInputHook`` to handle
175 This class installs various hooks under ``PyOSInputHook`` to handle
30 GUI event loop integration.
176 GUI event loop integration.
31 """
177 """
32
178
33 def __init__(self):
179 def __init__(self):
34 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
180 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
181 self._apps = {}
182 self._spinner_dict = {
183 GUI_QT4 : self._spin_qt4,
184 GUI_WX : self._spin_wx,
185 GUI_GTK : self._spin_gtk,
186 GUI_TK : self._spin_tk}
35 self._reset()
187 self._reset()
36
188
37 def _reset(self):
189 def _reset(self):
38 self._callback_pyfunctype = None
190 self._callback_pyfunctype = None
39 self._callback = None
191 self._callback = None
40 self._installed = False
192 self._installed = False
41 self._current_gui = None
193 self._current_gui = None
42
194
43 def get_pyos_inputhook(self):
195 def _hijack_wx(self):
44 """Return the current PyOS_InputHook as a ctypes.c_void_p.
196 """Hijack the wx mainloop so a user calling it won't cause badness.
197
198 We are not currently using this as it breaks GUI code that calls a
199 mainloop at anytime but startup.
200 """
201 import wx
202 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
203 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
204 else: raise AttributeError('Could not find wx core module')
205 orig_mainloop = core.PyApp_MainLoop
206 core.PyApp_MainLoop = _DummyMainloop
207 return orig_mainloop
208
209 def _hijack_qt4(self):
210 """Hijack the qt4 mainloop so a user calling it won't cause badness.
211
212 We are not currently using this as it breaks GUI code that calls a
213 mainloop at anytime but startup.
214 """
215 from PyQt4 import QtGui, QtCore
216 orig_mainloop = QtGui.qApp.exec_
217 dumb_ml = _DummyMainloop(orig_mainloop, self, GUI_QT4)
218 QtGui.qApp.exec_ = dumb_ml
219 QtGui.QApplication.exec_ = dumb_ml
220 QtCore.QCoreApplication.exec_ = dumb_ml
221 return orig_mainloop
222
223 def _hijack_gtk(self):
224 """Hijack the gtk mainloop so a user calling it won't cause badness.
225
226 We are not currently using this as it breaks GUI code that calls a
227 mainloop at anytime but startup.
228 """
229 import gtk
230 orig_mainloop = gtk.main
231 dumb_ml = _DummyMainloop(orig_mainloop, self, GUI_GTK)
232 gtk.mainloop = dumb_ml
233 gtk.main = dumb_ml
234 return orig_mainloop
235
236 def _hijack_tk(self):
237 """Hijack the tk mainloop so a user calling it won't cause badness.
238
239 We are not currently using this as it breaks GUI code that calls a
240 mainloop at anytime but startup.
241 """
242 import Tkinter
243 orig_mainloop = gtk.main
244 dumb_ml = _DummyMainloop(orig_mainloop, self, GUI_TK)
245 Tkinter.Misc.mainloop = dumb_ml
246 Tkinter.mainloop = dumb_ml
247
248 def _spin_qt4(self):
249 """Process all pending events in the qt4 event loop.
250
251 This is for internal IPython use only and user code should not call this.
252 Instead, they should issue the raw GUI calls themselves.
253 """
254 from PyQt4 import QtCore, QtGui
255
256 app = QtCore.QCoreApplication.instance()
257 if app is not None:
258 QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents)
259
260 def _spin_wx(self):
261 """Process all pending events in the wx event loop.
262
263 This is for internal IPython use only and user code should not call this.
264 Instead, they should issue the raw GUI calls themselves.
265 """
266 import wx
267 app = wx.GetApp()
268 if app is not None and wx.Thread_IsMain():
269 evtloop = wx.EventLoop()
270 ea = wx.EventLoopActivator(evtloop)
271 while evtloop.Pending():
272 evtloop.Dispatch()
273 app.ProcessIdle()
274 del ea
275
276 def _spin_gtk(self):
277 """Process all pending events in the gtk event loop.
278
279 This is for internal IPython use only and user code should not call this.
280 Instead, they should issue the raw GUI calls themselves.
281 """
282 import gtk
283 gtk.gdk.threads_enter()
284 while gtk.events_pending():
285 gtk.main_iteration(False)
286 gtk.gdk.flush()
287 gtk.gdk.threads_leave()
288
289 def _spin_tk(self):
290 """Process all pending events in the tk event loop.
291
292 This is for internal IPython use only and user code should not call this.
293 Instead, they should issue the raw GUI calls themselves.
45 """
294 """
295 app = self._apps.get(GUI_TK)
296 if app is not None:
297 app.update()
298
299 def spin(self):
300 """Process pending events in the current gui.
301
302 This method is just provided for IPython to use internally if needed
303 for things like testing. Third party projects should not call this
304 method, but instead should call the underlying GUI toolkit methods
305 that we are calling.
306 """
307 spinner = self._spinner_dict.get(self._current_gui, lambda: None)
308 spinner()
309
310 def get_pyos_inputhook(self):
311 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
46 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
312 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
47
313
48 def get_pyos_inputhook_as_func(self):
314 def get_pyos_inputhook_as_func(self):
49 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE.
315 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
50 """
51 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
316 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
52
317
53 def set_inputhook(self, callback):
318 def set_inputhook(self, callback):
54 """Set PyOS_InputHook to callback and return the previous one.
319 """Set PyOS_InputHook to callback and return the previous one."""
55 """
56 self._callback = callback
320 self._callback = callback
57 self._callback_pyfunctype = self.PYFUNC(callback)
321 self._callback_pyfunctype = self.PYFUNC(callback)
58 pyos_inputhook_ptr = self.get_pyos_inputhook()
322 pyos_inputhook_ptr = self.get_pyos_inputhook()
59 original = self.get_pyos_inputhook_as_func()
323 original = self.get_pyos_inputhook_as_func()
60 pyos_inputhook_ptr.value = \
324 pyos_inputhook_ptr.value = \
61 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
325 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
62 self._installed = True
326 self._installed = True
63 return original
327 return original
64
328
65 def clear_inputhook(self):
329 def clear_inputhook(self):
66 """Set PyOS_InputHook to NULL and return the previous one.
330 """Set PyOS_InputHook to NULL and return the previous one."""
67 """
68 pyos_inputhook_ptr = self.get_pyos_inputhook()
331 pyos_inputhook_ptr = self.get_pyos_inputhook()
69 original = self.get_pyos_inputhook_as_func()
332 original = self.get_pyos_inputhook_as_func()
70 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
333 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
71 self._reset()
334 self._reset()
72 return original
335 return original
73
336
337 def clear_app_refs(self, gui=None):
338 """Clear IPython's internal reference to an application instance.
339
340 Whenever we create an app for a user on qt4 or wx, we hold a
341 reference to the app. This is needed because in some cases bad things
342 can happen if a user doesn't hold a reference themselves. This
343 method is provided to clear the references we are holding.
344
345 Parameters
346 ----------
347 gui : None or str
348 If None, clear all app references. If ('wx', 'qt4') clear
349 the app for that toolkit. References are not held for gtk or tk
350 as those toolkits don't have the notion of an app.
351 """
352 if gui is None:
353 self._apps = {}
354 elif self._apps.has_key(gui):
355 del self._apps[gui]
356
74 def enable_wx(self, app=False):
357 def enable_wx(self, app=False):
75 """Enable event loop integration with wxPython.
358 """Enable event loop integration with wxPython.
76
359
77 Parameters
360 Parameters
78 ----------
361 ----------
79 app : bool
362 app : bool
80 Create a running application object or not.
363 Create a running application object or not.
81
364
82 Notes
365 Notes
83 -----
366 -----
84 This methods sets the PyOS_InputHook for wxPython, which allows
367 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
85 the wxPython to integrate with terminal based applications like
368 the wxPython to integrate with terminal based applications like
86 IPython.
369 IPython.
87
370
88 Once this has been called, you can use wx interactively by doing::
371 If ``app`` is True, we create an :class:`wx.App` as follows::
89
372
90 >>> import wx
373 import wx
91 >>> app = wx.App(redirect=False, clearSigInt=False)
374 app = wx.App(redirect=False, clearSigInt=False)
92
375
93 Both options this constructor are important for things to work
376 Both options this constructor are important for things to work
94 properly in an interactive context.
377 properly in an interactive context.
95
378
96 But, *don't start the event loop*. That is handled automatically by
379 But, we first check to see if an application has already been
97 PyOS_InputHook.
380 created. If so, we simply return that instance.
98 """
381 """
99 from IPython.lib.inputhookwx import inputhook_wx
382 from IPython.lib.inputhookwx import inputhook_wx
100 self.set_inputhook(inputhook_wx)
383 self.set_inputhook(inputhook_wx)
101 self._current_gui = 'wx'
384 self._current_gui = GUI_WX
102 if app:
385 if app:
103 import wx
386 import wx
104 app = wx.App(redirect=False, clearSigInt=False)
387 app = wx.GetApp()
388 if app is None:
389 app = wx.App(redirect=False, clearSigInt=False)
390 self._apps[GUI_WX] = app
105 return app
391 return app
106
392
107 def disable_wx(self):
393 def disable_wx(self):
108 """Disable event loop integration with wxPython.
394 """Disable event loop integration with wxPython.
109
395
110 This merely sets PyOS_InputHook to NULL.
396 This merely sets PyOS_InputHook to NULL.
111 """
397 """
112 self.clear_inputhook()
398 self.clear_inputhook()
113
399
114 def enable_qt4(self, app=False):
400 def enable_qt4(self, app=False):
115 """Enable event loop integration with PyQt4.
401 """Enable event loop integration with PyQt4.
116
402
117 Parameters
403 Parameters
118 ----------
404 ----------
119 app : bool
405 app : bool
120 Create a running application object or not.
406 Create a running application object or not.
121
407
122 Notes
408 Notes
123 -----
409 -----
124 This methods sets the PyOS_InputHook for wxPython, which allows
410 This methods sets the PyOS_InputHook for PyQt4, which allows
125 the PyQt4 to integrate with terminal based applications like
411 the PyQt4 to integrate with terminal based applications like
126 IPython.
412 IPython.
127
413
128 Once this has been called, you can simply create a QApplication and
414 If ``app`` is True, we create an :class:`QApplication` as follows::
129 use it. But, *don't start the event loop*. That is handled
415
130 automatically by PyOS_InputHook.
416 from PyQt4 import QtCore
417 app = QtGui.QApplication(sys.argv)
418
419 But, we first check to see if an application has already been
420 created. If so, we simply return that instance.
131 """
421 """
132 from PyQt4 import QtCore
422 from PyQt4 import QtCore
133 # PyQt4 has had this since 4.3.1. In version 4.2, PyOS_InputHook
423 # PyQt4 has had this since 4.3.1. In version 4.2, PyOS_InputHook
134 # was set when QtCore was imported, but if it ever got removed,
424 # was set when QtCore was imported, but if it ever got removed,
135 # you couldn't reset it. For earlier versions we can
425 # you couldn't reset it. For earlier versions we can
136 # probably implement a ctypes version.
426 # probably implement a ctypes version.
137 try:
427 try:
138 QtCore.pyqtRestoreInputHook()
428 QtCore.pyqtRestoreInputHook()
139 except AttributeError:
429 except AttributeError:
140 pass
430 pass
141 self._current_gui = 'qt4'
431 self._current_gui = GUI_QT4
142 if app:
432 if app:
143 from PyQt4 import QtGui
433 from PyQt4 import QtGui
144 app = QtGui.QApplication(sys.argv)
434 app = QtCore.QCoreApplication.instance()
435 if app is None:
436 app = QtGui.QApplication(sys.argv)
437 self._apps[GUI_QT4] = app
145 return app
438 return app
146
439
147 def disable_qt4(self):
440 def disable_qt4(self):
148 """Disable event loop integration with PyQt4.
441 """Disable event loop integration with PyQt4.
149
442
150 This merely sets PyOS_InputHook to NULL.
443 This merely sets PyOS_InputHook to NULL.
151 """
444 """
152 self.clear_inputhook()
445 self.clear_inputhook()
153
446
154 def enable_gtk(self, app=False):
447 def enable_gtk(self, app=False):
155 """Enable event loop integration with PyGTK.
448 """Enable event loop integration with PyGTK.
156
449
157 Parameters
450 Parameters
158 ----------
451 ----------
159 app : bool
452 app : bool
160 Create a running application object or not.
453 Create a running application object or not. Because gtk does't
454 have an app class, this does nothing.
161
455
162 Notes
456 Notes
163 -----
457 -----
164 This methods sets the PyOS_InputHook for PyGTK, which allows
458 This methods sets the PyOS_InputHook for PyGTK, which allows
165 the PyGTK to integrate with terminal based applications like
459 the PyGTK to integrate with terminal based applications like
166 IPython.
460 IPython.
167
168 Once this has been called, you can simple create PyGTK objects and
169 use them. But, *don't start the event loop*. That is handled
170 automatically by PyOS_InputHook.
171 """
461 """
172 import gtk
462 import gtk
173 try:
463 try:
174 gtk.set_interactive(True)
464 gtk.set_interactive(True)
175 self._current_gui = 'gtk'
465 self._current_gui = GUI_GTK
176 except AttributeError:
466 except AttributeError:
177 # For older versions of gtk, use our own ctypes version
467 # For older versions of gtk, use our own ctypes version
178 from IPython.lib.inputhookgtk import inputhook_gtk
468 from IPython.lib.inputhookgtk import inputhook_gtk
179 add_inputhook(inputhook_gtk)
469 self.set_inputhook(inputhook_gtk)
470 self._current_gui = GUI_GTK
180
471
181 def disable_gtk(self):
472 def disable_gtk(self):
182 """Disable event loop integration with PyGTK.
473 """Disable event loop integration with PyGTK.
183
474
184 This merely sets PyOS_InputHook to NULL.
475 This merely sets PyOS_InputHook to NULL.
185 """
476 """
186 self.clear_inputhook()
477 self.clear_inputhook()
187
478
188 def enable_tk(self, app=False):
479 def enable_tk(self, app=False):
189 """Enable event loop integration with Tk.
480 """Enable event loop integration with Tk.
190
481
191 Parameters
482 Parameters
192 ----------
483 ----------
193 app : bool
484 app : bool
194 Create a running application object or not.
485 Create a running application object or not.
195
486
196 Notes
487 Notes
197 -----
488 -----
198 Currently this is a no-op as creating a :class:`Tkinter.Tk` object
489 Currently this is a no-op as creating a :class:`Tkinter.Tk` object
199 sets ``PyOS_InputHook``.
490 sets ``PyOS_InputHook``.
200 """
491 """
201 self._current_gui = 'tk'
492 self._current_gui = GUI_TK
493 if app:
494 import Tkinter
495 app = Tkinter.Tk()
496 app.withdraw()
497 self._apps[GUI_TK] = app
498 return app
202
499
203 def disable_tk(self):
500 def disable_tk(self):
204 """Disable event loop integration with Tkinter.
501 """Disable event loop integration with Tkinter.
205
502
206 This merely sets PyOS_InputHook to NULL.
503 This merely sets PyOS_InputHook to NULL.
207 """
504 """
208 self.clear_inputhook()
505 self.clear_inputhook()
209
506
210 def current_gui(self):
507 def current_gui(self):
211 """Return a string indicating the currently active GUI or None."""
508 """Return a string indicating the currently active GUI or None."""
212 return self._current_gui
509 return self._current_gui
213
510
214 inputhook_manager = InputHookManager()
511 inputhook_manager = InputHookManager()
215
512
216 enable_wx = inputhook_manager.enable_wx
513 enable_wx = inputhook_manager.enable_wx
217 disable_wx = inputhook_manager.disable_wx
514 disable_wx = inputhook_manager.disable_wx
218 enable_qt4 = inputhook_manager.enable_qt4
515 enable_qt4 = inputhook_manager.enable_qt4
219 disable_qt4 = inputhook_manager.disable_qt4
516 disable_qt4 = inputhook_manager.disable_qt4
220 enable_gtk = inputhook_manager.enable_gtk
517 enable_gtk = inputhook_manager.enable_gtk
221 disable_gtk = inputhook_manager.disable_gtk
518 disable_gtk = inputhook_manager.disable_gtk
222 enable_tk = inputhook_manager.enable_tk
519 enable_tk = inputhook_manager.enable_tk
223 disable_tk = inputhook_manager.disable_tk
520 disable_tk = inputhook_manager.disable_tk
224 clear_inputhook = inputhook_manager.clear_inputhook
521 clear_inputhook = inputhook_manager.clear_inputhook
225 set_inputhook = inputhook_manager.set_inputhook
522 set_inputhook = inputhook_manager.set_inputhook
226 current_gui = inputhook_manager.current_gui No newline at end of file
523 current_gui = inputhook_manager.current_gui
524 clear_app_refs = inputhook_manager.clear_app_refs
525 spin = inputhook_manager.spin
@@ -1,153 +1,162 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 """
4 """
5 Enable wxPython to be used interacive by setting PyOS_InputHook.
5 Enable wxPython to be used interacive by setting PyOS_InputHook.
6
6
7 Authors: Robin Dunn, Brian Granger, Ondrej Certik
7 Authors: Robin Dunn, Brian Granger, Ondrej Certik
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2008-2009 The IPython Development Team
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 import os
21 import os
22 import signal
22 import sys
23 import sys
23 import time
24 import time
24 from timeit import default_timer as clock
25 from timeit import default_timer as clock
25 import wx
26 import wx
26
27
27 if os.name == 'posix':
28 if os.name == 'posix':
28 import select
29 import select
29 elif sys.platform == 'win32':
30 elif sys.platform == 'win32':
30 import msvcrt
31 import msvcrt
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
33 # Code
34 # Code
34 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
35
36
36 def stdin_ready():
37 def stdin_ready():
37 if os.name == 'posix':
38 if os.name == 'posix':
38 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
39 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
39 if infds:
40 if infds:
40 return True
41 return True
41 else:
42 else:
42 return False
43 return False
43 elif sys.platform == 'win32':
44 elif sys.platform == 'win32':
44 return msvcrt.kbhit()
45 return msvcrt.kbhit()
45
46
46
47
47 def inputhook_wx1():
48 def inputhook_wx1():
48 """Run the wx event loop by processing pending events only.
49 """Run the wx event loop by processing pending events only.
49
50
50 This approach seems to work, but its performance is not great as it
51 This approach seems to work, but its performance is not great as it
51 relies on having PyOS_InputHook called regularly.
52 relies on having PyOS_InputHook called regularly.
52 """
53 """
53 app = wx.GetApp()
54 app = wx.GetApp()
54 if app is not None:
55 if app is not None:
55 assert wx.Thread_IsMain()
56 assert wx.Thread_IsMain()
56
57
57 # Make a temporary event loop and process system events until
58 # Make a temporary event loop and process system events until
58 # there are no more waiting, then allow idle events (which
59 # there are no more waiting, then allow idle events (which
59 # will also deal with pending or posted wx events.)
60 # will also deal with pending or posted wx events.)
60 evtloop = wx.EventLoop()
61 evtloop = wx.EventLoop()
61 ea = wx.EventLoopActivator(evtloop)
62 ea = wx.EventLoopActivator(evtloop)
62 while evtloop.Pending():
63 while evtloop.Pending():
63 evtloop.Dispatch()
64 evtloop.Dispatch()
64 app.ProcessIdle()
65 app.ProcessIdle()
65 del ea
66 del ea
66 return 0
67 return 0
67
68
68 class EventLoopTimer(wx.Timer):
69 class EventLoopTimer(wx.Timer):
69
70
70 def __init__(self, func):
71 def __init__(self, func):
71 self.func = func
72 self.func = func
72 wx.Timer.__init__(self)
73 wx.Timer.__init__(self)
73
74
74 def Notify(self):
75 def Notify(self):
75 self.func()
76 self.func()
76
77
77 class EventLoopRunner(object):
78 class EventLoopRunner(object):
78
79
79 def Run(self, time):
80 def Run(self, time):
80 self.evtloop = wx.EventLoop()
81 self.evtloop = wx.EventLoop()
81 self.timer = EventLoopTimer(self.check_stdin)
82 self.timer = EventLoopTimer(self.check_stdin)
82 self.timer.Start(time)
83 self.timer.Start(time)
83 self.evtloop.Run()
84 self.evtloop.Run()
84
85
85 def check_stdin(self):
86 def check_stdin(self):
86 if stdin_ready():
87 if stdin_ready():
87 self.timer.Stop()
88 self.timer.Stop()
88 self.evtloop.Exit()
89 self.evtloop.Exit()
89
90
90 def inputhook_wx2():
91 def inputhook_wx2():
91 """Run the wx event loop, polling for stdin.
92 """Run the wx event loop, polling for stdin.
92
93
93 This version runs the wx eventloop for an undetermined amount of time,
94 This version runs the wx eventloop for an undetermined amount of time,
94 during which it periodically checks to see if anything is ready on
95 during which it periodically checks to see if anything is ready on
95 stdin. If anything is ready on stdin, the event loop exits.
96 stdin. If anything is ready on stdin, the event loop exits.
96
97
97 The argument to elr.Run controls how often the event loop looks at stdin.
98 The argument to elr.Run controls how often the event loop looks at stdin.
98 This determines the responsiveness at the keyboard. A setting of 1000
99 This determines the responsiveness at the keyboard. A setting of 1000
99 enables a user to type at most 1 char per second. I have found that a
100 enables a user to type at most 1 char per second. I have found that a
100 setting of 10 gives good keyboard response. We can shorten it further,
101 setting of 10 gives good keyboard response. We can shorten it further,
101 but eventually performance would suffer from calling select/kbhit too
102 but eventually performance would suffer from calling select/kbhit too
102 often.
103 often.
103 """
104 """
104 app = wx.GetApp()
105 app = wx.GetApp()
105 if app is not None:
106 if app is not None:
106 assert wx.Thread_IsMain()
107 assert wx.Thread_IsMain()
107 elr = EventLoopRunner()
108 elr = EventLoopRunner()
108 # As this time is made shorter, keyboard response improves, but idle
109 # As this time is made shorter, keyboard response improves, but idle
109 # CPU load goes up. 10 ms seems like a good compromise.
110 # CPU load goes up. 10 ms seems like a good compromise.
110 elr.Run(time=10) # CHANGE time here to control polling interval
111 elr.Run(time=10) # CHANGE time here to control polling interval
111 return 0
112 return 0
112
113
113 def inputhook_wx3():
114 def inputhook_wx3():
114 """Run the wx event loop by processing pending events only.
115 """Run the wx event loop by processing pending events only.
115
116
116 This is like inputhook_wx1, but it keeps processing pending events
117 This is like inputhook_wx1, but it keeps processing pending events
117 until stdin is ready. After processing all pending events, a call to
118 until stdin is ready. After processing all pending events, a call to
118 time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
119 time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
119 This sleep time should be tuned though for best performance.
120 This sleep time should be tuned though for best performance.
120 """
121 """
121 app = wx.GetApp()
122 app = wx.GetApp()
122 if app is not None:
123 if app is not None:
123 assert wx.Thread_IsMain()
124 assert wx.Thread_IsMain()
124
125
126 # The import of wx on Linux sets the handler for signal.SIGINT
127 # to 0. This is a bug in wx or gtk. We fix by just setting it
128 # back to the Python default.
129 if not callable(signal.getsignal(signal.SIGINT)):
130 signal.signal(signal.SIGINT, signal.default_int_handler)
131
125 evtloop = wx.EventLoop()
132 evtloop = wx.EventLoop()
126 ea = wx.EventLoopActivator(evtloop)
133 ea = wx.EventLoopActivator(evtloop)
127 t = clock()
134 t = clock()
128 while not stdin_ready():
135 while not stdin_ready():
129 while evtloop.Pending():
136 while evtloop.Pending():
130 t = clock()
137 t = clock()
131 evtloop.Dispatch()
138 evtloop.Dispatch()
132 app.ProcessIdle()
139 app.ProcessIdle()
133 # We need to sleep at this point to keep the idle CPU load
140 # We need to sleep at this point to keep the idle CPU load
134 # low. However, if sleep to long, GUI response is poor. As
141 # low. However, if sleep to long, GUI response is poor. As
135 # a compromise, we watch how often GUI events are being processed
142 # a compromise, we watch how often GUI events are being processed
136 # and switch between a short and long sleep time. Here are some
143 # and switch between a short and long sleep time. Here are some
137 # stats useful in helping to tune this.
144 # stats useful in helping to tune this.
138 # time CPU load
145 # time CPU load
139 # 0.001 13%
146 # 0.001 13%
140 # 0.005 3%
147 # 0.005 3%
141 # 0.01 1.5%
148 # 0.01 1.5%
142 # 0.05 0.5%
149 # 0.05 0.5%
150 if clock()-t > 1.0:
151 time.sleep(1.0)
143 if clock()-t > 0.1:
152 if clock()-t > 0.1:
144 # Few GUI events coming in, so we can sleep longer
153 # Few GUI events coming in, so we can sleep longer
145 time.sleep(0.05)
154 time.sleep(0.05)
146 else:
155 else:
147 # Many GUI events coming in, so sleep only very little
156 # Many GUI events coming in, so sleep only very little
148 time.sleep(0.001)
157 time.sleep(0.001)
149 del ea
158 del ea
150 return 0
159 return 0
151
160
152 # This is our default implementation
161 # This is our default implementation
153 inputhook_wx = inputhook_wx3 No newline at end of file
162 inputhook_wx = inputhook_wx3
@@ -1,1539 +1,1542 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 If invoked with no options, it executes all the files listed in sequence
14 If invoked with no options, it executes all the files listed in sequence
15 and drops you into the interpreter while still acknowledging any options
15 and drops you into the interpreter while still acknowledging any options
16 you may have set in your ipythonrc file. This behavior is different from
16 you may have set in your ipythonrc file. This behavior is different from
17 standard Python, which when called as python -i will only execute one
17 standard Python, which when called as python -i will only execute one
18 file and ignore your configuration setup.
18 file and ignore your configuration setup.
19
19
20 Please note that some of the configuration options are not available at
20 Please note that some of the configuration options are not available at
21 the command line, simply because they are not practical here. Look into
21 the command line, simply because they are not practical here. Look into
22 your ipythonrc configuration file for details on those. This file
22 your ipythonrc configuration file for details on those. This file
23 typically installed in the $HOME/.ipython directory. For Windows users,
23 typically installed in the $HOME/.ipython directory. For Windows users,
24 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
24 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
25 instances. In the rest of this text, we will refer to this directory as
25 instances. In the rest of this text, we will refer to this directory as
26 IPYTHONDIR.
26 IPYTHONDIR.
27
27
28
28
29
29
30 Special Threading Options
30 Special Threading Options
31 -------------------------
31 -------------------------
32
32
33 Previously IPython had command line options for controlling GUI event loop
33 Previously IPython had command line options for controlling GUI event loop
34 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
34 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
35 version 0.11, these have been deprecated. Please see the new ``%gui``
35 version 0.11, these have been deprecated. Please see the new ``%gui``
36 magic command or :ref:`this section <gui_support>` for details on the new
36 magic command or :ref:`this section <gui_support>` for details on the new
37 interface.
37 interface.
38
38
39 Regular Options
39 Regular Options
40 ---------------
40 ---------------
41
41
42 After the above threading options have been given, regular options can
42 After the above threading options have been given, regular options can
43 follow in any order. All options can be abbreviated to their shortest
43 follow in any order. All options can be abbreviated to their shortest
44 non-ambiguous form and are case-sensitive. One or two dashes can be
44 non-ambiguous form and are case-sensitive. One or two dashes can be
45 used. Some options have an alternate short form, indicated after a ``|``.
45 used. Some options have an alternate short form, indicated after a ``|``.
46
46
47 Most options can also be set from your ipythonrc configuration file. See
47 Most options can also be set from your ipythonrc configuration file. See
48 the provided example for more details on what the options do. Options
48 the provided example for more details on what the options do. Options
49 given at the command line override the values set in the ipythonrc file.
49 given at the command line override the values set in the ipythonrc file.
50
50
51 All options with a [no] prepended can be specified in negated form
51 All options with a [no] prepended can be specified in negated form
52 (-nooption instead of -option) to turn the feature off.
52 (-nooption instead of -option) to turn the feature off.
53
53
54 -help print a help message and exit.
54 -help print a help message and exit.
55
55
56 -pylab
56 -pylab
57 Deprecated. See :ref:`Matplotlib support <matplotlib_support>`
57 Deprecated. See :ref:`Matplotlib support <matplotlib_support>`
58 for more details.
58 for more details.
59
59
60 -autocall <val>
60 -autocall <val>
61 Make IPython automatically call any callable object even if you
61 Make IPython automatically call any callable object even if you
62 didn't type explicit parentheses. For example, 'str 43' becomes
62 didn't type explicit parentheses. For example, 'str 43' becomes
63 'str(43)' automatically. The value can be '0' to disable the feature,
63 'str(43)' automatically. The value can be '0' to disable the feature,
64 '1' for smart autocall, where it is not applied if there are no more
64 '1' for smart autocall, where it is not applied if there are no more
65 arguments on the line, and '2' for full autocall, where all callable
65 arguments on the line, and '2' for full autocall, where all callable
66 objects are automatically called (even if no arguments are
66 objects are automatically called (even if no arguments are
67 present). The default is '1'.
67 present). The default is '1'.
68
68
69 -[no]autoindent
69 -[no]autoindent
70 Turn automatic indentation on/off.
70 Turn automatic indentation on/off.
71
71
72 -[no]automagic
72 -[no]automagic
73 make magic commands automatic (without needing their first character
73 make magic commands automatic (without needing their first character
74 to be %). Type %magic at the IPython prompt for more information.
74 to be %). Type %magic at the IPython prompt for more information.
75
75
76 -[no]autoedit_syntax
76 -[no]autoedit_syntax
77 When a syntax error occurs after editing a file, automatically
77 When a syntax error occurs after editing a file, automatically
78 open the file to the trouble causing line for convenient
78 open the file to the trouble causing line for convenient
79 fixing.
79 fixing.
80
80
81 -[no]banner Print the initial information banner (default on).
81 -[no]banner Print the initial information banner (default on).
82
82
83 -c <command>
83 -c <command>
84 execute the given command string. This is similar to the -c
84 execute the given command string. This is similar to the -c
85 option in the normal Python interpreter.
85 option in the normal Python interpreter.
86
86
87 -cache_size, cs <n>
87 -cache_size, cs <n>
88 size of the output cache (maximum number of entries to hold in
88 size of the output cache (maximum number of entries to hold in
89 memory). The default is 1000, you can change it permanently in your
89 memory). The default is 1000, you can change it permanently in your
90 config file. Setting it to 0 completely disables the caching system,
90 config file. Setting it to 0 completely disables the caching system,
91 and the minimum value accepted is 20 (if you provide a value less than
91 and the minimum value accepted is 20 (if you provide a value less than
92 20, it is reset to 0 and a warning is issued) This limit is defined
92 20, it is reset to 0 and a warning is issued) This limit is defined
93 because otherwise you'll spend more time re-flushing a too small cache
93 because otherwise you'll spend more time re-flushing a too small cache
94 than working.
94 than working.
95
95
96 -classic, cl
96 -classic, cl
97 Gives IPython a similar feel to the classic Python
97 Gives IPython a similar feel to the classic Python
98 prompt.
98 prompt.
99
99
100 -colors <scheme>
100 -colors <scheme>
101 Color scheme for prompts and exception reporting. Currently
101 Color scheme for prompts and exception reporting. Currently
102 implemented: NoColor, Linux and LightBG.
102 implemented: NoColor, Linux and LightBG.
103
103
104 -[no]color_info
104 -[no]color_info
105 IPython can display information about objects via a set of functions,
105 IPython can display information about objects via a set of functions,
106 and optionally can use colors for this, syntax highlighting source
106 and optionally can use colors for this, syntax highlighting source
107 code and various other elements. However, because this information is
107 code and various other elements. However, because this information is
108 passed through a pager (like 'less') and many pagers get confused with
108 passed through a pager (like 'less') and many pagers get confused with
109 color codes, this option is off by default. You can test it and turn
109 color codes, this option is off by default. You can test it and turn
110 it on permanently in your ipythonrc file if it works for you. As a
110 it on permanently in your ipythonrc file if it works for you. As a
111 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
111 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
112 that in RedHat 7.2 doesn't.
112 that in RedHat 7.2 doesn't.
113
113
114 Test it and turn it on permanently if it works with your
114 Test it and turn it on permanently if it works with your
115 system. The magic function %color_info allows you to toggle this
115 system. The magic function %color_info allows you to toggle this
116 interactively for testing.
116 interactively for testing.
117
117
118 -[no]debug
118 -[no]debug
119 Show information about the loading process. Very useful to pin down
119 Show information about the loading process. Very useful to pin down
120 problems with your configuration files or to get details about
120 problems with your configuration files or to get details about
121 session restores.
121 session restores.
122
122
123 -[no]deep_reload:
123 -[no]deep_reload:
124 IPython can use the deep_reload module which reloads changes in
124 IPython can use the deep_reload module which reloads changes in
125 modules recursively (it replaces the reload() function, so you don't
125 modules recursively (it replaces the reload() function, so you don't
126 need to change anything to use it). deep_reload() forces a full
126 need to change anything to use it). deep_reload() forces a full
127 reload of modules whose code may have changed, which the default
127 reload of modules whose code may have changed, which the default
128 reload() function does not.
128 reload() function does not.
129
129
130 When deep_reload is off, IPython will use the normal reload(),
130 When deep_reload is off, IPython will use the normal reload(),
131 but deep_reload will still be available as dreload(). This
131 but deep_reload will still be available as dreload(). This
132 feature is off by default [which means that you have both
132 feature is off by default [which means that you have both
133 normal reload() and dreload()].
133 normal reload() and dreload()].
134
134
135 -editor <name>
135 -editor <name>
136 Which editor to use with the %edit command. By default,
136 Which editor to use with the %edit command. By default,
137 IPython will honor your EDITOR environment variable (if not
137 IPython will honor your EDITOR environment variable (if not
138 set, vi is the Unix default and notepad the Windows one).
138 set, vi is the Unix default and notepad the Windows one).
139 Since this editor is invoked on the fly by IPython and is
139 Since this editor is invoked on the fly by IPython and is
140 meant for editing small code snippets, you may want to use a
140 meant for editing small code snippets, you may want to use a
141 small, lightweight editor here (in case your default EDITOR is
141 small, lightweight editor here (in case your default EDITOR is
142 something like Emacs).
142 something like Emacs).
143
143
144 -ipythondir <name>
144 -ipythondir <name>
145 name of your IPython configuration directory IPYTHONDIR. This
145 name of your IPython configuration directory IPYTHONDIR. This
146 can also be specified through the environment variable
146 can also be specified through the environment variable
147 IPYTHONDIR.
147 IPYTHONDIR.
148
148
149 -log, l
149 -log, l
150 generate a log file of all input. The file is named
150 generate a log file of all input. The file is named
151 ipython_log.py in your current directory (which prevents logs
151 ipython_log.py in your current directory (which prevents logs
152 from multiple IPython sessions from trampling each other). You
152 from multiple IPython sessions from trampling each other). You
153 can use this to later restore a session by loading your
153 can use this to later restore a session by loading your
154 logfile as a file to be executed with option -logplay (see
154 logfile as a file to be executed with option -logplay (see
155 below).
155 below).
156
156
157 -logfile, lf <name> specify the name of your logfile.
157 -logfile, lf <name> specify the name of your logfile.
158
158
159 -logplay, lp <name>
159 -logplay, lp <name>
160
160
161 you can replay a previous log. For restoring a session as close as
161 you can replay a previous log. For restoring a session as close as
162 possible to the state you left it in, use this option (don't just run
162 possible to the state you left it in, use this option (don't just run
163 the logfile). With -logplay, IPython will try to reconstruct the
163 the logfile). With -logplay, IPython will try to reconstruct the
164 previous working environment in full, not just execute the commands in
164 previous working environment in full, not just execute the commands in
165 the logfile.
165 the logfile.
166
166
167 When a session is restored, logging is automatically turned on
167 When a session is restored, logging is automatically turned on
168 again with the name of the logfile it was invoked with (it is
168 again with the name of the logfile it was invoked with (it is
169 read from the log header). So once you've turned logging on for
169 read from the log header). So once you've turned logging on for
170 a session, you can quit IPython and reload it as many times as
170 a session, you can quit IPython and reload it as many times as
171 you want and it will continue to log its history and restore
171 you want and it will continue to log its history and restore
172 from the beginning every time.
172 from the beginning every time.
173
173
174 Caveats: there are limitations in this option. The history
174 Caveats: there are limitations in this option. The history
175 variables _i*,_* and _dh don't get restored properly. In the
175 variables _i*,_* and _dh don't get restored properly. In the
176 future we will try to implement full session saving by writing
176 future we will try to implement full session saving by writing
177 and retrieving a 'snapshot' of the memory state of IPython. But
177 and retrieving a 'snapshot' of the memory state of IPython. But
178 our first attempts failed because of inherent limitations of
178 our first attempts failed because of inherent limitations of
179 Python's Pickle module, so this may have to wait.
179 Python's Pickle module, so this may have to wait.
180
180
181 -[no]messages
181 -[no]messages
182 Print messages which IPython collects about its startup
182 Print messages which IPython collects about its startup
183 process (default on).
183 process (default on).
184
184
185 -[no]pdb
185 -[no]pdb
186 Automatically call the pdb debugger after every uncaught
186 Automatically call the pdb debugger after every uncaught
187 exception. If you are used to debugging using pdb, this puts
187 exception. If you are used to debugging using pdb, this puts
188 you automatically inside of it after any call (either in
188 you automatically inside of it after any call (either in
189 IPython or in code called by it) which triggers an exception
189 IPython or in code called by it) which triggers an exception
190 which goes uncaught.
190 which goes uncaught.
191
191
192 -pydb
192 -pydb
193 Makes IPython use the third party "pydb" package as debugger,
193 Makes IPython use the third party "pydb" package as debugger,
194 instead of pdb. Requires that pydb is installed.
194 instead of pdb. Requires that pydb is installed.
195
195
196 -[no]pprint
196 -[no]pprint
197 ipython can optionally use the pprint (pretty printer) module
197 ipython can optionally use the pprint (pretty printer) module
198 for displaying results. pprint tends to give a nicer display
198 for displaying results. pprint tends to give a nicer display
199 of nested data structures. If you like it, you can turn it on
199 of nested data structures. If you like it, you can turn it on
200 permanently in your config file (default off).
200 permanently in your config file (default off).
201
201
202 -profile, p <name>
202 -profile, p <name>
203
203
204 assume that your config file is ipythonrc-<name> or
204 assume that your config file is ipythonrc-<name> or
205 ipy_profile_<name>.py (looks in current dir first, then in
205 ipy_profile_<name>.py (looks in current dir first, then in
206 IPYTHONDIR). This is a quick way to keep and load multiple
206 IPYTHONDIR). This is a quick way to keep and load multiple
207 config files for different tasks, especially if you use the
207 config files for different tasks, especially if you use the
208 include option of config files. You can keep a basic
208 include option of config files. You can keep a basic
209 IPYTHONDIR/ipythonrc file and then have other 'profiles' which
209 IPYTHONDIR/ipythonrc file and then have other 'profiles' which
210 include this one and load extra things for particular
210 include this one and load extra things for particular
211 tasks. For example:
211 tasks. For example:
212
212
213 1. $HOME/.ipython/ipythonrc : load basic things you always want.
213 1. $HOME/.ipython/ipythonrc : load basic things you always want.
214 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules.
214 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules.
215 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules.
215 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules.
216
216
217 Since it is possible to create an endless loop by having
217 Since it is possible to create an endless loop by having
218 circular file inclusions, IPython will stop if it reaches 15
218 circular file inclusions, IPython will stop if it reaches 15
219 recursive inclusions.
219 recursive inclusions.
220
220
221 -prompt_in1, pi1 <string>
221 -prompt_in1, pi1 <string>
222
222
223 Specify the string used for input prompts. Note that if you are using
223 Specify the string used for input prompts. Note that if you are using
224 numbered prompts, the number is represented with a '\#' in the
224 numbered prompts, the number is represented with a '\#' in the
225 string. Don't forget to quote strings with spaces embedded in
225 string. Don't forget to quote strings with spaces embedded in
226 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
226 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
227 discusses in detail all the available escapes to customize your
227 discusses in detail all the available escapes to customize your
228 prompts.
228 prompts.
229
229
230 -prompt_in2, pi2 <string>
230 -prompt_in2, pi2 <string>
231 Similar to the previous option, but used for the continuation
231 Similar to the previous option, but used for the continuation
232 prompts. The special sequence '\D' is similar to '\#', but
232 prompts. The special sequence '\D' is similar to '\#', but
233 with all digits replaced dots (so you can have your
233 with all digits replaced dots (so you can have your
234 continuation prompt aligned with your input prompt). Default:
234 continuation prompt aligned with your input prompt). Default:
235 ' .\D.:' (note three spaces at the start for alignment with
235 ' .\D.:' (note three spaces at the start for alignment with
236 'In [\#]').
236 'In [\#]').
237
237
238 -prompt_out,po <string>
238 -prompt_out,po <string>
239 String used for output prompts, also uses numbers like
239 String used for output prompts, also uses numbers like
240 prompt_in1. Default: 'Out[\#]:'
240 prompt_in1. Default: 'Out[\#]:'
241
241
242 -quick start in bare bones mode (no config file loaded).
242 -quick start in bare bones mode (no config file loaded).
243
243
244 -rcfile <name>
244 -rcfile <name>
245 name of your IPython resource configuration file. Normally
245 name of your IPython resource configuration file. Normally
246 IPython loads ipythonrc (from current directory) or
246 IPython loads ipythonrc (from current directory) or
247 IPYTHONDIR/ipythonrc.
247 IPYTHONDIR/ipythonrc.
248
248
249 If the loading of your config file fails, IPython starts with
249 If the loading of your config file fails, IPython starts with
250 a bare bones configuration (no modules loaded at all).
250 a bare bones configuration (no modules loaded at all).
251
251
252 -[no]readline
252 -[no]readline
253 use the readline library, which is needed to support name
253 use the readline library, which is needed to support name
254 completion and command history, among other things. It is
254 completion and command history, among other things. It is
255 enabled by default, but may cause problems for users of
255 enabled by default, but may cause problems for users of
256 X/Emacs in Python comint or shell buffers.
256 X/Emacs in Python comint or shell buffers.
257
257
258 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
258 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
259 IPython's readline and syntax coloring fine, only 'emacs' (M-x
259 IPython's readline and syntax coloring fine, only 'emacs' (M-x
260 shell and C-c !) buffers do not.
260 shell and C-c !) buffers do not.
261
261
262 -screen_length, sl <n>
262 -screen_length, sl <n>
263 number of lines of your screen. This is used to control
263 number of lines of your screen. This is used to control
264 printing of very long strings. Strings longer than this number
264 printing of very long strings. Strings longer than this number
265 of lines will be sent through a pager instead of directly
265 of lines will be sent through a pager instead of directly
266 printed.
266 printed.
267
267
268 The default value for this is 0, which means IPython will
268 The default value for this is 0, which means IPython will
269 auto-detect your screen size every time it needs to print certain
269 auto-detect your screen size every time it needs to print certain
270 potentially long strings (this doesn't change the behavior of the
270 potentially long strings (this doesn't change the behavior of the
271 'print' keyword, it's only triggered internally). If for some
271 'print' keyword, it's only triggered internally). If for some
272 reason this isn't working well (it needs curses support), specify
272 reason this isn't working well (it needs curses support), specify
273 it yourself. Otherwise don't change the default.
273 it yourself. Otherwise don't change the default.
274
274
275 -separate_in, si <string>
275 -separate_in, si <string>
276
276
277 separator before input prompts.
277 separator before input prompts.
278 Default: '\n'
278 Default: '\n'
279
279
280 -separate_out, so <string>
280 -separate_out, so <string>
281 separator before output prompts.
281 separator before output prompts.
282 Default: nothing.
282 Default: nothing.
283
283
284 -separate_out2, so2
284 -separate_out2, so2
285 separator after output prompts.
285 separator after output prompts.
286 Default: nothing.
286 Default: nothing.
287 For these three options, use the value 0 to specify no separator.
287 For these three options, use the value 0 to specify no separator.
288
288
289 -nosep
289 -nosep
290 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
290 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
291 0'. Simply removes all input/output separators.
291 0'. Simply removes all input/output separators.
292
292
293 -upgrade
293 -upgrade
294 allows you to upgrade your IPYTHONDIR configuration when you
294 allows you to upgrade your IPYTHONDIR configuration when you
295 install a new version of IPython. Since new versions may
295 install a new version of IPython. Since new versions may
296 include new command line options or example files, this copies
296 include new command line options or example files, this copies
297 updated ipythonrc-type files. However, it backs up (with a
297 updated ipythonrc-type files. However, it backs up (with a
298 .old extension) all files which it overwrites so that you can
298 .old extension) all files which it overwrites so that you can
299 merge back any customizations you might have in your personal
299 merge back any customizations you might have in your personal
300 files. Note that you should probably use %upgrade instead,
300 files. Note that you should probably use %upgrade instead,
301 it's a safer alternative.
301 it's a safer alternative.
302
302
303
303
304 -Version print version information and exit.
304 -Version print version information and exit.
305
305
306 -wxversion <string>
306 -wxversion <string>
307 Deprecated.
307 Deprecated.
308
308
309 -xmode <modename>
309 -xmode <modename>
310
310
311 Mode for exception reporting.
311 Mode for exception reporting.
312
312
313 Valid modes: Plain, Context and Verbose.
313 Valid modes: Plain, Context and Verbose.
314
314
315 * Plain: similar to python's normal traceback printing.
315 * Plain: similar to python's normal traceback printing.
316 * Context: prints 5 lines of context source code around each
316 * Context: prints 5 lines of context source code around each
317 line in the traceback.
317 line in the traceback.
318 * Verbose: similar to Context, but additionally prints the
318 * Verbose: similar to Context, but additionally prints the
319 variables currently visible where the exception happened
319 variables currently visible where the exception happened
320 (shortening their strings if too long). This can potentially be
320 (shortening their strings if too long). This can potentially be
321 very slow, if you happen to have a huge data structure whose
321 very slow, if you happen to have a huge data structure whose
322 string representation is complex to compute. Your computer may
322 string representation is complex to compute. Your computer may
323 appear to freeze for a while with cpu usage at 100%. If this
323 appear to freeze for a while with cpu usage at 100%. If this
324 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
324 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
325 more than once).
325 more than once).
326
326
327 Interactive use
327 Interactive use
328 ===============
328 ===============
329
329
330 Warning: IPython relies on the existence of a global variable called
330 Warning: IPython relies on the existence of a global variable called
331 _ip which controls the shell itself. If you redefine _ip to anything,
331 _ip which controls the shell itself. If you redefine _ip to anything,
332 bizarre behavior will quickly occur.
332 bizarre behavior will quickly occur.
333
333
334 Other than the above warning, IPython is meant to work as a drop-in
334 Other than the above warning, IPython is meant to work as a drop-in
335 replacement for the standard interactive interpreter. As such, any code
335 replacement for the standard interactive interpreter. As such, any code
336 which is valid python should execute normally under IPython (cases where
336 which is valid python should execute normally under IPython (cases where
337 this is not true should be reported as bugs). It does, however, offer
337 this is not true should be reported as bugs). It does, however, offer
338 many features which are not available at a standard python prompt. What
338 many features which are not available at a standard python prompt. What
339 follows is a list of these.
339 follows is a list of these.
340
340
341
341
342 Caution for Windows users
342 Caution for Windows users
343 -------------------------
343 -------------------------
344
344
345 Windows, unfortunately, uses the '\' character as a path
345 Windows, unfortunately, uses the '\' character as a path
346 separator. This is a terrible choice, because '\' also represents the
346 separator. This is a terrible choice, because '\' also represents the
347 escape character in most modern programming languages, including
347 escape character in most modern programming languages, including
348 Python. For this reason, using '/' character is recommended if you
348 Python. For this reason, using '/' character is recommended if you
349 have problems with ``\``. However, in Windows commands '/' flags
349 have problems with ``\``. However, in Windows commands '/' flags
350 options, so you can not use it for the root directory. This means that
350 options, so you can not use it for the root directory. This means that
351 paths beginning at the root must be typed in a contrived manner like:
351 paths beginning at the root must be typed in a contrived manner like:
352 ``%copy \opt/foo/bar.txt \tmp``
352 ``%copy \opt/foo/bar.txt \tmp``
353
353
354 .. _magic:
354 .. _magic:
355
355
356 Magic command system
356 Magic command system
357 --------------------
357 --------------------
358
358
359 IPython will treat any line whose first character is a % as a special
359 IPython will treat any line whose first character is a % as a special
360 call to a 'magic' function. These allow you to control the behavior of
360 call to a 'magic' function. These allow you to control the behavior of
361 IPython itself, plus a lot of system-type features. They are all
361 IPython itself, plus a lot of system-type features. They are all
362 prefixed with a % character, but parameters are given without
362 prefixed with a % character, but parameters are given without
363 parentheses or quotes.
363 parentheses or quotes.
364
364
365 Example: typing '%cd mydir' (without the quotes) changes you working
365 Example: typing '%cd mydir' (without the quotes) changes you working
366 directory to 'mydir', if it exists.
366 directory to 'mydir', if it exists.
367
367
368 If you have 'automagic' enabled (in your ipythonrc file, via the command
368 If you have 'automagic' enabled (in your ipythonrc file, via the command
369 line option -automagic or with the %automagic function), you don't need
369 line option -automagic or with the %automagic function), you don't need
370 to type in the % explicitly. IPython will scan its internal list of
370 to type in the % explicitly. IPython will scan its internal list of
371 magic functions and call one if it exists. With automagic on you can
371 magic functions and call one if it exists. With automagic on you can
372 then just type 'cd mydir' to go to directory 'mydir'. The automagic
372 then just type 'cd mydir' to go to directory 'mydir'. The automagic
373 system has the lowest possible precedence in name searches, so defining
373 system has the lowest possible precedence in name searches, so defining
374 an identifier with the same name as an existing magic function will
374 an identifier with the same name as an existing magic function will
375 shadow it for automagic use. You can still access the shadowed magic
375 shadow it for automagic use. You can still access the shadowed magic
376 function by explicitly using the % character at the beginning of the line.
376 function by explicitly using the % character at the beginning of the line.
377
377
378 An example (with automagic on) should clarify all this::
378 An example (with automagic on) should clarify all this::
379
379
380 In [1]: cd ipython # %cd is called by automagic
380 In [1]: cd ipython # %cd is called by automagic
381
381
382 /home/fperez/ipython
382 /home/fperez/ipython
383
383
384 In [2]: cd=1 # now cd is just a variable
384 In [2]: cd=1 # now cd is just a variable
385
385
386 In [3]: cd .. # and doesn't work as a function anymore
386 In [3]: cd .. # and doesn't work as a function anymore
387
387
388 ------------------------------
388 ------------------------------
389
389
390 File "<console>", line 1
390 File "<console>", line 1
391
391
392 cd ..
392 cd ..
393
393
394 ^
394 ^
395
395
396 SyntaxError: invalid syntax
396 SyntaxError: invalid syntax
397
397
398 In [4]: %cd .. # but %cd always works
398 In [4]: %cd .. # but %cd always works
399
399
400 /home/fperez
400 /home/fperez
401
401
402 In [5]: del cd # if you remove the cd variable
402 In [5]: del cd # if you remove the cd variable
403
403
404 In [6]: cd ipython # automagic can work again
404 In [6]: cd ipython # automagic can work again
405
405
406 /home/fperez/ipython
406 /home/fperez/ipython
407
407
408 You can define your own magic functions to extend the system. The
408 You can define your own magic functions to extend the system. The
409 following example defines a new magic command, %impall::
409 following example defines a new magic command, %impall::
410
410
411 import IPython.ipapi
411 import IPython.ipapi
412
412
413 ip = IPython.ipapi.get()
413 ip = IPython.ipapi.get()
414
414
415 def doimp(self, arg):
415 def doimp(self, arg):
416
416
417 ip = self.api
417 ip = self.api
418
418
419 ip.ex("import %s; reload(%s); from %s import *" % (
419 ip.ex("import %s; reload(%s); from %s import *" % (
420
420
421 arg,arg,arg)
421 arg,arg,arg)
422
422
423 )
423 )
424
424
425 ip.expose_magic('impall', doimp)
425 ip.expose_magic('impall', doimp)
426
426
427 You can also define your own aliased names for magic functions. In your
427 You can also define your own aliased names for magic functions. In your
428 ipythonrc file, placing a line like::
428 ipythonrc file, placing a line like::
429
429
430 execute __IP.magic_cl = __IP.magic_clear
430 execute __IP.magic_cl = __IP.magic_clear
431
431
432 will define %cl as a new name for %clear.
432 will define %cl as a new name for %clear.
433
433
434 Type %magic for more information, including a list of all available
434 Type %magic for more information, including a list of all available
435 magic functions at any time and their docstrings. You can also type
435 magic functions at any time and their docstrings. You can also type
436 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
436 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
437 information on the '?' system) to get information about any particular
437 information on the '?' system) to get information about any particular
438 magic function you are interested in.
438 magic function you are interested in.
439
439
440 The API documentation for the :mod:`IPython.Magic` module contains the full
440 The API documentation for the :mod:`IPython.Magic` module contains the full
441 docstrings of all currently available magic commands.
441 docstrings of all currently available magic commands.
442
442
443
443
444 Access to the standard Python help
444 Access to the standard Python help
445 ----------------------------------
445 ----------------------------------
446
446
447 As of Python 2.1, a help system is available with access to object docstrings
447 As of Python 2.1, a help system is available with access to object docstrings
448 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
448 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
449 also type help(object) to obtain information about a given object, and
449 also type help(object) to obtain information about a given object, and
450 help('keyword') for information on a keyword. As noted :ref:`here
450 help('keyword') for information on a keyword. As noted :ref:`here
451 <accessing_help>`, you need to properly configure your environment variable
451 <accessing_help>`, you need to properly configure your environment variable
452 PYTHONDOCS for this feature to work correctly.
452 PYTHONDOCS for this feature to work correctly.
453
453
454 .. _dynamic_object_info:
454 .. _dynamic_object_info:
455
455
456 Dynamic object information
456 Dynamic object information
457 --------------------------
457 --------------------------
458
458
459 Typing ?word or word? prints detailed information about an object. If
459 Typing ?word or word? prints detailed information about an object. If
460 certain strings in the object are too long (docstrings, code, etc.) they
460 certain strings in the object are too long (docstrings, code, etc.) they
461 get snipped in the center for brevity. This system gives access variable
461 get snipped in the center for brevity. This system gives access variable
462 types and values, full source code for any object (if available),
462 types and values, full source code for any object (if available),
463 function prototypes and other useful information.
463 function prototypes and other useful information.
464
464
465 Typing ??word or word?? gives access to the full information without
465 Typing ??word or word?? gives access to the full information without
466 snipping long strings. Long strings are sent to the screen through the
466 snipping long strings. Long strings are sent to the screen through the
467 less pager if longer than the screen and printed otherwise. On systems
467 less pager if longer than the screen and printed otherwise. On systems
468 lacking the less command, IPython uses a very basic internal pager.
468 lacking the less command, IPython uses a very basic internal pager.
469
469
470 The following magic functions are particularly useful for gathering
470 The following magic functions are particularly useful for gathering
471 information about your working environment. You can get more details by
471 information about your working environment. You can get more details by
472 typing %magic or querying them individually (use %function_name? with or
472 typing %magic or querying them individually (use %function_name? with or
473 without the %), this is just a summary:
473 without the %), this is just a summary:
474
474
475 * **%pdoc <object>**: Print (or run through a pager if too long) the
475 * **%pdoc <object>**: Print (or run through a pager if too long) the
476 docstring for an object. If the given object is a class, it will
476 docstring for an object. If the given object is a class, it will
477 print both the class and the constructor docstrings.
477 print both the class and the constructor docstrings.
478 * **%pdef <object>**: Print the definition header for any callable
478 * **%pdef <object>**: Print the definition header for any callable
479 object. If the object is a class, print the constructor information.
479 object. If the object is a class, print the constructor information.
480 * **%psource <object>**: Print (or run through a pager if too long)
480 * **%psource <object>**: Print (or run through a pager if too long)
481 the source code for an object.
481 the source code for an object.
482 * **%pfile <object>**: Show the entire source file where an object was
482 * **%pfile <object>**: Show the entire source file where an object was
483 defined via a pager, opening it at the line where the object
483 defined via a pager, opening it at the line where the object
484 definition begins.
484 definition begins.
485 * **%who/%whos**: These functions give information about identifiers
485 * **%who/%whos**: These functions give information about identifiers
486 you have defined interactively (not things you loaded or defined
486 you have defined interactively (not things you loaded or defined
487 in your configuration files). %who just prints a list of
487 in your configuration files). %who just prints a list of
488 identifiers and %whos prints a table with some basic details about
488 identifiers and %whos prints a table with some basic details about
489 each identifier.
489 each identifier.
490
490
491 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
491 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
492 %pdef, %psource) give you access to documentation even on things which
492 %pdef, %psource) give you access to documentation even on things which
493 are not really defined as separate identifiers. Try for example typing
493 are not really defined as separate identifiers. Try for example typing
494 {}.get? or after doing import os, type os.path.abspath??.
494 {}.get? or after doing import os, type os.path.abspath??.
495
495
496
496
497 .. _readline:
497 .. _readline:
498
498
499 Readline-based features
499 Readline-based features
500 -----------------------
500 -----------------------
501
501
502 These features require the GNU readline library, so they won't work if
502 These features require the GNU readline library, so they won't work if
503 your Python installation lacks readline support. We will first describe
503 your Python installation lacks readline support. We will first describe
504 the default behavior IPython uses, and then how to change it to suit
504 the default behavior IPython uses, and then how to change it to suit
505 your preferences.
505 your preferences.
506
506
507
507
508 Command line completion
508 Command line completion
509 +++++++++++++++++++++++
509 +++++++++++++++++++++++
510
510
511 At any time, hitting TAB will complete any available python commands or
511 At any time, hitting TAB will complete any available python commands or
512 variable names, and show you a list of the possible completions if
512 variable names, and show you a list of the possible completions if
513 there's no unambiguous one. It will also complete filenames in the
513 there's no unambiguous one. It will also complete filenames in the
514 current directory if no python names match what you've typed so far.
514 current directory if no python names match what you've typed so far.
515
515
516
516
517 Search command history
517 Search command history
518 ++++++++++++++++++++++
518 ++++++++++++++++++++++
519
519
520 IPython provides two ways for searching through previous input and thus
520 IPython provides two ways for searching through previous input and thus
521 reduce the need for repetitive typing:
521 reduce the need for repetitive typing:
522
522
523 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
523 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
524 (next,down) to search through only the history items that match
524 (next,down) to search through only the history items that match
525 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
525 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
526 prompt, they just behave like normal arrow keys.
526 prompt, they just behave like normal arrow keys.
527 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
527 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
528 searches your history for lines that contain what you've typed so
528 searches your history for lines that contain what you've typed so
529 far, completing as much as it can.
529 far, completing as much as it can.
530
530
531
531
532 Persistent command history across sessions
532 Persistent command history across sessions
533 ++++++++++++++++++++++++++++++++++++++++++
533 ++++++++++++++++++++++++++++++++++++++++++
534
534
535 IPython will save your input history when it leaves and reload it next
535 IPython will save your input history when it leaves and reload it next
536 time you restart it. By default, the history file is named
536 time you restart it. By default, the history file is named
537 $IPYTHONDIR/history, but if you've loaded a named profile,
537 $IPYTHONDIR/history, but if you've loaded a named profile,
538 '-PROFILE_NAME' is appended to the name. This allows you to keep
538 '-PROFILE_NAME' is appended to the name. This allows you to keep
539 separate histories related to various tasks: commands related to
539 separate histories related to various tasks: commands related to
540 numerical work will not be clobbered by a system shell history, for
540 numerical work will not be clobbered by a system shell history, for
541 example.
541 example.
542
542
543
543
544 Autoindent
544 Autoindent
545 ++++++++++
545 ++++++++++
546
546
547 IPython can recognize lines ending in ':' and indent the next line,
547 IPython can recognize lines ending in ':' and indent the next line,
548 while also un-indenting automatically after 'raise' or 'return'.
548 while also un-indenting automatically after 'raise' or 'return'.
549
549
550 This feature uses the readline library, so it will honor your ~/.inputrc
550 This feature uses the readline library, so it will honor your ~/.inputrc
551 configuration (or whatever file your INPUTRC variable points to). Adding
551 configuration (or whatever file your INPUTRC variable points to). Adding
552 the following lines to your .inputrc file can make indenting/unindenting
552 the following lines to your .inputrc file can make indenting/unindenting
553 more convenient (M-i indents, M-u unindents)::
553 more convenient (M-i indents, M-u unindents)::
554
554
555 $if Python
555 $if Python
556 "\M-i": " "
556 "\M-i": " "
557 "\M-u": "\d\d\d\d"
557 "\M-u": "\d\d\d\d"
558 $endif
558 $endif
559
559
560 Note that there are 4 spaces between the quote marks after "M-i" above.
560 Note that there are 4 spaces between the quote marks after "M-i" above.
561
561
562 Warning: this feature is ON by default, but it can cause problems with
562 Warning: this feature is ON by default, but it can cause problems with
563 the pasting of multi-line indented code (the pasted code gets
563 the pasting of multi-line indented code (the pasted code gets
564 re-indented on each line). A magic function %autoindent allows you to
564 re-indented on each line). A magic function %autoindent allows you to
565 toggle it on/off at runtime. You can also disable it permanently on in
565 toggle it on/off at runtime. You can also disable it permanently on in
566 your ipythonrc file (set autoindent 0).
566 your ipythonrc file (set autoindent 0).
567
567
568
568
569 Customizing readline behavior
569 Customizing readline behavior
570 +++++++++++++++++++++++++++++
570 +++++++++++++++++++++++++++++
571
571
572 All these features are based on the GNU readline library, which has an
572 All these features are based on the GNU readline library, which has an
573 extremely customizable interface. Normally, readline is configured via a
573 extremely customizable interface. Normally, readline is configured via a
574 file which defines the behavior of the library; the details of the
574 file which defines the behavior of the library; the details of the
575 syntax for this can be found in the readline documentation available
575 syntax for this can be found in the readline documentation available
576 with your system or on the Internet. IPython doesn't read this file (if
576 with your system or on the Internet. IPython doesn't read this file (if
577 it exists) directly, but it does support passing to readline valid
577 it exists) directly, but it does support passing to readline valid
578 options via a simple interface. In brief, you can customize readline by
578 options via a simple interface. In brief, you can customize readline by
579 setting the following options in your ipythonrc configuration file (note
579 setting the following options in your ipythonrc configuration file (note
580 that these options can not be specified at the command line):
580 that these options can not be specified at the command line):
581
581
582 * **readline_parse_and_bind**: this option can appear as many times as
582 * **readline_parse_and_bind**: this option can appear as many times as
583 you want, each time defining a string to be executed via a
583 you want, each time defining a string to be executed via a
584 readline.parse_and_bind() command. The syntax for valid commands
584 readline.parse_and_bind() command. The syntax for valid commands
585 of this kind can be found by reading the documentation for the GNU
585 of this kind can be found by reading the documentation for the GNU
586 readline library, as these commands are of the kind which readline
586 readline library, as these commands are of the kind which readline
587 accepts in its configuration file.
587 accepts in its configuration file.
588 * **readline_remove_delims**: a string of characters to be removed
588 * **readline_remove_delims**: a string of characters to be removed
589 from the default word-delimiters list used by readline, so that
589 from the default word-delimiters list used by readline, so that
590 completions may be performed on strings which contain them. Do not
590 completions may be performed on strings which contain them. Do not
591 change the default value unless you know what you're doing.
591 change the default value unless you know what you're doing.
592 * **readline_omit__names**: when tab-completion is enabled, hitting
592 * **readline_omit__names**: when tab-completion is enabled, hitting
593 <tab> after a '.' in a name will complete all attributes of an
593 <tab> after a '.' in a name will complete all attributes of an
594 object, including all the special methods whose names include
594 object, including all the special methods whose names include
595 double underscores (like __getitem__ or __class__). If you'd
595 double underscores (like __getitem__ or __class__). If you'd
596 rather not see these names by default, you can set this option to
596 rather not see these names by default, you can set this option to
597 1. Note that even when this option is set, you can still see those
597 1. Note that even when this option is set, you can still see those
598 names by explicitly typing a _ after the period and hitting <tab>:
598 names by explicitly typing a _ after the period and hitting <tab>:
599 'name._<tab>' will always complete attribute names starting with '_'.
599 'name._<tab>' will always complete attribute names starting with '_'.
600
600
601 This option is off by default so that new users see all
601 This option is off by default so that new users see all
602 attributes of any objects they are dealing with.
602 attributes of any objects they are dealing with.
603
603
604 You will find the default values along with a corresponding detailed
604 You will find the default values along with a corresponding detailed
605 explanation in your ipythonrc file.
605 explanation in your ipythonrc file.
606
606
607
607
608 Session logging and restoring
608 Session logging and restoring
609 -----------------------------
609 -----------------------------
610
610
611 You can log all input from a session either by starting IPython with the
611 You can log all input from a session either by starting IPython with the
612 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
612 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
613 or by activating the logging at any moment with the magic function %logstart.
613 or by activating the logging at any moment with the magic function %logstart.
614
614
615 Log files can later be reloaded with the -logplay option and IPython
615 Log files can later be reloaded with the -logplay option and IPython
616 will attempt to 'replay' the log by executing all the lines in it, thus
616 will attempt to 'replay' the log by executing all the lines in it, thus
617 restoring the state of a previous session. This feature is not quite
617 restoring the state of a previous session. This feature is not quite
618 perfect, but can still be useful in many cases.
618 perfect, but can still be useful in many cases.
619
619
620 The log files can also be used as a way to have a permanent record of
620 The log files can also be used as a way to have a permanent record of
621 any code you wrote while experimenting. Log files are regular text files
621 any code you wrote while experimenting. Log files are regular text files
622 which you can later open in your favorite text editor to extract code or
622 which you can later open in your favorite text editor to extract code or
623 to 'clean them up' before using them to replay a session.
623 to 'clean them up' before using them to replay a session.
624
624
625 The %logstart function for activating logging in mid-session is used as
625 The %logstart function for activating logging in mid-session is used as
626 follows:
626 follows:
627
627
628 %logstart [log_name [log_mode]]
628 %logstart [log_name [log_mode]]
629
629
630 If no name is given, it defaults to a file named 'log' in your
630 If no name is given, it defaults to a file named 'log' in your
631 IPYTHONDIR directory, in 'rotate' mode (see below).
631 IPYTHONDIR directory, in 'rotate' mode (see below).
632
632
633 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
633 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
634 history up to that point and then continues logging.
634 history up to that point and then continues logging.
635
635
636 %logstart takes a second optional parameter: logging mode. This can be
636 %logstart takes a second optional parameter: logging mode. This can be
637 one of (note that the modes are given unquoted):
637 one of (note that the modes are given unquoted):
638
638
639 * [over:] overwrite existing log_name.
639 * [over:] overwrite existing log_name.
640 * [backup:] rename (if exists) to log_name~ and start log_name.
640 * [backup:] rename (if exists) to log_name~ and start log_name.
641 * [append:] well, that says it.
641 * [append:] well, that says it.
642 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
642 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
643
643
644 The %logoff and %logon functions allow you to temporarily stop and
644 The %logoff and %logon functions allow you to temporarily stop and
645 resume logging to a file which had previously been started with
645 resume logging to a file which had previously been started with
646 %logstart. They will fail (with an explanation) if you try to use them
646 %logstart. They will fail (with an explanation) if you try to use them
647 before logging has been started.
647 before logging has been started.
648
648
649 .. _system_shell_access:
649 .. _system_shell_access:
650
650
651 System shell access
651 System shell access
652 -------------------
652 -------------------
653
653
654 Any input line beginning with a ! character is passed verbatim (minus
654 Any input line beginning with a ! character is passed verbatim (minus
655 the !, of course) to the underlying operating system. For example,
655 the !, of course) to the underlying operating system. For example,
656 typing !ls will run 'ls' in the current directory.
656 typing !ls will run 'ls' in the current directory.
657
657
658 Manual capture of command output
658 Manual capture of command output
659 --------------------------------
659 --------------------------------
660
660
661 If the input line begins with two exclamation marks, !!, the command is
661 If the input line begins with two exclamation marks, !!, the command is
662 executed but its output is captured and returned as a python list, split
662 executed but its output is captured and returned as a python list, split
663 on newlines. Any output sent by the subprocess to standard error is
663 on newlines. Any output sent by the subprocess to standard error is
664 printed separately, so that the resulting list only captures standard
664 printed separately, so that the resulting list only captures standard
665 output. The !! syntax is a shorthand for the %sx magic command.
665 output. The !! syntax is a shorthand for the %sx magic command.
666
666
667 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
667 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
668 but allowing more fine-grained control of the capture details, and
668 but allowing more fine-grained control of the capture details, and
669 storing the result directly into a named variable. The direct use of
669 storing the result directly into a named variable. The direct use of
670 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
670 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
671 instead.
671 instead.
672
672
673 IPython also allows you to expand the value of python variables when
673 IPython also allows you to expand the value of python variables when
674 making system calls. Any python variable or expression which you prepend
674 making system calls. Any python variable or expression which you prepend
675 with $ will get expanded before the system call is made::
675 with $ will get expanded before the system call is made::
676
676
677 In [1]: pyvar='Hello world'
677 In [1]: pyvar='Hello world'
678 In [2]: !echo "A python variable: $pyvar"
678 In [2]: !echo "A python variable: $pyvar"
679 A python variable: Hello world
679 A python variable: Hello world
680
680
681 If you want the shell to actually see a literal $, you need to type it
681 If you want the shell to actually see a literal $, you need to type it
682 twice::
682 twice::
683
683
684 In [3]: !echo "A system variable: $$HOME"
684 In [3]: !echo "A system variable: $$HOME"
685 A system variable: /home/fperez
685 A system variable: /home/fperez
686
686
687 You can pass arbitrary expressions, though you'll need to delimit them
687 You can pass arbitrary expressions, though you'll need to delimit them
688 with {} if there is ambiguity as to the extent of the expression::
688 with {} if there is ambiguity as to the extent of the expression::
689
689
690 In [5]: x=10
690 In [5]: x=10
691 In [6]: y=20
691 In [6]: y=20
692 In [13]: !echo $x+y
692 In [13]: !echo $x+y
693 10+y
693 10+y
694 In [7]: !echo ${x+y}
694 In [7]: !echo ${x+y}
695 30
695 30
696
696
697 Even object attributes can be expanded::
697 Even object attributes can be expanded::
698
698
699 In [12]: !echo $sys.argv
699 In [12]: !echo $sys.argv
700 [/home/fperez/usr/bin/ipython]
700 [/home/fperez/usr/bin/ipython]
701
701
702
702
703 System command aliases
703 System command aliases
704 ----------------------
704 ----------------------
705
705
706 The %alias magic function and the alias option in the ipythonrc
706 The %alias magic function and the alias option in the ipythonrc
707 configuration file allow you to define magic functions which are in fact
707 configuration file allow you to define magic functions which are in fact
708 system shell commands. These aliases can have parameters.
708 system shell commands. These aliases can have parameters.
709
709
710 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
710 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
711
711
712 Then, typing '%alias_name params' will execute the system command 'cmd
712 Then, typing '%alias_name params' will execute the system command 'cmd
713 params' (from your underlying operating system).
713 params' (from your underlying operating system).
714
714
715 You can also define aliases with parameters using %s specifiers (one per
715 You can also define aliases with parameters using %s specifiers (one per
716 parameter). The following example defines the %parts function as an
716 parameter). The following example defines the %parts function as an
717 alias to the command 'echo first %s second %s' where each %s will be
717 alias to the command 'echo first %s second %s' where each %s will be
718 replaced by a positional parameter to the call to %parts::
718 replaced by a positional parameter to the call to %parts::
719
719
720 In [1]: alias parts echo first %s second %s
720 In [1]: alias parts echo first %s second %s
721 In [2]: %parts A B
721 In [2]: %parts A B
722 first A second B
722 first A second B
723 In [3]: %parts A
723 In [3]: %parts A
724 Incorrect number of arguments: 2 expected.
724 Incorrect number of arguments: 2 expected.
725 parts is an alias to: 'echo first %s second %s'
725 parts is an alias to: 'echo first %s second %s'
726
726
727 If called with no parameters, %alias prints the table of currently
727 If called with no parameters, %alias prints the table of currently
728 defined aliases.
728 defined aliases.
729
729
730 The %rehash/rehashx magics allow you to load your entire $PATH as
730 The %rehash/rehashx magics allow you to load your entire $PATH as
731 ipython aliases. See their respective docstrings (or sec. 6.2
731 ipython aliases. See their respective docstrings (or sec. 6.2
732 <#sec:magic> for further details).
732 <#sec:magic> for further details).
733
733
734
734
735 .. _dreload:
735 .. _dreload:
736
736
737 Recursive reload
737 Recursive reload
738 ----------------
738 ----------------
739
739
740 The dreload function does a recursive reload of a module: changes made
740 The dreload function does a recursive reload of a module: changes made
741 to the module since you imported will actually be available without
741 to the module since you imported will actually be available without
742 having to exit.
742 having to exit.
743
743
744
744
745 Verbose and colored exception traceback printouts
745 Verbose and colored exception traceback printouts
746 -------------------------------------------------
746 -------------------------------------------------
747
747
748 IPython provides the option to see very detailed exception tracebacks,
748 IPython provides the option to see very detailed exception tracebacks,
749 which can be especially useful when debugging large programs. You can
749 which can be especially useful when debugging large programs. You can
750 run any Python file with the %run function to benefit from these
750 run any Python file with the %run function to benefit from these
751 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
751 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
752 be colored (if your terminal supports it) which makes them much easier
752 be colored (if your terminal supports it) which makes them much easier
753 to parse visually.
753 to parse visually.
754
754
755 See the magic xmode and colors functions for details (just type %magic).
755 See the magic xmode and colors functions for details (just type %magic).
756
756
757 These features are basically a terminal version of Ka-Ping Yee's cgitb
757 These features are basically a terminal version of Ka-Ping Yee's cgitb
758 module, now part of the standard Python library.
758 module, now part of the standard Python library.
759
759
760
760
761 .. _input_caching:
761 .. _input_caching:
762
762
763 Input caching system
763 Input caching system
764 --------------------
764 --------------------
765
765
766 IPython offers numbered prompts (In/Out) with input and output caching
766 IPython offers numbered prompts (In/Out) with input and output caching
767 (also referred to as 'input history'). All input is saved and can be
767 (also referred to as 'input history'). All input is saved and can be
768 retrieved as variables (besides the usual arrow key recall), in
768 retrieved as variables (besides the usual arrow key recall), in
769 addition to the %rep magic command that brings a history entry
769 addition to the %rep magic command that brings a history entry
770 up for editing on the next command line.
770 up for editing on the next command line.
771
771
772 The following GLOBAL variables always exist (so don't overwrite them!):
772 The following GLOBAL variables always exist (so don't overwrite them!):
773 _i: stores previous input. _ii: next previous. _iii: next-next previous.
773 _i: stores previous input. _ii: next previous. _iii: next-next previous.
774 _ih : a list of all input _ih[n] is the input from line n and this list
774 _ih : a list of all input _ih[n] is the input from line n and this list
775 is aliased to the global variable In. If you overwrite In with a
775 is aliased to the global variable In. If you overwrite In with a
776 variable of your own, you can remake the assignment to the internal list
776 variable of your own, you can remake the assignment to the internal list
777 with a simple 'In=_ih'.
777 with a simple 'In=_ih'.
778
778
779 Additionally, global variables named _i<n> are dynamically created (<n>
779 Additionally, global variables named _i<n> are dynamically created (<n>
780 being the prompt counter), such that
780 being the prompt counter), such that
781 _i<n> == _ih[<n>] == In[<n>].
781 _i<n> == _ih[<n>] == In[<n>].
782
782
783 For example, what you typed at prompt 14 is available as _i14, _ih[14]
783 For example, what you typed at prompt 14 is available as _i14, _ih[14]
784 and In[14].
784 and In[14].
785
785
786 This allows you to easily cut and paste multi line interactive prompts
786 This allows you to easily cut and paste multi line interactive prompts
787 by printing them out: they print like a clean string, without prompt
787 by printing them out: they print like a clean string, without prompt
788 characters. You can also manipulate them like regular variables (they
788 characters. You can also manipulate them like regular variables (they
789 are strings), modify or exec them (typing 'exec _i9' will re-execute the
789 are strings), modify or exec them (typing 'exec _i9' will re-execute the
790 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
790 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
791 9 through 13 and line 18).
791 9 through 13 and line 18).
792
792
793 You can also re-execute multiple lines of input easily by using the
793 You can also re-execute multiple lines of input easily by using the
794 magic %macro function (which automates the process and allows
794 magic %macro function (which automates the process and allows
795 re-execution without having to type 'exec' every time). The macro system
795 re-execution without having to type 'exec' every time). The macro system
796 also allows you to re-execute previous lines which include magic
796 also allows you to re-execute previous lines which include magic
797 function calls (which require special processing). Type %macro? or see
797 function calls (which require special processing). Type %macro? or see
798 sec. 6.2 <#sec:magic> for more details on the macro system.
798 sec. 6.2 <#sec:magic> for more details on the macro system.
799
799
800 A history function %hist allows you to see any part of your input
800 A history function %hist allows you to see any part of your input
801 history by printing a range of the _i variables.
801 history by printing a range of the _i variables.
802
802
803 You can also search ('grep') through your history by typing
803 You can also search ('grep') through your history by typing
804 '%hist -g somestring'. This also searches through the so called *shadow history*,
804 '%hist -g somestring'. This also searches through the so called *shadow history*,
805 which remembers all the commands (apart from multiline code blocks)
805 which remembers all the commands (apart from multiline code blocks)
806 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
806 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
807 etc. You can bring shadow history entries listed by '%hist -g' up for editing
807 etc. You can bring shadow history entries listed by '%hist -g' up for editing
808 (or re-execution by just pressing ENTER) with %rep command. Shadow history
808 (or re-execution by just pressing ENTER) with %rep command. Shadow history
809 entries are not available as _iNUMBER variables, and they are identified by
809 entries are not available as _iNUMBER variables, and they are identified by
810 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
810 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
811 history entry, but 0231 is a shadow history entry.
811 history entry, but 0231 is a shadow history entry.
812
812
813 Shadow history was added because the readline history is inherently very
813 Shadow history was added because the readline history is inherently very
814 unsafe - if you have multiple IPython sessions open, the last session
814 unsafe - if you have multiple IPython sessions open, the last session
815 to close will overwrite the history of previountly closed session. Likewise,
815 to close will overwrite the history of previountly closed session. Likewise,
816 if a crash occurs, history is never saved, whereas shadow history entries
816 if a crash occurs, history is never saved, whereas shadow history entries
817 are added after entering every command (so a command executed
817 are added after entering every command (so a command executed
818 in another IPython session is immediately available in other IPython
818 in another IPython session is immediately available in other IPython
819 sessions that are open).
819 sessions that are open).
820
820
821 To conserve space, a command can exist in shadow history only once - it doesn't
821 To conserve space, a command can exist in shadow history only once - it doesn't
822 make sense to store a common line like "cd .." a thousand times. The idea is
822 make sense to store a common line like "cd .." a thousand times. The idea is
823 mainly to provide a reliable place where valuable, hard-to-remember commands can
823 mainly to provide a reliable place where valuable, hard-to-remember commands can
824 always be retrieved, as opposed to providing an exact sequence of commands
824 always be retrieved, as opposed to providing an exact sequence of commands
825 you have entered in actual order.
825 you have entered in actual order.
826
826
827 Because shadow history has all the commands you have ever executed,
827 Because shadow history has all the commands you have ever executed,
828 time taken by %hist -g will increase oven time. If it ever starts to take
828 time taken by %hist -g will increase oven time. If it ever starts to take
829 too long (or it ends up containing sensitive information like passwords),
829 too long (or it ends up containing sensitive information like passwords),
830 clear the shadow history by `%clear shadow_nuke`.
830 clear the shadow history by `%clear shadow_nuke`.
831
831
832 Time taken to add entries to shadow history should be negligible, but
832 Time taken to add entries to shadow history should be negligible, but
833 in any case, if you start noticing performance degradation after using
833 in any case, if you start noticing performance degradation after using
834 IPython for a long time (or running a script that floods the shadow history!),
834 IPython for a long time (or running a script that floods the shadow history!),
835 you can 'compress' the shadow history by executing
835 you can 'compress' the shadow history by executing
836 `%clear shadow_compress`. In practice, this should never be necessary
836 `%clear shadow_compress`. In practice, this should never be necessary
837 in normal use.
837 in normal use.
838
838
839 .. _output_caching:
839 .. _output_caching:
840
840
841 Output caching system
841 Output caching system
842 ---------------------
842 ---------------------
843
843
844 For output that is returned from actions, a system similar to the input
844 For output that is returned from actions, a system similar to the input
845 cache exists but using _ instead of _i. Only actions that produce a
845 cache exists but using _ instead of _i. Only actions that produce a
846 result (NOT assignments, for example) are cached. If you are familiar
846 result (NOT assignments, for example) are cached. If you are familiar
847 with Mathematica, IPython's _ variables behave exactly like
847 with Mathematica, IPython's _ variables behave exactly like
848 Mathematica's % variables.
848 Mathematica's % variables.
849
849
850 The following GLOBAL variables always exist (so don't overwrite them!):
850 The following GLOBAL variables always exist (so don't overwrite them!):
851
851
852 * [_] (a single underscore) : stores previous output, like Python's
852 * [_] (a single underscore) : stores previous output, like Python's
853 default interpreter.
853 default interpreter.
854 * [__] (two underscores): next previous.
854 * [__] (two underscores): next previous.
855 * [___] (three underscores): next-next previous.
855 * [___] (three underscores): next-next previous.
856
856
857 Additionally, global variables named _<n> are dynamically created (<n>
857 Additionally, global variables named _<n> are dynamically created (<n>
858 being the prompt counter), such that the result of output <n> is always
858 being the prompt counter), such that the result of output <n> is always
859 available as _<n> (don't use the angle brackets, just the number, e.g.
859 available as _<n> (don't use the angle brackets, just the number, e.g.
860 _21).
860 _21).
861
861
862 These global variables are all stored in a global dictionary (not a
862 These global variables are all stored in a global dictionary (not a
863 list, since it only has entries for lines which returned a result)
863 list, since it only has entries for lines which returned a result)
864 available under the names _oh and Out (similar to _ih and In). So the
864 available under the names _oh and Out (similar to _ih and In). So the
865 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
865 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
866 accidentally overwrite the Out variable you can recover it by typing
866 accidentally overwrite the Out variable you can recover it by typing
867 'Out=_oh' at the prompt.
867 'Out=_oh' at the prompt.
868
868
869 This system obviously can potentially put heavy memory demands on your
869 This system obviously can potentially put heavy memory demands on your
870 system, since it prevents Python's garbage collector from removing any
870 system, since it prevents Python's garbage collector from removing any
871 previously computed results. You can control how many results are kept
871 previously computed results. You can control how many results are kept
872 in memory with the option (at the command line or in your ipythonrc
872 in memory with the option (at the command line or in your ipythonrc
873 file) cache_size. If you set it to 0, the whole system is completely
873 file) cache_size. If you set it to 0, the whole system is completely
874 disabled and the prompts revert to the classic '>>>' of normal Python.
874 disabled and the prompts revert to the classic '>>>' of normal Python.
875
875
876
876
877 Directory history
877 Directory history
878 -----------------
878 -----------------
879
879
880 Your history of visited directories is kept in the global list _dh, and
880 Your history of visited directories is kept in the global list _dh, and
881 the magic %cd command can be used to go to any entry in that list. The
881 the magic %cd command can be used to go to any entry in that list. The
882 %dhist command allows you to view this history. Do ``cd -<TAB`` to
882 %dhist command allows you to view this history. Do ``cd -<TAB`` to
883 conventiently view the directory history.
883 conventiently view the directory history.
884
884
885
885
886 Automatic parentheses and quotes
886 Automatic parentheses and quotes
887 --------------------------------
887 --------------------------------
888
888
889 These features were adapted from Nathan Gray's LazyPython. They are
889 These features were adapted from Nathan Gray's LazyPython. They are
890 meant to allow less typing for common situations.
890 meant to allow less typing for common situations.
891
891
892
892
893 Automatic parentheses
893 Automatic parentheses
894 ---------------------
894 ---------------------
895
895
896 Callable objects (i.e. functions, methods, etc) can be invoked like this
896 Callable objects (i.e. functions, methods, etc) can be invoked like this
897 (notice the commas between the arguments)::
897 (notice the commas between the arguments)::
898
898
899 >>> callable_ob arg1, arg2, arg3
899 >>> callable_ob arg1, arg2, arg3
900
900
901 and the input will be translated to this::
901 and the input will be translated to this::
902
902
903 -> callable_ob(arg1, arg2, arg3)
903 -> callable_ob(arg1, arg2, arg3)
904
904
905 You can force automatic parentheses by using '/' as the first character
905 You can force automatic parentheses by using '/' as the first character
906 of a line. For example::
906 of a line. For example::
907
907
908 >>> /globals # becomes 'globals()'
908 >>> /globals # becomes 'globals()'
909
909
910 Note that the '/' MUST be the first character on the line! This won't work::
910 Note that the '/' MUST be the first character on the line! This won't work::
911
911
912 >>> print /globals # syntax error
912 >>> print /globals # syntax error
913
913
914 In most cases the automatic algorithm should work, so you should rarely
914 In most cases the automatic algorithm should work, so you should rarely
915 need to explicitly invoke /. One notable exception is if you are trying
915 need to explicitly invoke /. One notable exception is if you are trying
916 to call a function with a list of tuples as arguments (the parenthesis
916 to call a function with a list of tuples as arguments (the parenthesis
917 will confuse IPython)::
917 will confuse IPython)::
918
918
919 In [1]: zip (1,2,3),(4,5,6) # won't work
919 In [1]: zip (1,2,3),(4,5,6) # won't work
920
920
921 but this will work::
921 but this will work::
922
922
923 In [2]: /zip (1,2,3),(4,5,6)
923 In [2]: /zip (1,2,3),(4,5,6)
924 ---> zip ((1,2,3),(4,5,6))
924 ---> zip ((1,2,3),(4,5,6))
925 Out[2]= [(1, 4), (2, 5), (3, 6)]
925 Out[2]= [(1, 4), (2, 5), (3, 6)]
926
926
927 IPython tells you that it has altered your command line by displaying
927 IPython tells you that it has altered your command line by displaying
928 the new command line preceded by ->. e.g.::
928 the new command line preceded by ->. e.g.::
929
929
930 In [18]: callable list
930 In [18]: callable list
931 ----> callable (list)
931 ----> callable (list)
932
932
933
933
934 Automatic quoting
934 Automatic quoting
935 -----------------
935 -----------------
936
936
937 You can force automatic quoting of a function's arguments by using ','
937 You can force automatic quoting of a function's arguments by using ','
938 or ';' as the first character of a line. For example::
938 or ';' as the first character of a line. For example::
939
939
940 >>> ,my_function /home/me # becomes my_function("/home/me")
940 >>> ,my_function /home/me # becomes my_function("/home/me")
941
941
942 If you use ';' instead, the whole argument is quoted as a single string
942 If you use ';' instead, the whole argument is quoted as a single string
943 (while ',' splits on whitespace)::
943 (while ',' splits on whitespace)::
944
944
945 >>> ,my_function a b c # becomes my_function("a","b","c")
945 >>> ,my_function a b c # becomes my_function("a","b","c")
946
946
947 >>> ;my_function a b c # becomes my_function("a b c")
947 >>> ;my_function a b c # becomes my_function("a b c")
948
948
949 Note that the ',' or ';' MUST be the first character on the line! This
949 Note that the ',' or ';' MUST be the first character on the line! This
950 won't work::
950 won't work::
951
951
952 >>> x = ,my_function /home/me # syntax error
952 >>> x = ,my_function /home/me # syntax error
953
953
954 IPython as your default Python environment
954 IPython as your default Python environment
955 ==========================================
955 ==========================================
956
956
957 Python honors the environment variable PYTHONSTARTUP and will execute at
957 Python honors the environment variable PYTHONSTARTUP and will execute at
958 startup the file referenced by this variable. If you put at the end of
958 startup the file referenced by this variable. If you put at the end of
959 this file the following two lines of code::
959 this file the following two lines of code::
960
960
961 import IPython
961 import IPython
962 IPython.Shell.IPShell().mainloop(sys_exit=1)
962 IPython.Shell.IPShell().mainloop(sys_exit=1)
963
963
964 then IPython will be your working environment anytime you start Python.
964 then IPython will be your working environment anytime you start Python.
965 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
965 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
966 it finishes, otherwise you'll be back at the normal Python '>>>'
966 it finishes, otherwise you'll be back at the normal Python '>>>'
967 prompt.
967 prompt.
968
968
969 This is probably useful to developers who manage multiple Python
969 This is probably useful to developers who manage multiple Python
970 versions and don't want to have correspondingly multiple IPython
970 versions and don't want to have correspondingly multiple IPython
971 versions. Note that in this mode, there is no way to pass IPython any
971 versions. Note that in this mode, there is no way to pass IPython any
972 command-line options, as those are trapped first by Python itself.
972 command-line options, as those are trapped first by Python itself.
973
973
974 .. _Embedding:
974 .. _Embedding:
975
975
976 Embedding IPython
976 Embedding IPython
977 =================
977 =================
978
978
979 It is possible to start an IPython instance inside your own Python
979 It is possible to start an IPython instance inside your own Python
980 programs. This allows you to evaluate dynamically the state of your
980 programs. This allows you to evaluate dynamically the state of your
981 code, operate with your variables, analyze them, etc. Note however that
981 code, operate with your variables, analyze them, etc. Note however that
982 any changes you make to values while in the shell do not propagate back
982 any changes you make to values while in the shell do not propagate back
983 to the running code, so it is safe to modify your values because you
983 to the running code, so it is safe to modify your values because you
984 won't break your code in bizarre ways by doing so.
984 won't break your code in bizarre ways by doing so.
985
985
986 This feature allows you to easily have a fully functional python
986 This feature allows you to easily have a fully functional python
987 environment for doing object introspection anywhere in your code with a
987 environment for doing object introspection anywhere in your code with a
988 simple function call. In some cases a simple print statement is enough,
988 simple function call. In some cases a simple print statement is enough,
989 but if you need to do more detailed analysis of a code fragment this
989 but if you need to do more detailed analysis of a code fragment this
990 feature can be very valuable.
990 feature can be very valuable.
991
991
992 It can also be useful in scientific computing situations where it is
992 It can also be useful in scientific computing situations where it is
993 common to need to do some automatic, computationally intensive part and
993 common to need to do some automatic, computationally intensive part and
994 then stop to look at data, plots, etc.
994 then stop to look at data, plots, etc.
995 Opening an IPython instance will give you full access to your data and
995 Opening an IPython instance will give you full access to your data and
996 functions, and you can resume program execution once you are done with
996 functions, and you can resume program execution once you are done with
997 the interactive part (perhaps to stop again later, as many times as
997 the interactive part (perhaps to stop again later, as many times as
998 needed).
998 needed).
999
999
1000 The following code snippet is the bare minimum you need to include in
1000 The following code snippet is the bare minimum you need to include in
1001 your Python programs for this to work (detailed examples follow later)::
1001 your Python programs for this to work (detailed examples follow later)::
1002
1002
1003 from IPython.Shell import IPShellEmbed
1003 from IPython.Shell import IPShellEmbed
1004
1004
1005 ipshell = IPShellEmbed()
1005 ipshell = IPShellEmbed()
1006
1006
1007 ipshell() # this call anywhere in your program will start IPython
1007 ipshell() # this call anywhere in your program will start IPython
1008
1008
1009 You can run embedded instances even in code which is itself being run at
1009 You can run embedded instances even in code which is itself being run at
1010 the IPython interactive prompt with '%run <filename>'. Since it's easy
1010 the IPython interactive prompt with '%run <filename>'. Since it's easy
1011 to get lost as to where you are (in your top-level IPython or in your
1011 to get lost as to where you are (in your top-level IPython or in your
1012 embedded one), it's a good idea in such cases to set the in/out prompts
1012 embedded one), it's a good idea in such cases to set the in/out prompts
1013 to something different for the embedded instances. The code examples
1013 to something different for the embedded instances. The code examples
1014 below illustrate this.
1014 below illustrate this.
1015
1015
1016 You can also have multiple IPython instances in your program and open
1016 You can also have multiple IPython instances in your program and open
1017 them separately, for example with different options for data
1017 them separately, for example with different options for data
1018 presentation. If you close and open the same instance multiple times,
1018 presentation. If you close and open the same instance multiple times,
1019 its prompt counters simply continue from each execution to the next.
1019 its prompt counters simply continue from each execution to the next.
1020
1020
1021 Please look at the docstrings in the Shell.py module for more details on
1021 Please look at the docstrings in the Shell.py module for more details on
1022 the use of this system.
1022 the use of this system.
1023
1023
1024 The following sample file illustrating how to use the embedding
1024 The following sample file illustrating how to use the embedding
1025 functionality is provided in the examples directory as example-embed.py.
1025 functionality is provided in the examples directory as example-embed.py.
1026 It should be fairly self-explanatory::
1026 It should be fairly self-explanatory::
1027
1027
1028
1028
1029 #!/usr/bin/env python
1029 #!/usr/bin/env python
1030
1030
1031 """An example of how to embed an IPython shell into a running program.
1031 """An example of how to embed an IPython shell into a running program.
1032
1032
1033 Please see the documentation in the IPython.Shell module for more details.
1033 Please see the documentation in the IPython.Shell module for more details.
1034
1034
1035 The accompanying file example-embed-short.py has quick code fragments for
1035 The accompanying file example-embed-short.py has quick code fragments for
1036 embedding which you can cut and paste in your code once you understand how
1036 embedding which you can cut and paste in your code once you understand how
1037 things work.
1037 things work.
1038
1038
1039 The code in this file is deliberately extra-verbose, meant for learning."""
1039 The code in this file is deliberately extra-verbose, meant for learning."""
1040
1040
1041 # The basics to get you going:
1041 # The basics to get you going:
1042
1042
1043 # IPython sets the __IPYTHON__ variable so you can know if you have nested
1043 # IPython sets the __IPYTHON__ variable so you can know if you have nested
1044 # copies running.
1044 # copies running.
1045
1045
1046 # Try running this code both at the command line and from inside IPython (with
1046 # Try running this code both at the command line and from inside IPython (with
1047 # %run example-embed.py)
1047 # %run example-embed.py)
1048 try:
1048 try:
1049 __IPYTHON__
1049 __IPYTHON__
1050 except NameError:
1050 except NameError:
1051 nested = 0
1051 nested = 0
1052 args = ['']
1052 args = ['']
1053 else:
1053 else:
1054 print "Running nested copies of IPython."
1054 print "Running nested copies of IPython."
1055 print "The prompts for the nested copy have been modified"
1055 print "The prompts for the nested copy have been modified"
1056 nested = 1
1056 nested = 1
1057 # what the embedded instance will see as sys.argv:
1057 # what the embedded instance will see as sys.argv:
1058 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
1058 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
1059 '-po','Out<\\#>: ','-nosep']
1059 '-po','Out<\\#>: ','-nosep']
1060
1060
1061 # First import the embeddable shell class
1061 # First import the embeddable shell class
1062 from IPython.Shell import IPShellEmbed
1062 from IPython.Shell import IPShellEmbed
1063
1063
1064 # Now create an instance of the embeddable shell. The first argument is a
1064 # Now create an instance of the embeddable shell. The first argument is a
1065 # string with options exactly as you would type them if you were starting
1065 # string with options exactly as you would type them if you were starting
1066 # IPython at the system command line. Any parameters you want to define for
1066 # IPython at the system command line. Any parameters you want to define for
1067 # configuration can thus be specified here.
1067 # configuration can thus be specified here.
1068 ipshell = IPShellEmbed(args,
1068 ipshell = IPShellEmbed(args,
1069 banner = 'Dropping into IPython',
1069 banner = 'Dropping into IPython',
1070 exit_msg = 'Leaving Interpreter, back to program.')
1070 exit_msg = 'Leaving Interpreter, back to program.')
1071
1071
1072 # Make a second instance, you can have as many as you want.
1072 # Make a second instance, you can have as many as you want.
1073 if nested:
1073 if nested:
1074 args[1] = 'In2<\\#>'
1074 args[1] = 'In2<\\#>'
1075 else:
1075 else:
1076 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
1076 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
1077 '-po','Out<\\#>: ','-nosep']
1077 '-po','Out<\\#>: ','-nosep']
1078 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
1078 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
1079
1079
1080 print '\nHello. This is printed from the main controller program.\n'
1080 print '\nHello. This is printed from the main controller program.\n'
1081
1081
1082 # You can then call ipshell() anywhere you need it (with an optional
1082 # You can then call ipshell() anywhere you need it (with an optional
1083 # message):
1083 # message):
1084 ipshell('***Called from top level. '
1084 ipshell('***Called from top level. '
1085 'Hit Ctrl-D to exit interpreter and continue program.\n'
1085 'Hit Ctrl-D to exit interpreter and continue program.\n'
1086 'Note that if you use %kill_embedded, you can fully deactivate\n'
1086 'Note that if you use %kill_embedded, you can fully deactivate\n'
1087 'This embedded instance so it will never turn on again')
1087 'This embedded instance so it will never turn on again')
1088
1088
1089 print '\nBack in caller program, moving along...\n'
1089 print '\nBack in caller program, moving along...\n'
1090
1090
1091 #---------------------------------------------------------------------------
1091 #---------------------------------------------------------------------------
1092 # More details:
1092 # More details:
1093
1093
1094 # IPShellEmbed instances don't print the standard system banner and
1094 # IPShellEmbed instances don't print the standard system banner and
1095 # messages. The IPython banner (which actually may contain initialization
1095 # messages. The IPython banner (which actually may contain initialization
1096 # messages) is available as <instance>.IP.BANNER in case you want it.
1096 # messages) is available as <instance>.IP.BANNER in case you want it.
1097
1097
1098 # IPShellEmbed instances print the following information everytime they
1098 # IPShellEmbed instances print the following information everytime they
1099 # start:
1099 # start:
1100
1100
1101 # - A global startup banner.
1101 # - A global startup banner.
1102
1102
1103 # - A call-specific header string, which you can use to indicate where in the
1103 # - A call-specific header string, which you can use to indicate where in the
1104 # execution flow the shell is starting.
1104 # execution flow the shell is starting.
1105
1105
1106 # They also print an exit message every time they exit.
1106 # They also print an exit message every time they exit.
1107
1107
1108 # Both the startup banner and the exit message default to None, and can be set
1108 # Both the startup banner and the exit message default to None, and can be set
1109 # either at the instance constructor or at any other time with the
1109 # either at the instance constructor or at any other time with the
1110 # set_banner() and set_exit_msg() methods.
1110 # set_banner() and set_exit_msg() methods.
1111
1111
1112 # The shell instance can be also put in 'dummy' mode globally or on a per-call
1112 # The shell instance can be also put in 'dummy' mode globally or on a per-call
1113 # basis. This gives you fine control for debugging without having to change
1113 # basis. This gives you fine control for debugging without having to change
1114 # code all over the place.
1114 # code all over the place.
1115
1115
1116 # The code below illustrates all this.
1116 # The code below illustrates all this.
1117
1117
1118
1118
1119 # This is how the global banner and exit_msg can be reset at any point
1119 # This is how the global banner and exit_msg can be reset at any point
1120 ipshell.set_banner('Entering interpreter - New Banner')
1120 ipshell.set_banner('Entering interpreter - New Banner')
1121 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
1121 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
1122
1122
1123 def foo(m):
1123 def foo(m):
1124 s = 'spam'
1124 s = 'spam'
1125 ipshell('***In foo(). Try @whos, or print s or m:')
1125 ipshell('***In foo(). Try @whos, or print s or m:')
1126 print 'foo says m = ',m
1126 print 'foo says m = ',m
1127
1127
1128 def bar(n):
1128 def bar(n):
1129 s = 'eggs'
1129 s = 'eggs'
1130 ipshell('***In bar(). Try @whos, or print s or n:')
1130 ipshell('***In bar(). Try @whos, or print s or n:')
1131 print 'bar says n = ',n
1131 print 'bar says n = ',n
1132
1132
1133 # Some calls to the above functions which will trigger IPython:
1133 # Some calls to the above functions which will trigger IPython:
1134 print 'Main program calling foo("eggs")\n'
1134 print 'Main program calling foo("eggs")\n'
1135 foo('eggs')
1135 foo('eggs')
1136
1136
1137 # The shell can be put in 'dummy' mode where calls to it silently return. This
1137 # The shell can be put in 'dummy' mode where calls to it silently return. This
1138 # allows you, for example, to globally turn off debugging for a program with a
1138 # allows you, for example, to globally turn off debugging for a program with a
1139 # single call.
1139 # single call.
1140 ipshell.set_dummy_mode(1)
1140 ipshell.set_dummy_mode(1)
1141 print '\nTrying to call IPython which is now "dummy":'
1141 print '\nTrying to call IPython which is now "dummy":'
1142 ipshell()
1142 ipshell()
1143 print 'Nothing happened...'
1143 print 'Nothing happened...'
1144 # The global 'dummy' mode can still be overridden for a single call
1144 # The global 'dummy' mode can still be overridden for a single call
1145 print '\nOverriding dummy mode manually:'
1145 print '\nOverriding dummy mode manually:'
1146 ipshell(dummy=0)
1146 ipshell(dummy=0)
1147
1147
1148 # Reactivate the IPython shell
1148 # Reactivate the IPython shell
1149 ipshell.set_dummy_mode(0)
1149 ipshell.set_dummy_mode(0)
1150
1150
1151 print 'You can even have multiple embedded instances:'
1151 print 'You can even have multiple embedded instances:'
1152 ipshell2()
1152 ipshell2()
1153
1153
1154 print '\nMain program calling bar("spam")\n'
1154 print '\nMain program calling bar("spam")\n'
1155 bar('spam')
1155 bar('spam')
1156
1156
1157 print 'Main program finished. Bye!'
1157 print 'Main program finished. Bye!'
1158
1158
1159 #********************** End of file <example-embed.py> ***********************
1159 #********************** End of file <example-embed.py> ***********************
1160
1160
1161 Once you understand how the system functions, you can use the following
1161 Once you understand how the system functions, you can use the following
1162 code fragments in your programs which are ready for cut and paste::
1162 code fragments in your programs which are ready for cut and paste::
1163
1163
1164
1164
1165 """Quick code snippets for embedding IPython into other programs.
1165 """Quick code snippets for embedding IPython into other programs.
1166
1166
1167 See example-embed.py for full details, this file has the bare minimum code for
1167 See example-embed.py for full details, this file has the bare minimum code for
1168 cut and paste use once you understand how to use the system."""
1168 cut and paste use once you understand how to use the system."""
1169
1169
1170 #---------------------------------------------------------------------------
1170 #---------------------------------------------------------------------------
1171 # This code loads IPython but modifies a few things if it detects it's running
1171 # This code loads IPython but modifies a few things if it detects it's running
1172 # embedded in another IPython session (helps avoid confusion)
1172 # embedded in another IPython session (helps avoid confusion)
1173
1173
1174 try:
1174 try:
1175 __IPYTHON__
1175 __IPYTHON__
1176 except NameError:
1176 except NameError:
1177 argv = ['']
1177 argv = ['']
1178 banner = exit_msg = ''
1178 banner = exit_msg = ''
1179 else:
1179 else:
1180 # Command-line options for IPython (a list like sys.argv)
1180 # Command-line options for IPython (a list like sys.argv)
1181 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
1181 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
1182 banner = '*** Nested interpreter ***'
1182 banner = '*** Nested interpreter ***'
1183 exit_msg = '*** Back in main IPython ***'
1183 exit_msg = '*** Back in main IPython ***'
1184
1184
1185 # First import the embeddable shell class
1185 # First import the embeddable shell class
1186 from IPython.Shell import IPShellEmbed
1186 from IPython.Shell import IPShellEmbed
1187 # Now create the IPython shell instance. Put ipshell() anywhere in your code
1187 # Now create the IPython shell instance. Put ipshell() anywhere in your code
1188 # where you want it to open.
1188 # where you want it to open.
1189 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
1189 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
1190
1190
1191 #---------------------------------------------------------------------------
1191 #---------------------------------------------------------------------------
1192 # This code will load an embeddable IPython shell always with no changes for
1192 # This code will load an embeddable IPython shell always with no changes for
1193 # nested embededings.
1193 # nested embededings.
1194
1194
1195 from IPython.Shell import IPShellEmbed
1195 from IPython.Shell import IPShellEmbed
1196 ipshell = IPShellEmbed()
1196 ipshell = IPShellEmbed()
1197 # Now ipshell() will open IPython anywhere in the code.
1197 # Now ipshell() will open IPython anywhere in the code.
1198
1198
1199 #---------------------------------------------------------------------------
1199 #---------------------------------------------------------------------------
1200 # This code loads an embeddable shell only if NOT running inside
1200 # This code loads an embeddable shell only if NOT running inside
1201 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
1201 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
1202 # dummy function.
1202 # dummy function.
1203
1203
1204 try:
1204 try:
1205 __IPYTHON__
1205 __IPYTHON__
1206 except NameError:
1206 except NameError:
1207 from IPython.Shell import IPShellEmbed
1207 from IPython.Shell import IPShellEmbed
1208 ipshell = IPShellEmbed()
1208 ipshell = IPShellEmbed()
1209 # Now ipshell() will open IPython anywhere in the code
1209 # Now ipshell() will open IPython anywhere in the code
1210 else:
1210 else:
1211 # Define a dummy ipshell() so the same code doesn't crash inside an
1211 # Define a dummy ipshell() so the same code doesn't crash inside an
1212 # interactive IPython
1212 # interactive IPython
1213 def ipshell(): pass
1213 def ipshell(): pass
1214
1214
1215 #******************* End of file <example-embed-short.py> ********************
1215 #******************* End of file <example-embed-short.py> ********************
1216
1216
1217 Using the Python debugger (pdb)
1217 Using the Python debugger (pdb)
1218 ===============================
1218 ===============================
1219
1219
1220 Running entire programs via pdb
1220 Running entire programs via pdb
1221 -------------------------------
1221 -------------------------------
1222
1222
1223 pdb, the Python debugger, is a powerful interactive debugger which
1223 pdb, the Python debugger, is a powerful interactive debugger which
1224 allows you to step through code, set breakpoints, watch variables,
1224 allows you to step through code, set breakpoints, watch variables,
1225 etc. IPython makes it very easy to start any script under the control
1225 etc. IPython makes it very easy to start any script under the control
1226 of pdb, regardless of whether you have wrapped it into a 'main()'
1226 of pdb, regardless of whether you have wrapped it into a 'main()'
1227 function or not. For this, simply type '%run -d myscript' at an
1227 function or not. For this, simply type '%run -d myscript' at an
1228 IPython prompt. See the %run command's documentation (via '%run?' or
1228 IPython prompt. See the %run command's documentation (via '%run?' or
1229 in Sec. magic_ for more details, including how to control where pdb
1229 in Sec. magic_ for more details, including how to control where pdb
1230 will stop execution first.
1230 will stop execution first.
1231
1231
1232 For more information on the use of the pdb debugger, read the included
1232 For more information on the use of the pdb debugger, read the included
1233 pdb.doc file (part of the standard Python distribution). On a stock
1233 pdb.doc file (part of the standard Python distribution). On a stock
1234 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1234 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1235 easiest way to read it is by using the help() function of the pdb module
1235 easiest way to read it is by using the help() function of the pdb module
1236 as follows (in an IPython prompt):
1236 as follows (in an IPython prompt):
1237
1237
1238 In [1]: import pdb
1238 In [1]: import pdb
1239 In [2]: pdb.help()
1239 In [2]: pdb.help()
1240
1240
1241 This will load the pdb.doc document in a file viewer for you automatically.
1241 This will load the pdb.doc document in a file viewer for you automatically.
1242
1242
1243
1243
1244 Automatic invocation of pdb on exceptions
1244 Automatic invocation of pdb on exceptions
1245 -----------------------------------------
1245 -----------------------------------------
1246
1246
1247 IPython, if started with the -pdb option (or if the option is set in
1247 IPython, if started with the -pdb option (or if the option is set in
1248 your rc file) can call the Python pdb debugger every time your code
1248 your rc file) can call the Python pdb debugger every time your code
1249 triggers an uncaught exception. This feature
1249 triggers an uncaught exception. This feature
1250 can also be toggled at any time with the %pdb magic command. This can be
1250 can also be toggled at any time with the %pdb magic command. This can be
1251 extremely useful in order to find the origin of subtle bugs, because pdb
1251 extremely useful in order to find the origin of subtle bugs, because pdb
1252 opens up at the point in your code which triggered the exception, and
1252 opens up at the point in your code which triggered the exception, and
1253 while your program is at this point 'dead', all the data is still
1253 while your program is at this point 'dead', all the data is still
1254 available and you can walk up and down the stack frame and understand
1254 available and you can walk up and down the stack frame and understand
1255 the origin of the problem.
1255 the origin of the problem.
1256
1256
1257 Furthermore, you can use these debugging facilities both with the
1257 Furthermore, you can use these debugging facilities both with the
1258 embedded IPython mode and without IPython at all. For an embedded shell
1258 embedded IPython mode and without IPython at all. For an embedded shell
1259 (see sec. Embedding_), simply call the constructor with
1259 (see sec. Embedding_), simply call the constructor with
1260 '-pdb' in the argument string and automatically pdb will be called if an
1260 '-pdb' in the argument string and automatically pdb will be called if an
1261 uncaught exception is triggered by your code.
1261 uncaught exception is triggered by your code.
1262
1262
1263 For stand-alone use of the feature in your programs which do not use
1263 For stand-alone use of the feature in your programs which do not use
1264 IPython at all, put the following lines toward the top of your 'main'
1264 IPython at all, put the following lines toward the top of your 'main'
1265 routine::
1265 routine::
1266
1266
1267 import sys
1267 import sys
1268 from IPython.core import ultratb
1268 from IPython.core import ultratb
1269 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1269 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1270 color_scheme='Linux', call_pdb=1)
1270 color_scheme='Linux', call_pdb=1)
1271
1271
1272 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1272 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1273 detailed or normal tracebacks respectively. The color_scheme keyword can
1273 detailed or normal tracebacks respectively. The color_scheme keyword can
1274 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1274 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1275 options which can be set in IPython with -colors and -xmode.
1275 options which can be set in IPython with -colors and -xmode.
1276
1276
1277 This will give any of your programs detailed, colored tracebacks with
1277 This will give any of your programs detailed, colored tracebacks with
1278 automatic invocation of pdb.
1278 automatic invocation of pdb.
1279
1279
1280
1280
1281 Extensions for syntax processing
1281 Extensions for syntax processing
1282 ================================
1282 ================================
1283
1283
1284 This isn't for the faint of heart, because the potential for breaking
1284 This isn't for the faint of heart, because the potential for breaking
1285 things is quite high. But it can be a very powerful and useful feature.
1285 things is quite high. But it can be a very powerful and useful feature.
1286 In a nutshell, you can redefine the way IPython processes the user input
1286 In a nutshell, you can redefine the way IPython processes the user input
1287 line to accept new, special extensions to the syntax without needing to
1287 line to accept new, special extensions to the syntax without needing to
1288 change any of IPython's own code.
1288 change any of IPython's own code.
1289
1289
1290 In the IPython/extensions directory you will find some examples
1290 In the IPython/extensions directory you will find some examples
1291 supplied, which we will briefly describe now. These can be used 'as is'
1291 supplied, which we will briefly describe now. These can be used 'as is'
1292 (and both provide very useful functionality), or you can use them as a
1292 (and both provide very useful functionality), or you can use them as a
1293 starting point for writing your own extensions.
1293 starting point for writing your own extensions.
1294
1294
1295
1295
1296 Pasting of code starting with '>>> ' or '... '
1296 Pasting of code starting with '>>> ' or '... '
1297 ----------------------------------------------
1297 ----------------------------------------------
1298
1298
1299 In the python tutorial it is common to find code examples which have
1299 In the python tutorial it is common to find code examples which have
1300 been taken from real python sessions. The problem with those is that all
1300 been taken from real python sessions. The problem with those is that all
1301 the lines begin with either '>>> ' or '... ', which makes it impossible
1301 the lines begin with either '>>> ' or '... ', which makes it impossible
1302 to paste them all at once. One must instead do a line by line manual
1302 to paste them all at once. One must instead do a line by line manual
1303 copying, carefully removing the leading extraneous characters.
1303 copying, carefully removing the leading extraneous characters.
1304
1304
1305 This extension identifies those starting characters and removes them
1305 This extension identifies those starting characters and removes them
1306 from the input automatically, so that one can paste multi-line examples
1306 from the input automatically, so that one can paste multi-line examples
1307 directly into IPython, saving a lot of time. Please look at the file
1307 directly into IPython, saving a lot of time. Please look at the file
1308 InterpreterPasteInput.py in the IPython/extensions directory for details
1308 InterpreterPasteInput.py in the IPython/extensions directory for details
1309 on how this is done.
1309 on how this is done.
1310
1310
1311 IPython comes with a special profile enabling this feature, called
1311 IPython comes with a special profile enabling this feature, called
1312 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1312 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1313 will be available. In a normal IPython session you can activate the
1313 will be available. In a normal IPython session you can activate the
1314 feature by importing the corresponding module with:
1314 feature by importing the corresponding module with:
1315 In [1]: import IPython.extensions.InterpreterPasteInput
1315 In [1]: import IPython.extensions.InterpreterPasteInput
1316
1316
1317 The following is a 'screenshot' of how things work when this extension
1317 The following is a 'screenshot' of how things work when this extension
1318 is on, copying an example from the standard tutorial::
1318 is on, copying an example from the standard tutorial::
1319
1319
1320 IPython profile: tutorial
1320 IPython profile: tutorial
1321
1321
1322 *** Pasting of code with ">>>" or "..." has been enabled.
1322 *** Pasting of code with ">>>" or "..." has been enabled.
1323
1323
1324 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1324 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1325 ...: ... """Return a list containing the Fibonacci series up to
1325 ...: ... """Return a list containing the Fibonacci series up to
1326 n."""
1326 n."""
1327 ...: ... result = []
1327 ...: ... result = []
1328 ...: ... a, b = 0, 1
1328 ...: ... a, b = 0, 1
1329 ...: ... while b < n:
1329 ...: ... while b < n:
1330 ...: ... result.append(b) # see below
1330 ...: ... result.append(b) # see below
1331 ...: ... a, b = b, a+b
1331 ...: ... a, b = b, a+b
1332 ...: ... return result
1332 ...: ... return result
1333 ...:
1333 ...:
1334
1334
1335 In [2]: fib2(10)
1335 In [2]: fib2(10)
1336 Out[2]: [1, 1, 2, 3, 5, 8]
1336 Out[2]: [1, 1, 2, 3, 5, 8]
1337
1337
1338 Note that as currently written, this extension does not recognize
1338 Note that as currently written, this extension does not recognize
1339 IPython's prompts for pasting. Those are more complicated, since the
1339 IPython's prompts for pasting. Those are more complicated, since the
1340 user can change them very easily, they involve numbers and can vary in
1340 user can change them very easily, they involve numbers and can vary in
1341 length. One could however extract all the relevant information from the
1341 length. One could however extract all the relevant information from the
1342 IPython instance and build an appropriate regular expression. This is
1342 IPython instance and build an appropriate regular expression. This is
1343 left as an exercise for the reader.
1343 left as an exercise for the reader.
1344
1344
1345
1345
1346 Input of physical quantities with units
1346 Input of physical quantities with units
1347 ---------------------------------------
1347 ---------------------------------------
1348
1348
1349 The module PhysicalQInput allows a simplified form of input for physical
1349 The module PhysicalQInput allows a simplified form of input for physical
1350 quantities with units. This file is meant to be used in conjunction with
1350 quantities with units. This file is meant to be used in conjunction with
1351 the PhysicalQInteractive module (in the same directory) and
1351 the PhysicalQInteractive module (in the same directory) and
1352 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1352 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1353 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1353 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1354
1354
1355 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1355 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1356 but these must be declared as instances of a class. For example, to
1356 but these must be declared as instances of a class. For example, to
1357 define v as a velocity of 3 m/s, normally you would write::
1357 define v as a velocity of 3 m/s, normally you would write::
1358
1358
1359 In [1]: v = PhysicalQuantity(3,'m/s')
1359 In [1]: v = PhysicalQuantity(3,'m/s')
1360
1360
1361 Using the PhysicalQ_Input extension this can be input instead as:
1361 Using the PhysicalQ_Input extension this can be input instead as:
1362 In [1]: v = 3 m/s
1362 In [1]: v = 3 m/s
1363 which is much more convenient for interactive use (even though it is
1363 which is much more convenient for interactive use (even though it is
1364 blatantly invalid Python syntax).
1364 blatantly invalid Python syntax).
1365
1365
1366 The physics profile supplied with IPython (enabled via 'ipython -p
1366 The physics profile supplied with IPython (enabled via 'ipython -p
1367 physics') uses these extensions, which you can also activate with:
1367 physics') uses these extensions, which you can also activate with:
1368
1368
1369 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1369 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1370 from IPython.extensions.PhysicalQInteractive import *
1370 from IPython.extensions.PhysicalQInteractive import *
1371 import IPython.extensions.PhysicalQInput
1371 import IPython.extensions.PhysicalQInput
1372
1372
1373 .. _gui_support:
1373 .. _gui_support:
1374
1374
1375 GUI event loop support support
1375 GUI event loop support support
1376 ==============================
1376 ==============================
1377
1377
1378 .. versionadded:: 0.11
1378 .. versionadded:: 0.11
1379 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1379 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1380
1380
1381 IPython has excellent support for working interactively with Graphical User
1381 IPython has excellent support for working interactively with Graphical User
1382 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1382 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1383 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1383 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1384 is extremely robust compared to our previous threaded based version. The
1384 is extremely robust compared to our previous threaded based version. The
1385 advantages of
1385 advantages of
1386
1386
1387 * GUIs can be enabled and disabled dynamically at runtime.
1387 * GUIs can be enabled and disabled dynamically at runtime.
1388 * The active GUI can be switched dynamically at runtime.
1388 * The active GUI can be switched dynamically at runtime.
1389 * In some cases, multiple GUIs can run simultaneously with no problems.
1389 * In some cases, multiple GUIs can run simultaneously with no problems.
1390 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1390 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1391 all of these things.
1391 all of these things.
1392
1392
1393 For users, enabling GUI event loop integration is simple. You simple use the
1393 For users, enabling GUI event loop integration is simple. You simple use the
1394 ``%gui`` magic as follows::
1394 ``%gui`` magic as follows::
1395
1395
1396 %gui [-a] [GUINAME]
1396 %gui [-a] [GUINAME]
1397
1397
1398 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1398 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1399 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1399 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1400 create and return a running application object for the selected GUI toolkit.
1400 create and return a running application object for the selected GUI toolkit.
1401
1401
1402 This to use wxPython interactively and create a running :class:`wx.App`
1402 This to use wxPython interactively and create a running :class:`wx.App`
1403 object, do::
1403 object, do::
1404
1404
1405 %gui -a wx
1405 %gui -a wx
1406
1406
1407 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1407 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1408 see :ref:`this section <matplotlib_support>`.
1408 see :ref:`this section <matplotlib_support>`.
1409
1409
1410 For developers that want to use IPython's GUI event loop integration in
1410 For developers that want to use IPython's GUI event loop integration in
1411 the form of a library, the capabilities are exposed in library form
1411 the form of a library, the capabilities are exposed in library form
1412 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1412 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1413 module docstrings for more information.
1413 module docstrings for more information.
1414
1414
1415 In addition, we also have a number of examples in our source directory
1416 :file:`docs/examples/lib` that demonstrate these capabilities.
1417
1415 .. _matplotlib_support:
1418 .. _matplotlib_support:
1416
1419
1417 Plotting with matplotlib
1420 Plotting with matplotlib
1418 ========================
1421 ========================
1419
1422
1420
1423
1421 `Matplotlib`_ provides high quality 2D and
1424 `Matplotlib`_ provides high quality 2D and
1422 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1425 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1423 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1426 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1424 number of commands useful for scientific computing, all with a syntax
1427 number of commands useful for scientific computing, all with a syntax
1425 compatible with that of the popular Matlab program.
1428 compatible with that of the popular Matlab program.
1426
1429
1427 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1430 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1428 automates the integration of Matplotlib with IPython. We are still in the
1431 automates the integration of Matplotlib with IPython. We are still in the
1429 process of working with the Matplotlib developers to finalize the new pylab
1432 process of working with the Matplotlib developers to finalize the new pylab
1430 API, but for now you can use Matplotlib interactively using the following
1433 API, but for now you can use Matplotlib interactively using the following
1431 commands::
1434 commands::
1432
1435
1433 %gui -a wx
1436 %gui -a wx
1434 import matplotlib
1437 import matplotlib
1435 matplotlib.use('wxagg')
1438 matplotlib.use('wxagg')
1436 from matplotlib import pylab
1439 from matplotlib import pylab
1437 pylab.interactive(True)
1440 pylab.interactive(True)
1438
1441
1439 All of this will soon be automated as Matplotlib beings to include
1442 All of this will soon be automated as Matplotlib beings to include
1440 new logic that uses our new GUI support.
1443 new logic that uses our new GUI support.
1441
1444
1442 .. _interactive_demos:
1445 .. _interactive_demos:
1443
1446
1444 Interactive demos with IPython
1447 Interactive demos with IPython
1445 ==============================
1448 ==============================
1446
1449
1447 IPython ships with a basic system for running scripts interactively in
1450 IPython ships with a basic system for running scripts interactively in
1448 sections, useful when presenting code to audiences. A few tags embedded
1451 sections, useful when presenting code to audiences. A few tags embedded
1449 in comments (so that the script remains valid Python code) divide a file
1452 in comments (so that the script remains valid Python code) divide a file
1450 into separate blocks, and the demo can be run one block at a time, with
1453 into separate blocks, and the demo can be run one block at a time, with
1451 IPython printing (with syntax highlighting) the block before executing
1454 IPython printing (with syntax highlighting) the block before executing
1452 it, and returning to the interactive prompt after each block. The
1455 it, and returning to the interactive prompt after each block. The
1453 interactive namespace is updated after each block is run with the
1456 interactive namespace is updated after each block is run with the
1454 contents of the demo's namespace.
1457 contents of the demo's namespace.
1455
1458
1456 This allows you to show a piece of code, run it and then execute
1459 This allows you to show a piece of code, run it and then execute
1457 interactively commands based on the variables just created. Once you
1460 interactively commands based on the variables just created. Once you
1458 want to continue, you simply execute the next block of the demo. The
1461 want to continue, you simply execute the next block of the demo. The
1459 following listing shows the markup necessary for dividing a script into
1462 following listing shows the markup necessary for dividing a script into
1460 sections for execution as a demo::
1463 sections for execution as a demo::
1461
1464
1462
1465
1463 """A simple interactive demo to illustrate the use of IPython's Demo class.
1466 """A simple interactive demo to illustrate the use of IPython's Demo class.
1464
1467
1465 Any python script can be run as a demo, but that does little more than showing
1468 Any python script can be run as a demo, but that does little more than showing
1466 it on-screen, syntax-highlighted in one shot. If you add a little simple
1469 it on-screen, syntax-highlighted in one shot. If you add a little simple
1467 markup, you can stop at specified intervals and return to the ipython prompt,
1470 markup, you can stop at specified intervals and return to the ipython prompt,
1468 resuming execution later.
1471 resuming execution later.
1469 """
1472 """
1470
1473
1471 print 'Hello, welcome to an interactive IPython demo.'
1474 print 'Hello, welcome to an interactive IPython demo.'
1472 print 'Executing this block should require confirmation before proceeding,'
1475 print 'Executing this block should require confirmation before proceeding,'
1473 print 'unless auto_all has been set to true in the demo object'
1476 print 'unless auto_all has been set to true in the demo object'
1474
1477
1475 # The mark below defines a block boundary, which is a point where IPython will
1478 # The mark below defines a block boundary, which is a point where IPython will
1476 # stop execution and return to the interactive prompt.
1479 # stop execution and return to the interactive prompt.
1477 # Note that in actual interactive execution,
1480 # Note that in actual interactive execution,
1478 # <demo> --- stop ---
1481 # <demo> --- stop ---
1479
1482
1480 x = 1
1483 x = 1
1481 y = 2
1484 y = 2
1482
1485
1483 # <demo> --- stop ---
1486 # <demo> --- stop ---
1484
1487
1485 # the mark below makes this block as silent
1488 # the mark below makes this block as silent
1486 # <demo> silent
1489 # <demo> silent
1487
1490
1488 print 'This is a silent block, which gets executed but not printed.'
1491 print 'This is a silent block, which gets executed but not printed.'
1489
1492
1490 # <demo> --- stop ---
1493 # <demo> --- stop ---
1491 # <demo> auto
1494 # <demo> auto
1492 print 'This is an automatic block.'
1495 print 'This is an automatic block.'
1493 print 'It is executed without asking for confirmation, but printed.'
1496 print 'It is executed without asking for confirmation, but printed.'
1494 z = x+y
1497 z = x+y
1495
1498
1496 print 'z=',x
1499 print 'z=',x
1497
1500
1498 # <demo> --- stop ---
1501 # <demo> --- stop ---
1499 # This is just another normal block.
1502 # This is just another normal block.
1500 print 'z is now:', z
1503 print 'z is now:', z
1501
1504
1502 print 'bye!'
1505 print 'bye!'
1503
1506
1504 In order to run a file as a demo, you must first make a Demo object out
1507 In order to run a file as a demo, you must first make a Demo object out
1505 of it. If the file is named myscript.py, the following code will make a
1508 of it. If the file is named myscript.py, the following code will make a
1506 demo::
1509 demo::
1507
1510
1508 from IPython.demo import Demo
1511 from IPython.demo import Demo
1509
1512
1510 mydemo = Demo('myscript.py')
1513 mydemo = Demo('myscript.py')
1511
1514
1512 This creates the mydemo object, whose blocks you run one at a time by
1515 This creates the mydemo object, whose blocks you run one at a time by
1513 simply calling the object with no arguments. If you have autocall active
1516 simply calling the object with no arguments. If you have autocall active
1514 in IPython (the default), all you need to do is type::
1517 in IPython (the default), all you need to do is type::
1515
1518
1516 mydemo
1519 mydemo
1517
1520
1518 and IPython will call it, executing each block. Demo objects can be
1521 and IPython will call it, executing each block. Demo objects can be
1519 restarted, you can move forward or back skipping blocks, re-execute the
1522 restarted, you can move forward or back skipping blocks, re-execute the
1520 last block, etc. Simply use the Tab key on a demo object to see its
1523 last block, etc. Simply use the Tab key on a demo object to see its
1521 methods, and call '?' on them to see their docstrings for more usage
1524 methods, and call '?' on them to see their docstrings for more usage
1522 details. In addition, the demo module itself contains a comprehensive
1525 details. In addition, the demo module itself contains a comprehensive
1523 docstring, which you can access via::
1526 docstring, which you can access via::
1524
1527
1525 from IPython import demo
1528 from IPython import demo
1526
1529
1527 demo?
1530 demo?
1528
1531
1529 Limitations: It is important to note that these demos are limited to
1532 Limitations: It is important to note that these demos are limited to
1530 fairly simple uses. In particular, you can not put division marks in
1533 fairly simple uses. In particular, you can not put division marks in
1531 indented code (loops, if statements, function definitions, etc.)
1534 indented code (loops, if statements, function definitions, etc.)
1532 Supporting something like this would basically require tracking the
1535 Supporting something like this would basically require tracking the
1533 internal execution state of the Python interpreter, so only top-level
1536 internal execution state of the Python interpreter, so only top-level
1534 divisions are allowed. If you want to be able to open an IPython
1537 divisions are allowed. If you want to be able to open an IPython
1535 instance at an arbitrary point in a program, you can use IPython's
1538 instance at an arbitrary point in a program, you can use IPython's
1536 embedding facilities, described in detail in Sec. 9
1539 embedding facilities, described in detail in Sec. 9
1537
1540
1538 .. [Matplotlib] Matplotlib. http://matplotlib.sourceforge.net
1541 .. [Matplotlib] Matplotlib. http://matplotlib.sourceforge.net
1539
1542
General Comments 0
You need to be logged in to leave comments. Login now