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