##// END OF EJS Templates
Merging upstream changes from inputhook and config-refactor....
Brian Granger -
r2224:11a6689b merge
parent child Browse files
Show More
@@ -0,0 +1,35 b''
1 #!/usr/bin/env python
2 """Simple GTK example to manually test event loop integration.
3
4 This is meant to run tests manually in ipython as:
5
6 In [5]: %gui gtk
7
8 In [6]: %run gui-gtk.py
9 """
10
11
12 import pygtk
13 pygtk.require('2.0')
14 import gtk
15
16
17 def hello_world(wigdet, data=None):
18 print "Hello World"
19
20 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
21 button = gtk.Button("Hello World")
22 button.connect("clicked", hello_world, None)
23
24 window.add(self.button)
25 button.show()
26 window.show()
27
28 try:
29 from IPython.lib.inputhook import appstart_gtk
30 appstart_gtk()
31 except ImportError:
32 gtk.main()
33
34
35
@@ -0,0 +1,54 b''
1 """Test the new %gui command. Run this in ipython as
2
3 In [1]: %gui [backend]
4
5 In [2]: %run switchgui [backend]
6
7 where the optional backend can be one of: qt4, gtk, tk, wx.
8
9 Because of subtle difference in how Matplotlib handles the different GUI
10 toolkits (in things like draw and show), minor modifications to this script
11 have to be made for Tk to get it to work with the 0.99 and below releases
12 of Matplotlib. However, in the future, Matplotlib should be able to have
13 similar logic for all the toolkits, as they are all now using PyOS_InputHook.
14 """
15
16 import sys
17 import time
18
19 from IPython.lib import inputhook
20
21 gui = inputhook.current_gui()
22 if gui is None:
23 gui = 'qt4'
24 inputhook.enable_qt4(app=True)
25
26 backends = dict(wx='wxagg', qt4='qt4agg', gtk='gtkagg', tk='tkagg')
27
28 import matplotlib
29 matplotlib.use(backends[gui])
30 matplotlib.interactive(True)
31
32 import matplotlib
33 from matplotlib import pyplot as plt, mlab, pylab
34 import numpy as np
35
36 from numpy import *
37 from matplotlib.pyplot import *
38
39 x = np.linspace(0,pi,500)
40
41 print "A plot has been created"
42 line, = plot(x,sin(2*x))
43 inputhook.spin() # This has to be removed for Tk
44
45
46 print "Now, we will update the plot..."
47 print
48 for i in range(1,51):
49 print i,
50 sys.stdout.flush()
51 line.set_data(x,sin(x*i))
52 plt.title('i=%d' % i)
53 plt.draw()
54 inputhook.spin() # This has to be removed for Tk
@@ -0,0 +1,40 b''
1 #!/usr/bin/env python
2 """Simple Qt4 example to manually test event loop integration.
3
4 This is meant to run tests manually in ipython as:
5
6 In [5]: %gui qt
7
8 In [6]: %run gui-qt.py
9
10 Ref: Modified from http://zetcode.com/tutorials/pyqt4/firstprograms/
11 """
12
13 import sys
14 from PyQt4 import QtGui, QtCore
15
16 class SimpleWindow(QtGui.QWidget):
17 def __init__(self, parent=None):
18 QtGui.QWidget.__init__(self, parent)
19
20 self.setGeometry(300, 300, 200, 80)
21 self.setWindowTitle('Hello World')
22
23 quit = QtGui.QPushButton('Close', self)
24 quit.setGeometry(10, 10, 60, 35)
25
26 self.connect(quit, QtCore.SIGNAL('clicked()'),
27 self, QtCore.SLOT('close()'))
28
29 if __name__ == '__main__':
30 app = QtCore.QCoreApplication.instance()
31 if app is None:
32 app = QtGui.QApplication([])
33
34 sw = SimpleWindow()
35 sw.show()
36
37 try:
38 from IPython import appstart_qt4; appstart_qt4(app)
39 except ImportError:
40 app.exec_()
@@ -0,0 +1,32 b''
1 #!/usr/bin/env python
2 """Simple Tk example to manually test event loop integration.
3
4 This is meant to run tests manually in ipython as:
5
6 In [5]: %gui tk
7
8 In [6]: %run gui-tk.py
9 """
10
11 from Tkinter import *
12
13 class MyApp:
14
15 def __init__(self, root):
16 frame = Frame(root)
17 frame.pack()
18
19 self.button = Button(frame, text="Hello", command=self.hello_world)
20 self.button.pack(side=LEFT)
21
22 def hello_world(self):
23 print "Hello World!"
24
25 root = Tk()
26
27 app = MyApp(root)
28
29 try:
30 from IPython import appstart_tk; appstart_tk(root)
31 except ImportError:
32 root.mainloop()
@@ -0,0 +1,99 b''
1 """A Simple wx example to test IPython's event loop integration.
2
3 To run this do:
4
5 In [5]: %gui wx
6
7 In [6]: %run gui-wx.py
8
9 Ref: Modified from wxPython source code wxPython/samples/simple/simple.py
10
11 This example can only be run once in a given IPython session.
12 """
13
14 import wx
15
16
17 class MyFrame(wx.Frame):
18 """
19 This is MyFrame. It just shows a few controls on a wxPanel,
20 and has a simple menu.
21 """
22 def __init__(self, parent, title):
23 wx.Frame.__init__(self, parent, -1, title,
24 pos=(150, 150), size=(350, 200))
25
26 # Create the menubar
27 menuBar = wx.MenuBar()
28
29 # and a menu
30 menu = wx.Menu()
31
32 # add an item to the menu, using \tKeyName automatically
33 # creates an accelerator, the third param is some help text
34 # that will show up in the statusbar
35 menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")
36
37 # bind the menu event to an event handler
38 self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT)
39
40 # and put the menu on the menubar
41 menuBar.Append(menu, "&File")
42 self.SetMenuBar(menuBar)
43
44 self.CreateStatusBar()
45
46 # Now create the Panel to put the other controls on.
47 panel = wx.Panel(self)
48
49 # and a few controls
50 text = wx.StaticText(panel, -1, "Hello World!")
51 text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
52 text.SetSize(text.GetBestSize())
53 btn = wx.Button(panel, -1, "Close")
54 funbtn = wx.Button(panel, -1, "Just for fun...")
55
56 # bind the button events to handlers
57 self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, btn)
58 self.Bind(wx.EVT_BUTTON, self.OnFunButton, funbtn)
59
60 # Use a sizer to layout the controls, stacked vertically and with
61 # a 10 pixel border around each
62 sizer = wx.BoxSizer(wx.VERTICAL)
63 sizer.Add(text, 0, wx.ALL, 10)
64 sizer.Add(btn, 0, wx.ALL, 10)
65 sizer.Add(funbtn, 0, wx.ALL, 10)
66 panel.SetSizer(sizer)
67 panel.Layout()
68
69
70 def OnTimeToClose(self, evt):
71 """Event handler for the button click."""
72 print "See ya later!"
73 self.Close()
74
75 def OnFunButton(self, evt):
76 """Event handler for the button click."""
77 print "Having fun yet?"
78
79
80 class MyApp(wx.App):
81 def OnInit(self):
82 frame = MyFrame(None, "Simple wxPython App")
83 self.SetTopWindow(frame)
84
85 print "Print statements go to this stdout window by default."
86
87 frame.Show(True)
88 return True
89
90 app = wx.GetApp()
91 if app is None:
92 app = MyApp(redirect=False, clearSigInt=False)
93
94 try:
95 from IPython.lib.inputhook import appstart_wx
96 appstart_wx(app)
97 except ImportError:
98 app.MainLoop()
99
@@ -1,47 +1,62 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 IPython.
4 IPython.
5
5
6 IPython is a set of tools for interactive and exploratory computing in Python.
6 IPython is a set of tools for interactive and exploratory computing in Python.
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2009 The IPython Development Team
10 # Copyright (C) 2008-2009 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 import os
20 import os
21 import sys
21 import sys
22 from IPython.core import release
22 from IPython.core import release
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Setup everything
25 # Setup everything
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 if sys.version[0:3] < '2.4':
29 if sys.version[0:3] < '2.4':
30 raise ImportError('Python Version 2.4 or above is required for IPython.')
30 raise ImportError('Python Version 2.4 or above is required for IPython.')
31
31
32
32
33 # Make it easy to import extensions - they are always directly on pythonpath.
33 # Make it easy to import extensions - they are always directly on pythonpath.
34 # Therefore, non-IPython modules can be added to extensions directory
34 # Therefore, non-IPython modules can be added to extensions directory
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
36
36
37 from IPython.core import iplib
37 #-----------------------------------------------------------------------------
38 # Setup the top level names
39 #-----------------------------------------------------------------------------
38
40
41 from IPython.core.iplib import InteractiveShell
42 from IPython.core.error import TryNext
43
44 from IPython.lib import (
45 enable_wx, disable_wx,
46 enable_gtk, disable_gtk,
47 enable_qt4, disable_qt4,
48 enable_tk, disable_tk,
49 set_inputhook, clear_inputhook,
50 current_gui, spin,
51 appstart_qt4, appstart_wx,
52 appstart_gtk, appstart_tk
53 )
39
54
40 # Release data
55 # Release data
41 __author__ = ''
56 __author__ = ''
42 for author, email in release.authors.values():
57 for author, email in release.authors.values():
43 __author__ += author + ' <' + email + '>\n'
58 __author__ += author + ' <' + email + '>\n'
44 __license__ = release.license
59 __license__ = release.license
45 __version__ = release.version
60 __version__ = release.version
46 __revision__ = release.revision
61 __revision__ = release.revision
47
62
@@ -1,229 +1,233 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A lightweight component system for IPython.
4 A lightweight component system for IPython.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from copy import deepcopy
23 from copy import deepcopy
24 import datetime
24 import datetime
25 from weakref import WeakValueDictionary
25 from weakref import WeakValueDictionary
26
26
27 from IPython.utils.ipstruct import Struct
27 from IPython.utils.ipstruct import Struct
28 from IPython.utils.traitlets import (
28 from IPython.utils.traitlets import (
29 HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
29 HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
30 )
30 )
31
31
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Helper classes for Components
34 # Helper classes for Components
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37
37
38 class ComponentError(Exception):
38 class ComponentError(Exception):
39 pass
39 pass
40
40
41 class MetaComponentTracker(type):
41 class MetaComponentTracker(type):
42 """A metaclass that tracks instances of Components and its subclasses."""
42 """A metaclass that tracks instances of Components and its subclasses."""
43
43
44 def __init__(cls, name, bases, d):
44 def __init__(cls, name, bases, d):
45 super(MetaComponentTracker, cls).__init__(name, bases, d)
45 super(MetaComponentTracker, cls).__init__(name, bases, d)
46 cls.__instance_refs = WeakValueDictionary()
46 cls.__instance_refs = WeakValueDictionary()
47 cls.__numcreated = 0
47 cls.__numcreated = 0
48
48
49 def __call__(cls, *args, **kw):
49 def __call__(cls, *args, **kw):
50 """Called when *class* is called (instantiated)!!!
50 """Called when *class* is called (instantiated)!!!
51
51
52 When a Component or subclass is instantiated, this is called and
52 When a Component or subclass is instantiated, this is called and
53 the instance is saved in a WeakValueDictionary for tracking.
53 the instance is saved in a WeakValueDictionary for tracking.
54 """
54 """
55
55
56 instance = super(MetaComponentTracker, cls).__call__(*args, **kw)
56 instance = super(MetaComponentTracker, cls).__call__(*args, **kw)
57 for c in cls.__mro__:
57 for c in cls.__mro__:
58 if issubclass(cls, c) and issubclass(c, Component):
58 if issubclass(cls, c) and issubclass(c, Component):
59 c.__numcreated += 1
59 c.__numcreated += 1
60 c.__instance_refs[c.__numcreated] = instance
60 c.__instance_refs[c.__numcreated] = instance
61 return instance
61 return instance
62
62
63 def get_instances(cls, name=None, klass=None, root=None):
63 def get_instances(cls, name=None, root=None):
64 """Get all instances of cls and its subclasses.
64 """Get all instances of cls and its subclasses.
65
65
66 Parameters
66 Parameters
67 ----------
67 ----------
68 name : str
68 name : str
69 Limit to components with this name.
69 Limit to components with this name.
70 klass : class
71 Limit to components having isinstance(component, klass)
72 root : Component or subclass
70 root : Component or subclass
73 Limit to components having this root.
71 Limit to components having this root.
74 """
72 """
75 instances = cls.__instance_refs.values()
73 instances = cls.__instance_refs.values()
76 if name is not None:
74 if name is not None:
77 instances = [i for i in instances if i.name == name]
75 instances = [i for i in instances if i.name == name]
78 if klass is not None:
79 instances = [i for i in instances if isinstance(i, klass)]
80 if root is not None:
76 if root is not None:
81 instances = [i for i in instances if i.root == root]
77 instances = [i for i in instances if i.root == root]
82 return instances
78 return instances
83
79
84 def get_instances_by_condition(cls, call, name=None, klass=None, root=None):
80 def get_instances_by_condition(cls, call, name=None, root=None):
85 """Get all instances of cls, i such that call(i)==True.
81 """Get all instances of cls, i such that call(i)==True.
86
82
87 This also takes the ``name``, ``klass`` and ``root`` arguments of
83 This also takes the ``name`` and ``root`` arguments of
88 :meth:`get_instance`
84 :meth:`get_instance`
89 """
85 """
90 return [i for i in cls.get_instances(name,klass,root) if call(i)]
86 return [i for i in cls.get_instances(name, root) if call(i)]
91
87
92
88
93 class ComponentNameGenerator(object):
89 class ComponentNameGenerator(object):
94 """A Singleton to generate unique component names."""
90 """A Singleton to generate unique component names."""
95
91
96 def __init__(self, prefix):
92 def __init__(self, prefix):
97 self.prefix = prefix
93 self.prefix = prefix
98 self.i = 0
94 self.i = 0
99
95
100 def __call__(self):
96 def __call__(self):
101 count = self.i
97 count = self.i
102 self.i += 1
98 self.i += 1
103 return "%s%s" % (self.prefix, count)
99 return "%s%s" % (self.prefix, count)
104
100
105
101
106 ComponentNameGenerator = ComponentNameGenerator('ipython.component')
102 ComponentNameGenerator = ComponentNameGenerator('ipython.component')
107
103
108
104
109 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
105 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
110 pass
106 pass
111
107
112
108
113 #-----------------------------------------------------------------------------
109 #-----------------------------------------------------------------------------
114 # Component implementation
110 # Component implementation
115 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
116
112
117
113
118 class Component(HasTraitlets):
114 class Component(HasTraitlets):
119
115
120 __metaclass__ = MetaComponent
116 __metaclass__ = MetaComponent
121
117
122 # Traitlets are fun!
118 # Traitlets are fun!
123 config = Instance(Struct,(),{})
119 config = Instance(Struct,(),{})
124 parent = This()
120 parent = This()
125 root = This()
121 root = This()
126 created = None
122 created = None
127
123
128 def __init__(self, parent, name=None, config=None):
124 def __init__(self, parent, name=None, config=None):
129 """Create a component given a parent and possibly and name and config.
125 """Create a component given a parent and possibly and name and config.
130
126
131 Parameters
127 Parameters
132 ----------
128 ----------
133 parent : Component subclass
129 parent : Component subclass
134 The parent in the component graph. The parent is used
130 The parent in the component graph. The parent is used
135 to get the root of the component graph.
131 to get the root of the component graph.
136 name : str
132 name : str
137 The unique name of the component. If empty, then a unique
133 The unique name of the component. If empty, then a unique
138 one will be autogenerated.
134 one will be autogenerated.
139 config : Struct
135 config : Struct
140 If this is empty, self.config = parent.config, otherwise
136 If this is empty, self.config = parent.config, otherwise
141 self.config = config and root.config is ignored. This argument
137 self.config = config and root.config is ignored. This argument
142 should only be used to *override* the automatic inheritance of
138 should only be used to *override* the automatic inheritance of
143 parent.config. If a caller wants to modify parent.config
139 parent.config. If a caller wants to modify parent.config
144 (not override), the caller should make a copy and change
140 (not override), the caller should make a copy and change
145 attributes and then pass the copy to this argument.
141 attributes and then pass the copy to this argument.
146
142
147 Notes
143 Notes
148 -----
144 -----
149 Subclasses of Component must call the :meth:`__init__` method of
145 Subclasses of Component must call the :meth:`__init__` method of
150 :class:`Component` *before* doing anything else and using
146 :class:`Component` *before* doing anything else and using
151 :func:`super`::
147 :func:`super`::
152
148
153 class MyComponent(Component):
149 class MyComponent(Component):
154 def __init__(self, parent, name=None, config=None):
150 def __init__(self, parent, name=None, config=None):
155 super(MyComponent, self).__init__(parent, name, config)
151 super(MyComponent, self).__init__(parent, name, config)
156 # Then any other code you need to finish initialization.
152 # Then any other code you need to finish initialization.
157
153
158 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
154 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
159 attributes are handled properly.
155 attributes are handled properly.
160 """
156 """
161 super(Component, self).__init__()
157 super(Component, self).__init__()
162 self._children = []
158 self._children = []
163 if name is None:
159 if name is None:
164 self.name = ComponentNameGenerator()
160 self.name = ComponentNameGenerator()
165 else:
161 else:
166 self.name = name
162 self.name = name
167 self.root = self # This is the default, it is set when parent is set
163 self.root = self # This is the default, it is set when parent is set
168 self.parent = parent
164 self.parent = parent
169 if config is not None:
165 if config is not None:
170 self.config = deepcopy(config)
166 self.config = deepcopy(config)
171 else:
167 else:
172 if self.parent is not None:
168 if self.parent is not None:
173 self.config = deepcopy(self.parent.config)
169 self.config = deepcopy(self.parent.config)
174
170
175 self.created = datetime.datetime.now()
171 self.created = datetime.datetime.now()
176
172
177 #-------------------------------------------------------------------------
173 #-------------------------------------------------------------------------
178 # Static traitlet notifiations
174 # Static traitlet notifiations
179 #-------------------------------------------------------------------------
175 #-------------------------------------------------------------------------
180
176
181 def _parent_changed(self, name, old, new):
177 def _parent_changed(self, name, old, new):
182 if old is not None:
178 if old is not None:
183 old._remove_child(self)
179 old._remove_child(self)
184 if new is not None:
180 if new is not None:
185 new._add_child(self)
181 new._add_child(self)
186
182
187 if new is None:
183 if new is None:
188 self.root = self
184 self.root = self
189 else:
185 else:
190 self.root = new.root
186 self.root = new.root
191
187
192 def _root_changed(self, name, old, new):
188 def _root_changed(self, name, old, new):
193 if self.parent is None:
189 if self.parent is None:
194 if not (new is self):
190 if not (new is self):
195 raise ComponentError("Root not self, but parent is None.")
191 raise ComponentError("Root not self, but parent is None.")
196 else:
192 else:
197 if not self.parent.root is new:
193 if not self.parent.root is new:
198 raise ComponentError("Error in setting the root attribute: "
194 raise ComponentError("Error in setting the root attribute: "
199 "root != parent.root")
195 "root != parent.root")
200
196
201 def _config_changed(self, name, old, new):
197 def _config_changed(self, name, old, new):
198 """Update all the class traits having a config_key with the config.
199
200 For any class traitlet with a ``config_key`` metadata attribute, we
201 update the traitlet with the value of the corresponding config entry.
202
203 In the future, we might want to do a pop here so stale config info
204 is not passed onto children.
205 """
202 # Get all traitlets with a config_key metadata entry
206 # Get all traitlets with a config_key metadata entry
203 traitlets = self.traitlets('config_key')
207 traitlets = self.traitlets('config_key')
204 for k, v in traitlets.items():
208 for k, v in traitlets.items():
205 try:
209 try:
206 config_value = new[v.get_metadata('config_key')]
210 config_value = new[v.get_metadata('config_key')]
207 except KeyError:
211 except KeyError:
208 pass
212 pass
209 else:
213 else:
210 setattr(self, k, config_value)
214 setattr(self, k, config_value)
211
215
212 @property
216 @property
213 def children(self):
217 def children(self):
214 """A list of all my child components."""
218 """A list of all my child components."""
215 return self._children
219 return self._children
216
220
217 def _remove_child(self, child):
221 def _remove_child(self, child):
218 """A private method for removing children componenets."""
222 """A private method for removing children components."""
219 if child in self._children:
223 if child in self._children:
220 index = self._children.index(child)
224 index = self._children.index(child)
221 del self._children[index]
225 del self._children[index]
222
226
223 def _add_child(self, child):
227 def _add_child(self, child):
224 """A private method for adding children componenets."""
228 """A private method for adding children components."""
225 if child not in self._children:
229 if child not in self._children:
226 self._children.append(child)
230 self._children.append(child)
227
231
228 def __repr__(self):
232 def __repr__(self):
229 return "<Component('%s')>" % self.name
233 return "<Component('%s')>" % self.name
@@ -1,58 +1,59 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Oh my @#*%, where did ipapi go?
4 Oh my @#*%, where did ipapi go?
5
5
6 Originally, this module was designed to be a public api for IPython. It is
6 Originally, this module was designed to be a public api for IPython. It is
7 now deprecated and replaced by :class:`IPython.core.Interactive` shell.
7 now deprecated and replaced by :class:`IPython.core.Interactive` shell.
8 Almost all of the methods that were here are now there, but possibly renamed.
8 Almost all of the methods that were here are now there, but possibly renamed.
9
9
10 During our transition, we will keep this simple module with its :func:`get`
10 During our transition, we will keep this simple module with its :func:`get`
11 function. It too will eventually go away when the new component querying
11 function. It too will eventually go away when the new component querying
12 interface is fully used.
12 interface is fully used.
13
13
14 Authors:
14 Authors:
15
15
16 * Brian Granger
16 * Brian Granger
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2009 The IPython Development Team
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 from IPython.core.error import TryNext, UsageError
30 from IPython.core.error import TryNext, UsageError
31 from IPython.core.component import Component
31 from IPython.core.component import Component
32 from IPython.core.iplib import InteractiveShell
32
33
33 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
34 # Classes and functions
35 # Classes and functions
35 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
36
37
37 def get():
38 def get():
38 """Get the most recently created InteractiveShell instance."""
39 """Get the most recently created InteractiveShell instance."""
39 insts = Component.get_instances(name='__IP')
40 insts = InteractiveShell.get_instances()
40 most_recent = insts[0]
41 most_recent = insts[0]
41 for inst in insts[1:]:
42 for inst in insts[1:]:
42 if inst.created > most_recent.created:
43 if inst.created > most_recent.created:
43 most_recent = inst
44 most_recent = inst
44 return most_recent
45 return most_recent
45
46
46 def launch_new_instance():
47 def launch_new_instance():
47 """Create a run a full blown IPython instance"""
48 """Create a run a full blown IPython instance"""
48 from IPython.core.ipapp import IPythonApp
49 from IPython.core.ipapp import IPythonApp
49 app = IPythonApp()
50 app = IPythonApp()
50 app.start()
51 app.start()
51
52
52
53
53
54
54
55
55
56
56
57
57
58
58
59
@@ -1,3585 +1,3585 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #*****************************************************************************
5 #*****************************************************************************
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 #****************************************************************************
13 #****************************************************************************
14 # Modules and globals
14 # Modules and globals
15
15
16 # Python standard modules
16 # Python standard modules
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 import inspect
19 import inspect
20 import os
20 import os
21 import pdb
21 import pdb
22 import pydoc
22 import pydoc
23 import sys
23 import sys
24 import re
24 import re
25 import tempfile
25 import tempfile
26 import time
26 import time
27 import cPickle as pickle
27 import cPickle as pickle
28 import textwrap
28 import textwrap
29 from cStringIO import StringIO
29 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pprint, pformat
31 from pprint import pprint, pformat
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # Homebrewed
44 # Homebrewed
45 import IPython
45 import IPython
46 from IPython.utils import wildcard
46 from IPython.utils import wildcard
47 from IPython.core import debugger, oinspect
47 from IPython.core import debugger, oinspect
48 from IPython.core.error import TryNext
48 from IPython.core.error import TryNext
49 from IPython.core.fakemodule import FakeModule
49 from IPython.core.fakemodule import FakeModule
50 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
50 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
51 from IPython.utils.PyColorize import Parser
51 from IPython.utils.PyColorize import Parser
52 from IPython.utils.ipstruct import Struct
52 from IPython.utils.ipstruct import Struct
53 from IPython.core.macro import Macro
53 from IPython.core.macro import Macro
54 from IPython.utils.genutils import *
54 from IPython.utils.genutils import *
55 from IPython.core.page import page
55 from IPython.core.page import page
56 from IPython.utils import platutils
56 from IPython.utils import platutils
57 import IPython.utils.generics
57 import IPython.utils.generics
58 from IPython.core.error import UsageError
58 from IPython.core.error import UsageError
59 from IPython.testing import decorators as testdec
59 from IPython.testing import decorators as testdec
60
60
61 #***************************************************************************
61 #***************************************************************************
62 # Utility functions
62 # Utility functions
63 def on_off(tag):
63 def on_off(tag):
64 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
64 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
65 return ['OFF','ON'][tag]
65 return ['OFF','ON'][tag]
66
66
67 class Bunch: pass
67 class Bunch: pass
68
68
69 def compress_dhist(dh):
69 def compress_dhist(dh):
70 head, tail = dh[:-10], dh[-10:]
70 head, tail = dh[:-10], dh[-10:]
71
71
72 newhead = []
72 newhead = []
73 done = set()
73 done = set()
74 for h in head:
74 for h in head:
75 if h in done:
75 if h in done:
76 continue
76 continue
77 newhead.append(h)
77 newhead.append(h)
78 done.add(h)
78 done.add(h)
79
79
80 return newhead + tail
80 return newhead + tail
81
81
82
82
83 #***************************************************************************
83 #***************************************************************************
84 # Main class implementing Magic functionality
84 # Main class implementing Magic functionality
85 class Magic:
85 class Magic:
86 """Magic functions for InteractiveShell.
86 """Magic functions for InteractiveShell.
87
87
88 Shell functions which can be reached as %function_name. All magic
88 Shell functions which can be reached as %function_name. All magic
89 functions should accept a string, which they can parse for their own
89 functions should accept a string, which they can parse for their own
90 needs. This can make some functions easier to type, eg `%cd ../`
90 needs. This can make some functions easier to type, eg `%cd ../`
91 vs. `%cd("../")`
91 vs. `%cd("../")`
92
92
93 ALL definitions MUST begin with the prefix magic_. The user won't need it
93 ALL definitions MUST begin with the prefix magic_. The user won't need it
94 at the command line, but it is is needed in the definition. """
94 at the command line, but it is is needed in the definition. """
95
95
96 # class globals
96 # class globals
97 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
97 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
98 'Automagic is ON, % prefix NOT needed for magic functions.']
98 'Automagic is ON, % prefix NOT needed for magic functions.']
99
99
100 #......................................................................
100 #......................................................................
101 # some utility functions
101 # some utility functions
102
102
103 def __init__(self,shell):
103 def __init__(self,shell):
104
104
105 self.options_table = {}
105 self.options_table = {}
106 if profile is None:
106 if profile is None:
107 self.magic_prun = self.profile_missing_notice
107 self.magic_prun = self.profile_missing_notice
108 self.shell = shell
108 self.shell = shell
109
109
110 # namespace for holding state we may need
110 # namespace for holding state we may need
111 self._magic_state = Bunch()
111 self._magic_state = Bunch()
112
112
113 def profile_missing_notice(self, *args, **kwargs):
113 def profile_missing_notice(self, *args, **kwargs):
114 error("""\
114 error("""\
115 The profile module could not be found. It has been removed from the standard
115 The profile module could not be found. It has been removed from the standard
116 python packages because of its non-free license. To use profiling, install the
116 python packages because of its non-free license. To use profiling, install the
117 python-profiler package from non-free.""")
117 python-profiler package from non-free.""")
118
118
119 def default_option(self,fn,optstr):
119 def default_option(self,fn,optstr):
120 """Make an entry in the options_table for fn, with value optstr"""
120 """Make an entry in the options_table for fn, with value optstr"""
121
121
122 if fn not in self.lsmagic():
122 if fn not in self.lsmagic():
123 error("%s is not a magic function" % fn)
123 error("%s is not a magic function" % fn)
124 self.options_table[fn] = optstr
124 self.options_table[fn] = optstr
125
125
126 def lsmagic(self):
126 def lsmagic(self):
127 """Return a list of currently available magic functions.
127 """Return a list of currently available magic functions.
128
128
129 Gives a list of the bare names after mangling (['ls','cd', ...], not
129 Gives a list of the bare names after mangling (['ls','cd', ...], not
130 ['magic_ls','magic_cd',...]"""
130 ['magic_ls','magic_cd',...]"""
131
131
132 # FIXME. This needs a cleanup, in the way the magics list is built.
132 # FIXME. This needs a cleanup, in the way the magics list is built.
133
133
134 # magics in class definition
134 # magics in class definition
135 class_magic = lambda fn: fn.startswith('magic_') and \
135 class_magic = lambda fn: fn.startswith('magic_') and \
136 callable(Magic.__dict__[fn])
136 callable(Magic.__dict__[fn])
137 # in instance namespace (run-time user additions)
137 # in instance namespace (run-time user additions)
138 inst_magic = lambda fn: fn.startswith('magic_') and \
138 inst_magic = lambda fn: fn.startswith('magic_') and \
139 callable(self.__dict__[fn])
139 callable(self.__dict__[fn])
140 # and bound magics by user (so they can access self):
140 # and bound magics by user (so they can access self):
141 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
141 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
142 callable(self.__class__.__dict__[fn])
142 callable(self.__class__.__dict__[fn])
143 magics = filter(class_magic,Magic.__dict__.keys()) + \
143 magics = filter(class_magic,Magic.__dict__.keys()) + \
144 filter(inst_magic,self.__dict__.keys()) + \
144 filter(inst_magic,self.__dict__.keys()) + \
145 filter(inst_bound_magic,self.__class__.__dict__.keys())
145 filter(inst_bound_magic,self.__class__.__dict__.keys())
146 out = []
146 out = []
147 for fn in set(magics):
147 for fn in set(magics):
148 out.append(fn.replace('magic_','',1))
148 out.append(fn.replace('magic_','',1))
149 out.sort()
149 out.sort()
150 return out
150 return out
151
151
152 def extract_input_slices(self,slices,raw=False):
152 def extract_input_slices(self,slices,raw=False):
153 """Return as a string a set of input history slices.
153 """Return as a string a set of input history slices.
154
154
155 Inputs:
155 Inputs:
156
156
157 - slices: the set of slices is given as a list of strings (like
157 - slices: the set of slices is given as a list of strings (like
158 ['1','4:8','9'], since this function is for use by magic functions
158 ['1','4:8','9'], since this function is for use by magic functions
159 which get their arguments as strings.
159 which get their arguments as strings.
160
160
161 Optional inputs:
161 Optional inputs:
162
162
163 - raw(False): by default, the processed input is used. If this is
163 - raw(False): by default, the processed input is used. If this is
164 true, the raw input history is used instead.
164 true, the raw input history is used instead.
165
165
166 Note that slices can be called with two notations:
166 Note that slices can be called with two notations:
167
167
168 N:M -> standard python form, means including items N...(M-1).
168 N:M -> standard python form, means including items N...(M-1).
169
169
170 N-M -> include items N..M (closed endpoint)."""
170 N-M -> include items N..M (closed endpoint)."""
171
171
172 if raw:
172 if raw:
173 hist = self.shell.input_hist_raw
173 hist = self.shell.input_hist_raw
174 else:
174 else:
175 hist = self.shell.input_hist
175 hist = self.shell.input_hist
176
176
177 cmds = []
177 cmds = []
178 for chunk in slices:
178 for chunk in slices:
179 if ':' in chunk:
179 if ':' in chunk:
180 ini,fin = map(int,chunk.split(':'))
180 ini,fin = map(int,chunk.split(':'))
181 elif '-' in chunk:
181 elif '-' in chunk:
182 ini,fin = map(int,chunk.split('-'))
182 ini,fin = map(int,chunk.split('-'))
183 fin += 1
183 fin += 1
184 else:
184 else:
185 ini = int(chunk)
185 ini = int(chunk)
186 fin = ini+1
186 fin = ini+1
187 cmds.append(hist[ini:fin])
187 cmds.append(hist[ini:fin])
188 return cmds
188 return cmds
189
189
190 def _ofind(self, oname, namespaces=None):
190 def _ofind(self, oname, namespaces=None):
191 """Find an object in the available namespaces.
191 """Find an object in the available namespaces.
192
192
193 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
193 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
194
194
195 Has special code to detect magic functions.
195 Has special code to detect magic functions.
196 """
196 """
197
197
198 oname = oname.strip()
198 oname = oname.strip()
199
199
200 alias_ns = None
200 alias_ns = None
201 if namespaces is None:
201 if namespaces is None:
202 # Namespaces to search in:
202 # Namespaces to search in:
203 # Put them in a list. The order is important so that we
203 # Put them in a list. The order is important so that we
204 # find things in the same order that Python finds them.
204 # find things in the same order that Python finds them.
205 namespaces = [ ('Interactive', self.shell.user_ns),
205 namespaces = [ ('Interactive', self.shell.user_ns),
206 ('IPython internal', self.shell.internal_ns),
206 ('IPython internal', self.shell.internal_ns),
207 ('Python builtin', __builtin__.__dict__),
207 ('Python builtin', __builtin__.__dict__),
208 ('Alias', self.shell.alias_table),
208 ('Alias', self.shell.alias_table),
209 ]
209 ]
210 alias_ns = self.shell.alias_table
210 alias_ns = self.shell.alias_table
211
211
212 # initialize results to 'null'
212 # initialize results to 'null'
213 found = 0; obj = None; ospace = None; ds = None;
213 found = 0; obj = None; ospace = None; ds = None;
214 ismagic = 0; isalias = 0; parent = None
214 ismagic = 0; isalias = 0; parent = None
215
215
216 # Look for the given name by splitting it in parts. If the head is
216 # Look for the given name by splitting it in parts. If the head is
217 # found, then we look for all the remaining parts as members, and only
217 # found, then we look for all the remaining parts as members, and only
218 # declare success if we can find them all.
218 # declare success if we can find them all.
219 oname_parts = oname.split('.')
219 oname_parts = oname.split('.')
220 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
220 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
221 for nsname,ns in namespaces:
221 for nsname,ns in namespaces:
222 try:
222 try:
223 obj = ns[oname_head]
223 obj = ns[oname_head]
224 except KeyError:
224 except KeyError:
225 continue
225 continue
226 else:
226 else:
227 #print 'oname_rest:', oname_rest # dbg
227 #print 'oname_rest:', oname_rest # dbg
228 for part in oname_rest:
228 for part in oname_rest:
229 try:
229 try:
230 parent = obj
230 parent = obj
231 obj = getattr(obj,part)
231 obj = getattr(obj,part)
232 except:
232 except:
233 # Blanket except b/c some badly implemented objects
233 # Blanket except b/c some badly implemented objects
234 # allow __getattr__ to raise exceptions other than
234 # allow __getattr__ to raise exceptions other than
235 # AttributeError, which then crashes IPython.
235 # AttributeError, which then crashes IPython.
236 break
236 break
237 else:
237 else:
238 # If we finish the for loop (no break), we got all members
238 # If we finish the for loop (no break), we got all members
239 found = 1
239 found = 1
240 ospace = nsname
240 ospace = nsname
241 if ns == alias_ns:
241 if ns == alias_ns:
242 isalias = 1
242 isalias = 1
243 break # namespace loop
243 break # namespace loop
244
244
245 # Try to see if it's magic
245 # Try to see if it's magic
246 if not found:
246 if not found:
247 if oname.startswith(self.shell.ESC_MAGIC):
247 if oname.startswith(self.shell.ESC_MAGIC):
248 oname = oname[1:]
248 oname = oname[1:]
249 obj = getattr(self,'magic_'+oname,None)
249 obj = getattr(self,'magic_'+oname,None)
250 if obj is not None:
250 if obj is not None:
251 found = 1
251 found = 1
252 ospace = 'IPython internal'
252 ospace = 'IPython internal'
253 ismagic = 1
253 ismagic = 1
254
254
255 # Last try: special-case some literals like '', [], {}, etc:
255 # Last try: special-case some literals like '', [], {}, etc:
256 if not found and oname_head in ["''",'""','[]','{}','()']:
256 if not found and oname_head in ["''",'""','[]','{}','()']:
257 obj = eval(oname_head)
257 obj = eval(oname_head)
258 found = 1
258 found = 1
259 ospace = 'Interactive'
259 ospace = 'Interactive'
260
260
261 return {'found':found, 'obj':obj, 'namespace':ospace,
261 return {'found':found, 'obj':obj, 'namespace':ospace,
262 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
262 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
263
263
264 def arg_err(self,func):
264 def arg_err(self,func):
265 """Print docstring if incorrect arguments were passed"""
265 """Print docstring if incorrect arguments were passed"""
266 print 'Error in arguments:'
266 print 'Error in arguments:'
267 print OInspect.getdoc(func)
267 print OInspect.getdoc(func)
268
268
269 def format_latex(self,strng):
269 def format_latex(self,strng):
270 """Format a string for latex inclusion."""
270 """Format a string for latex inclusion."""
271
271
272 # Characters that need to be escaped for latex:
272 # Characters that need to be escaped for latex:
273 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
273 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
274 # Magic command names as headers:
274 # Magic command names as headers:
275 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
275 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
276 re.MULTILINE)
276 re.MULTILINE)
277 # Magic commands
277 # Magic commands
278 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
278 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
279 re.MULTILINE)
279 re.MULTILINE)
280 # Paragraph continue
280 # Paragraph continue
281 par_re = re.compile(r'\\$',re.MULTILINE)
281 par_re = re.compile(r'\\$',re.MULTILINE)
282
282
283 # The "\n" symbol
283 # The "\n" symbol
284 newline_re = re.compile(r'\\n')
284 newline_re = re.compile(r'\\n')
285
285
286 # Now build the string for output:
286 # Now build the string for output:
287 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
287 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
288 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
288 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
289 strng)
289 strng)
290 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
290 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
291 strng = par_re.sub(r'\\\\',strng)
291 strng = par_re.sub(r'\\\\',strng)
292 strng = escape_re.sub(r'\\\1',strng)
292 strng = escape_re.sub(r'\\\1',strng)
293 strng = newline_re.sub(r'\\textbackslash{}n',strng)
293 strng = newline_re.sub(r'\\textbackslash{}n',strng)
294 return strng
294 return strng
295
295
296 def format_screen(self,strng):
296 def format_screen(self,strng):
297 """Format a string for screen printing.
297 """Format a string for screen printing.
298
298
299 This removes some latex-type format codes."""
299 This removes some latex-type format codes."""
300 # Paragraph continue
300 # Paragraph continue
301 par_re = re.compile(r'\\$',re.MULTILINE)
301 par_re = re.compile(r'\\$',re.MULTILINE)
302 strng = par_re.sub('',strng)
302 strng = par_re.sub('',strng)
303 return strng
303 return strng
304
304
305 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
305 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
306 """Parse options passed to an argument string.
306 """Parse options passed to an argument string.
307
307
308 The interface is similar to that of getopt(), but it returns back a
308 The interface is similar to that of getopt(), but it returns back a
309 Struct with the options as keys and the stripped argument string still
309 Struct with the options as keys and the stripped argument string still
310 as a string.
310 as a string.
311
311
312 arg_str is quoted as a true sys.argv vector by using shlex.split.
312 arg_str is quoted as a true sys.argv vector by using shlex.split.
313 This allows us to easily expand variables, glob files, quote
313 This allows us to easily expand variables, glob files, quote
314 arguments, etc.
314 arguments, etc.
315
315
316 Options:
316 Options:
317 -mode: default 'string'. If given as 'list', the argument string is
317 -mode: default 'string'. If given as 'list', the argument string is
318 returned as a list (split on whitespace) instead of a string.
318 returned as a list (split on whitespace) instead of a string.
319
319
320 -list_all: put all option values in lists. Normally only options
320 -list_all: put all option values in lists. Normally only options
321 appearing more than once are put in a list.
321 appearing more than once are put in a list.
322
322
323 -posix (True): whether to split the input line in POSIX mode or not,
323 -posix (True): whether to split the input line in POSIX mode or not,
324 as per the conventions outlined in the shlex module from the
324 as per the conventions outlined in the shlex module from the
325 standard library."""
325 standard library."""
326
326
327 # inject default options at the beginning of the input line
327 # inject default options at the beginning of the input line
328 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
328 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
329 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
329 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
330
330
331 mode = kw.get('mode','string')
331 mode = kw.get('mode','string')
332 if mode not in ['string','list']:
332 if mode not in ['string','list']:
333 raise ValueError,'incorrect mode given: %s' % mode
333 raise ValueError,'incorrect mode given: %s' % mode
334 # Get options
334 # Get options
335 list_all = kw.get('list_all',0)
335 list_all = kw.get('list_all',0)
336 posix = kw.get('posix',True)
336 posix = kw.get('posix',True)
337
337
338 # Check if we have more than one argument to warrant extra processing:
338 # Check if we have more than one argument to warrant extra processing:
339 odict = {} # Dictionary with options
339 odict = {} # Dictionary with options
340 args = arg_str.split()
340 args = arg_str.split()
341 if len(args) >= 1:
341 if len(args) >= 1:
342 # If the list of inputs only has 0 or 1 thing in it, there's no
342 # If the list of inputs only has 0 or 1 thing in it, there's no
343 # need to look for options
343 # need to look for options
344 argv = arg_split(arg_str,posix)
344 argv = arg_split(arg_str,posix)
345 # Do regular option processing
345 # Do regular option processing
346 try:
346 try:
347 opts,args = getopt(argv,opt_str,*long_opts)
347 opts,args = getopt(argv,opt_str,*long_opts)
348 except GetoptError,e:
348 except GetoptError,e:
349 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
349 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
350 " ".join(long_opts)))
350 " ".join(long_opts)))
351 for o,a in opts:
351 for o,a in opts:
352 if o.startswith('--'):
352 if o.startswith('--'):
353 o = o[2:]
353 o = o[2:]
354 else:
354 else:
355 o = o[1:]
355 o = o[1:]
356 try:
356 try:
357 odict[o].append(a)
357 odict[o].append(a)
358 except AttributeError:
358 except AttributeError:
359 odict[o] = [odict[o],a]
359 odict[o] = [odict[o],a]
360 except KeyError:
360 except KeyError:
361 if list_all:
361 if list_all:
362 odict[o] = [a]
362 odict[o] = [a]
363 else:
363 else:
364 odict[o] = a
364 odict[o] = a
365
365
366 # Prepare opts,args for return
366 # Prepare opts,args for return
367 opts = Struct(odict)
367 opts = Struct(odict)
368 if mode == 'string':
368 if mode == 'string':
369 args = ' '.join(args)
369 args = ' '.join(args)
370
370
371 return opts,args
371 return opts,args
372
372
373 #......................................................................
373 #......................................................................
374 # And now the actual magic functions
374 # And now the actual magic functions
375
375
376 # Functions for IPython shell work (vars,funcs, config, etc)
376 # Functions for IPython shell work (vars,funcs, config, etc)
377 def magic_lsmagic(self, parameter_s = ''):
377 def magic_lsmagic(self, parameter_s = ''):
378 """List currently available magic functions."""
378 """List currently available magic functions."""
379 mesc = self.shell.ESC_MAGIC
379 mesc = self.shell.ESC_MAGIC
380 print 'Available magic functions:\n'+mesc+\
380 print 'Available magic functions:\n'+mesc+\
381 (' '+mesc).join(self.lsmagic())
381 (' '+mesc).join(self.lsmagic())
382 print '\n' + Magic.auto_status[self.shell.automagic]
382 print '\n' + Magic.auto_status[self.shell.automagic]
383 return None
383 return None
384
384
385 def magic_magic(self, parameter_s = ''):
385 def magic_magic(self, parameter_s = ''):
386 """Print information about the magic function system.
386 """Print information about the magic function system.
387
387
388 Supported formats: -latex, -brief, -rest
388 Supported formats: -latex, -brief, -rest
389 """
389 """
390
390
391 mode = ''
391 mode = ''
392 try:
392 try:
393 if parameter_s.split()[0] == '-latex':
393 if parameter_s.split()[0] == '-latex':
394 mode = 'latex'
394 mode = 'latex'
395 if parameter_s.split()[0] == '-brief':
395 if parameter_s.split()[0] == '-brief':
396 mode = 'brief'
396 mode = 'brief'
397 if parameter_s.split()[0] == '-rest':
397 if parameter_s.split()[0] == '-rest':
398 mode = 'rest'
398 mode = 'rest'
399 rest_docs = []
399 rest_docs = []
400 except:
400 except:
401 pass
401 pass
402
402
403 magic_docs = []
403 magic_docs = []
404 for fname in self.lsmagic():
404 for fname in self.lsmagic():
405 mname = 'magic_' + fname
405 mname = 'magic_' + fname
406 for space in (Magic,self,self.__class__):
406 for space in (Magic,self,self.__class__):
407 try:
407 try:
408 fn = space.__dict__[mname]
408 fn = space.__dict__[mname]
409 except KeyError:
409 except KeyError:
410 pass
410 pass
411 else:
411 else:
412 break
412 break
413 if mode == 'brief':
413 if mode == 'brief':
414 # only first line
414 # only first line
415 if fn.__doc__:
415 if fn.__doc__:
416 fndoc = fn.__doc__.split('\n',1)[0]
416 fndoc = fn.__doc__.split('\n',1)[0]
417 else:
417 else:
418 fndoc = 'No documentation'
418 fndoc = 'No documentation'
419 else:
419 else:
420 if fn.__doc__:
420 if fn.__doc__:
421 fndoc = fn.__doc__.rstrip()
421 fndoc = fn.__doc__.rstrip()
422 else:
422 else:
423 fndoc = 'No documentation'
423 fndoc = 'No documentation'
424
424
425
425
426 if mode == 'rest':
426 if mode == 'rest':
427 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
427 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
428 fname,fndoc))
428 fname,fndoc))
429
429
430 else:
430 else:
431 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
431 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
432 fname,fndoc))
432 fname,fndoc))
433
433
434 magic_docs = ''.join(magic_docs)
434 magic_docs = ''.join(magic_docs)
435
435
436 if mode == 'rest':
436 if mode == 'rest':
437 return "".join(rest_docs)
437 return "".join(rest_docs)
438
438
439 if mode == 'latex':
439 if mode == 'latex':
440 print self.format_latex(magic_docs)
440 print self.format_latex(magic_docs)
441 return
441 return
442 else:
442 else:
443 magic_docs = self.format_screen(magic_docs)
443 magic_docs = self.format_screen(magic_docs)
444 if mode == 'brief':
444 if mode == 'brief':
445 return magic_docs
445 return magic_docs
446
446
447 outmsg = """
447 outmsg = """
448 IPython's 'magic' functions
448 IPython's 'magic' functions
449 ===========================
449 ===========================
450
450
451 The magic function system provides a series of functions which allow you to
451 The magic function system provides a series of functions which allow you to
452 control the behavior of IPython itself, plus a lot of system-type
452 control the behavior of IPython itself, plus a lot of system-type
453 features. All these functions are prefixed with a % character, but parameters
453 features. All these functions are prefixed with a % character, but parameters
454 are given without parentheses or quotes.
454 are given without parentheses or quotes.
455
455
456 NOTE: If you have 'automagic' enabled (via the command line option or with the
456 NOTE: If you have 'automagic' enabled (via the command line option or with the
457 %automagic function), you don't need to type in the % explicitly. By default,
457 %automagic function), you don't need to type in the % explicitly. By default,
458 IPython ships with automagic on, so you should only rarely need the % escape.
458 IPython ships with automagic on, so you should only rarely need the % escape.
459
459
460 Example: typing '%cd mydir' (without the quotes) changes you working directory
460 Example: typing '%cd mydir' (without the quotes) changes you working directory
461 to 'mydir', if it exists.
461 to 'mydir', if it exists.
462
462
463 You can define your own magic functions to extend the system. See the supplied
463 You can define your own magic functions to extend the system. See the supplied
464 ipythonrc and example-magic.py files for details (in your ipython
464 ipythonrc and example-magic.py files for details (in your ipython
465 configuration directory, typically $HOME/.ipython/).
465 configuration directory, typically $HOME/.ipython/).
466
466
467 You can also define your own aliased names for magic functions. In your
467 You can also define your own aliased names for magic functions. In your
468 ipythonrc file, placing a line like:
468 ipythonrc file, placing a line like:
469
469
470 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
470 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
471
471
472 will define %pf as a new name for %profile.
472 will define %pf as a new name for %profile.
473
473
474 You can also call magics in code using the magic() function, which IPython
474 You can also call magics in code using the magic() function, which IPython
475 automatically adds to the builtin namespace. Type 'magic?' for details.
475 automatically adds to the builtin namespace. Type 'magic?' for details.
476
476
477 For a list of the available magic functions, use %lsmagic. For a description
477 For a list of the available magic functions, use %lsmagic. For a description
478 of any of them, type %magic_name?, e.g. '%cd?'.
478 of any of them, type %magic_name?, e.g. '%cd?'.
479
479
480 Currently the magic system has the following functions:\n"""
480 Currently the magic system has the following functions:\n"""
481
481
482 mesc = self.shell.ESC_MAGIC
482 mesc = self.shell.ESC_MAGIC
483 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
483 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
484 "\n\n%s%s\n\n%s" % (outmsg,
484 "\n\n%s%s\n\n%s" % (outmsg,
485 magic_docs,mesc,mesc,
485 magic_docs,mesc,mesc,
486 (' '+mesc).join(self.lsmagic()),
486 (' '+mesc).join(self.lsmagic()),
487 Magic.auto_status[self.shell.automagic] ) )
487 Magic.auto_status[self.shell.automagic] ) )
488
488
489 page(outmsg,screen_lines=self.shell.usable_screen_length)
489 page(outmsg,screen_lines=self.shell.usable_screen_length)
490
490
491
491
492 def magic_autoindent(self, parameter_s = ''):
492 def magic_autoindent(self, parameter_s = ''):
493 """Toggle autoindent on/off (if available)."""
493 """Toggle autoindent on/off (if available)."""
494
494
495 self.shell.set_autoindent()
495 self.shell.set_autoindent()
496 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
496 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
497
497
498
498
499 def magic_automagic(self, parameter_s = ''):
499 def magic_automagic(self, parameter_s = ''):
500 """Make magic functions callable without having to type the initial %.
500 """Make magic functions callable without having to type the initial %.
501
501
502 Without argumentsl toggles on/off (when off, you must call it as
502 Without argumentsl toggles on/off (when off, you must call it as
503 %automagic, of course). With arguments it sets the value, and you can
503 %automagic, of course). With arguments it sets the value, and you can
504 use any of (case insensitive):
504 use any of (case insensitive):
505
505
506 - on,1,True: to activate
506 - on,1,True: to activate
507
507
508 - off,0,False: to deactivate.
508 - off,0,False: to deactivate.
509
509
510 Note that magic functions have lowest priority, so if there's a
510 Note that magic functions have lowest priority, so if there's a
511 variable whose name collides with that of a magic fn, automagic won't
511 variable whose name collides with that of a magic fn, automagic won't
512 work for that function (you get the variable instead). However, if you
512 work for that function (you get the variable instead). However, if you
513 delete the variable (del var), the previously shadowed magic function
513 delete the variable (del var), the previously shadowed magic function
514 becomes visible to automagic again."""
514 becomes visible to automagic again."""
515
515
516 arg = parameter_s.lower()
516 arg = parameter_s.lower()
517 if parameter_s in ('on','1','true'):
517 if parameter_s in ('on','1','true'):
518 self.shell.automagic = True
518 self.shell.automagic = True
519 elif parameter_s in ('off','0','false'):
519 elif parameter_s in ('off','0','false'):
520 self.shell.automagic = False
520 self.shell.automagic = False
521 else:
521 else:
522 self.shell.automagic = not self.shell.automagic
522 self.shell.automagic = not self.shell.automagic
523 print '\n' + Magic.auto_status[self.shell.automagic]
523 print '\n' + Magic.auto_status[self.shell.automagic]
524
524
525 @testdec.skip_doctest
525 @testdec.skip_doctest
526 def magic_autocall(self, parameter_s = ''):
526 def magic_autocall(self, parameter_s = ''):
527 """Make functions callable without having to type parentheses.
527 """Make functions callable without having to type parentheses.
528
528
529 Usage:
529 Usage:
530
530
531 %autocall [mode]
531 %autocall [mode]
532
532
533 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
533 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
534 value is toggled on and off (remembering the previous state).
534 value is toggled on and off (remembering the previous state).
535
535
536 In more detail, these values mean:
536 In more detail, these values mean:
537
537
538 0 -> fully disabled
538 0 -> fully disabled
539
539
540 1 -> active, but do not apply if there are no arguments on the line.
540 1 -> active, but do not apply if there are no arguments on the line.
541
541
542 In this mode, you get:
542 In this mode, you get:
543
543
544 In [1]: callable
544 In [1]: callable
545 Out[1]: <built-in function callable>
545 Out[1]: <built-in function callable>
546
546
547 In [2]: callable 'hello'
547 In [2]: callable 'hello'
548 ------> callable('hello')
548 ------> callable('hello')
549 Out[2]: False
549 Out[2]: False
550
550
551 2 -> Active always. Even if no arguments are present, the callable
551 2 -> Active always. Even if no arguments are present, the callable
552 object is called:
552 object is called:
553
553
554 In [2]: float
554 In [2]: float
555 ------> float()
555 ------> float()
556 Out[2]: 0.0
556 Out[2]: 0.0
557
557
558 Note that even with autocall off, you can still use '/' at the start of
558 Note that even with autocall off, you can still use '/' at the start of
559 a line to treat the first argument on the command line as a function
559 a line to treat the first argument on the command line as a function
560 and add parentheses to it:
560 and add parentheses to it:
561
561
562 In [8]: /str 43
562 In [8]: /str 43
563 ------> str(43)
563 ------> str(43)
564 Out[8]: '43'
564 Out[8]: '43'
565
565
566 # all-random (note for auto-testing)
566 # all-random (note for auto-testing)
567 """
567 """
568
568
569 if parameter_s:
569 if parameter_s:
570 arg = int(parameter_s)
570 arg = int(parameter_s)
571 else:
571 else:
572 arg = 'toggle'
572 arg = 'toggle'
573
573
574 if not arg in (0,1,2,'toggle'):
574 if not arg in (0,1,2,'toggle'):
575 error('Valid modes: (0->Off, 1->Smart, 2->Full')
575 error('Valid modes: (0->Off, 1->Smart, 2->Full')
576 return
576 return
577
577
578 if arg in (0,1,2):
578 if arg in (0,1,2):
579 self.shell.autocall = arg
579 self.shell.autocall = arg
580 else: # toggle
580 else: # toggle
581 if self.shell.autocall:
581 if self.shell.autocall:
582 self._magic_state.autocall_save = self.shell.autocall
582 self._magic_state.autocall_save = self.shell.autocall
583 self.shell.autocall = 0
583 self.shell.autocall = 0
584 else:
584 else:
585 try:
585 try:
586 self.shell.autocall = self._magic_state.autocall_save
586 self.shell.autocall = self._magic_state.autocall_save
587 except AttributeError:
587 except AttributeError:
588 self.shell.autocall = self._magic_state.autocall_save = 1
588 self.shell.autocall = self._magic_state.autocall_save = 1
589
589
590 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
590 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
591
591
592 def magic_system_verbose(self, parameter_s = ''):
592 def magic_system_verbose(self, parameter_s = ''):
593 """Set verbose printing of system calls.
593 """Set verbose printing of system calls.
594
594
595 If called without an argument, act as a toggle"""
595 If called without an argument, act as a toggle"""
596
596
597 if parameter_s:
597 if parameter_s:
598 val = bool(eval(parameter_s))
598 val = bool(eval(parameter_s))
599 else:
599 else:
600 val = None
600 val = None
601
601
602 if self.shell.system_verbose:
602 if self.shell.system_verbose:
603 self.shell.system_verbose = False
603 self.shell.system_verbose = False
604 else:
604 else:
605 self.shell.system_verbose = True
605 self.shell.system_verbose = True
606 print "System verbose printing is:",\
606 print "System verbose printing is:",\
607 ['OFF','ON'][self.shell.system_verbose]
607 ['OFF','ON'][self.shell.system_verbose]
608
608
609
609
610 def magic_page(self, parameter_s=''):
610 def magic_page(self, parameter_s=''):
611 """Pretty print the object and display it through a pager.
611 """Pretty print the object and display it through a pager.
612
612
613 %page [options] OBJECT
613 %page [options] OBJECT
614
614
615 If no object is given, use _ (last output).
615 If no object is given, use _ (last output).
616
616
617 Options:
617 Options:
618
618
619 -r: page str(object), don't pretty-print it."""
619 -r: page str(object), don't pretty-print it."""
620
620
621 # After a function contributed by Olivier Aubert, slightly modified.
621 # After a function contributed by Olivier Aubert, slightly modified.
622
622
623 # Process options/args
623 # Process options/args
624 opts,args = self.parse_options(parameter_s,'r')
624 opts,args = self.parse_options(parameter_s,'r')
625 raw = 'r' in opts
625 raw = 'r' in opts
626
626
627 oname = args and args or '_'
627 oname = args and args or '_'
628 info = self._ofind(oname)
628 info = self._ofind(oname)
629 if info['found']:
629 if info['found']:
630 txt = (raw and str or pformat)( info['obj'] )
630 txt = (raw and str or pformat)( info['obj'] )
631 page(txt)
631 page(txt)
632 else:
632 else:
633 print 'Object `%s` not found' % oname
633 print 'Object `%s` not found' % oname
634
634
635 def magic_profile(self, parameter_s=''):
635 def magic_profile(self, parameter_s=''):
636 """Print your currently active IPyhton profile."""
636 """Print your currently active IPyhton profile."""
637 if self.shell.profile:
637 if self.shell.profile:
638 printpl('Current IPython profile: $self.shell.profile.')
638 printpl('Current IPython profile: $self.shell.profile.')
639 else:
639 else:
640 print 'No profile active.'
640 print 'No profile active.'
641
641
642 def magic_pinfo(self, parameter_s='', namespaces=None):
642 def magic_pinfo(self, parameter_s='', namespaces=None):
643 """Provide detailed information about an object.
643 """Provide detailed information about an object.
644
644
645 '%pinfo object' is just a synonym for object? or ?object."""
645 '%pinfo object' is just a synonym for object? or ?object."""
646
646
647 #print 'pinfo par: <%s>' % parameter_s # dbg
647 #print 'pinfo par: <%s>' % parameter_s # dbg
648
648
649
649
650 # detail_level: 0 -> obj? , 1 -> obj??
650 # detail_level: 0 -> obj? , 1 -> obj??
651 detail_level = 0
651 detail_level = 0
652 # We need to detect if we got called as 'pinfo pinfo foo', which can
652 # We need to detect if we got called as 'pinfo pinfo foo', which can
653 # happen if the user types 'pinfo foo?' at the cmd line.
653 # happen if the user types 'pinfo foo?' at the cmd line.
654 pinfo,qmark1,oname,qmark2 = \
654 pinfo,qmark1,oname,qmark2 = \
655 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
655 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
656 if pinfo or qmark1 or qmark2:
656 if pinfo or qmark1 or qmark2:
657 detail_level = 1
657 detail_level = 1
658 if "*" in oname:
658 if "*" in oname:
659 self.magic_psearch(oname)
659 self.magic_psearch(oname)
660 else:
660 else:
661 self._inspect('pinfo', oname, detail_level=detail_level,
661 self._inspect('pinfo', oname, detail_level=detail_level,
662 namespaces=namespaces)
662 namespaces=namespaces)
663
663
664 def magic_pdef(self, parameter_s='', namespaces=None):
664 def magic_pdef(self, parameter_s='', namespaces=None):
665 """Print the definition header for any callable object.
665 """Print the definition header for any callable object.
666
666
667 If the object is a class, print the constructor information."""
667 If the object is a class, print the constructor information."""
668 self._inspect('pdef',parameter_s, namespaces)
668 self._inspect('pdef',parameter_s, namespaces)
669
669
670 def magic_pdoc(self, parameter_s='', namespaces=None):
670 def magic_pdoc(self, parameter_s='', namespaces=None):
671 """Print the docstring for an object.
671 """Print the docstring for an object.
672
672
673 If the given object is a class, it will print both the class and the
673 If the given object is a class, it will print both the class and the
674 constructor docstrings."""
674 constructor docstrings."""
675 self._inspect('pdoc',parameter_s, namespaces)
675 self._inspect('pdoc',parameter_s, namespaces)
676
676
677 def magic_psource(self, parameter_s='', namespaces=None):
677 def magic_psource(self, parameter_s='', namespaces=None):
678 """Print (or run through pager) the source code for an object."""
678 """Print (or run through pager) the source code for an object."""
679 self._inspect('psource',parameter_s, namespaces)
679 self._inspect('psource',parameter_s, namespaces)
680
680
681 def magic_pfile(self, parameter_s=''):
681 def magic_pfile(self, parameter_s=''):
682 """Print (or run through pager) the file where an object is defined.
682 """Print (or run through pager) the file where an object is defined.
683
683
684 The file opens at the line where the object definition begins. IPython
684 The file opens at the line where the object definition begins. IPython
685 will honor the environment variable PAGER if set, and otherwise will
685 will honor the environment variable PAGER if set, and otherwise will
686 do its best to print the file in a convenient form.
686 do its best to print the file in a convenient form.
687
687
688 If the given argument is not an object currently defined, IPython will
688 If the given argument is not an object currently defined, IPython will
689 try to interpret it as a filename (automatically adding a .py extension
689 try to interpret it as a filename (automatically adding a .py extension
690 if needed). You can thus use %pfile as a syntax highlighting code
690 if needed). You can thus use %pfile as a syntax highlighting code
691 viewer."""
691 viewer."""
692
692
693 # first interpret argument as an object name
693 # first interpret argument as an object name
694 out = self._inspect('pfile',parameter_s)
694 out = self._inspect('pfile',parameter_s)
695 # if not, try the input as a filename
695 # if not, try the input as a filename
696 if out == 'not found':
696 if out == 'not found':
697 try:
697 try:
698 filename = get_py_filename(parameter_s)
698 filename = get_py_filename(parameter_s)
699 except IOError,msg:
699 except IOError,msg:
700 print msg
700 print msg
701 return
701 return
702 page(self.shell.inspector.format(file(filename).read()))
702 page(self.shell.inspector.format(file(filename).read()))
703
703
704 def _inspect(self,meth,oname,namespaces=None,**kw):
704 def _inspect(self,meth,oname,namespaces=None,**kw):
705 """Generic interface to the inspector system.
705 """Generic interface to the inspector system.
706
706
707 This function is meant to be called by pdef, pdoc & friends."""
707 This function is meant to be called by pdef, pdoc & friends."""
708
708
709 #oname = oname.strip()
709 #oname = oname.strip()
710 #print '1- oname: <%r>' % oname # dbg
710 #print '1- oname: <%r>' % oname # dbg
711 try:
711 try:
712 oname = oname.strip().encode('ascii')
712 oname = oname.strip().encode('ascii')
713 #print '2- oname: <%r>' % oname # dbg
713 #print '2- oname: <%r>' % oname # dbg
714 except UnicodeEncodeError:
714 except UnicodeEncodeError:
715 print 'Python identifiers can only contain ascii characters.'
715 print 'Python identifiers can only contain ascii characters.'
716 return 'not found'
716 return 'not found'
717
717
718 info = Struct(self._ofind(oname, namespaces))
718 info = Struct(self._ofind(oname, namespaces))
719
719
720 if info.found:
720 if info.found:
721 try:
721 try:
722 IPython.utils.generics.inspect_object(info.obj)
722 IPython.utils.generics.inspect_object(info.obj)
723 return
723 return
724 except TryNext:
724 except TryNext:
725 pass
725 pass
726 # Get the docstring of the class property if it exists.
726 # Get the docstring of the class property if it exists.
727 path = oname.split('.')
727 path = oname.split('.')
728 root = '.'.join(path[:-1])
728 root = '.'.join(path[:-1])
729 if info.parent is not None:
729 if info.parent is not None:
730 try:
730 try:
731 target = getattr(info.parent, '__class__')
731 target = getattr(info.parent, '__class__')
732 # The object belongs to a class instance.
732 # The object belongs to a class instance.
733 try:
733 try:
734 target = getattr(target, path[-1])
734 target = getattr(target, path[-1])
735 # The class defines the object.
735 # The class defines the object.
736 if isinstance(target, property):
736 if isinstance(target, property):
737 oname = root + '.__class__.' + path[-1]
737 oname = root + '.__class__.' + path[-1]
738 info = Struct(self._ofind(oname))
738 info = Struct(self._ofind(oname))
739 except AttributeError: pass
739 except AttributeError: pass
740 except AttributeError: pass
740 except AttributeError: pass
741
741
742 pmethod = getattr(self.shell.inspector,meth)
742 pmethod = getattr(self.shell.inspector,meth)
743 formatter = info.ismagic and self.format_screen or None
743 formatter = info.ismagic and self.format_screen or None
744 if meth == 'pdoc':
744 if meth == 'pdoc':
745 pmethod(info.obj,oname,formatter)
745 pmethod(info.obj,oname,formatter)
746 elif meth == 'pinfo':
746 elif meth == 'pinfo':
747 pmethod(info.obj,oname,formatter,info,**kw)
747 pmethod(info.obj,oname,formatter,info,**kw)
748 else:
748 else:
749 pmethod(info.obj,oname)
749 pmethod(info.obj,oname)
750 else:
750 else:
751 print 'Object `%s` not found.' % oname
751 print 'Object `%s` not found.' % oname
752 return 'not found' # so callers can take other action
752 return 'not found' # so callers can take other action
753
753
754 def magic_psearch(self, parameter_s=''):
754 def magic_psearch(self, parameter_s=''):
755 """Search for object in namespaces by wildcard.
755 """Search for object in namespaces by wildcard.
756
756
757 %psearch [options] PATTERN [OBJECT TYPE]
757 %psearch [options] PATTERN [OBJECT TYPE]
758
758
759 Note: ? can be used as a synonym for %psearch, at the beginning or at
759 Note: ? can be used as a synonym for %psearch, at the beginning or at
760 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
760 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
761 rest of the command line must be unchanged (options come first), so
761 rest of the command line must be unchanged (options come first), so
762 for example the following forms are equivalent
762 for example the following forms are equivalent
763
763
764 %psearch -i a* function
764 %psearch -i a* function
765 -i a* function?
765 -i a* function?
766 ?-i a* function
766 ?-i a* function
767
767
768 Arguments:
768 Arguments:
769
769
770 PATTERN
770 PATTERN
771
771
772 where PATTERN is a string containing * as a wildcard similar to its
772 where PATTERN is a string containing * as a wildcard similar to its
773 use in a shell. The pattern is matched in all namespaces on the
773 use in a shell. The pattern is matched in all namespaces on the
774 search path. By default objects starting with a single _ are not
774 search path. By default objects starting with a single _ are not
775 matched, many IPython generated objects have a single
775 matched, many IPython generated objects have a single
776 underscore. The default is case insensitive matching. Matching is
776 underscore. The default is case insensitive matching. Matching is
777 also done on the attributes of objects and not only on the objects
777 also done on the attributes of objects and not only on the objects
778 in a module.
778 in a module.
779
779
780 [OBJECT TYPE]
780 [OBJECT TYPE]
781
781
782 Is the name of a python type from the types module. The name is
782 Is the name of a python type from the types module. The name is
783 given in lowercase without the ending type, ex. StringType is
783 given in lowercase without the ending type, ex. StringType is
784 written string. By adding a type here only objects matching the
784 written string. By adding a type here only objects matching the
785 given type are matched. Using all here makes the pattern match all
785 given type are matched. Using all here makes the pattern match all
786 types (this is the default).
786 types (this is the default).
787
787
788 Options:
788 Options:
789
789
790 -a: makes the pattern match even objects whose names start with a
790 -a: makes the pattern match even objects whose names start with a
791 single underscore. These names are normally ommitted from the
791 single underscore. These names are normally ommitted from the
792 search.
792 search.
793
793
794 -i/-c: make the pattern case insensitive/sensitive. If neither of
794 -i/-c: make the pattern case insensitive/sensitive. If neither of
795 these options is given, the default is read from your ipythonrc
795 these options is given, the default is read from your ipythonrc
796 file. The option name which sets this value is
796 file. The option name which sets this value is
797 'wildcards_case_sensitive'. If this option is not specified in your
797 'wildcards_case_sensitive'. If this option is not specified in your
798 ipythonrc file, IPython's internal default is to do a case sensitive
798 ipythonrc file, IPython's internal default is to do a case sensitive
799 search.
799 search.
800
800
801 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
801 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
802 specifiy can be searched in any of the following namespaces:
802 specifiy can be searched in any of the following namespaces:
803 'builtin', 'user', 'user_global','internal', 'alias', where
803 'builtin', 'user', 'user_global','internal', 'alias', where
804 'builtin' and 'user' are the search defaults. Note that you should
804 'builtin' and 'user' are the search defaults. Note that you should
805 not use quotes when specifying namespaces.
805 not use quotes when specifying namespaces.
806
806
807 'Builtin' contains the python module builtin, 'user' contains all
807 'Builtin' contains the python module builtin, 'user' contains all
808 user data, 'alias' only contain the shell aliases and no python
808 user data, 'alias' only contain the shell aliases and no python
809 objects, 'internal' contains objects used by IPython. The
809 objects, 'internal' contains objects used by IPython. The
810 'user_global' namespace is only used by embedded IPython instances,
810 'user_global' namespace is only used by embedded IPython instances,
811 and it contains module-level globals. You can add namespaces to the
811 and it contains module-level globals. You can add namespaces to the
812 search with -s or exclude them with -e (these options can be given
812 search with -s or exclude them with -e (these options can be given
813 more than once).
813 more than once).
814
814
815 Examples:
815 Examples:
816
816
817 %psearch a* -> objects beginning with an a
817 %psearch a* -> objects beginning with an a
818 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
818 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
819 %psearch a* function -> all functions beginning with an a
819 %psearch a* function -> all functions beginning with an a
820 %psearch re.e* -> objects beginning with an e in module re
820 %psearch re.e* -> objects beginning with an e in module re
821 %psearch r*.e* -> objects that start with e in modules starting in r
821 %psearch r*.e* -> objects that start with e in modules starting in r
822 %psearch r*.* string -> all strings in modules beginning with r
822 %psearch r*.* string -> all strings in modules beginning with r
823
823
824 Case sensitve search:
824 Case sensitve search:
825
825
826 %psearch -c a* list all object beginning with lower case a
826 %psearch -c a* list all object beginning with lower case a
827
827
828 Show objects beginning with a single _:
828 Show objects beginning with a single _:
829
829
830 %psearch -a _* list objects beginning with a single underscore"""
830 %psearch -a _* list objects beginning with a single underscore"""
831 try:
831 try:
832 parameter_s = parameter_s.encode('ascii')
832 parameter_s = parameter_s.encode('ascii')
833 except UnicodeEncodeError:
833 except UnicodeEncodeError:
834 print 'Python identifiers can only contain ascii characters.'
834 print 'Python identifiers can only contain ascii characters.'
835 return
835 return
836
836
837 # default namespaces to be searched
837 # default namespaces to be searched
838 def_search = ['user','builtin']
838 def_search = ['user','builtin']
839
839
840 # Process options/args
840 # Process options/args
841 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
841 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
842 opt = opts.get
842 opt = opts.get
843 shell = self.shell
843 shell = self.shell
844 psearch = shell.inspector.psearch
844 psearch = shell.inspector.psearch
845
845
846 # select case options
846 # select case options
847 if opts.has_key('i'):
847 if opts.has_key('i'):
848 ignore_case = True
848 ignore_case = True
849 elif opts.has_key('c'):
849 elif opts.has_key('c'):
850 ignore_case = False
850 ignore_case = False
851 else:
851 else:
852 ignore_case = not shell.wildcards_case_sensitive
852 ignore_case = not shell.wildcards_case_sensitive
853
853
854 # Build list of namespaces to search from user options
854 # Build list of namespaces to search from user options
855 def_search.extend(opt('s',[]))
855 def_search.extend(opt('s',[]))
856 ns_exclude = ns_exclude=opt('e',[])
856 ns_exclude = ns_exclude=opt('e',[])
857 ns_search = [nm for nm in def_search if nm not in ns_exclude]
857 ns_search = [nm for nm in def_search if nm not in ns_exclude]
858
858
859 # Call the actual search
859 # Call the actual search
860 try:
860 try:
861 psearch(args,shell.ns_table,ns_search,
861 psearch(args,shell.ns_table,ns_search,
862 show_all=opt('a'),ignore_case=ignore_case)
862 show_all=opt('a'),ignore_case=ignore_case)
863 except:
863 except:
864 shell.showtraceback()
864 shell.showtraceback()
865
865
866 def magic_who_ls(self, parameter_s=''):
866 def magic_who_ls(self, parameter_s=''):
867 """Return a sorted list of all interactive variables.
867 """Return a sorted list of all interactive variables.
868
868
869 If arguments are given, only variables of types matching these
869 If arguments are given, only variables of types matching these
870 arguments are returned."""
870 arguments are returned."""
871
871
872 user_ns = self.shell.user_ns
872 user_ns = self.shell.user_ns
873 internal_ns = self.shell.internal_ns
873 internal_ns = self.shell.internal_ns
874 user_config_ns = self.shell.user_config_ns
874 user_config_ns = self.shell.user_config_ns
875 out = []
875 out = []
876 typelist = parameter_s.split()
876 typelist = parameter_s.split()
877
877
878 for i in user_ns:
878 for i in user_ns:
879 if not (i.startswith('_') or i.startswith('_i')) \
879 if not (i.startswith('_') or i.startswith('_i')) \
880 and not (i in internal_ns or i in user_config_ns):
880 and not (i in internal_ns or i in user_config_ns):
881 if typelist:
881 if typelist:
882 if type(user_ns[i]).__name__ in typelist:
882 if type(user_ns[i]).__name__ in typelist:
883 out.append(i)
883 out.append(i)
884 else:
884 else:
885 out.append(i)
885 out.append(i)
886 out.sort()
886 out.sort()
887 return out
887 return out
888
888
889 def magic_who(self, parameter_s=''):
889 def magic_who(self, parameter_s=''):
890 """Print all interactive variables, with some minimal formatting.
890 """Print all interactive variables, with some minimal formatting.
891
891
892 If any arguments are given, only variables whose type matches one of
892 If any arguments are given, only variables whose type matches one of
893 these are printed. For example:
893 these are printed. For example:
894
894
895 %who function str
895 %who function str
896
896
897 will only list functions and strings, excluding all other types of
897 will only list functions and strings, excluding all other types of
898 variables. To find the proper type names, simply use type(var) at a
898 variables. To find the proper type names, simply use type(var) at a
899 command line to see how python prints type names. For example:
899 command line to see how python prints type names. For example:
900
900
901 In [1]: type('hello')\\
901 In [1]: type('hello')\\
902 Out[1]: <type 'str'>
902 Out[1]: <type 'str'>
903
903
904 indicates that the type name for strings is 'str'.
904 indicates that the type name for strings is 'str'.
905
905
906 %who always excludes executed names loaded through your configuration
906 %who always excludes executed names loaded through your configuration
907 file and things which are internal to IPython.
907 file and things which are internal to IPython.
908
908
909 This is deliberate, as typically you may load many modules and the
909 This is deliberate, as typically you may load many modules and the
910 purpose of %who is to show you only what you've manually defined."""
910 purpose of %who is to show you only what you've manually defined."""
911
911
912 varlist = self.magic_who_ls(parameter_s)
912 varlist = self.magic_who_ls(parameter_s)
913 if not varlist:
913 if not varlist:
914 if parameter_s:
914 if parameter_s:
915 print 'No variables match your requested type.'
915 print 'No variables match your requested type.'
916 else:
916 else:
917 print 'Interactive namespace is empty.'
917 print 'Interactive namespace is empty.'
918 return
918 return
919
919
920 # if we have variables, move on...
920 # if we have variables, move on...
921 count = 0
921 count = 0
922 for i in varlist:
922 for i in varlist:
923 print i+'\t',
923 print i+'\t',
924 count += 1
924 count += 1
925 if count > 8:
925 if count > 8:
926 count = 0
926 count = 0
927 print
927 print
928 print
928 print
929
929
930 def magic_whos(self, parameter_s=''):
930 def magic_whos(self, parameter_s=''):
931 """Like %who, but gives some extra information about each variable.
931 """Like %who, but gives some extra information about each variable.
932
932
933 The same type filtering of %who can be applied here.
933 The same type filtering of %who can be applied here.
934
934
935 For all variables, the type is printed. Additionally it prints:
935 For all variables, the type is printed. Additionally it prints:
936
936
937 - For {},[],(): their length.
937 - For {},[],(): their length.
938
938
939 - For numpy and Numeric arrays, a summary with shape, number of
939 - For numpy and Numeric arrays, a summary with shape, number of
940 elements, typecode and size in memory.
940 elements, typecode and size in memory.
941
941
942 - Everything else: a string representation, snipping their middle if
942 - Everything else: a string representation, snipping their middle if
943 too long."""
943 too long."""
944
944
945 varnames = self.magic_who_ls(parameter_s)
945 varnames = self.magic_who_ls(parameter_s)
946 if not varnames:
946 if not varnames:
947 if parameter_s:
947 if parameter_s:
948 print 'No variables match your requested type.'
948 print 'No variables match your requested type.'
949 else:
949 else:
950 print 'Interactive namespace is empty.'
950 print 'Interactive namespace is empty.'
951 return
951 return
952
952
953 # if we have variables, move on...
953 # if we have variables, move on...
954
954
955 # for these types, show len() instead of data:
955 # for these types, show len() instead of data:
956 seq_types = [types.DictType,types.ListType,types.TupleType]
956 seq_types = [types.DictType,types.ListType,types.TupleType]
957
957
958 # for numpy/Numeric arrays, display summary info
958 # for numpy/Numeric arrays, display summary info
959 try:
959 try:
960 import numpy
960 import numpy
961 except ImportError:
961 except ImportError:
962 ndarray_type = None
962 ndarray_type = None
963 else:
963 else:
964 ndarray_type = numpy.ndarray.__name__
964 ndarray_type = numpy.ndarray.__name__
965 try:
965 try:
966 import Numeric
966 import Numeric
967 except ImportError:
967 except ImportError:
968 array_type = None
968 array_type = None
969 else:
969 else:
970 array_type = Numeric.ArrayType.__name__
970 array_type = Numeric.ArrayType.__name__
971
971
972 # Find all variable names and types so we can figure out column sizes
972 # Find all variable names and types so we can figure out column sizes
973 def get_vars(i):
973 def get_vars(i):
974 return self.shell.user_ns[i]
974 return self.shell.user_ns[i]
975
975
976 # some types are well known and can be shorter
976 # some types are well known and can be shorter
977 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
977 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
978 def type_name(v):
978 def type_name(v):
979 tn = type(v).__name__
979 tn = type(v).__name__
980 return abbrevs.get(tn,tn)
980 return abbrevs.get(tn,tn)
981
981
982 varlist = map(get_vars,varnames)
982 varlist = map(get_vars,varnames)
983
983
984 typelist = []
984 typelist = []
985 for vv in varlist:
985 for vv in varlist:
986 tt = type_name(vv)
986 tt = type_name(vv)
987
987
988 if tt=='instance':
988 if tt=='instance':
989 typelist.append( abbrevs.get(str(vv.__class__),
989 typelist.append( abbrevs.get(str(vv.__class__),
990 str(vv.__class__)))
990 str(vv.__class__)))
991 else:
991 else:
992 typelist.append(tt)
992 typelist.append(tt)
993
993
994 # column labels and # of spaces as separator
994 # column labels and # of spaces as separator
995 varlabel = 'Variable'
995 varlabel = 'Variable'
996 typelabel = 'Type'
996 typelabel = 'Type'
997 datalabel = 'Data/Info'
997 datalabel = 'Data/Info'
998 colsep = 3
998 colsep = 3
999 # variable format strings
999 # variable format strings
1000 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1000 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1001 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1001 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1002 aformat = "%s: %s elems, type `%s`, %s bytes"
1002 aformat = "%s: %s elems, type `%s`, %s bytes"
1003 # find the size of the columns to format the output nicely
1003 # find the size of the columns to format the output nicely
1004 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1004 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1005 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1005 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1006 # table header
1006 # table header
1007 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1007 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1008 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1008 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1009 # and the table itself
1009 # and the table itself
1010 kb = 1024
1010 kb = 1024
1011 Mb = 1048576 # kb**2
1011 Mb = 1048576 # kb**2
1012 for vname,var,vtype in zip(varnames,varlist,typelist):
1012 for vname,var,vtype in zip(varnames,varlist,typelist):
1013 print itpl(vformat),
1013 print itpl(vformat),
1014 if vtype in seq_types:
1014 if vtype in seq_types:
1015 print len(var)
1015 print len(var)
1016 elif vtype in [array_type,ndarray_type]:
1016 elif vtype in [array_type,ndarray_type]:
1017 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1017 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1018 if vtype==ndarray_type:
1018 if vtype==ndarray_type:
1019 # numpy
1019 # numpy
1020 vsize = var.size
1020 vsize = var.size
1021 vbytes = vsize*var.itemsize
1021 vbytes = vsize*var.itemsize
1022 vdtype = var.dtype
1022 vdtype = var.dtype
1023 else:
1023 else:
1024 # Numeric
1024 # Numeric
1025 vsize = Numeric.size(var)
1025 vsize = Numeric.size(var)
1026 vbytes = vsize*var.itemsize()
1026 vbytes = vsize*var.itemsize()
1027 vdtype = var.typecode()
1027 vdtype = var.typecode()
1028
1028
1029 if vbytes < 100000:
1029 if vbytes < 100000:
1030 print aformat % (vshape,vsize,vdtype,vbytes)
1030 print aformat % (vshape,vsize,vdtype,vbytes)
1031 else:
1031 else:
1032 print aformat % (vshape,vsize,vdtype,vbytes),
1032 print aformat % (vshape,vsize,vdtype,vbytes),
1033 if vbytes < Mb:
1033 if vbytes < Mb:
1034 print '(%s kb)' % (vbytes/kb,)
1034 print '(%s kb)' % (vbytes/kb,)
1035 else:
1035 else:
1036 print '(%s Mb)' % (vbytes/Mb,)
1036 print '(%s Mb)' % (vbytes/Mb,)
1037 else:
1037 else:
1038 try:
1038 try:
1039 vstr = str(var)
1039 vstr = str(var)
1040 except UnicodeEncodeError:
1040 except UnicodeEncodeError:
1041 vstr = unicode(var).encode(sys.getdefaultencoding(),
1041 vstr = unicode(var).encode(sys.getdefaultencoding(),
1042 'backslashreplace')
1042 'backslashreplace')
1043 vstr = vstr.replace('\n','\\n')
1043 vstr = vstr.replace('\n','\\n')
1044 if len(vstr) < 50:
1044 if len(vstr) < 50:
1045 print vstr
1045 print vstr
1046 else:
1046 else:
1047 printpl(vfmt_short)
1047 printpl(vfmt_short)
1048
1048
1049 def magic_reset(self, parameter_s=''):
1049 def magic_reset(self, parameter_s=''):
1050 """Resets the namespace by removing all names defined by the user.
1050 """Resets the namespace by removing all names defined by the user.
1051
1051
1052 Input/Output history are left around in case you need them.
1052 Input/Output history are left around in case you need them.
1053
1053
1054 Parameters
1054 Parameters
1055 ----------
1055 ----------
1056 -y : force reset without asking for confirmation.
1056 -y : force reset without asking for confirmation.
1057
1057
1058 Examples
1058 Examples
1059 --------
1059 --------
1060 In [6]: a = 1
1060 In [6]: a = 1
1061
1061
1062 In [7]: a
1062 In [7]: a
1063 Out[7]: 1
1063 Out[7]: 1
1064
1064
1065 In [8]: 'a' in _ip.user_ns
1065 In [8]: 'a' in _ip.user_ns
1066 Out[8]: True
1066 Out[8]: True
1067
1067
1068 In [9]: %reset -f
1068 In [9]: %reset -f
1069
1069
1070 In [10]: 'a' in _ip.user_ns
1070 In [10]: 'a' in _ip.user_ns
1071 Out[10]: False
1071 Out[10]: False
1072 """
1072 """
1073
1073
1074 if parameter_s == '-f':
1074 if parameter_s == '-f':
1075 ans = True
1075 ans = True
1076 else:
1076 else:
1077 ans = self.shell.ask_yes_no(
1077 ans = self.shell.ask_yes_no(
1078 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1078 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1079 if not ans:
1079 if not ans:
1080 print 'Nothing done.'
1080 print 'Nothing done.'
1081 return
1081 return
1082 user_ns = self.shell.user_ns
1082 user_ns = self.shell.user_ns
1083 for i in self.magic_who_ls():
1083 for i in self.magic_who_ls():
1084 del(user_ns[i])
1084 del(user_ns[i])
1085
1085
1086 # Also flush the private list of module references kept for script
1086 # Also flush the private list of module references kept for script
1087 # execution protection
1087 # execution protection
1088 self.shell.clear_main_mod_cache()
1088 self.shell.clear_main_mod_cache()
1089
1089
1090 def magic_logstart(self,parameter_s=''):
1090 def magic_logstart(self,parameter_s=''):
1091 """Start logging anywhere in a session.
1091 """Start logging anywhere in a session.
1092
1092
1093 %logstart [-o|-r|-t] [log_name [log_mode]]
1093 %logstart [-o|-r|-t] [log_name [log_mode]]
1094
1094
1095 If no name is given, it defaults to a file named 'ipython_log.py' in your
1095 If no name is given, it defaults to a file named 'ipython_log.py' in your
1096 current directory, in 'rotate' mode (see below).
1096 current directory, in 'rotate' mode (see below).
1097
1097
1098 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1098 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1099 history up to that point and then continues logging.
1099 history up to that point and then continues logging.
1100
1100
1101 %logstart takes a second optional parameter: logging mode. This can be one
1101 %logstart takes a second optional parameter: logging mode. This can be one
1102 of (note that the modes are given unquoted):\\
1102 of (note that the modes are given unquoted):\\
1103 append: well, that says it.\\
1103 append: well, that says it.\\
1104 backup: rename (if exists) to name~ and start name.\\
1104 backup: rename (if exists) to name~ and start name.\\
1105 global: single logfile in your home dir, appended to.\\
1105 global: single logfile in your home dir, appended to.\\
1106 over : overwrite existing log.\\
1106 over : overwrite existing log.\\
1107 rotate: create rotating logs name.1~, name.2~, etc.
1107 rotate: create rotating logs name.1~, name.2~, etc.
1108
1108
1109 Options:
1109 Options:
1110
1110
1111 -o: log also IPython's output. In this mode, all commands which
1111 -o: log also IPython's output. In this mode, all commands which
1112 generate an Out[NN] prompt are recorded to the logfile, right after
1112 generate an Out[NN] prompt are recorded to the logfile, right after
1113 their corresponding input line. The output lines are always
1113 their corresponding input line. The output lines are always
1114 prepended with a '#[Out]# ' marker, so that the log remains valid
1114 prepended with a '#[Out]# ' marker, so that the log remains valid
1115 Python code.
1115 Python code.
1116
1116
1117 Since this marker is always the same, filtering only the output from
1117 Since this marker is always the same, filtering only the output from
1118 a log is very easy, using for example a simple awk call:
1118 a log is very easy, using for example a simple awk call:
1119
1119
1120 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1120 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1121
1121
1122 -r: log 'raw' input. Normally, IPython's logs contain the processed
1122 -r: log 'raw' input. Normally, IPython's logs contain the processed
1123 input, so that user lines are logged in their final form, converted
1123 input, so that user lines are logged in their final form, converted
1124 into valid Python. For example, %Exit is logged as
1124 into valid Python. For example, %Exit is logged as
1125 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1125 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1126 exactly as typed, with no transformations applied.
1126 exactly as typed, with no transformations applied.
1127
1127
1128 -t: put timestamps before each input line logged (these are put in
1128 -t: put timestamps before each input line logged (these are put in
1129 comments)."""
1129 comments)."""
1130
1130
1131 opts,par = self.parse_options(parameter_s,'ort')
1131 opts,par = self.parse_options(parameter_s,'ort')
1132 log_output = 'o' in opts
1132 log_output = 'o' in opts
1133 log_raw_input = 'r' in opts
1133 log_raw_input = 'r' in opts
1134 timestamp = 't' in opts
1134 timestamp = 't' in opts
1135
1135
1136 logger = self.shell.logger
1136 logger = self.shell.logger
1137
1137
1138 # if no args are given, the defaults set in the logger constructor by
1138 # if no args are given, the defaults set in the logger constructor by
1139 # ipytohn remain valid
1139 # ipytohn remain valid
1140 if par:
1140 if par:
1141 try:
1141 try:
1142 logfname,logmode = par.split()
1142 logfname,logmode = par.split()
1143 except:
1143 except:
1144 logfname = par
1144 logfname = par
1145 logmode = 'backup'
1145 logmode = 'backup'
1146 else:
1146 else:
1147 logfname = logger.logfname
1147 logfname = logger.logfname
1148 logmode = logger.logmode
1148 logmode = logger.logmode
1149 # put logfname into rc struct as if it had been called on the command
1149 # put logfname into rc struct as if it had been called on the command
1150 # line, so it ends up saved in the log header Save it in case we need
1150 # line, so it ends up saved in the log header Save it in case we need
1151 # to restore it...
1151 # to restore it...
1152 old_logfile = self.shell.logfile
1152 old_logfile = self.shell.logfile
1153 if logfname:
1153 if logfname:
1154 logfname = os.path.expanduser(logfname)
1154 logfname = os.path.expanduser(logfname)
1155 self.shell.logfile = logfname
1155 self.shell.logfile = logfname
1156 # TODO: we need to re-think how logs with args/opts are replayed
1156 # TODO: we need to re-think how logs with args/opts are replayed
1157 # and tracked.
1157 # and tracked.
1158 # loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1158 # loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1159 loghead = self.shell.loghead_tpl % ('','')
1159 loghead = self.shell.loghead_tpl % ('','')
1160 try:
1160 try:
1161 started = logger.logstart(logfname,loghead,logmode,
1161 started = logger.logstart(logfname,loghead,logmode,
1162 log_output,timestamp,log_raw_input)
1162 log_output,timestamp,log_raw_input)
1163 except:
1163 except:
1164 rc.opts.logfile = old_logfile
1164 rc.opts.logfile = old_logfile
1165 warn("Couldn't start log: %s" % sys.exc_info()[1])
1165 warn("Couldn't start log: %s" % sys.exc_info()[1])
1166 else:
1166 else:
1167 # log input history up to this point, optionally interleaving
1167 # log input history up to this point, optionally interleaving
1168 # output if requested
1168 # output if requested
1169
1169
1170 if timestamp:
1170 if timestamp:
1171 # disable timestamping for the previous history, since we've
1171 # disable timestamping for the previous history, since we've
1172 # lost those already (no time machine here).
1172 # lost those already (no time machine here).
1173 logger.timestamp = False
1173 logger.timestamp = False
1174
1174
1175 if log_raw_input:
1175 if log_raw_input:
1176 input_hist = self.shell.input_hist_raw
1176 input_hist = self.shell.input_hist_raw
1177 else:
1177 else:
1178 input_hist = self.shell.input_hist
1178 input_hist = self.shell.input_hist
1179
1179
1180 if log_output:
1180 if log_output:
1181 log_write = logger.log_write
1181 log_write = logger.log_write
1182 output_hist = self.shell.output_hist
1182 output_hist = self.shell.output_hist
1183 for n in range(1,len(input_hist)-1):
1183 for n in range(1,len(input_hist)-1):
1184 log_write(input_hist[n].rstrip())
1184 log_write(input_hist[n].rstrip())
1185 if n in output_hist:
1185 if n in output_hist:
1186 log_write(repr(output_hist[n]),'output')
1186 log_write(repr(output_hist[n]),'output')
1187 else:
1187 else:
1188 logger.log_write(input_hist[1:])
1188 logger.log_write(input_hist[1:])
1189 if timestamp:
1189 if timestamp:
1190 # re-enable timestamping
1190 # re-enable timestamping
1191 logger.timestamp = True
1191 logger.timestamp = True
1192
1192
1193 print ('Activating auto-logging. '
1193 print ('Activating auto-logging. '
1194 'Current session state plus future input saved.')
1194 'Current session state plus future input saved.')
1195 logger.logstate()
1195 logger.logstate()
1196
1196
1197 def magic_logstop(self,parameter_s=''):
1197 def magic_logstop(self,parameter_s=''):
1198 """Fully stop logging and close log file.
1198 """Fully stop logging and close log file.
1199
1199
1200 In order to start logging again, a new %logstart call needs to be made,
1200 In order to start logging again, a new %logstart call needs to be made,
1201 possibly (though not necessarily) with a new filename, mode and other
1201 possibly (though not necessarily) with a new filename, mode and other
1202 options."""
1202 options."""
1203 self.logger.logstop()
1203 self.logger.logstop()
1204
1204
1205 def magic_logoff(self,parameter_s=''):
1205 def magic_logoff(self,parameter_s=''):
1206 """Temporarily stop logging.
1206 """Temporarily stop logging.
1207
1207
1208 You must have previously started logging."""
1208 You must have previously started logging."""
1209 self.shell.logger.switch_log(0)
1209 self.shell.logger.switch_log(0)
1210
1210
1211 def magic_logon(self,parameter_s=''):
1211 def magic_logon(self,parameter_s=''):
1212 """Restart logging.
1212 """Restart logging.
1213
1213
1214 This function is for restarting logging which you've temporarily
1214 This function is for restarting logging which you've temporarily
1215 stopped with %logoff. For starting logging for the first time, you
1215 stopped with %logoff. For starting logging for the first time, you
1216 must use the %logstart function, which allows you to specify an
1216 must use the %logstart function, which allows you to specify an
1217 optional log filename."""
1217 optional log filename."""
1218
1218
1219 self.shell.logger.switch_log(1)
1219 self.shell.logger.switch_log(1)
1220
1220
1221 def magic_logstate(self,parameter_s=''):
1221 def magic_logstate(self,parameter_s=''):
1222 """Print the status of the logging system."""
1222 """Print the status of the logging system."""
1223
1223
1224 self.shell.logger.logstate()
1224 self.shell.logger.logstate()
1225
1225
1226 def magic_pdb(self, parameter_s=''):
1226 def magic_pdb(self, parameter_s=''):
1227 """Control the automatic calling of the pdb interactive debugger.
1227 """Control the automatic calling of the pdb interactive debugger.
1228
1228
1229 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1229 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1230 argument it works as a toggle.
1230 argument it works as a toggle.
1231
1231
1232 When an exception is triggered, IPython can optionally call the
1232 When an exception is triggered, IPython can optionally call the
1233 interactive pdb debugger after the traceback printout. %pdb toggles
1233 interactive pdb debugger after the traceback printout. %pdb toggles
1234 this feature on and off.
1234 this feature on and off.
1235
1235
1236 The initial state of this feature is set in your ipythonrc
1236 The initial state of this feature is set in your ipythonrc
1237 configuration file (the variable is called 'pdb').
1237 configuration file (the variable is called 'pdb').
1238
1238
1239 If you want to just activate the debugger AFTER an exception has fired,
1239 If you want to just activate the debugger AFTER an exception has fired,
1240 without having to type '%pdb on' and rerunning your code, you can use
1240 without having to type '%pdb on' and rerunning your code, you can use
1241 the %debug magic."""
1241 the %debug magic."""
1242
1242
1243 par = parameter_s.strip().lower()
1243 par = parameter_s.strip().lower()
1244
1244
1245 if par:
1245 if par:
1246 try:
1246 try:
1247 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1247 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1248 except KeyError:
1248 except KeyError:
1249 print ('Incorrect argument. Use on/1, off/0, '
1249 print ('Incorrect argument. Use on/1, off/0, '
1250 'or nothing for a toggle.')
1250 'or nothing for a toggle.')
1251 return
1251 return
1252 else:
1252 else:
1253 # toggle
1253 # toggle
1254 new_pdb = not self.shell.call_pdb
1254 new_pdb = not self.shell.call_pdb
1255
1255
1256 # set on the shell
1256 # set on the shell
1257 self.shell.call_pdb = new_pdb
1257 self.shell.call_pdb = new_pdb
1258 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1258 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1259
1259
1260 def magic_debug(self, parameter_s=''):
1260 def magic_debug(self, parameter_s=''):
1261 """Activate the interactive debugger in post-mortem mode.
1261 """Activate the interactive debugger in post-mortem mode.
1262
1262
1263 If an exception has just occurred, this lets you inspect its stack
1263 If an exception has just occurred, this lets you inspect its stack
1264 frames interactively. Note that this will always work only on the last
1264 frames interactively. Note that this will always work only on the last
1265 traceback that occurred, so you must call this quickly after an
1265 traceback that occurred, so you must call this quickly after an
1266 exception that you wish to inspect has fired, because if another one
1266 exception that you wish to inspect has fired, because if another one
1267 occurs, it clobbers the previous one.
1267 occurs, it clobbers the previous one.
1268
1268
1269 If you want IPython to automatically do this on every exception, see
1269 If you want IPython to automatically do this on every exception, see
1270 the %pdb magic for more details.
1270 the %pdb magic for more details.
1271 """
1271 """
1272
1272
1273 self.shell.debugger(force=True)
1273 self.shell.debugger(force=True)
1274
1274
1275 @testdec.skip_doctest
1275 @testdec.skip_doctest
1276 def magic_prun(self, parameter_s ='',user_mode=1,
1276 def magic_prun(self, parameter_s ='',user_mode=1,
1277 opts=None,arg_lst=None,prog_ns=None):
1277 opts=None,arg_lst=None,prog_ns=None):
1278
1278
1279 """Run a statement through the python code profiler.
1279 """Run a statement through the python code profiler.
1280
1280
1281 Usage:
1281 Usage:
1282 %prun [options] statement
1282 %prun [options] statement
1283
1283
1284 The given statement (which doesn't require quote marks) is run via the
1284 The given statement (which doesn't require quote marks) is run via the
1285 python profiler in a manner similar to the profile.run() function.
1285 python profiler in a manner similar to the profile.run() function.
1286 Namespaces are internally managed to work correctly; profile.run
1286 Namespaces are internally managed to work correctly; profile.run
1287 cannot be used in IPython because it makes certain assumptions about
1287 cannot be used in IPython because it makes certain assumptions about
1288 namespaces which do not hold under IPython.
1288 namespaces which do not hold under IPython.
1289
1289
1290 Options:
1290 Options:
1291
1291
1292 -l <limit>: you can place restrictions on what or how much of the
1292 -l <limit>: you can place restrictions on what or how much of the
1293 profile gets printed. The limit value can be:
1293 profile gets printed. The limit value can be:
1294
1294
1295 * A string: only information for function names containing this string
1295 * A string: only information for function names containing this string
1296 is printed.
1296 is printed.
1297
1297
1298 * An integer: only these many lines are printed.
1298 * An integer: only these many lines are printed.
1299
1299
1300 * A float (between 0 and 1): this fraction of the report is printed
1300 * A float (between 0 and 1): this fraction of the report is printed
1301 (for example, use a limit of 0.4 to see the topmost 40% only).
1301 (for example, use a limit of 0.4 to see the topmost 40% only).
1302
1302
1303 You can combine several limits with repeated use of the option. For
1303 You can combine several limits with repeated use of the option. For
1304 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1304 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1305 information about class constructors.
1305 information about class constructors.
1306
1306
1307 -r: return the pstats.Stats object generated by the profiling. This
1307 -r: return the pstats.Stats object generated by the profiling. This
1308 object has all the information about the profile in it, and you can
1308 object has all the information about the profile in it, and you can
1309 later use it for further analysis or in other functions.
1309 later use it for further analysis or in other functions.
1310
1310
1311 -s <key>: sort profile by given key. You can provide more than one key
1311 -s <key>: sort profile by given key. You can provide more than one key
1312 by using the option several times: '-s key1 -s key2 -s key3...'. The
1312 by using the option several times: '-s key1 -s key2 -s key3...'. The
1313 default sorting key is 'time'.
1313 default sorting key is 'time'.
1314
1314
1315 The following is copied verbatim from the profile documentation
1315 The following is copied verbatim from the profile documentation
1316 referenced below:
1316 referenced below:
1317
1317
1318 When more than one key is provided, additional keys are used as
1318 When more than one key is provided, additional keys are used as
1319 secondary criteria when the there is equality in all keys selected
1319 secondary criteria when the there is equality in all keys selected
1320 before them.
1320 before them.
1321
1321
1322 Abbreviations can be used for any key names, as long as the
1322 Abbreviations can be used for any key names, as long as the
1323 abbreviation is unambiguous. The following are the keys currently
1323 abbreviation is unambiguous. The following are the keys currently
1324 defined:
1324 defined:
1325
1325
1326 Valid Arg Meaning
1326 Valid Arg Meaning
1327 "calls" call count
1327 "calls" call count
1328 "cumulative" cumulative time
1328 "cumulative" cumulative time
1329 "file" file name
1329 "file" file name
1330 "module" file name
1330 "module" file name
1331 "pcalls" primitive call count
1331 "pcalls" primitive call count
1332 "line" line number
1332 "line" line number
1333 "name" function name
1333 "name" function name
1334 "nfl" name/file/line
1334 "nfl" name/file/line
1335 "stdname" standard name
1335 "stdname" standard name
1336 "time" internal time
1336 "time" internal time
1337
1337
1338 Note that all sorts on statistics are in descending order (placing
1338 Note that all sorts on statistics are in descending order (placing
1339 most time consuming items first), where as name, file, and line number
1339 most time consuming items first), where as name, file, and line number
1340 searches are in ascending order (i.e., alphabetical). The subtle
1340 searches are in ascending order (i.e., alphabetical). The subtle
1341 distinction between "nfl" and "stdname" is that the standard name is a
1341 distinction between "nfl" and "stdname" is that the standard name is a
1342 sort of the name as printed, which means that the embedded line
1342 sort of the name as printed, which means that the embedded line
1343 numbers get compared in an odd way. For example, lines 3, 20, and 40
1343 numbers get compared in an odd way. For example, lines 3, 20, and 40
1344 would (if the file names were the same) appear in the string order
1344 would (if the file names were the same) appear in the string order
1345 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1345 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1346 line numbers. In fact, sort_stats("nfl") is the same as
1346 line numbers. In fact, sort_stats("nfl") is the same as
1347 sort_stats("name", "file", "line").
1347 sort_stats("name", "file", "line").
1348
1348
1349 -T <filename>: save profile results as shown on screen to a text
1349 -T <filename>: save profile results as shown on screen to a text
1350 file. The profile is still shown on screen.
1350 file. The profile is still shown on screen.
1351
1351
1352 -D <filename>: save (via dump_stats) profile statistics to given
1352 -D <filename>: save (via dump_stats) profile statistics to given
1353 filename. This data is in a format understod by the pstats module, and
1353 filename. This data is in a format understod by the pstats module, and
1354 is generated by a call to the dump_stats() method of profile
1354 is generated by a call to the dump_stats() method of profile
1355 objects. The profile is still shown on screen.
1355 objects. The profile is still shown on screen.
1356
1356
1357 If you want to run complete programs under the profiler's control, use
1357 If you want to run complete programs under the profiler's control, use
1358 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1358 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1359 contains profiler specific options as described here.
1359 contains profiler specific options as described here.
1360
1360
1361 You can read the complete documentation for the profile module with::
1361 You can read the complete documentation for the profile module with::
1362
1362
1363 In [1]: import profile; profile.help()
1363 In [1]: import profile; profile.help()
1364 """
1364 """
1365
1365
1366 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1366 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1367 # protect user quote marks
1367 # protect user quote marks
1368 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1368 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1369
1369
1370 if user_mode: # regular user call
1370 if user_mode: # regular user call
1371 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1371 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1372 list_all=1)
1372 list_all=1)
1373 namespace = self.shell.user_ns
1373 namespace = self.shell.user_ns
1374 else: # called to run a program by %run -p
1374 else: # called to run a program by %run -p
1375 try:
1375 try:
1376 filename = get_py_filename(arg_lst[0])
1376 filename = get_py_filename(arg_lst[0])
1377 except IOError,msg:
1377 except IOError,msg:
1378 error(msg)
1378 error(msg)
1379 return
1379 return
1380
1380
1381 arg_str = 'execfile(filename,prog_ns)'
1381 arg_str = 'execfile(filename,prog_ns)'
1382 namespace = locals()
1382 namespace = locals()
1383
1383
1384 opts.merge(opts_def)
1384 opts.merge(opts_def)
1385
1385
1386 prof = profile.Profile()
1386 prof = profile.Profile()
1387 try:
1387 try:
1388 prof = prof.runctx(arg_str,namespace,namespace)
1388 prof = prof.runctx(arg_str,namespace,namespace)
1389 sys_exit = ''
1389 sys_exit = ''
1390 except SystemExit:
1390 except SystemExit:
1391 sys_exit = """*** SystemExit exception caught in code being profiled."""
1391 sys_exit = """*** SystemExit exception caught in code being profiled."""
1392
1392
1393 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1393 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1394
1394
1395 lims = opts.l
1395 lims = opts.l
1396 if lims:
1396 if lims:
1397 lims = [] # rebuild lims with ints/floats/strings
1397 lims = [] # rebuild lims with ints/floats/strings
1398 for lim in opts.l:
1398 for lim in opts.l:
1399 try:
1399 try:
1400 lims.append(int(lim))
1400 lims.append(int(lim))
1401 except ValueError:
1401 except ValueError:
1402 try:
1402 try:
1403 lims.append(float(lim))
1403 lims.append(float(lim))
1404 except ValueError:
1404 except ValueError:
1405 lims.append(lim)
1405 lims.append(lim)
1406
1406
1407 # Trap output.
1407 # Trap output.
1408 stdout_trap = StringIO()
1408 stdout_trap = StringIO()
1409
1409
1410 if hasattr(stats,'stream'):
1410 if hasattr(stats,'stream'):
1411 # In newer versions of python, the stats object has a 'stream'
1411 # In newer versions of python, the stats object has a 'stream'
1412 # attribute to write into.
1412 # attribute to write into.
1413 stats.stream = stdout_trap
1413 stats.stream = stdout_trap
1414 stats.print_stats(*lims)
1414 stats.print_stats(*lims)
1415 else:
1415 else:
1416 # For older versions, we manually redirect stdout during printing
1416 # For older versions, we manually redirect stdout during printing
1417 sys_stdout = sys.stdout
1417 sys_stdout = sys.stdout
1418 try:
1418 try:
1419 sys.stdout = stdout_trap
1419 sys.stdout = stdout_trap
1420 stats.print_stats(*lims)
1420 stats.print_stats(*lims)
1421 finally:
1421 finally:
1422 sys.stdout = sys_stdout
1422 sys.stdout = sys_stdout
1423
1423
1424 output = stdout_trap.getvalue()
1424 output = stdout_trap.getvalue()
1425 output = output.rstrip()
1425 output = output.rstrip()
1426
1426
1427 page(output,screen_lines=self.shell.usable_screen_length)
1427 page(output,screen_lines=self.shell.usable_screen_length)
1428 print sys_exit,
1428 print sys_exit,
1429
1429
1430 dump_file = opts.D[0]
1430 dump_file = opts.D[0]
1431 text_file = opts.T[0]
1431 text_file = opts.T[0]
1432 if dump_file:
1432 if dump_file:
1433 prof.dump_stats(dump_file)
1433 prof.dump_stats(dump_file)
1434 print '\n*** Profile stats marshalled to file',\
1434 print '\n*** Profile stats marshalled to file',\
1435 `dump_file`+'.',sys_exit
1435 `dump_file`+'.',sys_exit
1436 if text_file:
1436 if text_file:
1437 pfile = file(text_file,'w')
1437 pfile = file(text_file,'w')
1438 pfile.write(output)
1438 pfile.write(output)
1439 pfile.close()
1439 pfile.close()
1440 print '\n*** Profile printout saved to text file',\
1440 print '\n*** Profile printout saved to text file',\
1441 `text_file`+'.',sys_exit
1441 `text_file`+'.',sys_exit
1442
1442
1443 if opts.has_key('r'):
1443 if opts.has_key('r'):
1444 return stats
1444 return stats
1445 else:
1445 else:
1446 return None
1446 return None
1447
1447
1448 @testdec.skip_doctest
1448 @testdec.skip_doctest
1449 def magic_run(self, parameter_s ='',runner=None,
1449 def magic_run(self, parameter_s ='',runner=None,
1450 file_finder=get_py_filename):
1450 file_finder=get_py_filename):
1451 """Run the named file inside IPython as a program.
1451 """Run the named file inside IPython as a program.
1452
1452
1453 Usage:\\
1453 Usage:\\
1454 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1454 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1455
1455
1456 Parameters after the filename are passed as command-line arguments to
1456 Parameters after the filename are passed as command-line arguments to
1457 the program (put in sys.argv). Then, control returns to IPython's
1457 the program (put in sys.argv). Then, control returns to IPython's
1458 prompt.
1458 prompt.
1459
1459
1460 This is similar to running at a system prompt:\\
1460 This is similar to running at a system prompt:\\
1461 $ python file args\\
1461 $ python file args\\
1462 but with the advantage of giving you IPython's tracebacks, and of
1462 but with the advantage of giving you IPython's tracebacks, and of
1463 loading all variables into your interactive namespace for further use
1463 loading all variables into your interactive namespace for further use
1464 (unless -p is used, see below).
1464 (unless -p is used, see below).
1465
1465
1466 The file is executed in a namespace initially consisting only of
1466 The file is executed in a namespace initially consisting only of
1467 __name__=='__main__' and sys.argv constructed as indicated. It thus
1467 __name__=='__main__' and sys.argv constructed as indicated. It thus
1468 sees its environment as if it were being run as a stand-alone program
1468 sees its environment as if it were being run as a stand-alone program
1469 (except for sharing global objects such as previously imported
1469 (except for sharing global objects such as previously imported
1470 modules). But after execution, the IPython interactive namespace gets
1470 modules). But after execution, the IPython interactive namespace gets
1471 updated with all variables defined in the program (except for __name__
1471 updated with all variables defined in the program (except for __name__
1472 and sys.argv). This allows for very convenient loading of code for
1472 and sys.argv). This allows for very convenient loading of code for
1473 interactive work, while giving each program a 'clean sheet' to run in.
1473 interactive work, while giving each program a 'clean sheet' to run in.
1474
1474
1475 Options:
1475 Options:
1476
1476
1477 -n: __name__ is NOT set to '__main__', but to the running file's name
1477 -n: __name__ is NOT set to '__main__', but to the running file's name
1478 without extension (as python does under import). This allows running
1478 without extension (as python does under import). This allows running
1479 scripts and reloading the definitions in them without calling code
1479 scripts and reloading the definitions in them without calling code
1480 protected by an ' if __name__ == "__main__" ' clause.
1480 protected by an ' if __name__ == "__main__" ' clause.
1481
1481
1482 -i: run the file in IPython's namespace instead of an empty one. This
1482 -i: run the file in IPython's namespace instead of an empty one. This
1483 is useful if you are experimenting with code written in a text editor
1483 is useful if you are experimenting with code written in a text editor
1484 which depends on variables defined interactively.
1484 which depends on variables defined interactively.
1485
1485
1486 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1486 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1487 being run. This is particularly useful if IPython is being used to
1487 being run. This is particularly useful if IPython is being used to
1488 run unittests, which always exit with a sys.exit() call. In such
1488 run unittests, which always exit with a sys.exit() call. In such
1489 cases you are interested in the output of the test results, not in
1489 cases you are interested in the output of the test results, not in
1490 seeing a traceback of the unittest module.
1490 seeing a traceback of the unittest module.
1491
1491
1492 -t: print timing information at the end of the run. IPython will give
1492 -t: print timing information at the end of the run. IPython will give
1493 you an estimated CPU time consumption for your script, which under
1493 you an estimated CPU time consumption for your script, which under
1494 Unix uses the resource module to avoid the wraparound problems of
1494 Unix uses the resource module to avoid the wraparound problems of
1495 time.clock(). Under Unix, an estimate of time spent on system tasks
1495 time.clock(). Under Unix, an estimate of time spent on system tasks
1496 is also given (for Windows platforms this is reported as 0.0).
1496 is also given (for Windows platforms this is reported as 0.0).
1497
1497
1498 If -t is given, an additional -N<N> option can be given, where <N>
1498 If -t is given, an additional -N<N> option can be given, where <N>
1499 must be an integer indicating how many times you want the script to
1499 must be an integer indicating how many times you want the script to
1500 run. The final timing report will include total and per run results.
1500 run. The final timing report will include total and per run results.
1501
1501
1502 For example (testing the script uniq_stable.py):
1502 For example (testing the script uniq_stable.py):
1503
1503
1504 In [1]: run -t uniq_stable
1504 In [1]: run -t uniq_stable
1505
1505
1506 IPython CPU timings (estimated):\\
1506 IPython CPU timings (estimated):\\
1507 User : 0.19597 s.\\
1507 User : 0.19597 s.\\
1508 System: 0.0 s.\\
1508 System: 0.0 s.\\
1509
1509
1510 In [2]: run -t -N5 uniq_stable
1510 In [2]: run -t -N5 uniq_stable
1511
1511
1512 IPython CPU timings (estimated):\\
1512 IPython CPU timings (estimated):\\
1513 Total runs performed: 5\\
1513 Total runs performed: 5\\
1514 Times : Total Per run\\
1514 Times : Total Per run\\
1515 User : 0.910862 s, 0.1821724 s.\\
1515 User : 0.910862 s, 0.1821724 s.\\
1516 System: 0.0 s, 0.0 s.
1516 System: 0.0 s, 0.0 s.
1517
1517
1518 -d: run your program under the control of pdb, the Python debugger.
1518 -d: run your program under the control of pdb, the Python debugger.
1519 This allows you to execute your program step by step, watch variables,
1519 This allows you to execute your program step by step, watch variables,
1520 etc. Internally, what IPython does is similar to calling:
1520 etc. Internally, what IPython does is similar to calling:
1521
1521
1522 pdb.run('execfile("YOURFILENAME")')
1522 pdb.run('execfile("YOURFILENAME")')
1523
1523
1524 with a breakpoint set on line 1 of your file. You can change the line
1524 with a breakpoint set on line 1 of your file. You can change the line
1525 number for this automatic breakpoint to be <N> by using the -bN option
1525 number for this automatic breakpoint to be <N> by using the -bN option
1526 (where N must be an integer). For example:
1526 (where N must be an integer). For example:
1527
1527
1528 %run -d -b40 myscript
1528 %run -d -b40 myscript
1529
1529
1530 will set the first breakpoint at line 40 in myscript.py. Note that
1530 will set the first breakpoint at line 40 in myscript.py. Note that
1531 the first breakpoint must be set on a line which actually does
1531 the first breakpoint must be set on a line which actually does
1532 something (not a comment or docstring) for it to stop execution.
1532 something (not a comment or docstring) for it to stop execution.
1533
1533
1534 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1534 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1535 first enter 'c' (without qoutes) to start execution up to the first
1535 first enter 'c' (without qoutes) to start execution up to the first
1536 breakpoint.
1536 breakpoint.
1537
1537
1538 Entering 'help' gives information about the use of the debugger. You
1538 Entering 'help' gives information about the use of the debugger. You
1539 can easily see pdb's full documentation with "import pdb;pdb.help()"
1539 can easily see pdb's full documentation with "import pdb;pdb.help()"
1540 at a prompt.
1540 at a prompt.
1541
1541
1542 -p: run program under the control of the Python profiler module (which
1542 -p: run program under the control of the Python profiler module (which
1543 prints a detailed report of execution times, function calls, etc).
1543 prints a detailed report of execution times, function calls, etc).
1544
1544
1545 You can pass other options after -p which affect the behavior of the
1545 You can pass other options after -p which affect the behavior of the
1546 profiler itself. See the docs for %prun for details.
1546 profiler itself. See the docs for %prun for details.
1547
1547
1548 In this mode, the program's variables do NOT propagate back to the
1548 In this mode, the program's variables do NOT propagate back to the
1549 IPython interactive namespace (because they remain in the namespace
1549 IPython interactive namespace (because they remain in the namespace
1550 where the profiler executes them).
1550 where the profiler executes them).
1551
1551
1552 Internally this triggers a call to %prun, see its documentation for
1552 Internally this triggers a call to %prun, see its documentation for
1553 details on the options available specifically for profiling.
1553 details on the options available specifically for profiling.
1554
1554
1555 There is one special usage for which the text above doesn't apply:
1555 There is one special usage for which the text above doesn't apply:
1556 if the filename ends with .ipy, the file is run as ipython script,
1556 if the filename ends with .ipy, the file is run as ipython script,
1557 just as if the commands were written on IPython prompt.
1557 just as if the commands were written on IPython prompt.
1558 """
1558 """
1559
1559
1560 # get arguments and set sys.argv for program to be run.
1560 # get arguments and set sys.argv for program to be run.
1561 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1561 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1562 mode='list',list_all=1)
1562 mode='list',list_all=1)
1563
1563
1564 try:
1564 try:
1565 filename = file_finder(arg_lst[0])
1565 filename = file_finder(arg_lst[0])
1566 except IndexError:
1566 except IndexError:
1567 warn('you must provide at least a filename.')
1567 warn('you must provide at least a filename.')
1568 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1568 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1569 return
1569 return
1570 except IOError,msg:
1570 except IOError,msg:
1571 error(msg)
1571 error(msg)
1572 return
1572 return
1573
1573
1574 if filename.lower().endswith('.ipy'):
1574 if filename.lower().endswith('.ipy'):
1575 self.runlines(open(filename).read(), clean=True)
1575 self.runlines(open(filename).read(), clean=True)
1576 return
1576 return
1577
1577
1578 # Control the response to exit() calls made by the script being run
1578 # Control the response to exit() calls made by the script being run
1579 exit_ignore = opts.has_key('e')
1579 exit_ignore = opts.has_key('e')
1580
1580
1581 # Make sure that the running script gets a proper sys.argv as if it
1581 # Make sure that the running script gets a proper sys.argv as if it
1582 # were run from a system shell.
1582 # were run from a system shell.
1583 save_argv = sys.argv # save it for later restoring
1583 save_argv = sys.argv # save it for later restoring
1584 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1584 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1585
1585
1586 if opts.has_key('i'):
1586 if opts.has_key('i'):
1587 # Run in user's interactive namespace
1587 # Run in user's interactive namespace
1588 prog_ns = self.shell.user_ns
1588 prog_ns = self.shell.user_ns
1589 __name__save = self.shell.user_ns['__name__']
1589 __name__save = self.shell.user_ns['__name__']
1590 prog_ns['__name__'] = '__main__'
1590 prog_ns['__name__'] = '__main__'
1591 main_mod = self.shell.new_main_mod(prog_ns)
1591 main_mod = self.shell.new_main_mod(prog_ns)
1592 else:
1592 else:
1593 # Run in a fresh, empty namespace
1593 # Run in a fresh, empty namespace
1594 if opts.has_key('n'):
1594 if opts.has_key('n'):
1595 name = os.path.splitext(os.path.basename(filename))[0]
1595 name = os.path.splitext(os.path.basename(filename))[0]
1596 else:
1596 else:
1597 name = '__main__'
1597 name = '__main__'
1598
1598
1599 main_mod = self.shell.new_main_mod()
1599 main_mod = self.shell.new_main_mod()
1600 prog_ns = main_mod.__dict__
1600 prog_ns = main_mod.__dict__
1601 prog_ns['__name__'] = name
1601 prog_ns['__name__'] = name
1602
1602
1603 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1603 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1604 # set the __file__ global in the script's namespace
1604 # set the __file__ global in the script's namespace
1605 prog_ns['__file__'] = filename
1605 prog_ns['__file__'] = filename
1606
1606
1607 # pickle fix. See iplib for an explanation. But we need to make sure
1607 # pickle fix. See iplib for an explanation. But we need to make sure
1608 # that, if we overwrite __main__, we replace it at the end
1608 # that, if we overwrite __main__, we replace it at the end
1609 main_mod_name = prog_ns['__name__']
1609 main_mod_name = prog_ns['__name__']
1610
1610
1611 if main_mod_name == '__main__':
1611 if main_mod_name == '__main__':
1612 restore_main = sys.modules['__main__']
1612 restore_main = sys.modules['__main__']
1613 else:
1613 else:
1614 restore_main = False
1614 restore_main = False
1615
1615
1616 # This needs to be undone at the end to prevent holding references to
1616 # This needs to be undone at the end to prevent holding references to
1617 # every single object ever created.
1617 # every single object ever created.
1618 sys.modules[main_mod_name] = main_mod
1618 sys.modules[main_mod_name] = main_mod
1619
1619
1620 stats = None
1620 stats = None
1621 try:
1621 try:
1622 self.shell.savehist()
1622 self.shell.savehist()
1623
1623
1624 if opts.has_key('p'):
1624 if opts.has_key('p'):
1625 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1625 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1626 else:
1626 else:
1627 if opts.has_key('d'):
1627 if opts.has_key('d'):
1628 deb = debugger.Pdb(self.shell.colors)
1628 deb = debugger.Pdb(self.shell.colors)
1629 # reset Breakpoint state, which is moronically kept
1629 # reset Breakpoint state, which is moronically kept
1630 # in a class
1630 # in a class
1631 bdb.Breakpoint.next = 1
1631 bdb.Breakpoint.next = 1
1632 bdb.Breakpoint.bplist = {}
1632 bdb.Breakpoint.bplist = {}
1633 bdb.Breakpoint.bpbynumber = [None]
1633 bdb.Breakpoint.bpbynumber = [None]
1634 # Set an initial breakpoint to stop execution
1634 # Set an initial breakpoint to stop execution
1635 maxtries = 10
1635 maxtries = 10
1636 bp = int(opts.get('b',[1])[0])
1636 bp = int(opts.get('b',[1])[0])
1637 checkline = deb.checkline(filename,bp)
1637 checkline = deb.checkline(filename,bp)
1638 if not checkline:
1638 if not checkline:
1639 for bp in range(bp+1,bp+maxtries+1):
1639 for bp in range(bp+1,bp+maxtries+1):
1640 if deb.checkline(filename,bp):
1640 if deb.checkline(filename,bp):
1641 break
1641 break
1642 else:
1642 else:
1643 msg = ("\nI failed to find a valid line to set "
1643 msg = ("\nI failed to find a valid line to set "
1644 "a breakpoint\n"
1644 "a breakpoint\n"
1645 "after trying up to line: %s.\n"
1645 "after trying up to line: %s.\n"
1646 "Please set a valid breakpoint manually "
1646 "Please set a valid breakpoint manually "
1647 "with the -b option." % bp)
1647 "with the -b option." % bp)
1648 error(msg)
1648 error(msg)
1649 return
1649 return
1650 # if we find a good linenumber, set the breakpoint
1650 # if we find a good linenumber, set the breakpoint
1651 deb.do_break('%s:%s' % (filename,bp))
1651 deb.do_break('%s:%s' % (filename,bp))
1652 # Start file run
1652 # Start file run
1653 print "NOTE: Enter 'c' at the",
1653 print "NOTE: Enter 'c' at the",
1654 print "%s prompt to start your script." % deb.prompt
1654 print "%s prompt to start your script." % deb.prompt
1655 try:
1655 try:
1656 deb.run('execfile("%s")' % filename,prog_ns)
1656 deb.run('execfile("%s")' % filename,prog_ns)
1657
1657
1658 except:
1658 except:
1659 etype, value, tb = sys.exc_info()
1659 etype, value, tb = sys.exc_info()
1660 # Skip three frames in the traceback: the %run one,
1660 # Skip three frames in the traceback: the %run one,
1661 # one inside bdb.py, and the command-line typed by the
1661 # one inside bdb.py, and the command-line typed by the
1662 # user (run by exec in pdb itself).
1662 # user (run by exec in pdb itself).
1663 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1663 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1664 else:
1664 else:
1665 if runner is None:
1665 if runner is None:
1666 runner = self.shell.safe_execfile
1666 runner = self.shell.safe_execfile
1667 if opts.has_key('t'):
1667 if opts.has_key('t'):
1668 # timed execution
1668 # timed execution
1669 try:
1669 try:
1670 nruns = int(opts['N'][0])
1670 nruns = int(opts['N'][0])
1671 if nruns < 1:
1671 if nruns < 1:
1672 error('Number of runs must be >=1')
1672 error('Number of runs must be >=1')
1673 return
1673 return
1674 except (KeyError):
1674 except (KeyError):
1675 nruns = 1
1675 nruns = 1
1676 if nruns == 1:
1676 if nruns == 1:
1677 t0 = clock2()
1677 t0 = clock2()
1678 runner(filename,prog_ns,prog_ns,
1678 runner(filename,prog_ns,prog_ns,
1679 exit_ignore=exit_ignore)
1679 exit_ignore=exit_ignore)
1680 t1 = clock2()
1680 t1 = clock2()
1681 t_usr = t1[0]-t0[0]
1681 t_usr = t1[0]-t0[0]
1682 t_sys = t1[1]-t0[1]
1682 t_sys = t1[1]-t0[1]
1683 print "\nIPython CPU timings (estimated):"
1683 print "\nIPython CPU timings (estimated):"
1684 print " User : %10s s." % t_usr
1684 print " User : %10s s." % t_usr
1685 print " System: %10s s." % t_sys
1685 print " System: %10s s." % t_sys
1686 else:
1686 else:
1687 runs = range(nruns)
1687 runs = range(nruns)
1688 t0 = clock2()
1688 t0 = clock2()
1689 for nr in runs:
1689 for nr in runs:
1690 runner(filename,prog_ns,prog_ns,
1690 runner(filename,prog_ns,prog_ns,
1691 exit_ignore=exit_ignore)
1691 exit_ignore=exit_ignore)
1692 t1 = clock2()
1692 t1 = clock2()
1693 t_usr = t1[0]-t0[0]
1693 t_usr = t1[0]-t0[0]
1694 t_sys = t1[1]-t0[1]
1694 t_sys = t1[1]-t0[1]
1695 print "\nIPython CPU timings (estimated):"
1695 print "\nIPython CPU timings (estimated):"
1696 print "Total runs performed:",nruns
1696 print "Total runs performed:",nruns
1697 print " Times : %10s %10s" % ('Total','Per run')
1697 print " Times : %10s %10s" % ('Total','Per run')
1698 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1698 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1699 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1699 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1700
1700
1701 else:
1701 else:
1702 # regular execution
1702 # regular execution
1703 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1703 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1704
1704
1705 if opts.has_key('i'):
1705 if opts.has_key('i'):
1706 self.shell.user_ns['__name__'] = __name__save
1706 self.shell.user_ns['__name__'] = __name__save
1707 else:
1707 else:
1708 # The shell MUST hold a reference to prog_ns so after %run
1708 # The shell MUST hold a reference to prog_ns so after %run
1709 # exits, the python deletion mechanism doesn't zero it out
1709 # exits, the python deletion mechanism doesn't zero it out
1710 # (leaving dangling references).
1710 # (leaving dangling references).
1711 self.shell.cache_main_mod(prog_ns,filename)
1711 self.shell.cache_main_mod(prog_ns,filename)
1712 # update IPython interactive namespace
1712 # update IPython interactive namespace
1713
1713
1714 # Some forms of read errors on the file may mean the
1714 # Some forms of read errors on the file may mean the
1715 # __name__ key was never set; using pop we don't have to
1715 # __name__ key was never set; using pop we don't have to
1716 # worry about a possible KeyError.
1716 # worry about a possible KeyError.
1717 prog_ns.pop('__name__', None)
1717 prog_ns.pop('__name__', None)
1718
1718
1719 self.shell.user_ns.update(prog_ns)
1719 self.shell.user_ns.update(prog_ns)
1720 finally:
1720 finally:
1721 # It's a bit of a mystery why, but __builtins__ can change from
1721 # It's a bit of a mystery why, but __builtins__ can change from
1722 # being a module to becoming a dict missing some key data after
1722 # being a module to becoming a dict missing some key data after
1723 # %run. As best I can see, this is NOT something IPython is doing
1723 # %run. As best I can see, this is NOT something IPython is doing
1724 # at all, and similar problems have been reported before:
1724 # at all, and similar problems have been reported before:
1725 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1725 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1726 # Since this seems to be done by the interpreter itself, the best
1726 # Since this seems to be done by the interpreter itself, the best
1727 # we can do is to at least restore __builtins__ for the user on
1727 # we can do is to at least restore __builtins__ for the user on
1728 # exit.
1728 # exit.
1729 self.shell.user_ns['__builtins__'] = __builtin__
1729 self.shell.user_ns['__builtins__'] = __builtin__
1730
1730
1731 # Ensure key global structures are restored
1731 # Ensure key global structures are restored
1732 sys.argv = save_argv
1732 sys.argv = save_argv
1733 if restore_main:
1733 if restore_main:
1734 sys.modules['__main__'] = restore_main
1734 sys.modules['__main__'] = restore_main
1735 else:
1735 else:
1736 # Remove from sys.modules the reference to main_mod we'd
1736 # Remove from sys.modules the reference to main_mod we'd
1737 # added. Otherwise it will trap references to objects
1737 # added. Otherwise it will trap references to objects
1738 # contained therein.
1738 # contained therein.
1739 del sys.modules[main_mod_name]
1739 del sys.modules[main_mod_name]
1740
1740
1741 self.shell.reloadhist()
1741 self.shell.reloadhist()
1742
1742
1743 return stats
1743 return stats
1744
1744
1745 def magic_runlog(self, parameter_s =''):
1745 def magic_runlog(self, parameter_s =''):
1746 """Run files as logs.
1746 """Run files as logs.
1747
1747
1748 Usage:\\
1748 Usage:\\
1749 %runlog file1 file2 ...
1749 %runlog file1 file2 ...
1750
1750
1751 Run the named files (treating them as log files) in sequence inside
1751 Run the named files (treating them as log files) in sequence inside
1752 the interpreter, and return to the prompt. This is much slower than
1752 the interpreter, and return to the prompt. This is much slower than
1753 %run because each line is executed in a try/except block, but it
1753 %run because each line is executed in a try/except block, but it
1754 allows running files with syntax errors in them.
1754 allows running files with syntax errors in them.
1755
1755
1756 Normally IPython will guess when a file is one of its own logfiles, so
1756 Normally IPython will guess when a file is one of its own logfiles, so
1757 you can typically use %run even for logs. This shorthand allows you to
1757 you can typically use %run even for logs. This shorthand allows you to
1758 force any file to be treated as a log file."""
1758 force any file to be treated as a log file."""
1759
1759
1760 for f in parameter_s.split():
1760 for f in parameter_s.split():
1761 self.shell.safe_execfile(f,self.shell.user_ns,
1761 self.shell.safe_execfile(f,self.shell.user_ns,
1762 self.shell.user_ns,islog=1)
1762 self.shell.user_ns,islog=1)
1763
1763
1764 @testdec.skip_doctest
1764 @testdec.skip_doctest
1765 def magic_timeit(self, parameter_s =''):
1765 def magic_timeit(self, parameter_s =''):
1766 """Time execution of a Python statement or expression
1766 """Time execution of a Python statement or expression
1767
1767
1768 Usage:\\
1768 Usage:\\
1769 %timeit [-n<N> -r<R> [-t|-c]] statement
1769 %timeit [-n<N> -r<R> [-t|-c]] statement
1770
1770
1771 Time execution of a Python statement or expression using the timeit
1771 Time execution of a Python statement or expression using the timeit
1772 module.
1772 module.
1773
1773
1774 Options:
1774 Options:
1775 -n<N>: execute the given statement <N> times in a loop. If this value
1775 -n<N>: execute the given statement <N> times in a loop. If this value
1776 is not given, a fitting value is chosen.
1776 is not given, a fitting value is chosen.
1777
1777
1778 -r<R>: repeat the loop iteration <R> times and take the best result.
1778 -r<R>: repeat the loop iteration <R> times and take the best result.
1779 Default: 3
1779 Default: 3
1780
1780
1781 -t: use time.time to measure the time, which is the default on Unix.
1781 -t: use time.time to measure the time, which is the default on Unix.
1782 This function measures wall time.
1782 This function measures wall time.
1783
1783
1784 -c: use time.clock to measure the time, which is the default on
1784 -c: use time.clock to measure the time, which is the default on
1785 Windows and measures wall time. On Unix, resource.getrusage is used
1785 Windows and measures wall time. On Unix, resource.getrusage is used
1786 instead and returns the CPU user time.
1786 instead and returns the CPU user time.
1787
1787
1788 -p<P>: use a precision of <P> digits to display the timing result.
1788 -p<P>: use a precision of <P> digits to display the timing result.
1789 Default: 3
1789 Default: 3
1790
1790
1791
1791
1792 Examples:
1792 Examples:
1793
1793
1794 In [1]: %timeit pass
1794 In [1]: %timeit pass
1795 10000000 loops, best of 3: 53.3 ns per loop
1795 10000000 loops, best of 3: 53.3 ns per loop
1796
1796
1797 In [2]: u = None
1797 In [2]: u = None
1798
1798
1799 In [3]: %timeit u is None
1799 In [3]: %timeit u is None
1800 10000000 loops, best of 3: 184 ns per loop
1800 10000000 loops, best of 3: 184 ns per loop
1801
1801
1802 In [4]: %timeit -r 4 u == None
1802 In [4]: %timeit -r 4 u == None
1803 1000000 loops, best of 4: 242 ns per loop
1803 1000000 loops, best of 4: 242 ns per loop
1804
1804
1805 In [5]: import time
1805 In [5]: import time
1806
1806
1807 In [6]: %timeit -n1 time.sleep(2)
1807 In [6]: %timeit -n1 time.sleep(2)
1808 1 loops, best of 3: 2 s per loop
1808 1 loops, best of 3: 2 s per loop
1809
1809
1810
1810
1811 The times reported by %timeit will be slightly higher than those
1811 The times reported by %timeit will be slightly higher than those
1812 reported by the timeit.py script when variables are accessed. This is
1812 reported by the timeit.py script when variables are accessed. This is
1813 due to the fact that %timeit executes the statement in the namespace
1813 due to the fact that %timeit executes the statement in the namespace
1814 of the shell, compared with timeit.py, which uses a single setup
1814 of the shell, compared with timeit.py, which uses a single setup
1815 statement to import function or create variables. Generally, the bias
1815 statement to import function or create variables. Generally, the bias
1816 does not matter as long as results from timeit.py are not mixed with
1816 does not matter as long as results from timeit.py are not mixed with
1817 those from %timeit."""
1817 those from %timeit."""
1818
1818
1819 import timeit
1819 import timeit
1820 import math
1820 import math
1821
1821
1822 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1822 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1823 # certain terminals. Until we figure out a robust way of
1823 # certain terminals. Until we figure out a robust way of
1824 # auto-detecting if the terminal can deal with it, use plain 'us' for
1824 # auto-detecting if the terminal can deal with it, use plain 'us' for
1825 # microseconds. I am really NOT happy about disabling the proper
1825 # microseconds. I am really NOT happy about disabling the proper
1826 # 'micro' prefix, but crashing is worse... If anyone knows what the
1826 # 'micro' prefix, but crashing is worse... If anyone knows what the
1827 # right solution for this is, I'm all ears...
1827 # right solution for this is, I'm all ears...
1828 #
1828 #
1829 # Note: using
1829 # Note: using
1830 #
1830 #
1831 # s = u'\xb5'
1831 # s = u'\xb5'
1832 # s.encode(sys.getdefaultencoding())
1832 # s.encode(sys.getdefaultencoding())
1833 #
1833 #
1834 # is not sufficient, as I've seen terminals where that fails but
1834 # is not sufficient, as I've seen terminals where that fails but
1835 # print s
1835 # print s
1836 #
1836 #
1837 # succeeds
1837 # succeeds
1838 #
1838 #
1839 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1839 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1840
1840
1841 #units = [u"s", u"ms",u'\xb5',"ns"]
1841 #units = [u"s", u"ms",u'\xb5',"ns"]
1842 units = [u"s", u"ms",u'us',"ns"]
1842 units = [u"s", u"ms",u'us',"ns"]
1843
1843
1844 scaling = [1, 1e3, 1e6, 1e9]
1844 scaling = [1, 1e3, 1e6, 1e9]
1845
1845
1846 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1846 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1847 posix=False)
1847 posix=False)
1848 if stmt == "":
1848 if stmt == "":
1849 return
1849 return
1850 timefunc = timeit.default_timer
1850 timefunc = timeit.default_timer
1851 number = int(getattr(opts, "n", 0))
1851 number = int(getattr(opts, "n", 0))
1852 repeat = int(getattr(opts, "r", timeit.default_repeat))
1852 repeat = int(getattr(opts, "r", timeit.default_repeat))
1853 precision = int(getattr(opts, "p", 3))
1853 precision = int(getattr(opts, "p", 3))
1854 if hasattr(opts, "t"):
1854 if hasattr(opts, "t"):
1855 timefunc = time.time
1855 timefunc = time.time
1856 if hasattr(opts, "c"):
1856 if hasattr(opts, "c"):
1857 timefunc = clock
1857 timefunc = clock
1858
1858
1859 timer = timeit.Timer(timer=timefunc)
1859 timer = timeit.Timer(timer=timefunc)
1860 # this code has tight coupling to the inner workings of timeit.Timer,
1860 # this code has tight coupling to the inner workings of timeit.Timer,
1861 # but is there a better way to achieve that the code stmt has access
1861 # but is there a better way to achieve that the code stmt has access
1862 # to the shell namespace?
1862 # to the shell namespace?
1863
1863
1864 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1864 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1865 'setup': "pass"}
1865 'setup': "pass"}
1866 # Track compilation time so it can be reported if too long
1866 # Track compilation time so it can be reported if too long
1867 # Minimum time above which compilation time will be reported
1867 # Minimum time above which compilation time will be reported
1868 tc_min = 0.1
1868 tc_min = 0.1
1869
1869
1870 t0 = clock()
1870 t0 = clock()
1871 code = compile(src, "<magic-timeit>", "exec")
1871 code = compile(src, "<magic-timeit>", "exec")
1872 tc = clock()-t0
1872 tc = clock()-t0
1873
1873
1874 ns = {}
1874 ns = {}
1875 exec code in self.shell.user_ns, ns
1875 exec code in self.shell.user_ns, ns
1876 timer.inner = ns["inner"]
1876 timer.inner = ns["inner"]
1877
1877
1878 if number == 0:
1878 if number == 0:
1879 # determine number so that 0.2 <= total time < 2.0
1879 # determine number so that 0.2 <= total time < 2.0
1880 number = 1
1880 number = 1
1881 for i in range(1, 10):
1881 for i in range(1, 10):
1882 if timer.timeit(number) >= 0.2:
1882 if timer.timeit(number) >= 0.2:
1883 break
1883 break
1884 number *= 10
1884 number *= 10
1885
1885
1886 best = min(timer.repeat(repeat, number)) / number
1886 best = min(timer.repeat(repeat, number)) / number
1887
1887
1888 if best > 0.0:
1888 if best > 0.0:
1889 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1889 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1890 else:
1890 else:
1891 order = 3
1891 order = 3
1892 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1892 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1893 precision,
1893 precision,
1894 best * scaling[order],
1894 best * scaling[order],
1895 units[order])
1895 units[order])
1896 if tc > tc_min:
1896 if tc > tc_min:
1897 print "Compiler time: %.2f s" % tc
1897 print "Compiler time: %.2f s" % tc
1898
1898
1899 @testdec.skip_doctest
1899 @testdec.skip_doctest
1900 def magic_time(self,parameter_s = ''):
1900 def magic_time(self,parameter_s = ''):
1901 """Time execution of a Python statement or expression.
1901 """Time execution of a Python statement or expression.
1902
1902
1903 The CPU and wall clock times are printed, and the value of the
1903 The CPU and wall clock times are printed, and the value of the
1904 expression (if any) is returned. Note that under Win32, system time
1904 expression (if any) is returned. Note that under Win32, system time
1905 is always reported as 0, since it can not be measured.
1905 is always reported as 0, since it can not be measured.
1906
1906
1907 This function provides very basic timing functionality. In Python
1907 This function provides very basic timing functionality. In Python
1908 2.3, the timeit module offers more control and sophistication, so this
1908 2.3, the timeit module offers more control and sophistication, so this
1909 could be rewritten to use it (patches welcome).
1909 could be rewritten to use it (patches welcome).
1910
1910
1911 Some examples:
1911 Some examples:
1912
1912
1913 In [1]: time 2**128
1913 In [1]: time 2**128
1914 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1914 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1915 Wall time: 0.00
1915 Wall time: 0.00
1916 Out[1]: 340282366920938463463374607431768211456L
1916 Out[1]: 340282366920938463463374607431768211456L
1917
1917
1918 In [2]: n = 1000000
1918 In [2]: n = 1000000
1919
1919
1920 In [3]: time sum(range(n))
1920 In [3]: time sum(range(n))
1921 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1921 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1922 Wall time: 1.37
1922 Wall time: 1.37
1923 Out[3]: 499999500000L
1923 Out[3]: 499999500000L
1924
1924
1925 In [4]: time print 'hello world'
1925 In [4]: time print 'hello world'
1926 hello world
1926 hello world
1927 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1927 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1928 Wall time: 0.00
1928 Wall time: 0.00
1929
1929
1930 Note that the time needed by Python to compile the given expression
1930 Note that the time needed by Python to compile the given expression
1931 will be reported if it is more than 0.1s. In this example, the
1931 will be reported if it is more than 0.1s. In this example, the
1932 actual exponentiation is done by Python at compilation time, so while
1932 actual exponentiation is done by Python at compilation time, so while
1933 the expression can take a noticeable amount of time to compute, that
1933 the expression can take a noticeable amount of time to compute, that
1934 time is purely due to the compilation:
1934 time is purely due to the compilation:
1935
1935
1936 In [5]: time 3**9999;
1936 In [5]: time 3**9999;
1937 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1937 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1938 Wall time: 0.00 s
1938 Wall time: 0.00 s
1939
1939
1940 In [6]: time 3**999999;
1940 In [6]: time 3**999999;
1941 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1941 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1942 Wall time: 0.00 s
1942 Wall time: 0.00 s
1943 Compiler : 0.78 s
1943 Compiler : 0.78 s
1944 """
1944 """
1945
1945
1946 # fail immediately if the given expression can't be compiled
1946 # fail immediately if the given expression can't be compiled
1947
1947
1948 expr = self.shell.prefilter(parameter_s,False)
1948 expr = self.shell.prefilter(parameter_s,False)
1949
1949
1950 # Minimum time above which compilation time will be reported
1950 # Minimum time above which compilation time will be reported
1951 tc_min = 0.1
1951 tc_min = 0.1
1952
1952
1953 try:
1953 try:
1954 mode = 'eval'
1954 mode = 'eval'
1955 t0 = clock()
1955 t0 = clock()
1956 code = compile(expr,'<timed eval>',mode)
1956 code = compile(expr,'<timed eval>',mode)
1957 tc = clock()-t0
1957 tc = clock()-t0
1958 except SyntaxError:
1958 except SyntaxError:
1959 mode = 'exec'
1959 mode = 'exec'
1960 t0 = clock()
1960 t0 = clock()
1961 code = compile(expr,'<timed exec>',mode)
1961 code = compile(expr,'<timed exec>',mode)
1962 tc = clock()-t0
1962 tc = clock()-t0
1963 # skew measurement as little as possible
1963 # skew measurement as little as possible
1964 glob = self.shell.user_ns
1964 glob = self.shell.user_ns
1965 clk = clock2
1965 clk = clock2
1966 wtime = time.time
1966 wtime = time.time
1967 # time execution
1967 # time execution
1968 wall_st = wtime()
1968 wall_st = wtime()
1969 if mode=='eval':
1969 if mode=='eval':
1970 st = clk()
1970 st = clk()
1971 out = eval(code,glob)
1971 out = eval(code,glob)
1972 end = clk()
1972 end = clk()
1973 else:
1973 else:
1974 st = clk()
1974 st = clk()
1975 exec code in glob
1975 exec code in glob
1976 end = clk()
1976 end = clk()
1977 out = None
1977 out = None
1978 wall_end = wtime()
1978 wall_end = wtime()
1979 # Compute actual times and report
1979 # Compute actual times and report
1980 wall_time = wall_end-wall_st
1980 wall_time = wall_end-wall_st
1981 cpu_user = end[0]-st[0]
1981 cpu_user = end[0]-st[0]
1982 cpu_sys = end[1]-st[1]
1982 cpu_sys = end[1]-st[1]
1983 cpu_tot = cpu_user+cpu_sys
1983 cpu_tot = cpu_user+cpu_sys
1984 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1984 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1985 (cpu_user,cpu_sys,cpu_tot)
1985 (cpu_user,cpu_sys,cpu_tot)
1986 print "Wall time: %.2f s" % wall_time
1986 print "Wall time: %.2f s" % wall_time
1987 if tc > tc_min:
1987 if tc > tc_min:
1988 print "Compiler : %.2f s" % tc
1988 print "Compiler : %.2f s" % tc
1989 return out
1989 return out
1990
1990
1991 @testdec.skip_doctest
1991 @testdec.skip_doctest
1992 def magic_macro(self,parameter_s = ''):
1992 def magic_macro(self,parameter_s = ''):
1993 """Define a set of input lines as a macro for future re-execution.
1993 """Define a set of input lines as a macro for future re-execution.
1994
1994
1995 Usage:\\
1995 Usage:\\
1996 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1996 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1997
1997
1998 Options:
1998 Options:
1999
1999
2000 -r: use 'raw' input. By default, the 'processed' history is used,
2000 -r: use 'raw' input. By default, the 'processed' history is used,
2001 so that magics are loaded in their transformed version to valid
2001 so that magics are loaded in their transformed version to valid
2002 Python. If this option is given, the raw input as typed as the
2002 Python. If this option is given, the raw input as typed as the
2003 command line is used instead.
2003 command line is used instead.
2004
2004
2005 This will define a global variable called `name` which is a string
2005 This will define a global variable called `name` which is a string
2006 made of joining the slices and lines you specify (n1,n2,... numbers
2006 made of joining the slices and lines you specify (n1,n2,... numbers
2007 above) from your input history into a single string. This variable
2007 above) from your input history into a single string. This variable
2008 acts like an automatic function which re-executes those lines as if
2008 acts like an automatic function which re-executes those lines as if
2009 you had typed them. You just type 'name' at the prompt and the code
2009 you had typed them. You just type 'name' at the prompt and the code
2010 executes.
2010 executes.
2011
2011
2012 The notation for indicating number ranges is: n1-n2 means 'use line
2012 The notation for indicating number ranges is: n1-n2 means 'use line
2013 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2013 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2014 using the lines numbered 5,6 and 7.
2014 using the lines numbered 5,6 and 7.
2015
2015
2016 Note: as a 'hidden' feature, you can also use traditional python slice
2016 Note: as a 'hidden' feature, you can also use traditional python slice
2017 notation, where N:M means numbers N through M-1.
2017 notation, where N:M means numbers N through M-1.
2018
2018
2019 For example, if your history contains (%hist prints it):
2019 For example, if your history contains (%hist prints it):
2020
2020
2021 44: x=1
2021 44: x=1
2022 45: y=3
2022 45: y=3
2023 46: z=x+y
2023 46: z=x+y
2024 47: print x
2024 47: print x
2025 48: a=5
2025 48: a=5
2026 49: print 'x',x,'y',y
2026 49: print 'x',x,'y',y
2027
2027
2028 you can create a macro with lines 44 through 47 (included) and line 49
2028 you can create a macro with lines 44 through 47 (included) and line 49
2029 called my_macro with:
2029 called my_macro with:
2030
2030
2031 In [55]: %macro my_macro 44-47 49
2031 In [55]: %macro my_macro 44-47 49
2032
2032
2033 Now, typing `my_macro` (without quotes) will re-execute all this code
2033 Now, typing `my_macro` (without quotes) will re-execute all this code
2034 in one pass.
2034 in one pass.
2035
2035
2036 You don't need to give the line-numbers in order, and any given line
2036 You don't need to give the line-numbers in order, and any given line
2037 number can appear multiple times. You can assemble macros with any
2037 number can appear multiple times. You can assemble macros with any
2038 lines from your input history in any order.
2038 lines from your input history in any order.
2039
2039
2040 The macro is a simple object which holds its value in an attribute,
2040 The macro is a simple object which holds its value in an attribute,
2041 but IPython's display system checks for macros and executes them as
2041 but IPython's display system checks for macros and executes them as
2042 code instead of printing them when you type their name.
2042 code instead of printing them when you type their name.
2043
2043
2044 You can view a macro's contents by explicitly printing it with:
2044 You can view a macro's contents by explicitly printing it with:
2045
2045
2046 'print macro_name'.
2046 'print macro_name'.
2047
2047
2048 For one-off cases which DON'T contain magic function calls in them you
2048 For one-off cases which DON'T contain magic function calls in them you
2049 can obtain similar results by explicitly executing slices from your
2049 can obtain similar results by explicitly executing slices from your
2050 input history with:
2050 input history with:
2051
2051
2052 In [60]: exec In[44:48]+In[49]"""
2052 In [60]: exec In[44:48]+In[49]"""
2053
2053
2054 opts,args = self.parse_options(parameter_s,'r',mode='list')
2054 opts,args = self.parse_options(parameter_s,'r',mode='list')
2055 if not args:
2055 if not args:
2056 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2056 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2057 macs.sort()
2057 macs.sort()
2058 return macs
2058 return macs
2059 if len(args) == 1:
2059 if len(args) == 1:
2060 raise UsageError(
2060 raise UsageError(
2061 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2061 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2062 name,ranges = args[0], args[1:]
2062 name,ranges = args[0], args[1:]
2063
2063
2064 #print 'rng',ranges # dbg
2064 #print 'rng',ranges # dbg
2065 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2065 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2066 macro = Macro(lines)
2066 macro = Macro(lines)
2067 self.shell.define_macro(name, macro)
2067 self.shell.define_macro(name, macro)
2068 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2068 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2069 print 'Macro contents:'
2069 print 'Macro contents:'
2070 print macro,
2070 print macro,
2071
2071
2072 def magic_save(self,parameter_s = ''):
2072 def magic_save(self,parameter_s = ''):
2073 """Save a set of lines to a given filename.
2073 """Save a set of lines to a given filename.
2074
2074
2075 Usage:\\
2075 Usage:\\
2076 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2076 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2077
2077
2078 Options:
2078 Options:
2079
2079
2080 -r: use 'raw' input. By default, the 'processed' history is used,
2080 -r: use 'raw' input. By default, the 'processed' history is used,
2081 so that magics are loaded in their transformed version to valid
2081 so that magics are loaded in their transformed version to valid
2082 Python. If this option is given, the raw input as typed as the
2082 Python. If this option is given, the raw input as typed as the
2083 command line is used instead.
2083 command line is used instead.
2084
2084
2085 This function uses the same syntax as %macro for line extraction, but
2085 This function uses the same syntax as %macro for line extraction, but
2086 instead of creating a macro it saves the resulting string to the
2086 instead of creating a macro it saves the resulting string to the
2087 filename you specify.
2087 filename you specify.
2088
2088
2089 It adds a '.py' extension to the file if you don't do so yourself, and
2089 It adds a '.py' extension to the file if you don't do so yourself, and
2090 it asks for confirmation before overwriting existing files."""
2090 it asks for confirmation before overwriting existing files."""
2091
2091
2092 opts,args = self.parse_options(parameter_s,'r',mode='list')
2092 opts,args = self.parse_options(parameter_s,'r',mode='list')
2093 fname,ranges = args[0], args[1:]
2093 fname,ranges = args[0], args[1:]
2094 if not fname.endswith('.py'):
2094 if not fname.endswith('.py'):
2095 fname += '.py'
2095 fname += '.py'
2096 if os.path.isfile(fname):
2096 if os.path.isfile(fname):
2097 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2097 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2098 if ans.lower() not in ['y','yes']:
2098 if ans.lower() not in ['y','yes']:
2099 print 'Operation cancelled.'
2099 print 'Operation cancelled.'
2100 return
2100 return
2101 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2101 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2102 f = file(fname,'w')
2102 f = file(fname,'w')
2103 f.write(cmds)
2103 f.write(cmds)
2104 f.close()
2104 f.close()
2105 print 'The following commands were written to file `%s`:' % fname
2105 print 'The following commands were written to file `%s`:' % fname
2106 print cmds
2106 print cmds
2107
2107
2108 def _edit_macro(self,mname,macro):
2108 def _edit_macro(self,mname,macro):
2109 """open an editor with the macro data in a file"""
2109 """open an editor with the macro data in a file"""
2110 filename = self.shell.mktempfile(macro.value)
2110 filename = self.shell.mktempfile(macro.value)
2111 self.shell.hooks.editor(filename)
2111 self.shell.hooks.editor(filename)
2112
2112
2113 # and make a new macro object, to replace the old one
2113 # and make a new macro object, to replace the old one
2114 mfile = open(filename)
2114 mfile = open(filename)
2115 mvalue = mfile.read()
2115 mvalue = mfile.read()
2116 mfile.close()
2116 mfile.close()
2117 self.shell.user_ns[mname] = Macro(mvalue)
2117 self.shell.user_ns[mname] = Macro(mvalue)
2118
2118
2119 def magic_ed(self,parameter_s=''):
2119 def magic_ed(self,parameter_s=''):
2120 """Alias to %edit."""
2120 """Alias to %edit."""
2121 return self.magic_edit(parameter_s)
2121 return self.magic_edit(parameter_s)
2122
2122
2123 @testdec.skip_doctest
2123 @testdec.skip_doctest
2124 def magic_edit(self,parameter_s='',last_call=['','']):
2124 def magic_edit(self,parameter_s='',last_call=['','']):
2125 """Bring up an editor and execute the resulting code.
2125 """Bring up an editor and execute the resulting code.
2126
2126
2127 Usage:
2127 Usage:
2128 %edit [options] [args]
2128 %edit [options] [args]
2129
2129
2130 %edit runs IPython's editor hook. The default version of this hook is
2130 %edit runs IPython's editor hook. The default version of this hook is
2131 set to call the __IPYTHON__.rc.editor command. This is read from your
2131 set to call the __IPYTHON__.rc.editor command. This is read from your
2132 environment variable $EDITOR. If this isn't found, it will default to
2132 environment variable $EDITOR. If this isn't found, it will default to
2133 vi under Linux/Unix and to notepad under Windows. See the end of this
2133 vi under Linux/Unix and to notepad under Windows. See the end of this
2134 docstring for how to change the editor hook.
2134 docstring for how to change the editor hook.
2135
2135
2136 You can also set the value of this editor via the command line option
2136 You can also set the value of this editor via the command line option
2137 '-editor' or in your ipythonrc file. This is useful if you wish to use
2137 '-editor' or in your ipythonrc file. This is useful if you wish to use
2138 specifically for IPython an editor different from your typical default
2138 specifically for IPython an editor different from your typical default
2139 (and for Windows users who typically don't set environment variables).
2139 (and for Windows users who typically don't set environment variables).
2140
2140
2141 This command allows you to conveniently edit multi-line code right in
2141 This command allows you to conveniently edit multi-line code right in
2142 your IPython session.
2142 your IPython session.
2143
2143
2144 If called without arguments, %edit opens up an empty editor with a
2144 If called without arguments, %edit opens up an empty editor with a
2145 temporary file and will execute the contents of this file when you
2145 temporary file and will execute the contents of this file when you
2146 close it (don't forget to save it!).
2146 close it (don't forget to save it!).
2147
2147
2148
2148
2149 Options:
2149 Options:
2150
2150
2151 -n <number>: open the editor at a specified line number. By default,
2151 -n <number>: open the editor at a specified line number. By default,
2152 the IPython editor hook uses the unix syntax 'editor +N filename', but
2152 the IPython editor hook uses the unix syntax 'editor +N filename', but
2153 you can configure this by providing your own modified hook if your
2153 you can configure this by providing your own modified hook if your
2154 favorite editor supports line-number specifications with a different
2154 favorite editor supports line-number specifications with a different
2155 syntax.
2155 syntax.
2156
2156
2157 -p: this will call the editor with the same data as the previous time
2157 -p: this will call the editor with the same data as the previous time
2158 it was used, regardless of how long ago (in your current session) it
2158 it was used, regardless of how long ago (in your current session) it
2159 was.
2159 was.
2160
2160
2161 -r: use 'raw' input. This option only applies to input taken from the
2161 -r: use 'raw' input. This option only applies to input taken from the
2162 user's history. By default, the 'processed' history is used, so that
2162 user's history. By default, the 'processed' history is used, so that
2163 magics are loaded in their transformed version to valid Python. If
2163 magics are loaded in their transformed version to valid Python. If
2164 this option is given, the raw input as typed as the command line is
2164 this option is given, the raw input as typed as the command line is
2165 used instead. When you exit the editor, it will be executed by
2165 used instead. When you exit the editor, it will be executed by
2166 IPython's own processor.
2166 IPython's own processor.
2167
2167
2168 -x: do not execute the edited code immediately upon exit. This is
2168 -x: do not execute the edited code immediately upon exit. This is
2169 mainly useful if you are editing programs which need to be called with
2169 mainly useful if you are editing programs which need to be called with
2170 command line arguments, which you can then do using %run.
2170 command line arguments, which you can then do using %run.
2171
2171
2172
2172
2173 Arguments:
2173 Arguments:
2174
2174
2175 If arguments are given, the following possibilites exist:
2175 If arguments are given, the following possibilites exist:
2176
2176
2177 - The arguments are numbers or pairs of colon-separated numbers (like
2177 - The arguments are numbers or pairs of colon-separated numbers (like
2178 1 4:8 9). These are interpreted as lines of previous input to be
2178 1 4:8 9). These are interpreted as lines of previous input to be
2179 loaded into the editor. The syntax is the same of the %macro command.
2179 loaded into the editor. The syntax is the same of the %macro command.
2180
2180
2181 - If the argument doesn't start with a number, it is evaluated as a
2181 - If the argument doesn't start with a number, it is evaluated as a
2182 variable and its contents loaded into the editor. You can thus edit
2182 variable and its contents loaded into the editor. You can thus edit
2183 any string which contains python code (including the result of
2183 any string which contains python code (including the result of
2184 previous edits).
2184 previous edits).
2185
2185
2186 - If the argument is the name of an object (other than a string),
2186 - If the argument is the name of an object (other than a string),
2187 IPython will try to locate the file where it was defined and open the
2187 IPython will try to locate the file where it was defined and open the
2188 editor at the point where it is defined. You can use `%edit function`
2188 editor at the point where it is defined. You can use `%edit function`
2189 to load an editor exactly at the point where 'function' is defined,
2189 to load an editor exactly at the point where 'function' is defined,
2190 edit it and have the file be executed automatically.
2190 edit it and have the file be executed automatically.
2191
2191
2192 If the object is a macro (see %macro for details), this opens up your
2192 If the object is a macro (see %macro for details), this opens up your
2193 specified editor with a temporary file containing the macro's data.
2193 specified editor with a temporary file containing the macro's data.
2194 Upon exit, the macro is reloaded with the contents of the file.
2194 Upon exit, the macro is reloaded with the contents of the file.
2195
2195
2196 Note: opening at an exact line is only supported under Unix, and some
2196 Note: opening at an exact line is only supported under Unix, and some
2197 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2197 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2198 '+NUMBER' parameter necessary for this feature. Good editors like
2198 '+NUMBER' parameter necessary for this feature. Good editors like
2199 (X)Emacs, vi, jed, pico and joe all do.
2199 (X)Emacs, vi, jed, pico and joe all do.
2200
2200
2201 - If the argument is not found as a variable, IPython will look for a
2201 - If the argument is not found as a variable, IPython will look for a
2202 file with that name (adding .py if necessary) and load it into the
2202 file with that name (adding .py if necessary) and load it into the
2203 editor. It will execute its contents with execfile() when you exit,
2203 editor. It will execute its contents with execfile() when you exit,
2204 loading any code in the file into your interactive namespace.
2204 loading any code in the file into your interactive namespace.
2205
2205
2206 After executing your code, %edit will return as output the code you
2206 After executing your code, %edit will return as output the code you
2207 typed in the editor (except when it was an existing file). This way
2207 typed in the editor (except when it was an existing file). This way
2208 you can reload the code in further invocations of %edit as a variable,
2208 you can reload the code in further invocations of %edit as a variable,
2209 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2209 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2210 the output.
2210 the output.
2211
2211
2212 Note that %edit is also available through the alias %ed.
2212 Note that %edit is also available through the alias %ed.
2213
2213
2214 This is an example of creating a simple function inside the editor and
2214 This is an example of creating a simple function inside the editor and
2215 then modifying it. First, start up the editor:
2215 then modifying it. First, start up the editor:
2216
2216
2217 In [1]: ed
2217 In [1]: ed
2218 Editing... done. Executing edited code...
2218 Editing... done. Executing edited code...
2219 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2219 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2220
2220
2221 We can then call the function foo():
2221 We can then call the function foo():
2222
2222
2223 In [2]: foo()
2223 In [2]: foo()
2224 foo() was defined in an editing session
2224 foo() was defined in an editing session
2225
2225
2226 Now we edit foo. IPython automatically loads the editor with the
2226 Now we edit foo. IPython automatically loads the editor with the
2227 (temporary) file where foo() was previously defined:
2227 (temporary) file where foo() was previously defined:
2228
2228
2229 In [3]: ed foo
2229 In [3]: ed foo
2230 Editing... done. Executing edited code...
2230 Editing... done. Executing edited code...
2231
2231
2232 And if we call foo() again we get the modified version:
2232 And if we call foo() again we get the modified version:
2233
2233
2234 In [4]: foo()
2234 In [4]: foo()
2235 foo() has now been changed!
2235 foo() has now been changed!
2236
2236
2237 Here is an example of how to edit a code snippet successive
2237 Here is an example of how to edit a code snippet successive
2238 times. First we call the editor:
2238 times. First we call the editor:
2239
2239
2240 In [5]: ed
2240 In [5]: ed
2241 Editing... done. Executing edited code...
2241 Editing... done. Executing edited code...
2242 hello
2242 hello
2243 Out[5]: "print 'hello'n"
2243 Out[5]: "print 'hello'n"
2244
2244
2245 Now we call it again with the previous output (stored in _):
2245 Now we call it again with the previous output (stored in _):
2246
2246
2247 In [6]: ed _
2247 In [6]: ed _
2248 Editing... done. Executing edited code...
2248 Editing... done. Executing edited code...
2249 hello world
2249 hello world
2250 Out[6]: "print 'hello world'n"
2250 Out[6]: "print 'hello world'n"
2251
2251
2252 Now we call it with the output #8 (stored in _8, also as Out[8]):
2252 Now we call it with the output #8 (stored in _8, also as Out[8]):
2253
2253
2254 In [7]: ed _8
2254 In [7]: ed _8
2255 Editing... done. Executing edited code...
2255 Editing... done. Executing edited code...
2256 hello again
2256 hello again
2257 Out[7]: "print 'hello again'n"
2257 Out[7]: "print 'hello again'n"
2258
2258
2259
2259
2260 Changing the default editor hook:
2260 Changing the default editor hook:
2261
2261
2262 If you wish to write your own editor hook, you can put it in a
2262 If you wish to write your own editor hook, you can put it in a
2263 configuration file which you load at startup time. The default hook
2263 configuration file which you load at startup time. The default hook
2264 is defined in the IPython.core.hooks module, and you can use that as a
2264 is defined in the IPython.core.hooks module, and you can use that as a
2265 starting example for further modifications. That file also has
2265 starting example for further modifications. That file also has
2266 general instructions on how to set a new hook for use once you've
2266 general instructions on how to set a new hook for use once you've
2267 defined it."""
2267 defined it."""
2268
2268
2269 # FIXME: This function has become a convoluted mess. It needs a
2269 # FIXME: This function has become a convoluted mess. It needs a
2270 # ground-up rewrite with clean, simple logic.
2270 # ground-up rewrite with clean, simple logic.
2271
2271
2272 def make_filename(arg):
2272 def make_filename(arg):
2273 "Make a filename from the given args"
2273 "Make a filename from the given args"
2274 try:
2274 try:
2275 filename = get_py_filename(arg)
2275 filename = get_py_filename(arg)
2276 except IOError:
2276 except IOError:
2277 if args.endswith('.py'):
2277 if args.endswith('.py'):
2278 filename = arg
2278 filename = arg
2279 else:
2279 else:
2280 filename = None
2280 filename = None
2281 return filename
2281 return filename
2282
2282
2283 # custom exceptions
2283 # custom exceptions
2284 class DataIsObject(Exception): pass
2284 class DataIsObject(Exception): pass
2285
2285
2286 opts,args = self.parse_options(parameter_s,'prxn:')
2286 opts,args = self.parse_options(parameter_s,'prxn:')
2287 # Set a few locals from the options for convenience:
2287 # Set a few locals from the options for convenience:
2288 opts_p = opts.has_key('p')
2288 opts_p = opts.has_key('p')
2289 opts_r = opts.has_key('r')
2289 opts_r = opts.has_key('r')
2290
2290
2291 # Default line number value
2291 # Default line number value
2292 lineno = opts.get('n',None)
2292 lineno = opts.get('n',None)
2293
2293
2294 if opts_p:
2294 if opts_p:
2295 args = '_%s' % last_call[0]
2295 args = '_%s' % last_call[0]
2296 if not self.shell.user_ns.has_key(args):
2296 if not self.shell.user_ns.has_key(args):
2297 args = last_call[1]
2297 args = last_call[1]
2298
2298
2299 # use last_call to remember the state of the previous call, but don't
2299 # use last_call to remember the state of the previous call, but don't
2300 # let it be clobbered by successive '-p' calls.
2300 # let it be clobbered by successive '-p' calls.
2301 try:
2301 try:
2302 last_call[0] = self.shell.outputcache.prompt_count
2302 last_call[0] = self.shell.outputcache.prompt_count
2303 if not opts_p:
2303 if not opts_p:
2304 last_call[1] = parameter_s
2304 last_call[1] = parameter_s
2305 except:
2305 except:
2306 pass
2306 pass
2307
2307
2308 # by default this is done with temp files, except when the given
2308 # by default this is done with temp files, except when the given
2309 # arg is a filename
2309 # arg is a filename
2310 use_temp = 1
2310 use_temp = 1
2311
2311
2312 if re.match(r'\d',args):
2312 if re.match(r'\d',args):
2313 # Mode where user specifies ranges of lines, like in %macro.
2313 # Mode where user specifies ranges of lines, like in %macro.
2314 # This means that you can't edit files whose names begin with
2314 # This means that you can't edit files whose names begin with
2315 # numbers this way. Tough.
2315 # numbers this way. Tough.
2316 ranges = args.split()
2316 ranges = args.split()
2317 data = ''.join(self.extract_input_slices(ranges,opts_r))
2317 data = ''.join(self.extract_input_slices(ranges,opts_r))
2318 elif args.endswith('.py'):
2318 elif args.endswith('.py'):
2319 filename = make_filename(args)
2319 filename = make_filename(args)
2320 data = ''
2320 data = ''
2321 use_temp = 0
2321 use_temp = 0
2322 elif args:
2322 elif args:
2323 try:
2323 try:
2324 # Load the parameter given as a variable. If not a string,
2324 # Load the parameter given as a variable. If not a string,
2325 # process it as an object instead (below)
2325 # process it as an object instead (below)
2326
2326
2327 #print '*** args',args,'type',type(args) # dbg
2327 #print '*** args',args,'type',type(args) # dbg
2328 data = eval(args,self.shell.user_ns)
2328 data = eval(args,self.shell.user_ns)
2329 if not type(data) in StringTypes:
2329 if not type(data) in StringTypes:
2330 raise DataIsObject
2330 raise DataIsObject
2331
2331
2332 except (NameError,SyntaxError):
2332 except (NameError,SyntaxError):
2333 # given argument is not a variable, try as a filename
2333 # given argument is not a variable, try as a filename
2334 filename = make_filename(args)
2334 filename = make_filename(args)
2335 if filename is None:
2335 if filename is None:
2336 warn("Argument given (%s) can't be found as a variable "
2336 warn("Argument given (%s) can't be found as a variable "
2337 "or as a filename." % args)
2337 "or as a filename." % args)
2338 return
2338 return
2339
2339
2340 data = ''
2340 data = ''
2341 use_temp = 0
2341 use_temp = 0
2342 except DataIsObject:
2342 except DataIsObject:
2343
2343
2344 # macros have a special edit function
2344 # macros have a special edit function
2345 if isinstance(data,Macro):
2345 if isinstance(data,Macro):
2346 self._edit_macro(args,data)
2346 self._edit_macro(args,data)
2347 return
2347 return
2348
2348
2349 # For objects, try to edit the file where they are defined
2349 # For objects, try to edit the file where they are defined
2350 try:
2350 try:
2351 filename = inspect.getabsfile(data)
2351 filename = inspect.getabsfile(data)
2352 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2352 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2353 # class created by %edit? Try to find source
2353 # class created by %edit? Try to find source
2354 # by looking for method definitions instead, the
2354 # by looking for method definitions instead, the
2355 # __module__ in those classes is FakeModule.
2355 # __module__ in those classes is FakeModule.
2356 attrs = [getattr(data, aname) for aname in dir(data)]
2356 attrs = [getattr(data, aname) for aname in dir(data)]
2357 for attr in attrs:
2357 for attr in attrs:
2358 if not inspect.ismethod(attr):
2358 if not inspect.ismethod(attr):
2359 continue
2359 continue
2360 filename = inspect.getabsfile(attr)
2360 filename = inspect.getabsfile(attr)
2361 if filename and 'fakemodule' not in filename.lower():
2361 if filename and 'fakemodule' not in filename.lower():
2362 # change the attribute to be the edit target instead
2362 # change the attribute to be the edit target instead
2363 data = attr
2363 data = attr
2364 break
2364 break
2365
2365
2366 datafile = 1
2366 datafile = 1
2367 except TypeError:
2367 except TypeError:
2368 filename = make_filename(args)
2368 filename = make_filename(args)
2369 datafile = 1
2369 datafile = 1
2370 warn('Could not find file where `%s` is defined.\n'
2370 warn('Could not find file where `%s` is defined.\n'
2371 'Opening a file named `%s`' % (args,filename))
2371 'Opening a file named `%s`' % (args,filename))
2372 # Now, make sure we can actually read the source (if it was in
2372 # Now, make sure we can actually read the source (if it was in
2373 # a temp file it's gone by now).
2373 # a temp file it's gone by now).
2374 if datafile:
2374 if datafile:
2375 try:
2375 try:
2376 if lineno is None:
2376 if lineno is None:
2377 lineno = inspect.getsourcelines(data)[1]
2377 lineno = inspect.getsourcelines(data)[1]
2378 except IOError:
2378 except IOError:
2379 filename = make_filename(args)
2379 filename = make_filename(args)
2380 if filename is None:
2380 if filename is None:
2381 warn('The file `%s` where `%s` was defined cannot '
2381 warn('The file `%s` where `%s` was defined cannot '
2382 'be read.' % (filename,data))
2382 'be read.' % (filename,data))
2383 return
2383 return
2384 use_temp = 0
2384 use_temp = 0
2385 else:
2385 else:
2386 data = ''
2386 data = ''
2387
2387
2388 if use_temp:
2388 if use_temp:
2389 filename = self.shell.mktempfile(data)
2389 filename = self.shell.mktempfile(data)
2390 print 'IPython will make a temporary file named:',filename
2390 print 'IPython will make a temporary file named:',filename
2391
2391
2392 # do actual editing here
2392 # do actual editing here
2393 print 'Editing...',
2393 print 'Editing...',
2394 sys.stdout.flush()
2394 sys.stdout.flush()
2395 try:
2395 try:
2396 self.shell.hooks.editor(filename,lineno)
2396 self.shell.hooks.editor(filename,lineno)
2397 except TryNext:
2397 except TryNext:
2398 warn('Could not open editor')
2398 warn('Could not open editor')
2399 return
2399 return
2400
2400
2401 # XXX TODO: should this be generalized for all string vars?
2401 # XXX TODO: should this be generalized for all string vars?
2402 # For now, this is special-cased to blocks created by cpaste
2402 # For now, this is special-cased to blocks created by cpaste
2403 if args.strip() == 'pasted_block':
2403 if args.strip() == 'pasted_block':
2404 self.shell.user_ns['pasted_block'] = file_read(filename)
2404 self.shell.user_ns['pasted_block'] = file_read(filename)
2405
2405
2406 if opts.has_key('x'): # -x prevents actual execution
2406 if opts.has_key('x'): # -x prevents actual execution
2407 print
2407 print
2408 else:
2408 else:
2409 print 'done. Executing edited code...'
2409 print 'done. Executing edited code...'
2410 if opts_r:
2410 if opts_r:
2411 self.shell.runlines(file_read(filename))
2411 self.shell.runlines(file_read(filename))
2412 else:
2412 else:
2413 self.shell.safe_execfile(filename,self.shell.user_ns,
2413 self.shell.safe_execfile(filename,self.shell.user_ns,
2414 self.shell.user_ns)
2414 self.shell.user_ns)
2415
2415
2416
2416
2417 if use_temp:
2417 if use_temp:
2418 try:
2418 try:
2419 return open(filename).read()
2419 return open(filename).read()
2420 except IOError,msg:
2420 except IOError,msg:
2421 if msg.filename == filename:
2421 if msg.filename == filename:
2422 warn('File not found. Did you forget to save?')
2422 warn('File not found. Did you forget to save?')
2423 return
2423 return
2424 else:
2424 else:
2425 self.shell.showtraceback()
2425 self.shell.showtraceback()
2426
2426
2427 def magic_xmode(self,parameter_s = ''):
2427 def magic_xmode(self,parameter_s = ''):
2428 """Switch modes for the exception handlers.
2428 """Switch modes for the exception handlers.
2429
2429
2430 Valid modes: Plain, Context and Verbose.
2430 Valid modes: Plain, Context and Verbose.
2431
2431
2432 If called without arguments, acts as a toggle."""
2432 If called without arguments, acts as a toggle."""
2433
2433
2434 def xmode_switch_err(name):
2434 def xmode_switch_err(name):
2435 warn('Error changing %s exception modes.\n%s' %
2435 warn('Error changing %s exception modes.\n%s' %
2436 (name,sys.exc_info()[1]))
2436 (name,sys.exc_info()[1]))
2437
2437
2438 shell = self.shell
2438 shell = self.shell
2439 new_mode = parameter_s.strip().capitalize()
2439 new_mode = parameter_s.strip().capitalize()
2440 try:
2440 try:
2441 shell.InteractiveTB.set_mode(mode=new_mode)
2441 shell.InteractiveTB.set_mode(mode=new_mode)
2442 print 'Exception reporting mode:',shell.InteractiveTB.mode
2442 print 'Exception reporting mode:',shell.InteractiveTB.mode
2443 except:
2443 except:
2444 xmode_switch_err('user')
2444 xmode_switch_err('user')
2445
2445
2446 # threaded shells use a special handler in sys.excepthook
2446 # threaded shells use a special handler in sys.excepthook
2447 if shell.isthreaded:
2447 if shell.isthreaded:
2448 try:
2448 try:
2449 shell.sys_excepthook.set_mode(mode=new_mode)
2449 shell.sys_excepthook.set_mode(mode=new_mode)
2450 except:
2450 except:
2451 xmode_switch_err('threaded')
2451 xmode_switch_err('threaded')
2452
2452
2453 def magic_colors(self,parameter_s = ''):
2453 def magic_colors(self,parameter_s = ''):
2454 """Switch color scheme for prompts, info system and exception handlers.
2454 """Switch color scheme for prompts, info system and exception handlers.
2455
2455
2456 Currently implemented schemes: NoColor, Linux, LightBG.
2456 Currently implemented schemes: NoColor, Linux, LightBG.
2457
2457
2458 Color scheme names are not case-sensitive."""
2458 Color scheme names are not case-sensitive."""
2459
2459
2460 def color_switch_err(name):
2460 def color_switch_err(name):
2461 warn('Error changing %s color schemes.\n%s' %
2461 warn('Error changing %s color schemes.\n%s' %
2462 (name,sys.exc_info()[1]))
2462 (name,sys.exc_info()[1]))
2463
2463
2464
2464
2465 new_scheme = parameter_s.strip()
2465 new_scheme = parameter_s.strip()
2466 if not new_scheme:
2466 if not new_scheme:
2467 raise UsageError(
2467 raise UsageError(
2468 "%colors: you must specify a color scheme. See '%colors?'")
2468 "%colors: you must specify a color scheme. See '%colors?'")
2469 return
2469 return
2470 # local shortcut
2470 # local shortcut
2471 shell = self.shell
2471 shell = self.shell
2472
2472
2473 import IPython.utils.rlineimpl as readline
2473 import IPython.utils.rlineimpl as readline
2474
2474
2475 if not readline.have_readline and sys.platform == "win32":
2475 if not readline.have_readline and sys.platform == "win32":
2476 msg = """\
2476 msg = """\
2477 Proper color support under MS Windows requires the pyreadline library.
2477 Proper color support under MS Windows requires the pyreadline library.
2478 You can find it at:
2478 You can find it at:
2479 http://ipython.scipy.org/moin/PyReadline/Intro
2479 http://ipython.scipy.org/moin/PyReadline/Intro
2480 Gary's readline needs the ctypes module, from:
2480 Gary's readline needs the ctypes module, from:
2481 http://starship.python.net/crew/theller/ctypes
2481 http://starship.python.net/crew/theller/ctypes
2482 (Note that ctypes is already part of Python versions 2.5 and newer).
2482 (Note that ctypes is already part of Python versions 2.5 and newer).
2483
2483
2484 Defaulting color scheme to 'NoColor'"""
2484 Defaulting color scheme to 'NoColor'"""
2485 new_scheme = 'NoColor'
2485 new_scheme = 'NoColor'
2486 warn(msg)
2486 warn(msg)
2487
2487
2488 # readline option is 0
2488 # readline option is 0
2489 if not shell.has_readline:
2489 if not shell.has_readline:
2490 new_scheme = 'NoColor'
2490 new_scheme = 'NoColor'
2491
2491
2492 # Set prompt colors
2492 # Set prompt colors
2493 try:
2493 try:
2494 shell.outputcache.set_colors(new_scheme)
2494 shell.outputcache.set_colors(new_scheme)
2495 except:
2495 except:
2496 color_switch_err('prompt')
2496 color_switch_err('prompt')
2497 else:
2497 else:
2498 shell.colors = \
2498 shell.colors = \
2499 shell.outputcache.color_table.active_scheme_name
2499 shell.outputcache.color_table.active_scheme_name
2500 # Set exception colors
2500 # Set exception colors
2501 try:
2501 try:
2502 shell.InteractiveTB.set_colors(scheme = new_scheme)
2502 shell.InteractiveTB.set_colors(scheme = new_scheme)
2503 shell.SyntaxTB.set_colors(scheme = new_scheme)
2503 shell.SyntaxTB.set_colors(scheme = new_scheme)
2504 except:
2504 except:
2505 color_switch_err('exception')
2505 color_switch_err('exception')
2506
2506
2507 # threaded shells use a verbose traceback in sys.excepthook
2507 # threaded shells use a verbose traceback in sys.excepthook
2508 if shell.isthreaded:
2508 if shell.isthreaded:
2509 try:
2509 try:
2510 shell.sys_excepthook.set_colors(scheme=new_scheme)
2510 shell.sys_excepthook.set_colors(scheme=new_scheme)
2511 except:
2511 except:
2512 color_switch_err('system exception handler')
2512 color_switch_err('system exception handler')
2513
2513
2514 # Set info (for 'object?') colors
2514 # Set info (for 'object?') colors
2515 if shell.color_info:
2515 if shell.color_info:
2516 try:
2516 try:
2517 shell.inspector.set_active_scheme(new_scheme)
2517 shell.inspector.set_active_scheme(new_scheme)
2518 except:
2518 except:
2519 color_switch_err('object inspector')
2519 color_switch_err('object inspector')
2520 else:
2520 else:
2521 shell.inspector.set_active_scheme('NoColor')
2521 shell.inspector.set_active_scheme('NoColor')
2522
2522
2523 def magic_color_info(self,parameter_s = ''):
2523 def magic_color_info(self,parameter_s = ''):
2524 """Toggle color_info.
2524 """Toggle color_info.
2525
2525
2526 The color_info configuration parameter controls whether colors are
2526 The color_info configuration parameter controls whether colors are
2527 used for displaying object details (by things like %psource, %pfile or
2527 used for displaying object details (by things like %psource, %pfile or
2528 the '?' system). This function toggles this value with each call.
2528 the '?' system). This function toggles this value with each call.
2529
2529
2530 Note that unless you have a fairly recent pager (less works better
2530 Note that unless you have a fairly recent pager (less works better
2531 than more) in your system, using colored object information displays
2531 than more) in your system, using colored object information displays
2532 will not work properly. Test it and see."""
2532 will not work properly. Test it and see."""
2533
2533
2534 self.shell.color_info = not self.shell.color_info
2534 self.shell.color_info = not self.shell.color_info
2535 self.magic_colors(self.shell.colors)
2535 self.magic_colors(self.shell.colors)
2536 print 'Object introspection functions have now coloring:',
2536 print 'Object introspection functions have now coloring:',
2537 print ['OFF','ON'][int(self.shell.color_info)]
2537 print ['OFF','ON'][int(self.shell.color_info)]
2538
2538
2539 def magic_Pprint(self, parameter_s=''):
2539 def magic_Pprint(self, parameter_s=''):
2540 """Toggle pretty printing on/off."""
2540 """Toggle pretty printing on/off."""
2541
2541
2542 self.shell.pprint = 1 - self.shell.pprint
2542 self.shell.pprint = 1 - self.shell.pprint
2543 print 'Pretty printing has been turned', \
2543 print 'Pretty printing has been turned', \
2544 ['OFF','ON'][self.shell.pprint]
2544 ['OFF','ON'][self.shell.pprint]
2545
2545
2546 def magic_exit(self, parameter_s=''):
2546 def magic_exit(self, parameter_s=''):
2547 """Exit IPython, confirming if configured to do so.
2547 """Exit IPython, confirming if configured to do so.
2548
2548
2549 You can configure whether IPython asks for confirmation upon exit by
2549 You can configure whether IPython asks for confirmation upon exit by
2550 setting the confirm_exit flag in the ipythonrc file."""
2550 setting the confirm_exit flag in the ipythonrc file."""
2551
2551
2552 self.shell.exit()
2552 self.shell.exit()
2553
2553
2554 def magic_quit(self, parameter_s=''):
2554 def magic_quit(self, parameter_s=''):
2555 """Exit IPython, confirming if configured to do so (like %exit)"""
2555 """Exit IPython, confirming if configured to do so (like %exit)"""
2556
2556
2557 self.shell.exit()
2557 self.shell.exit()
2558
2558
2559 def magic_Exit(self, parameter_s=''):
2559 def magic_Exit(self, parameter_s=''):
2560 """Exit IPython without confirmation."""
2560 """Exit IPython without confirmation."""
2561
2561
2562 self.shell.ask_exit()
2562 self.shell.ask_exit()
2563
2563
2564 #......................................................................
2564 #......................................................................
2565 # Functions to implement unix shell-type things
2565 # Functions to implement unix shell-type things
2566
2566
2567 @testdec.skip_doctest
2567 @testdec.skip_doctest
2568 def magic_alias(self, parameter_s = ''):
2568 def magic_alias(self, parameter_s = ''):
2569 """Define an alias for a system command.
2569 """Define an alias for a system command.
2570
2570
2571 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2571 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2572
2572
2573 Then, typing 'alias_name params' will execute the system command 'cmd
2573 Then, typing 'alias_name params' will execute the system command 'cmd
2574 params' (from your underlying operating system).
2574 params' (from your underlying operating system).
2575
2575
2576 Aliases have lower precedence than magic functions and Python normal
2576 Aliases have lower precedence than magic functions and Python normal
2577 variables, so if 'foo' is both a Python variable and an alias, the
2577 variables, so if 'foo' is both a Python variable and an alias, the
2578 alias can not be executed until 'del foo' removes the Python variable.
2578 alias can not be executed until 'del foo' removes the Python variable.
2579
2579
2580 You can use the %l specifier in an alias definition to represent the
2580 You can use the %l specifier in an alias definition to represent the
2581 whole line when the alias is called. For example:
2581 whole line when the alias is called. For example:
2582
2582
2583 In [2]: alias all echo "Input in brackets: <%l>"
2583 In [2]: alias all echo "Input in brackets: <%l>"
2584 In [3]: all hello world
2584 In [3]: all hello world
2585 Input in brackets: <hello world>
2585 Input in brackets: <hello world>
2586
2586
2587 You can also define aliases with parameters using %s specifiers (one
2587 You can also define aliases with parameters using %s specifiers (one
2588 per parameter):
2588 per parameter):
2589
2589
2590 In [1]: alias parts echo first %s second %s
2590 In [1]: alias parts echo first %s second %s
2591 In [2]: %parts A B
2591 In [2]: %parts A B
2592 first A second B
2592 first A second B
2593 In [3]: %parts A
2593 In [3]: %parts A
2594 Incorrect number of arguments: 2 expected.
2594 Incorrect number of arguments: 2 expected.
2595 parts is an alias to: 'echo first %s second %s'
2595 parts is an alias to: 'echo first %s second %s'
2596
2596
2597 Note that %l and %s are mutually exclusive. You can only use one or
2597 Note that %l and %s are mutually exclusive. You can only use one or
2598 the other in your aliases.
2598 the other in your aliases.
2599
2599
2600 Aliases expand Python variables just like system calls using ! or !!
2600 Aliases expand Python variables just like system calls using ! or !!
2601 do: all expressions prefixed with '$' get expanded. For details of
2601 do: all expressions prefixed with '$' get expanded. For details of
2602 the semantic rules, see PEP-215:
2602 the semantic rules, see PEP-215:
2603 http://www.python.org/peps/pep-0215.html. This is the library used by
2603 http://www.python.org/peps/pep-0215.html. This is the library used by
2604 IPython for variable expansion. If you want to access a true shell
2604 IPython for variable expansion. If you want to access a true shell
2605 variable, an extra $ is necessary to prevent its expansion by IPython:
2605 variable, an extra $ is necessary to prevent its expansion by IPython:
2606
2606
2607 In [6]: alias show echo
2607 In [6]: alias show echo
2608 In [7]: PATH='A Python string'
2608 In [7]: PATH='A Python string'
2609 In [8]: show $PATH
2609 In [8]: show $PATH
2610 A Python string
2610 A Python string
2611 In [9]: show $$PATH
2611 In [9]: show $$PATH
2612 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2612 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2613
2613
2614 You can use the alias facility to acess all of $PATH. See the %rehash
2614 You can use the alias facility to acess all of $PATH. See the %rehash
2615 and %rehashx functions, which automatically create aliases for the
2615 and %rehashx functions, which automatically create aliases for the
2616 contents of your $PATH.
2616 contents of your $PATH.
2617
2617
2618 If called with no parameters, %alias prints the current alias table."""
2618 If called with no parameters, %alias prints the current alias table."""
2619
2619
2620 par = parameter_s.strip()
2620 par = parameter_s.strip()
2621 if not par:
2621 if not par:
2622 stored = self.db.get('stored_aliases', {} )
2622 stored = self.db.get('stored_aliases', {} )
2623 atab = self.shell.alias_table
2623 atab = self.shell.alias_table
2624 aliases = atab.keys()
2624 aliases = atab.keys()
2625 aliases.sort()
2625 aliases.sort()
2626 res = []
2626 res = []
2627 showlast = []
2627 showlast = []
2628 for alias in aliases:
2628 for alias in aliases:
2629 special = False
2629 special = False
2630 try:
2630 try:
2631 tgt = atab[alias][1]
2631 tgt = atab[alias][1]
2632 except (TypeError, AttributeError):
2632 except (TypeError, AttributeError):
2633 # unsubscriptable? probably a callable
2633 # unsubscriptable? probably a callable
2634 tgt = atab[alias]
2634 tgt = atab[alias]
2635 special = True
2635 special = True
2636 # 'interesting' aliases
2636 # 'interesting' aliases
2637 if (alias in stored or
2637 if (alias in stored or
2638 special or
2638 special or
2639 alias.lower() != os.path.splitext(tgt)[0].lower() or
2639 alias.lower() != os.path.splitext(tgt)[0].lower() or
2640 ' ' in tgt):
2640 ' ' in tgt):
2641 showlast.append((alias, tgt))
2641 showlast.append((alias, tgt))
2642 else:
2642 else:
2643 res.append((alias, tgt ))
2643 res.append((alias, tgt ))
2644
2644
2645 # show most interesting aliases last
2645 # show most interesting aliases last
2646 res.extend(showlast)
2646 res.extend(showlast)
2647 print "Total number of aliases:",len(aliases)
2647 print "Total number of aliases:",len(aliases)
2648 return res
2648 return res
2649 try:
2649 try:
2650 alias,cmd = par.split(None,1)
2650 alias,cmd = par.split(None,1)
2651 except:
2651 except:
2652 print oinspect.getdoc(self.magic_alias)
2652 print oinspect.getdoc(self.magic_alias)
2653 else:
2653 else:
2654 nargs = cmd.count('%s')
2654 nargs = cmd.count('%s')
2655 if nargs>0 and cmd.find('%l')>=0:
2655 if nargs>0 and cmd.find('%l')>=0:
2656 error('The %s and %l specifiers are mutually exclusive '
2656 error('The %s and %l specifiers are mutually exclusive '
2657 'in alias definitions.')
2657 'in alias definitions.')
2658 else: # all looks OK
2658 else: # all looks OK
2659 self.shell.alias_table[alias] = (nargs,cmd)
2659 self.shell.alias_table[alias] = (nargs,cmd)
2660 self.shell.alias_table_validate(verbose=0)
2660 self.shell.alias_table_validate(verbose=0)
2661 # end magic_alias
2661 # end magic_alias
2662
2662
2663 def magic_unalias(self, parameter_s = ''):
2663 def magic_unalias(self, parameter_s = ''):
2664 """Remove an alias"""
2664 """Remove an alias"""
2665
2665
2666 aname = parameter_s.strip()
2666 aname = parameter_s.strip()
2667 if aname in self.shell.alias_table:
2667 if aname in self.shell.alias_table:
2668 del self.shell.alias_table[aname]
2668 del self.shell.alias_table[aname]
2669 stored = self.db.get('stored_aliases', {} )
2669 stored = self.db.get('stored_aliases', {} )
2670 if aname in stored:
2670 if aname in stored:
2671 print "Removing %stored alias",aname
2671 print "Removing %stored alias",aname
2672 del stored[aname]
2672 del stored[aname]
2673 self.db['stored_aliases'] = stored
2673 self.db['stored_aliases'] = stored
2674
2674
2675
2675
2676 def magic_rehashx(self, parameter_s = ''):
2676 def magic_rehashx(self, parameter_s = ''):
2677 """Update the alias table with all executable files in $PATH.
2677 """Update the alias table with all executable files in $PATH.
2678
2678
2679 This version explicitly checks that every entry in $PATH is a file
2679 This version explicitly checks that every entry in $PATH is a file
2680 with execute access (os.X_OK), so it is much slower than %rehash.
2680 with execute access (os.X_OK), so it is much slower than %rehash.
2681
2681
2682 Under Windows, it checks executability as a match agains a
2682 Under Windows, it checks executability as a match agains a
2683 '|'-separated string of extensions, stored in the IPython config
2683 '|'-separated string of extensions, stored in the IPython config
2684 variable win_exec_ext. This defaults to 'exe|com|bat'.
2684 variable win_exec_ext. This defaults to 'exe|com|bat'.
2685
2685
2686 This function also resets the root module cache of module completer,
2686 This function also resets the root module cache of module completer,
2687 used on slow filesystems.
2687 used on slow filesystems.
2688 """
2688 """
2689
2689
2690 # for the benefit of module completer in ipy_completers.py
2690 # for the benefit of module completer in ipy_completers.py
2691 del self.db['rootmodules']
2691 del self.db['rootmodules']
2692
2692
2693 path = [os.path.abspath(os.path.expanduser(p)) for p in
2693 path = [os.path.abspath(os.path.expanduser(p)) for p in
2694 os.environ.get('PATH','').split(os.pathsep)]
2694 os.environ.get('PATH','').split(os.pathsep)]
2695 path = filter(os.path.isdir,path)
2695 path = filter(os.path.isdir,path)
2696
2696
2697 alias_table = self.shell.alias_table
2697 alias_table = self.shell.alias_table
2698 syscmdlist = []
2698 syscmdlist = []
2699 if os.name == 'posix':
2699 if os.name == 'posix':
2700 isexec = lambda fname:os.path.isfile(fname) and \
2700 isexec = lambda fname:os.path.isfile(fname) and \
2701 os.access(fname,os.X_OK)
2701 os.access(fname,os.X_OK)
2702 else:
2702 else:
2703
2703
2704 try:
2704 try:
2705 winext = os.environ['pathext'].replace(';','|').replace('.','')
2705 winext = os.environ['pathext'].replace(';','|').replace('.','')
2706 except KeyError:
2706 except KeyError:
2707 winext = 'exe|com|bat|py'
2707 winext = 'exe|com|bat|py'
2708 if 'py' not in winext:
2708 if 'py' not in winext:
2709 winext += '|py'
2709 winext += '|py'
2710 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2710 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2711 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2711 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2712 savedir = os.getcwd()
2712 savedir = os.getcwd()
2713 try:
2713 try:
2714 # write the whole loop for posix/Windows so we don't have an if in
2714 # write the whole loop for posix/Windows so we don't have an if in
2715 # the innermost part
2715 # the innermost part
2716 if os.name == 'posix':
2716 if os.name == 'posix':
2717 for pdir in path:
2717 for pdir in path:
2718 os.chdir(pdir)
2718 os.chdir(pdir)
2719 for ff in os.listdir(pdir):
2719 for ff in os.listdir(pdir):
2720 if isexec(ff) and ff not in self.shell.no_alias:
2720 if isexec(ff) and ff not in self.shell.no_alias:
2721 # each entry in the alias table must be (N,name),
2721 # each entry in the alias table must be (N,name),
2722 # where N is the number of positional arguments of the
2722 # where N is the number of positional arguments of the
2723 # alias.
2723 # alias.
2724 # Dots will be removed from alias names, since ipython
2724 # Dots will be removed from alias names, since ipython
2725 # assumes names with dots to be python code
2725 # assumes names with dots to be python code
2726 alias_table[ff.replace('.','')] = (0,ff)
2726 alias_table[ff.replace('.','')] = (0,ff)
2727 syscmdlist.append(ff)
2727 syscmdlist.append(ff)
2728 else:
2728 else:
2729 for pdir in path:
2729 for pdir in path:
2730 os.chdir(pdir)
2730 os.chdir(pdir)
2731 for ff in os.listdir(pdir):
2731 for ff in os.listdir(pdir):
2732 base, ext = os.path.splitext(ff)
2732 base, ext = os.path.splitext(ff)
2733 if isexec(ff) and base.lower() not in self.shell.no_alias:
2733 if isexec(ff) and base.lower() not in self.shell.no_alias:
2734 if ext.lower() == '.exe':
2734 if ext.lower() == '.exe':
2735 ff = base
2735 ff = base
2736 alias_table[base.lower().replace('.','')] = (0,ff)
2736 alias_table[base.lower().replace('.','')] = (0,ff)
2737 syscmdlist.append(ff)
2737 syscmdlist.append(ff)
2738 # Make sure the alias table doesn't contain keywords or builtins
2738 # Make sure the alias table doesn't contain keywords or builtins
2739 self.shell.alias_table_validate()
2739 self.shell.alias_table_validate()
2740 # Call again init_auto_alias() so we get 'rm -i' and other
2740 # Call again init_auto_alias() so we get 'rm -i' and other
2741 # modified aliases since %rehashx will probably clobber them
2741 # modified aliases since %rehashx will probably clobber them
2742
2742
2743 # no, we don't want them. if %rehashx clobbers them, good,
2743 # no, we don't want them. if %rehashx clobbers them, good,
2744 # we'll probably get better versions
2744 # we'll probably get better versions
2745 # self.shell.init_auto_alias()
2745 # self.shell.init_auto_alias()
2746 db = self.db
2746 db = self.db
2747 db['syscmdlist'] = syscmdlist
2747 db['syscmdlist'] = syscmdlist
2748 finally:
2748 finally:
2749 os.chdir(savedir)
2749 os.chdir(savedir)
2750
2750
2751 def magic_pwd(self, parameter_s = ''):
2751 def magic_pwd(self, parameter_s = ''):
2752 """Return the current working directory path."""
2752 """Return the current working directory path."""
2753 return os.getcwd()
2753 return os.getcwd()
2754
2754
2755 def magic_cd(self, parameter_s=''):
2755 def magic_cd(self, parameter_s=''):
2756 """Change the current working directory.
2756 """Change the current working directory.
2757
2757
2758 This command automatically maintains an internal list of directories
2758 This command automatically maintains an internal list of directories
2759 you visit during your IPython session, in the variable _dh. The
2759 you visit during your IPython session, in the variable _dh. The
2760 command %dhist shows this history nicely formatted. You can also
2760 command %dhist shows this history nicely formatted. You can also
2761 do 'cd -<tab>' to see directory history conveniently.
2761 do 'cd -<tab>' to see directory history conveniently.
2762
2762
2763 Usage:
2763 Usage:
2764
2764
2765 cd 'dir': changes to directory 'dir'.
2765 cd 'dir': changes to directory 'dir'.
2766
2766
2767 cd -: changes to the last visited directory.
2767 cd -: changes to the last visited directory.
2768
2768
2769 cd -<n>: changes to the n-th directory in the directory history.
2769 cd -<n>: changes to the n-th directory in the directory history.
2770
2770
2771 cd --foo: change to directory that matches 'foo' in history
2771 cd --foo: change to directory that matches 'foo' in history
2772
2772
2773 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2773 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2774 (note: cd <bookmark_name> is enough if there is no
2774 (note: cd <bookmark_name> is enough if there is no
2775 directory <bookmark_name>, but a bookmark with the name exists.)
2775 directory <bookmark_name>, but a bookmark with the name exists.)
2776 'cd -b <tab>' allows you to tab-complete bookmark names.
2776 'cd -b <tab>' allows you to tab-complete bookmark names.
2777
2777
2778 Options:
2778 Options:
2779
2779
2780 -q: quiet. Do not print the working directory after the cd command is
2780 -q: quiet. Do not print the working directory after the cd command is
2781 executed. By default IPython's cd command does print this directory,
2781 executed. By default IPython's cd command does print this directory,
2782 since the default prompts do not display path information.
2782 since the default prompts do not display path information.
2783
2783
2784 Note that !cd doesn't work for this purpose because the shell where
2784 Note that !cd doesn't work for this purpose because the shell where
2785 !command runs is immediately discarded after executing 'command'."""
2785 !command runs is immediately discarded after executing 'command'."""
2786
2786
2787 parameter_s = parameter_s.strip()
2787 parameter_s = parameter_s.strip()
2788 #bkms = self.shell.persist.get("bookmarks",{})
2788 #bkms = self.shell.persist.get("bookmarks",{})
2789
2789
2790 oldcwd = os.getcwd()
2790 oldcwd = os.getcwd()
2791 numcd = re.match(r'(-)(\d+)$',parameter_s)
2791 numcd = re.match(r'(-)(\d+)$',parameter_s)
2792 # jump in directory history by number
2792 # jump in directory history by number
2793 if numcd:
2793 if numcd:
2794 nn = int(numcd.group(2))
2794 nn = int(numcd.group(2))
2795 try:
2795 try:
2796 ps = self.shell.user_ns['_dh'][nn]
2796 ps = self.shell.user_ns['_dh'][nn]
2797 except IndexError:
2797 except IndexError:
2798 print 'The requested directory does not exist in history.'
2798 print 'The requested directory does not exist in history.'
2799 return
2799 return
2800 else:
2800 else:
2801 opts = {}
2801 opts = {}
2802 elif parameter_s.startswith('--'):
2802 elif parameter_s.startswith('--'):
2803 ps = None
2803 ps = None
2804 fallback = None
2804 fallback = None
2805 pat = parameter_s[2:]
2805 pat = parameter_s[2:]
2806 dh = self.shell.user_ns['_dh']
2806 dh = self.shell.user_ns['_dh']
2807 # first search only by basename (last component)
2807 # first search only by basename (last component)
2808 for ent in reversed(dh):
2808 for ent in reversed(dh):
2809 if pat in os.path.basename(ent) and os.path.isdir(ent):
2809 if pat in os.path.basename(ent) and os.path.isdir(ent):
2810 ps = ent
2810 ps = ent
2811 break
2811 break
2812
2812
2813 if fallback is None and pat in ent and os.path.isdir(ent):
2813 if fallback is None and pat in ent and os.path.isdir(ent):
2814 fallback = ent
2814 fallback = ent
2815
2815
2816 # if we have no last part match, pick the first full path match
2816 # if we have no last part match, pick the first full path match
2817 if ps is None:
2817 if ps is None:
2818 ps = fallback
2818 ps = fallback
2819
2819
2820 if ps is None:
2820 if ps is None:
2821 print "No matching entry in directory history"
2821 print "No matching entry in directory history"
2822 return
2822 return
2823 else:
2823 else:
2824 opts = {}
2824 opts = {}
2825
2825
2826
2826
2827 else:
2827 else:
2828 #turn all non-space-escaping backslashes to slashes,
2828 #turn all non-space-escaping backslashes to slashes,
2829 # for c:\windows\directory\names\
2829 # for c:\windows\directory\names\
2830 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2830 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2831 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2831 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2832 # jump to previous
2832 # jump to previous
2833 if ps == '-':
2833 if ps == '-':
2834 try:
2834 try:
2835 ps = self.shell.user_ns['_dh'][-2]
2835 ps = self.shell.user_ns['_dh'][-2]
2836 except IndexError:
2836 except IndexError:
2837 raise UsageError('%cd -: No previous directory to change to.')
2837 raise UsageError('%cd -: No previous directory to change to.')
2838 # jump to bookmark if needed
2838 # jump to bookmark if needed
2839 else:
2839 else:
2840 if not os.path.isdir(ps) or opts.has_key('b'):
2840 if not os.path.isdir(ps) or opts.has_key('b'):
2841 bkms = self.db.get('bookmarks', {})
2841 bkms = self.db.get('bookmarks', {})
2842
2842
2843 if bkms.has_key(ps):
2843 if bkms.has_key(ps):
2844 target = bkms[ps]
2844 target = bkms[ps]
2845 print '(bookmark:%s) -> %s' % (ps,target)
2845 print '(bookmark:%s) -> %s' % (ps,target)
2846 ps = target
2846 ps = target
2847 else:
2847 else:
2848 if opts.has_key('b'):
2848 if opts.has_key('b'):
2849 raise UsageError("Bookmark '%s' not found. "
2849 raise UsageError("Bookmark '%s' not found. "
2850 "Use '%%bookmark -l' to see your bookmarks." % ps)
2850 "Use '%%bookmark -l' to see your bookmarks." % ps)
2851
2851
2852 # at this point ps should point to the target dir
2852 # at this point ps should point to the target dir
2853 if ps:
2853 if ps:
2854 try:
2854 try:
2855 os.chdir(os.path.expanduser(ps))
2855 os.chdir(os.path.expanduser(ps))
2856 if self.shell.term_title:
2856 if self.shell.term_title:
2857 platutils.set_term_title('IPython: ' + abbrev_cwd())
2857 platutils.set_term_title('IPython: ' + abbrev_cwd())
2858 except OSError:
2858 except OSError:
2859 print sys.exc_info()[1]
2859 print sys.exc_info()[1]
2860 else:
2860 else:
2861 cwd = os.getcwd()
2861 cwd = os.getcwd()
2862 dhist = self.shell.user_ns['_dh']
2862 dhist = self.shell.user_ns['_dh']
2863 if oldcwd != cwd:
2863 if oldcwd != cwd:
2864 dhist.append(cwd)
2864 dhist.append(cwd)
2865 self.db['dhist'] = compress_dhist(dhist)[-100:]
2865 self.db['dhist'] = compress_dhist(dhist)[-100:]
2866
2866
2867 else:
2867 else:
2868 os.chdir(self.shell.home_dir)
2868 os.chdir(self.shell.home_dir)
2869 if self.shell.term_title:
2869 if self.shell.term_title:
2870 platutils.set_term_title('IPython: ' + '~')
2870 platutils.set_term_title('IPython: ' + '~')
2871 cwd = os.getcwd()
2871 cwd = os.getcwd()
2872 dhist = self.shell.user_ns['_dh']
2872 dhist = self.shell.user_ns['_dh']
2873
2873
2874 if oldcwd != cwd:
2874 if oldcwd != cwd:
2875 dhist.append(cwd)
2875 dhist.append(cwd)
2876 self.db['dhist'] = compress_dhist(dhist)[-100:]
2876 self.db['dhist'] = compress_dhist(dhist)[-100:]
2877 if not 'q' in opts and self.shell.user_ns['_dh']:
2877 if not 'q' in opts and self.shell.user_ns['_dh']:
2878 print self.shell.user_ns['_dh'][-1]
2878 print self.shell.user_ns['_dh'][-1]
2879
2879
2880
2880
2881 def magic_env(self, parameter_s=''):
2881 def magic_env(self, parameter_s=''):
2882 """List environment variables."""
2882 """List environment variables."""
2883
2883
2884 return os.environ.data
2884 return os.environ.data
2885
2885
2886 def magic_pushd(self, parameter_s=''):
2886 def magic_pushd(self, parameter_s=''):
2887 """Place the current dir on stack and change directory.
2887 """Place the current dir on stack and change directory.
2888
2888
2889 Usage:\\
2889 Usage:\\
2890 %pushd ['dirname']
2890 %pushd ['dirname']
2891 """
2891 """
2892
2892
2893 dir_s = self.shell.dir_stack
2893 dir_s = self.shell.dir_stack
2894 tgt = os.path.expanduser(parameter_s)
2894 tgt = os.path.expanduser(parameter_s)
2895 cwd = os.getcwd().replace(self.home_dir,'~')
2895 cwd = os.getcwd().replace(self.home_dir,'~')
2896 if tgt:
2896 if tgt:
2897 self.magic_cd(parameter_s)
2897 self.magic_cd(parameter_s)
2898 dir_s.insert(0,cwd)
2898 dir_s.insert(0,cwd)
2899 return self.magic_dirs()
2899 return self.magic_dirs()
2900
2900
2901 def magic_popd(self, parameter_s=''):
2901 def magic_popd(self, parameter_s=''):
2902 """Change to directory popped off the top of the stack.
2902 """Change to directory popped off the top of the stack.
2903 """
2903 """
2904 if not self.shell.dir_stack:
2904 if not self.shell.dir_stack:
2905 raise UsageError("%popd on empty stack")
2905 raise UsageError("%popd on empty stack")
2906 top = self.shell.dir_stack.pop(0)
2906 top = self.shell.dir_stack.pop(0)
2907 self.magic_cd(top)
2907 self.magic_cd(top)
2908 print "popd ->",top
2908 print "popd ->",top
2909
2909
2910 def magic_dirs(self, parameter_s=''):
2910 def magic_dirs(self, parameter_s=''):
2911 """Return the current directory stack."""
2911 """Return the current directory stack."""
2912
2912
2913 return self.shell.dir_stack
2913 return self.shell.dir_stack
2914
2914
2915 def magic_dhist(self, parameter_s=''):
2915 def magic_dhist(self, parameter_s=''):
2916 """Print your history of visited directories.
2916 """Print your history of visited directories.
2917
2917
2918 %dhist -> print full history\\
2918 %dhist -> print full history\\
2919 %dhist n -> print last n entries only\\
2919 %dhist n -> print last n entries only\\
2920 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2920 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2921
2921
2922 This history is automatically maintained by the %cd command, and
2922 This history is automatically maintained by the %cd command, and
2923 always available as the global list variable _dh. You can use %cd -<n>
2923 always available as the global list variable _dh. You can use %cd -<n>
2924 to go to directory number <n>.
2924 to go to directory number <n>.
2925
2925
2926 Note that most of time, you should view directory history by entering
2926 Note that most of time, you should view directory history by entering
2927 cd -<TAB>.
2927 cd -<TAB>.
2928
2928
2929 """
2929 """
2930
2930
2931 dh = self.shell.user_ns['_dh']
2931 dh = self.shell.user_ns['_dh']
2932 if parameter_s:
2932 if parameter_s:
2933 try:
2933 try:
2934 args = map(int,parameter_s.split())
2934 args = map(int,parameter_s.split())
2935 except:
2935 except:
2936 self.arg_err(Magic.magic_dhist)
2936 self.arg_err(Magic.magic_dhist)
2937 return
2937 return
2938 if len(args) == 1:
2938 if len(args) == 1:
2939 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2939 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2940 elif len(args) == 2:
2940 elif len(args) == 2:
2941 ini,fin = args
2941 ini,fin = args
2942 else:
2942 else:
2943 self.arg_err(Magic.magic_dhist)
2943 self.arg_err(Magic.magic_dhist)
2944 return
2944 return
2945 else:
2945 else:
2946 ini,fin = 0,len(dh)
2946 ini,fin = 0,len(dh)
2947 nlprint(dh,
2947 nlprint(dh,
2948 header = 'Directory history (kept in _dh)',
2948 header = 'Directory history (kept in _dh)',
2949 start=ini,stop=fin)
2949 start=ini,stop=fin)
2950
2950
2951 @testdec.skip_doctest
2951 @testdec.skip_doctest
2952 def magic_sc(self, parameter_s=''):
2952 def magic_sc(self, parameter_s=''):
2953 """Shell capture - execute a shell command and capture its output.
2953 """Shell capture - execute a shell command and capture its output.
2954
2954
2955 DEPRECATED. Suboptimal, retained for backwards compatibility.
2955 DEPRECATED. Suboptimal, retained for backwards compatibility.
2956
2956
2957 You should use the form 'var = !command' instead. Example:
2957 You should use the form 'var = !command' instead. Example:
2958
2958
2959 "%sc -l myfiles = ls ~" should now be written as
2959 "%sc -l myfiles = ls ~" should now be written as
2960
2960
2961 "myfiles = !ls ~"
2961 "myfiles = !ls ~"
2962
2962
2963 myfiles.s, myfiles.l and myfiles.n still apply as documented
2963 myfiles.s, myfiles.l and myfiles.n still apply as documented
2964 below.
2964 below.
2965
2965
2966 --
2966 --
2967 %sc [options] varname=command
2967 %sc [options] varname=command
2968
2968
2969 IPython will run the given command using commands.getoutput(), and
2969 IPython will run the given command using commands.getoutput(), and
2970 will then update the user's interactive namespace with a variable
2970 will then update the user's interactive namespace with a variable
2971 called varname, containing the value of the call. Your command can
2971 called varname, containing the value of the call. Your command can
2972 contain shell wildcards, pipes, etc.
2972 contain shell wildcards, pipes, etc.
2973
2973
2974 The '=' sign in the syntax is mandatory, and the variable name you
2974 The '=' sign in the syntax is mandatory, and the variable name you
2975 supply must follow Python's standard conventions for valid names.
2975 supply must follow Python's standard conventions for valid names.
2976
2976
2977 (A special format without variable name exists for internal use)
2977 (A special format without variable name exists for internal use)
2978
2978
2979 Options:
2979 Options:
2980
2980
2981 -l: list output. Split the output on newlines into a list before
2981 -l: list output. Split the output on newlines into a list before
2982 assigning it to the given variable. By default the output is stored
2982 assigning it to the given variable. By default the output is stored
2983 as a single string.
2983 as a single string.
2984
2984
2985 -v: verbose. Print the contents of the variable.
2985 -v: verbose. Print the contents of the variable.
2986
2986
2987 In most cases you should not need to split as a list, because the
2987 In most cases you should not need to split as a list, because the
2988 returned value is a special type of string which can automatically
2988 returned value is a special type of string which can automatically
2989 provide its contents either as a list (split on newlines) or as a
2989 provide its contents either as a list (split on newlines) or as a
2990 space-separated string. These are convenient, respectively, either
2990 space-separated string. These are convenient, respectively, either
2991 for sequential processing or to be passed to a shell command.
2991 for sequential processing or to be passed to a shell command.
2992
2992
2993 For example:
2993 For example:
2994
2994
2995 # all-random
2995 # all-random
2996
2996
2997 # Capture into variable a
2997 # Capture into variable a
2998 In [1]: sc a=ls *py
2998 In [1]: sc a=ls *py
2999
2999
3000 # a is a string with embedded newlines
3000 # a is a string with embedded newlines
3001 In [2]: a
3001 In [2]: a
3002 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3002 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3003
3003
3004 # which can be seen as a list:
3004 # which can be seen as a list:
3005 In [3]: a.l
3005 In [3]: a.l
3006 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3006 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3007
3007
3008 # or as a whitespace-separated string:
3008 # or as a whitespace-separated string:
3009 In [4]: a.s
3009 In [4]: a.s
3010 Out[4]: 'setup.py win32_manual_post_install.py'
3010 Out[4]: 'setup.py win32_manual_post_install.py'
3011
3011
3012 # a.s is useful to pass as a single command line:
3012 # a.s is useful to pass as a single command line:
3013 In [5]: !wc -l $a.s
3013 In [5]: !wc -l $a.s
3014 146 setup.py
3014 146 setup.py
3015 130 win32_manual_post_install.py
3015 130 win32_manual_post_install.py
3016 276 total
3016 276 total
3017
3017
3018 # while the list form is useful to loop over:
3018 # while the list form is useful to loop over:
3019 In [6]: for f in a.l:
3019 In [6]: for f in a.l:
3020 ...: !wc -l $f
3020 ...: !wc -l $f
3021 ...:
3021 ...:
3022 146 setup.py
3022 146 setup.py
3023 130 win32_manual_post_install.py
3023 130 win32_manual_post_install.py
3024
3024
3025 Similiarly, the lists returned by the -l option are also special, in
3025 Similiarly, the lists returned by the -l option are also special, in
3026 the sense that you can equally invoke the .s attribute on them to
3026 the sense that you can equally invoke the .s attribute on them to
3027 automatically get a whitespace-separated string from their contents:
3027 automatically get a whitespace-separated string from their contents:
3028
3028
3029 In [7]: sc -l b=ls *py
3029 In [7]: sc -l b=ls *py
3030
3030
3031 In [8]: b
3031 In [8]: b
3032 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3032 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3033
3033
3034 In [9]: b.s
3034 In [9]: b.s
3035 Out[9]: 'setup.py win32_manual_post_install.py'
3035 Out[9]: 'setup.py win32_manual_post_install.py'
3036
3036
3037 In summary, both the lists and strings used for ouptut capture have
3037 In summary, both the lists and strings used for ouptut capture have
3038 the following special attributes:
3038 the following special attributes:
3039
3039
3040 .l (or .list) : value as list.
3040 .l (or .list) : value as list.
3041 .n (or .nlstr): value as newline-separated string.
3041 .n (or .nlstr): value as newline-separated string.
3042 .s (or .spstr): value as space-separated string.
3042 .s (or .spstr): value as space-separated string.
3043 """
3043 """
3044
3044
3045 opts,args = self.parse_options(parameter_s,'lv')
3045 opts,args = self.parse_options(parameter_s,'lv')
3046 # Try to get a variable name and command to run
3046 # Try to get a variable name and command to run
3047 try:
3047 try:
3048 # the variable name must be obtained from the parse_options
3048 # the variable name must be obtained from the parse_options
3049 # output, which uses shlex.split to strip options out.
3049 # output, which uses shlex.split to strip options out.
3050 var,_ = args.split('=',1)
3050 var,_ = args.split('=',1)
3051 var = var.strip()
3051 var = var.strip()
3052 # But the the command has to be extracted from the original input
3052 # But the the command has to be extracted from the original input
3053 # parameter_s, not on what parse_options returns, to avoid the
3053 # parameter_s, not on what parse_options returns, to avoid the
3054 # quote stripping which shlex.split performs on it.
3054 # quote stripping which shlex.split performs on it.
3055 _,cmd = parameter_s.split('=',1)
3055 _,cmd = parameter_s.split('=',1)
3056 except ValueError:
3056 except ValueError:
3057 var,cmd = '',''
3057 var,cmd = '',''
3058 # If all looks ok, proceed
3058 # If all looks ok, proceed
3059 out,err = self.shell.getoutputerror(cmd)
3059 out,err = self.shell.getoutputerror(cmd)
3060 if err:
3060 if err:
3061 print >> Term.cerr,err
3061 print >> Term.cerr,err
3062 if opts.has_key('l'):
3062 if opts.has_key('l'):
3063 out = SList(out.split('\n'))
3063 out = SList(out.split('\n'))
3064 else:
3064 else:
3065 out = LSString(out)
3065 out = LSString(out)
3066 if opts.has_key('v'):
3066 if opts.has_key('v'):
3067 print '%s ==\n%s' % (var,pformat(out))
3067 print '%s ==\n%s' % (var,pformat(out))
3068 if var:
3068 if var:
3069 self.shell.user_ns.update({var:out})
3069 self.shell.user_ns.update({var:out})
3070 else:
3070 else:
3071 return out
3071 return out
3072
3072
3073 def magic_sx(self, parameter_s=''):
3073 def magic_sx(self, parameter_s=''):
3074 """Shell execute - run a shell command and capture its output.
3074 """Shell execute - run a shell command and capture its output.
3075
3075
3076 %sx command
3076 %sx command
3077
3077
3078 IPython will run the given command using commands.getoutput(), and
3078 IPython will run the given command using commands.getoutput(), and
3079 return the result formatted as a list (split on '\\n'). Since the
3079 return the result formatted as a list (split on '\\n'). Since the
3080 output is _returned_, it will be stored in ipython's regular output
3080 output is _returned_, it will be stored in ipython's regular output
3081 cache Out[N] and in the '_N' automatic variables.
3081 cache Out[N] and in the '_N' automatic variables.
3082
3082
3083 Notes:
3083 Notes:
3084
3084
3085 1) If an input line begins with '!!', then %sx is automatically
3085 1) If an input line begins with '!!', then %sx is automatically
3086 invoked. That is, while:
3086 invoked. That is, while:
3087 !ls
3087 !ls
3088 causes ipython to simply issue system('ls'), typing
3088 causes ipython to simply issue system('ls'), typing
3089 !!ls
3089 !!ls
3090 is a shorthand equivalent to:
3090 is a shorthand equivalent to:
3091 %sx ls
3091 %sx ls
3092
3092
3093 2) %sx differs from %sc in that %sx automatically splits into a list,
3093 2) %sx differs from %sc in that %sx automatically splits into a list,
3094 like '%sc -l'. The reason for this is to make it as easy as possible
3094 like '%sc -l'. The reason for this is to make it as easy as possible
3095 to process line-oriented shell output via further python commands.
3095 to process line-oriented shell output via further python commands.
3096 %sc is meant to provide much finer control, but requires more
3096 %sc is meant to provide much finer control, but requires more
3097 typing.
3097 typing.
3098
3098
3099 3) Just like %sc -l, this is a list with special attributes:
3099 3) Just like %sc -l, this is a list with special attributes:
3100
3100
3101 .l (or .list) : value as list.
3101 .l (or .list) : value as list.
3102 .n (or .nlstr): value as newline-separated string.
3102 .n (or .nlstr): value as newline-separated string.
3103 .s (or .spstr): value as whitespace-separated string.
3103 .s (or .spstr): value as whitespace-separated string.
3104
3104
3105 This is very useful when trying to use such lists as arguments to
3105 This is very useful when trying to use such lists as arguments to
3106 system commands."""
3106 system commands."""
3107
3107
3108 if parameter_s:
3108 if parameter_s:
3109 out,err = self.shell.getoutputerror(parameter_s)
3109 out,err = self.shell.getoutputerror(parameter_s)
3110 if err:
3110 if err:
3111 print >> Term.cerr,err
3111 print >> Term.cerr,err
3112 return SList(out.split('\n'))
3112 return SList(out.split('\n'))
3113
3113
3114 def magic_bg(self, parameter_s=''):
3114 def magic_bg(self, parameter_s=''):
3115 """Run a job in the background, in a separate thread.
3115 """Run a job in the background, in a separate thread.
3116
3116
3117 For example,
3117 For example,
3118
3118
3119 %bg myfunc(x,y,z=1)
3119 %bg myfunc(x,y,z=1)
3120
3120
3121 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3121 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3122 execution starts, a message will be printed indicating the job
3122 execution starts, a message will be printed indicating the job
3123 number. If your job number is 5, you can use
3123 number. If your job number is 5, you can use
3124
3124
3125 myvar = jobs.result(5) or myvar = jobs[5].result
3125 myvar = jobs.result(5) or myvar = jobs[5].result
3126
3126
3127 to assign this result to variable 'myvar'.
3127 to assign this result to variable 'myvar'.
3128
3128
3129 IPython has a job manager, accessible via the 'jobs' object. You can
3129 IPython has a job manager, accessible via the 'jobs' object. You can
3130 type jobs? to get more information about it, and use jobs.<TAB> to see
3130 type jobs? to get more information about it, and use jobs.<TAB> to see
3131 its attributes. All attributes not starting with an underscore are
3131 its attributes. All attributes not starting with an underscore are
3132 meant for public use.
3132 meant for public use.
3133
3133
3134 In particular, look at the jobs.new() method, which is used to create
3134 In particular, look at the jobs.new() method, which is used to create
3135 new jobs. This magic %bg function is just a convenience wrapper
3135 new jobs. This magic %bg function is just a convenience wrapper
3136 around jobs.new(), for expression-based jobs. If you want to create a
3136 around jobs.new(), for expression-based jobs. If you want to create a
3137 new job with an explicit function object and arguments, you must call
3137 new job with an explicit function object and arguments, you must call
3138 jobs.new() directly.
3138 jobs.new() directly.
3139
3139
3140 The jobs.new docstring also describes in detail several important
3140 The jobs.new docstring also describes in detail several important
3141 caveats associated with a thread-based model for background job
3141 caveats associated with a thread-based model for background job
3142 execution. Type jobs.new? for details.
3142 execution. Type jobs.new? for details.
3143
3143
3144 You can check the status of all jobs with jobs.status().
3144 You can check the status of all jobs with jobs.status().
3145
3145
3146 The jobs variable is set by IPython into the Python builtin namespace.
3146 The jobs variable is set by IPython into the Python builtin namespace.
3147 If you ever declare a variable named 'jobs', you will shadow this
3147 If you ever declare a variable named 'jobs', you will shadow this
3148 name. You can either delete your global jobs variable to regain
3148 name. You can either delete your global jobs variable to regain
3149 access to the job manager, or make a new name and assign it manually
3149 access to the job manager, or make a new name and assign it manually
3150 to the manager (stored in IPython's namespace). For example, to
3150 to the manager (stored in IPython's namespace). For example, to
3151 assign the job manager to the Jobs name, use:
3151 assign the job manager to the Jobs name, use:
3152
3152
3153 Jobs = __builtins__.jobs"""
3153 Jobs = __builtins__.jobs"""
3154
3154
3155 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3155 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3156
3156
3157 def magic_r(self, parameter_s=''):
3157 def magic_r(self, parameter_s=''):
3158 """Repeat previous input.
3158 """Repeat previous input.
3159
3159
3160 Note: Consider using the more powerfull %rep instead!
3160 Note: Consider using the more powerfull %rep instead!
3161
3161
3162 If given an argument, repeats the previous command which starts with
3162 If given an argument, repeats the previous command which starts with
3163 the same string, otherwise it just repeats the previous input.
3163 the same string, otherwise it just repeats the previous input.
3164
3164
3165 Shell escaped commands (with ! as first character) are not recognized
3165 Shell escaped commands (with ! as first character) are not recognized
3166 by this system, only pure python code and magic commands.
3166 by this system, only pure python code and magic commands.
3167 """
3167 """
3168
3168
3169 start = parameter_s.strip()
3169 start = parameter_s.strip()
3170 esc_magic = self.shell.ESC_MAGIC
3170 esc_magic = self.shell.ESC_MAGIC
3171 # Identify magic commands even if automagic is on (which means
3171 # Identify magic commands even if automagic is on (which means
3172 # the in-memory version is different from that typed by the user).
3172 # the in-memory version is different from that typed by the user).
3173 if self.shell.automagic:
3173 if self.shell.automagic:
3174 start_magic = esc_magic+start
3174 start_magic = esc_magic+start
3175 else:
3175 else:
3176 start_magic = start
3176 start_magic = start
3177 # Look through the input history in reverse
3177 # Look through the input history in reverse
3178 for n in range(len(self.shell.input_hist)-2,0,-1):
3178 for n in range(len(self.shell.input_hist)-2,0,-1):
3179 input = self.shell.input_hist[n]
3179 input = self.shell.input_hist[n]
3180 # skip plain 'r' lines so we don't recurse to infinity
3180 # skip plain 'r' lines so we don't recurse to infinity
3181 if input != '_ip.magic("r")\n' and \
3181 if input != '_ip.magic("r")\n' and \
3182 (input.startswith(start) or input.startswith(start_magic)):
3182 (input.startswith(start) or input.startswith(start_magic)):
3183 #print 'match',`input` # dbg
3183 #print 'match',`input` # dbg
3184 print 'Executing:',input,
3184 print 'Executing:',input,
3185 self.shell.runlines(input)
3185 self.shell.runlines(input)
3186 return
3186 return
3187 print 'No previous input matching `%s` found.' % start
3187 print 'No previous input matching `%s` found.' % start
3188
3188
3189
3189
3190 def magic_bookmark(self, parameter_s=''):
3190 def magic_bookmark(self, parameter_s=''):
3191 """Manage IPython's bookmark system.
3191 """Manage IPython's bookmark system.
3192
3192
3193 %bookmark <name> - set bookmark to current dir
3193 %bookmark <name> - set bookmark to current dir
3194 %bookmark <name> <dir> - set bookmark to <dir>
3194 %bookmark <name> <dir> - set bookmark to <dir>
3195 %bookmark -l - list all bookmarks
3195 %bookmark -l - list all bookmarks
3196 %bookmark -d <name> - remove bookmark
3196 %bookmark -d <name> - remove bookmark
3197 %bookmark -r - remove all bookmarks
3197 %bookmark -r - remove all bookmarks
3198
3198
3199 You can later on access a bookmarked folder with:
3199 You can later on access a bookmarked folder with:
3200 %cd -b <name>
3200 %cd -b <name>
3201 or simply '%cd <name>' if there is no directory called <name> AND
3201 or simply '%cd <name>' if there is no directory called <name> AND
3202 there is such a bookmark defined.
3202 there is such a bookmark defined.
3203
3203
3204 Your bookmarks persist through IPython sessions, but they are
3204 Your bookmarks persist through IPython sessions, but they are
3205 associated with each profile."""
3205 associated with each profile."""
3206
3206
3207 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3207 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3208 if len(args) > 2:
3208 if len(args) > 2:
3209 raise UsageError("%bookmark: too many arguments")
3209 raise UsageError("%bookmark: too many arguments")
3210
3210
3211 bkms = self.db.get('bookmarks',{})
3211 bkms = self.db.get('bookmarks',{})
3212
3212
3213 if opts.has_key('d'):
3213 if opts.has_key('d'):
3214 try:
3214 try:
3215 todel = args[0]
3215 todel = args[0]
3216 except IndexError:
3216 except IndexError:
3217 raise UsageError(
3217 raise UsageError(
3218 "%bookmark -d: must provide a bookmark to delete")
3218 "%bookmark -d: must provide a bookmark to delete")
3219 else:
3219 else:
3220 try:
3220 try:
3221 del bkms[todel]
3221 del bkms[todel]
3222 except KeyError:
3222 except KeyError:
3223 raise UsageError(
3223 raise UsageError(
3224 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3224 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3225
3225
3226 elif opts.has_key('r'):
3226 elif opts.has_key('r'):
3227 bkms = {}
3227 bkms = {}
3228 elif opts.has_key('l'):
3228 elif opts.has_key('l'):
3229 bks = bkms.keys()
3229 bks = bkms.keys()
3230 bks.sort()
3230 bks.sort()
3231 if bks:
3231 if bks:
3232 size = max(map(len,bks))
3232 size = max(map(len,bks))
3233 else:
3233 else:
3234 size = 0
3234 size = 0
3235 fmt = '%-'+str(size)+'s -> %s'
3235 fmt = '%-'+str(size)+'s -> %s'
3236 print 'Current bookmarks:'
3236 print 'Current bookmarks:'
3237 for bk in bks:
3237 for bk in bks:
3238 print fmt % (bk,bkms[bk])
3238 print fmt % (bk,bkms[bk])
3239 else:
3239 else:
3240 if not args:
3240 if not args:
3241 raise UsageError("%bookmark: You must specify the bookmark name")
3241 raise UsageError("%bookmark: You must specify the bookmark name")
3242 elif len(args)==1:
3242 elif len(args)==1:
3243 bkms[args[0]] = os.getcwd()
3243 bkms[args[0]] = os.getcwd()
3244 elif len(args)==2:
3244 elif len(args)==2:
3245 bkms[args[0]] = args[1]
3245 bkms[args[0]] = args[1]
3246 self.db['bookmarks'] = bkms
3246 self.db['bookmarks'] = bkms
3247
3247
3248 def magic_pycat(self, parameter_s=''):
3248 def magic_pycat(self, parameter_s=''):
3249 """Show a syntax-highlighted file through a pager.
3249 """Show a syntax-highlighted file through a pager.
3250
3250
3251 This magic is similar to the cat utility, but it will assume the file
3251 This magic is similar to the cat utility, but it will assume the file
3252 to be Python source and will show it with syntax highlighting. """
3252 to be Python source and will show it with syntax highlighting. """
3253
3253
3254 try:
3254 try:
3255 filename = get_py_filename(parameter_s)
3255 filename = get_py_filename(parameter_s)
3256 cont = file_read(filename)
3256 cont = file_read(filename)
3257 except IOError:
3257 except IOError:
3258 try:
3258 try:
3259 cont = eval(parameter_s,self.user_ns)
3259 cont = eval(parameter_s,self.user_ns)
3260 except NameError:
3260 except NameError:
3261 cont = None
3261 cont = None
3262 if cont is None:
3262 if cont is None:
3263 print "Error: no such file or variable"
3263 print "Error: no such file or variable"
3264 return
3264 return
3265
3265
3266 page(self.shell.pycolorize(cont),
3266 page(self.shell.pycolorize(cont),
3267 screen_lines=self.shell.usable_screen_length)
3267 screen_lines=self.shell.usable_screen_length)
3268
3268
3269 def _rerun_pasted(self):
3269 def _rerun_pasted(self):
3270 """ Rerun a previously pasted command.
3270 """ Rerun a previously pasted command.
3271 """
3271 """
3272 b = self.user_ns.get('pasted_block', None)
3272 b = self.user_ns.get('pasted_block', None)
3273 if b is None:
3273 if b is None:
3274 raise UsageError('No previous pasted block available')
3274 raise UsageError('No previous pasted block available')
3275 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3275 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3276 exec b in self.user_ns
3276 exec b in self.user_ns
3277
3277
3278 def _get_pasted_lines(self, sentinel):
3278 def _get_pasted_lines(self, sentinel):
3279 """ Yield pasted lines until the user enters the given sentinel value.
3279 """ Yield pasted lines until the user enters the given sentinel value.
3280 """
3280 """
3281 from IPython.core import iplib
3281 from IPython.core import iplib
3282 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3282 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3283 while True:
3283 while True:
3284 l = iplib.raw_input_original(':')
3284 l = iplib.raw_input_original(':')
3285 if l == sentinel:
3285 if l == sentinel:
3286 return
3286 return
3287 else:
3287 else:
3288 yield l
3288 yield l
3289
3289
3290 def _strip_pasted_lines_for_code(self, raw_lines):
3290 def _strip_pasted_lines_for_code(self, raw_lines):
3291 """ Strip non-code parts of a sequence of lines to return a block of
3291 """ Strip non-code parts of a sequence of lines to return a block of
3292 code.
3292 code.
3293 """
3293 """
3294 # Regular expressions that declare text we strip from the input:
3294 # Regular expressions that declare text we strip from the input:
3295 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3295 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3296 r'^\s*(\s?>)+', # Python input prompt
3296 r'^\s*(\s?>)+', # Python input prompt
3297 r'^\s*\.{3,}', # Continuation prompts
3297 r'^\s*\.{3,}', # Continuation prompts
3298 r'^\++',
3298 r'^\++',
3299 ]
3299 ]
3300
3300
3301 strip_from_start = map(re.compile,strip_re)
3301 strip_from_start = map(re.compile,strip_re)
3302
3302
3303 lines = []
3303 lines = []
3304 for l in raw_lines:
3304 for l in raw_lines:
3305 for pat in strip_from_start:
3305 for pat in strip_from_start:
3306 l = pat.sub('',l)
3306 l = pat.sub('',l)
3307 lines.append(l)
3307 lines.append(l)
3308
3308
3309 block = "\n".join(lines) + '\n'
3309 block = "\n".join(lines) + '\n'
3310 #print "block:\n",block
3310 #print "block:\n",block
3311 return block
3311 return block
3312
3312
3313 def _execute_block(self, block, par):
3313 def _execute_block(self, block, par):
3314 """ Execute a block, or store it in a variable, per the user's request.
3314 """ Execute a block, or store it in a variable, per the user's request.
3315 """
3315 """
3316 if not par:
3316 if not par:
3317 b = textwrap.dedent(block)
3317 b = textwrap.dedent(block)
3318 self.user_ns['pasted_block'] = b
3318 self.user_ns['pasted_block'] = b
3319 exec b in self.user_ns
3319 exec b in self.user_ns
3320 else:
3320 else:
3321 self.user_ns[par] = SList(block.splitlines())
3321 self.user_ns[par] = SList(block.splitlines())
3322 print "Block assigned to '%s'" % par
3322 print "Block assigned to '%s'" % par
3323
3323
3324 def magic_cpaste(self, parameter_s=''):
3324 def magic_cpaste(self, parameter_s=''):
3325 """Allows you to paste & execute a pre-formatted code block from clipboard.
3325 """Allows you to paste & execute a pre-formatted code block from clipboard.
3326
3326
3327 You must terminate the block with '--' (two minus-signs) alone on the
3327 You must terminate the block with '--' (two minus-signs) alone on the
3328 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3328 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3329 is the new sentinel for this operation)
3329 is the new sentinel for this operation)
3330
3330
3331 The block is dedented prior to execution to enable execution of method
3331 The block is dedented prior to execution to enable execution of method
3332 definitions. '>' and '+' characters at the beginning of a line are
3332 definitions. '>' and '+' characters at the beginning of a line are
3333 ignored, to allow pasting directly from e-mails, diff files and
3333 ignored, to allow pasting directly from e-mails, diff files and
3334 doctests (the '...' continuation prompt is also stripped). The
3334 doctests (the '...' continuation prompt is also stripped). The
3335 executed block is also assigned to variable named 'pasted_block' for
3335 executed block is also assigned to variable named 'pasted_block' for
3336 later editing with '%edit pasted_block'.
3336 later editing with '%edit pasted_block'.
3337
3337
3338 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3338 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3339 This assigns the pasted block to variable 'foo' as string, without
3339 This assigns the pasted block to variable 'foo' as string, without
3340 dedenting or executing it (preceding >>> and + is still stripped)
3340 dedenting or executing it (preceding >>> and + is still stripped)
3341
3341
3342 '%cpaste -r' re-executes the block previously entered by cpaste.
3342 '%cpaste -r' re-executes the block previously entered by cpaste.
3343
3343
3344 Do not be alarmed by garbled output on Windows (it's a readline bug).
3344 Do not be alarmed by garbled output on Windows (it's a readline bug).
3345 Just press enter and type -- (and press enter again) and the block
3345 Just press enter and type -- (and press enter again) and the block
3346 will be what was just pasted.
3346 will be what was just pasted.
3347
3347
3348 IPython statements (magics, shell escapes) are not supported (yet).
3348 IPython statements (magics, shell escapes) are not supported (yet).
3349
3349
3350 See also
3350 See also
3351 --------
3351 --------
3352 paste: automatically pull code from clipboard.
3352 paste: automatically pull code from clipboard.
3353 """
3353 """
3354
3354
3355 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3355 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3356 par = args.strip()
3356 par = args.strip()
3357 if opts.has_key('r'):
3357 if opts.has_key('r'):
3358 self._rerun_pasted()
3358 self._rerun_pasted()
3359 return
3359 return
3360
3360
3361 sentinel = opts.get('s','--')
3361 sentinel = opts.get('s','--')
3362
3362
3363 block = self._strip_pasted_lines_for_code(
3363 block = self._strip_pasted_lines_for_code(
3364 self._get_pasted_lines(sentinel))
3364 self._get_pasted_lines(sentinel))
3365
3365
3366 self._execute_block(block, par)
3366 self._execute_block(block, par)
3367
3367
3368 def magic_paste(self, parameter_s=''):
3368 def magic_paste(self, parameter_s=''):
3369 """Allows you to paste & execute a pre-formatted code block from clipboard.
3369 """Allows you to paste & execute a pre-formatted code block from clipboard.
3370
3370
3371 The text is pulled directly from the clipboard without user
3371 The text is pulled directly from the clipboard without user
3372 intervention and printed back on the screen before execution (unless
3372 intervention and printed back on the screen before execution (unless
3373 the -q flag is given to force quiet mode).
3373 the -q flag is given to force quiet mode).
3374
3374
3375 The block is dedented prior to execution to enable execution of method
3375 The block is dedented prior to execution to enable execution of method
3376 definitions. '>' and '+' characters at the beginning of a line are
3376 definitions. '>' and '+' characters at the beginning of a line are
3377 ignored, to allow pasting directly from e-mails, diff files and
3377 ignored, to allow pasting directly from e-mails, diff files and
3378 doctests (the '...' continuation prompt is also stripped). The
3378 doctests (the '...' continuation prompt is also stripped). The
3379 executed block is also assigned to variable named 'pasted_block' for
3379 executed block is also assigned to variable named 'pasted_block' for
3380 later editing with '%edit pasted_block'.
3380 later editing with '%edit pasted_block'.
3381
3381
3382 You can also pass a variable name as an argument, e.g. '%paste foo'.
3382 You can also pass a variable name as an argument, e.g. '%paste foo'.
3383 This assigns the pasted block to variable 'foo' as string, without
3383 This assigns the pasted block to variable 'foo' as string, without
3384 dedenting or executing it (preceding >>> and + is still stripped)
3384 dedenting or executing it (preceding >>> and + is still stripped)
3385
3385
3386 Options
3386 Options
3387 -------
3387 -------
3388
3388
3389 -r: re-executes the block previously entered by cpaste.
3389 -r: re-executes the block previously entered by cpaste.
3390
3390
3391 -q: quiet mode: do not echo the pasted text back to the terminal.
3391 -q: quiet mode: do not echo the pasted text back to the terminal.
3392
3392
3393 IPython statements (magics, shell escapes) are not supported (yet).
3393 IPython statements (magics, shell escapes) are not supported (yet).
3394
3394
3395 See also
3395 See also
3396 --------
3396 --------
3397 cpaste: manually paste code into terminal until you mark its end.
3397 cpaste: manually paste code into terminal until you mark its end.
3398 """
3398 """
3399 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3399 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3400 par = args.strip()
3400 par = args.strip()
3401 if opts.has_key('r'):
3401 if opts.has_key('r'):
3402 self._rerun_pasted()
3402 self._rerun_pasted()
3403 return
3403 return
3404
3404
3405 text = self.shell.hooks.clipboard_get()
3405 text = self.shell.hooks.clipboard_get()
3406 block = self._strip_pasted_lines_for_code(text.splitlines())
3406 block = self._strip_pasted_lines_for_code(text.splitlines())
3407
3407
3408 # By default, echo back to terminal unless quiet mode is requested
3408 # By default, echo back to terminal unless quiet mode is requested
3409 if not opts.has_key('q'):
3409 if not opts.has_key('q'):
3410 write = self.shell.write
3410 write = self.shell.write
3411 write(block)
3411 write(block)
3412 if not block.endswith('\n'):
3412 if not block.endswith('\n'):
3413 write('\n')
3413 write('\n')
3414 write("## -- End pasted text --\n")
3414 write("## -- End pasted text --\n")
3415
3415
3416 self._execute_block(block, par)
3416 self._execute_block(block, par)
3417
3417
3418 def magic_quickref(self,arg):
3418 def magic_quickref(self,arg):
3419 """ Show a quick reference sheet """
3419 """ Show a quick reference sheet """
3420 import IPython.core.usage
3420 import IPython.core.usage
3421 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3421 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3422
3422
3423 page(qr)
3423 page(qr)
3424
3424
3425 def magic_upgrade(self,arg):
3425 def magic_upgrade(self,arg):
3426 """ Upgrade your IPython installation
3426 """ Upgrade your IPython installation
3427
3427
3428 This will copy the config files that don't yet exist in your
3428 This will copy the config files that don't yet exist in your
3429 ipython dir from the system config dir. Use this after upgrading
3429 ipython dir from the system config dir. Use this after upgrading
3430 IPython if you don't wish to delete your .ipython dir.
3430 IPython if you don't wish to delete your .ipython dir.
3431
3431
3432 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3432 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3433 new users)
3433 new users)
3434
3434
3435 """
3435 """
3436 ip = self.getapi()
3436 ip = self.getapi()
3437 ipinstallation = path(IPython.__file__).dirname()
3437 ipinstallation = path(IPython.__file__).dirname()
3438 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3438 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3439 src_config = ipinstallation / 'config' / 'userconfig'
3439 src_config = ipinstallation / 'config' / 'userconfig'
3440 userdir = path(ip.config.IPYTHONDIR)
3440 userdir = path(ip.config.IPYTHONDIR)
3441 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3441 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3442 print ">",cmd
3442 print ">",cmd
3443 shell(cmd)
3443 shell(cmd)
3444 if arg == '-nolegacy':
3444 if arg == '-nolegacy':
3445 legacy = userdir.files('ipythonrc*')
3445 legacy = userdir.files('ipythonrc*')
3446 print "Nuking legacy files:",legacy
3446 print "Nuking legacy files:",legacy
3447
3447
3448 [p.remove() for p in legacy]
3448 [p.remove() for p in legacy]
3449 suffix = (sys.platform == 'win32' and '.ini' or '')
3449 suffix = (sys.platform == 'win32' and '.ini' or '')
3450 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3450 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3451
3451
3452
3452
3453 def magic_doctest_mode(self,parameter_s=''):
3453 def magic_doctest_mode(self,parameter_s=''):
3454 """Toggle doctest mode on and off.
3454 """Toggle doctest mode on and off.
3455
3455
3456 This mode allows you to toggle the prompt behavior between normal
3456 This mode allows you to toggle the prompt behavior between normal
3457 IPython prompts and ones that are as similar to the default IPython
3457 IPython prompts and ones that are as similar to the default IPython
3458 interpreter as possible.
3458 interpreter as possible.
3459
3459
3460 It also supports the pasting of code snippets that have leading '>>>'
3460 It also supports the pasting of code snippets that have leading '>>>'
3461 and '...' prompts in them. This means that you can paste doctests from
3461 and '...' prompts in them. This means that you can paste doctests from
3462 files or docstrings (even if they have leading whitespace), and the
3462 files or docstrings (even if they have leading whitespace), and the
3463 code will execute correctly. You can then use '%history -tn' to see
3463 code will execute correctly. You can then use '%history -tn' to see
3464 the translated history without line numbers; this will give you the
3464 the translated history without line numbers; this will give you the
3465 input after removal of all the leading prompts and whitespace, which
3465 input after removal of all the leading prompts and whitespace, which
3466 can be pasted back into an editor.
3466 can be pasted back into an editor.
3467
3467
3468 With these features, you can switch into this mode easily whenever you
3468 With these features, you can switch into this mode easily whenever you
3469 need to do testing and changes to doctests, without having to leave
3469 need to do testing and changes to doctests, without having to leave
3470 your existing IPython session.
3470 your existing IPython session.
3471 """
3471 """
3472
3472
3473 # XXX - Fix this to have cleaner activate/deactivate calls.
3473 # XXX - Fix this to have cleaner activate/deactivate calls.
3474 from IPython.extensions import InterpreterPasteInput as ipaste
3474 from IPython.extensions import InterpreterPasteInput as ipaste
3475 from IPython.utils.ipstruct import Struct
3475 from IPython.utils.ipstruct import Struct
3476
3476
3477 # Shorthands
3477 # Shorthands
3478 shell = self.shell
3478 shell = self.shell
3479 oc = shell.outputcache
3479 oc = shell.outputcache
3480 meta = shell.meta
3480 meta = shell.meta
3481 # dstore is a data store kept in the instance metadata bag to track any
3481 # dstore is a data store kept in the instance metadata bag to track any
3482 # changes we make, so we can undo them later.
3482 # changes we make, so we can undo them later.
3483 dstore = meta.setdefault('doctest_mode',Struct())
3483 dstore = meta.setdefault('doctest_mode',Struct())
3484 save_dstore = dstore.setdefault
3484 save_dstore = dstore.setdefault
3485
3485
3486 # save a few values we'll need to recover later
3486 # save a few values we'll need to recover later
3487 mode = save_dstore('mode',False)
3487 mode = save_dstore('mode',False)
3488 save_dstore('rc_pprint',shell.pprint)
3488 save_dstore('rc_pprint',shell.pprint)
3489 save_dstore('xmode',shell.InteractiveTB.mode)
3489 save_dstore('xmode',shell.InteractiveTB.mode)
3490 save_dstore('rc_separate_out',shell.separate_out)
3490 save_dstore('rc_separate_out',shell.separate_out)
3491 save_dstore('rc_separate_out2',shell.separate_out2)
3491 save_dstore('rc_separate_out2',shell.separate_out2)
3492 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3492 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3493 save_dstore('rc_separate_in',shell.separate_in)
3493 save_dstore('rc_separate_in',shell.separate_in)
3494
3494
3495 if mode == False:
3495 if mode == False:
3496 # turn on
3496 # turn on
3497 ipaste.activate_prefilter()
3497 ipaste.activate_prefilter()
3498
3498
3499 oc.prompt1.p_template = '>>> '
3499 oc.prompt1.p_template = '>>> '
3500 oc.prompt2.p_template = '... '
3500 oc.prompt2.p_template = '... '
3501 oc.prompt_out.p_template = ''
3501 oc.prompt_out.p_template = ''
3502
3502
3503 # Prompt separators like plain python
3503 # Prompt separators like plain python
3504 oc.input_sep = oc.prompt1.sep = ''
3504 oc.input_sep = oc.prompt1.sep = ''
3505 oc.output_sep = ''
3505 oc.output_sep = ''
3506 oc.output_sep2 = ''
3506 oc.output_sep2 = ''
3507
3507
3508 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3508 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3509 oc.prompt_out.pad_left = False
3509 oc.prompt_out.pad_left = False
3510
3510
3511 shell.pprint = False
3511 shell.pprint = False
3512
3512
3513 shell.magic_xmode('Plain')
3513 shell.magic_xmode('Plain')
3514
3514
3515 else:
3515 else:
3516 # turn off
3516 # turn off
3517 ipaste.deactivate_prefilter()
3517 ipaste.deactivate_prefilter()
3518
3518
3519 oc.prompt1.p_template = shell.prompt_in1
3519 oc.prompt1.p_template = shell.prompt_in1
3520 oc.prompt2.p_template = shell.prompt_in2
3520 oc.prompt2.p_template = shell.prompt_in2
3521 oc.prompt_out.p_template = shell.prompt_out
3521 oc.prompt_out.p_template = shell.prompt_out
3522
3522
3523 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3523 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3524
3524
3525 oc.output_sep = dstore.rc_separate_out
3525 oc.output_sep = dstore.rc_separate_out
3526 oc.output_sep2 = dstore.rc_separate_out2
3526 oc.output_sep2 = dstore.rc_separate_out2
3527
3527
3528 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3528 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3529 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3529 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3530
3530
3531 rc.pprint = dstore.rc_pprint
3531 rc.pprint = dstore.rc_pprint
3532
3532
3533 shell.magic_xmode(dstore.xmode)
3533 shell.magic_xmode(dstore.xmode)
3534
3534
3535 # Store new mode and inform
3535 # Store new mode and inform
3536 dstore.mode = bool(1-int(mode))
3536 dstore.mode = bool(1-int(mode))
3537 print 'Doctest mode is:',
3537 print 'Doctest mode is:',
3538 print ['OFF','ON'][dstore.mode]
3538 print ['OFF','ON'][dstore.mode]
3539
3539
3540 def magic_gui(self, parameter_s=''):
3540 def magic_gui(self, parameter_s=''):
3541 """Enable or disable IPython GUI event loop integration.
3541 """Enable or disable IPython GUI event loop integration.
3542
3542
3543 %gui [-a] [GUINAME]
3543 %gui [-a] [GUINAME]
3544
3544
3545 This magic replaces IPython's threaded shells that were activated
3545 This magic replaces IPython's threaded shells that were activated
3546 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3546 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3547 can now be enabled, disabled and swtiched at runtime and keyboard
3547 can now be enabled, disabled and swtiched at runtime and keyboard
3548 interrupts should work without any problems. The following toolkits
3548 interrupts should work without any problems. The following toolkits
3549 are supports: wxPython, PyQt4, PyGTK, and Tk::
3549 are supports: wxPython, PyQt4, PyGTK, and Tk::
3550
3550
3551 %gui wx # enable wxPython event loop integration
3551 %gui wx # enable wxPython event loop integration
3552 %gui qt4 # enable PyQt4 event loop integration
3552 %gui qt4|qt # enable PyQt4 event loop integration
3553 %gui gtk # enable PyGTK event loop integration
3553 %gui gtk # enable PyGTK event loop integration
3554 %gui tk # enable Tk event loop integration
3554 %gui tk # enable Tk event loop integration
3555 %gui # disable all event loop integration
3555 %gui # disable all event loop integration
3556
3556
3557 WARNING: after any of these has been called you can simply create
3557 WARNING: after any of these has been called you can simply create
3558 an application object, but DO NOT start the event loop yourself, as
3558 an application object, but DO NOT start the event loop yourself, as
3559 we have already handled that.
3559 we have already handled that.
3560
3560
3561 If you want us to create an appropriate application object add the
3561 If you want us to create an appropriate application object add the
3562 "-a" flag to your command::
3562 "-a" flag to your command::
3563
3563
3564 %gui -a wx
3564 %gui -a wx
3565
3565
3566 This is highly recommended for most users.
3566 This is highly recommended for most users.
3567 """
3567 """
3568 from IPython.lib import inputhook
3568 from IPython.lib import inputhook
3569 if "-a" in parameter_s:
3569 if "-a" in parameter_s:
3570 app = True
3570 app = True
3571 else:
3571 else:
3572 app = False
3572 app = False
3573 if not parameter_s:
3573 if not parameter_s:
3574 inputhook.clear_inputhook()
3574 inputhook.clear_inputhook()
3575 elif 'wx' in parameter_s:
3575 elif 'wx' in parameter_s:
3576 return inputhook.enable_wx(app)
3576 return inputhook.enable_wx(app)
3577 elif 'qt4' in parameter_s:
3577 elif ('qt4' in parameter_s) or ('qt' in parameter_s):
3578 return inputhook.enable_qt4(app)
3578 return inputhook.enable_qt4(app)
3579 elif 'gtk' in parameter_s:
3579 elif 'gtk' in parameter_s:
3580 return inputhook.enable_gtk(app)
3580 return inputhook.enable_gtk(app)
3581 elif 'tk' in parameter_s:
3581 elif 'tk' in parameter_s:
3582 return inputhook.enable_tk(app)
3582 return inputhook.enable_tk(app)
3583
3583
3584
3584
3585 # end Magic
3585 # end Magic
@@ -1,194 +1,194 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Tests for IPython.core.component
4 Tests for IPython.core.component
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez (design help)
9 * Fernando Perez (design help)
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from unittest import TestCase
23 from unittest import TestCase
24
24
25 from IPython.core.component import Component, ComponentError
25 from IPython.core.component import Component, ComponentError
26 from IPython.utils.traitlets import (
26 from IPython.utils.traitlets import (
27 TraitletError, Int, Float, Str
27 TraitletError, Int, Float, Str
28 )
28 )
29 from IPython.utils.ipstruct import Struct
29 from IPython.utils.ipstruct import Struct
30
30
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Test cases
33 # Test cases
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36
36
37 class TestComponentMeta(TestCase):
37 class TestComponentMeta(TestCase):
38
38
39 def test_get_instances(self):
39 def test_get_instances(self):
40 class BaseComponent(Component):
40 class BaseComponent(Component):
41 pass
41 pass
42 c1 = BaseComponent(None)
42 c1 = BaseComponent(None)
43 c2 = BaseComponent(c1)
43 c2 = BaseComponent(c1)
44 self.assertEquals(BaseComponent.get_instances(),[c1,c2])
44 self.assertEquals(BaseComponent.get_instances(),[c1,c2])
45
45
46 def test_get_instances_subclass(self):
46 def test_get_instances_subclass(self):
47 class MyComponent(Component):
47 class MyComponent(Component):
48 pass
48 pass
49 class MyOtherComponent(MyComponent):
49 class MyOtherComponent(MyComponent):
50 pass
50 pass
51 c1 = MyComponent(None)
51 c1 = MyComponent(None)
52 c2 = MyOtherComponent(c1)
52 c2 = MyOtherComponent(c1)
53 c3 = MyOtherComponent(c2)
53 c3 = MyOtherComponent(c2)
54 self.assertEquals(MyComponent.get_instances(), [c1, c2, c3])
54 self.assertEquals(MyComponent.get_instances(), [c1, c2, c3])
55 self.assertEquals(MyComponent.get_instances(klass=MyOtherComponent), [c2, c3])
55 self.assertEquals(MyOtherComponent.get_instances(), [c2, c3])
56
56
57 def test_get_instances_root(self):
57 def test_get_instances_root(self):
58 class MyComponent(Component):
58 class MyComponent(Component):
59 pass
59 pass
60 class MyOtherComponent(MyComponent):
60 class MyOtherComponent(MyComponent):
61 pass
61 pass
62 c1 = MyComponent(None)
62 c1 = MyComponent(None)
63 c2 = MyOtherComponent(c1)
63 c2 = MyOtherComponent(c1)
64 c3 = MyOtherComponent(c2)
64 c3 = MyOtherComponent(c2)
65 c4 = MyComponent(None)
65 c4 = MyComponent(None)
66 c5 = MyComponent(c4)
66 c5 = MyComponent(c4)
67 self.assertEquals(MyComponent.get_instances(root=c1), [c1, c2, c3])
67 self.assertEquals(MyComponent.get_instances(root=c1), [c1, c2, c3])
68 self.assertEquals(MyComponent.get_instances(root=c4), [c4, c5])
68 self.assertEquals(MyComponent.get_instances(root=c4), [c4, c5])
69
69
70
70
71 class TestComponent(TestCase):
71 class TestComponent(TestCase):
72
72
73 def test_parent_child(self):
73 def test_parent_child(self):
74 c1 = Component(None)
74 c1 = Component(None)
75 c2 = Component(c1)
75 c2 = Component(c1)
76 c3 = Component(c1)
76 c3 = Component(c1)
77 c4 = Component(c3)
77 c4 = Component(c3)
78 self.assertEquals(c1.parent, None)
78 self.assertEquals(c1.parent, None)
79 self.assertEquals(c2.parent, c1)
79 self.assertEquals(c2.parent, c1)
80 self.assertEquals(c3.parent, c1)
80 self.assertEquals(c3.parent, c1)
81 self.assertEquals(c4.parent, c3)
81 self.assertEquals(c4.parent, c3)
82 self.assertEquals(c1.children, [c2, c3])
82 self.assertEquals(c1.children, [c2, c3])
83 self.assertEquals(c2.children, [])
83 self.assertEquals(c2.children, [])
84 self.assertEquals(c3.children, [c4])
84 self.assertEquals(c3.children, [c4])
85 self.assertEquals(c4.children, [])
85 self.assertEquals(c4.children, [])
86
86
87 def test_root(self):
87 def test_root(self):
88 c1 = Component(None)
88 c1 = Component(None)
89 c2 = Component(c1)
89 c2 = Component(c1)
90 c3 = Component(c1)
90 c3 = Component(c1)
91 c4 = Component(c3)
91 c4 = Component(c3)
92 self.assertEquals(c1.root, c1.root)
92 self.assertEquals(c1.root, c1.root)
93 self.assertEquals(c2.root, c1)
93 self.assertEquals(c2.root, c1)
94 self.assertEquals(c3.root, c1)
94 self.assertEquals(c3.root, c1)
95 self.assertEquals(c4.root, c1)
95 self.assertEquals(c4.root, c1)
96
96
97 def test_change_parent(self):
97 def test_change_parent(self):
98 c1 = Component(None)
98 c1 = Component(None)
99 c2 = Component(None)
99 c2 = Component(None)
100 c3 = Component(c1)
100 c3 = Component(c1)
101 self.assertEquals(c3.root, c1)
101 self.assertEquals(c3.root, c1)
102 self.assertEquals(c3.parent, c1)
102 self.assertEquals(c3.parent, c1)
103 self.assertEquals(c1.children,[c3])
103 self.assertEquals(c1.children,[c3])
104 c3.parent = c2
104 c3.parent = c2
105 self.assertEquals(c3.root, c2)
105 self.assertEquals(c3.root, c2)
106 self.assertEquals(c3.parent, c2)
106 self.assertEquals(c3.parent, c2)
107 self.assertEquals(c2.children,[c3])
107 self.assertEquals(c2.children,[c3])
108 self.assertEquals(c1.children,[])
108 self.assertEquals(c1.children,[])
109
109
110 def test_subclass_parent(self):
110 def test_subclass_parent(self):
111 c1 = Component(None)
111 c1 = Component(None)
112 self.assertRaises(TraitletError, setattr, c1, 'parent', 10)
112 self.assertRaises(TraitletError, setattr, c1, 'parent', 10)
113
113
114 class MyComponent(Component):
114 class MyComponent(Component):
115 pass
115 pass
116 c1 = Component(None)
116 c1 = Component(None)
117 c2 = MyComponent(c1)
117 c2 = MyComponent(c1)
118 self.assertEquals(MyComponent.parent.this_class, Component)
118 self.assertEquals(MyComponent.parent.this_class, Component)
119 self.assertEquals(c2.parent, c1)
119 self.assertEquals(c2.parent, c1)
120
120
121 def test_bad_root(self):
121 def test_bad_root(self):
122 c1 = Component(None)
122 c1 = Component(None)
123 c2 = Component(None)
123 c2 = Component(None)
124 c3 = Component(None)
124 c3 = Component(None)
125 self.assertRaises(ComponentError, setattr, c1, 'root', c2)
125 self.assertRaises(ComponentError, setattr, c1, 'root', c2)
126 c1.parent = c2
126 c1.parent = c2
127 self.assertEquals(c1.root, c2)
127 self.assertEquals(c1.root, c2)
128 self.assertRaises(ComponentError, setattr, c1, 'root', c3)
128 self.assertRaises(ComponentError, setattr, c1, 'root', c3)
129
129
130
130
131 class TestComponentConfig(TestCase):
131 class TestComponentConfig(TestCase):
132
132
133 def test_default(self):
133 def test_default(self):
134 c1 = Component(None)
134 c1 = Component(None)
135 c2 = Component(c1)
135 c2 = Component(c1)
136 c3 = Component(c2)
136 c3 = Component(c2)
137 self.assertEquals(c1.config, c2.config)
137 self.assertEquals(c1.config, c2.config)
138 self.assertEquals(c2.config, c3.config)
138 self.assertEquals(c2.config, c3.config)
139
139
140 def test_custom(self):
140 def test_custom(self):
141 config = Struct()
141 config = Struct()
142 config.FOO = 'foo'
142 config.FOO = 'foo'
143 config.BAR = 'bar'
143 config.BAR = 'bar'
144 c1 = Component(None, config=config)
144 c1 = Component(None, config=config)
145 c2 = Component(c1)
145 c2 = Component(c1)
146 c3 = Component(c2)
146 c3 = Component(c2)
147 self.assertEquals(c1.config, config)
147 self.assertEquals(c1.config, config)
148 self.assertEquals(c2.config, config)
148 self.assertEquals(c2.config, config)
149 self.assertEquals(c3.config, config)
149 self.assertEquals(c3.config, config)
150 # Test that we always make copies
150 # Test that we always make copies
151 self.assert_(c1.config is not config)
151 self.assert_(c1.config is not config)
152 self.assert_(c2.config is not config)
152 self.assert_(c2.config is not config)
153 self.assert_(c3.config is not config)
153 self.assert_(c3.config is not config)
154 self.assert_(c1.config is not c2.config)
154 self.assert_(c1.config is not c2.config)
155 self.assert_(c2.config is not c3.config)
155 self.assert_(c2.config is not c3.config)
156
156
157 def test_inheritance(self):
157 def test_inheritance(self):
158 class MyComponent(Component):
158 class MyComponent(Component):
159 a = Int(1, config_key='A')
159 a = Int(1, config_key='A')
160 b = Float(1.0, config_key='B')
160 b = Float(1.0, config_key='B')
161 c = Str('no config')
161 c = Str('no config')
162 config = Struct()
162 config = Struct()
163 config.A = 2
163 config.A = 2
164 config.B = 2.0
164 config.B = 2.0
165 c1 = MyComponent(None, config=config)
165 c1 = MyComponent(None, config=config)
166 c2 = MyComponent(c1)
166 c2 = MyComponent(c1)
167 self.assertEquals(c1.a, config.A)
167 self.assertEquals(c1.a, config.A)
168 self.assertEquals(c1.b, config.B)
168 self.assertEquals(c1.b, config.B)
169 self.assertEquals(c2.a, config.A)
169 self.assertEquals(c2.a, config.A)
170 self.assertEquals(c2.b, config.B)
170 self.assertEquals(c2.b, config.B)
171 c4 = MyComponent(c2, config=Struct())
171 c4 = MyComponent(c2, config=Struct())
172 self.assertEquals(c4.a, 1)
172 self.assertEquals(c4.a, 1)
173 self.assertEquals(c4.b, 1.0)
173 self.assertEquals(c4.b, 1.0)
174
174
175 class TestComponentName(TestCase):
175 class TestComponentName(TestCase):
176
176
177 def test_default(self):
177 def test_default(self):
178 class MyComponent(Component):
178 class MyComponent(Component):
179 pass
179 pass
180 c1 = Component(None)
180 c1 = Component(None)
181 c2 = MyComponent(None)
181 c2 = MyComponent(None)
182 c3 = Component(c2)
182 c3 = Component(c2)
183 self.assertNotEquals(c1.name, c2.name)
183 self.assertNotEquals(c1.name, c2.name)
184 self.assertNotEquals(c1.name, c3.name)
184 self.assertNotEquals(c1.name, c3.name)
185
185
186 def test_manual(self):
186 def test_manual(self):
187 class MyComponent(Component):
187 class MyComponent(Component):
188 pass
188 pass
189 c1 = Component(None, name='foo')
189 c1 = Component(None, name='foo')
190 c2 = MyComponent(None, name='bar')
190 c2 = MyComponent(None, name='bar')
191 c3 = Component(c2, name='bah')
191 c3 = Component(c2, name='bah')
192 self.assertEquals(c1.name, 'foo')
192 self.assertEquals(c1.name, 'foo')
193 self.assertEquals(c2.name, 'bar')
193 self.assertEquals(c2.name, 'bar')
194 self.assertEquals(c3.name, 'bah')
194 self.assertEquals(c3.name, 'bah')
@@ -1,28 +1,31 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Extra capabilities for IPython
4 Extra capabilities for IPython
5 """
5 """
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 from IPython.lib.inputhook import (
18 from IPython.lib.inputhook import (
19 enable_wx, disable_wx,
19 enable_wx, disable_wx,
20 enable_gtk, disable_gtk,
20 enable_gtk, disable_gtk,
21 enable_qt4, disable_qt4,
21 enable_qt4, disable_qt4,
22 enable_tk, disable_tk,
22 enable_tk, disable_tk,
23 set_inputhook, clear_inputhook
23 set_inputhook, clear_inputhook,
24 current_gui, spin,
25 appstart_qt4, appstart_wx,
26 appstart_gtk, appstart_tk
24 )
27 )
25
28
26 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
27 # Code
30 # Code
28 #----------------------------------------------------------------------------- No newline at end of file
31 #-----------------------------------------------------------------------------
@@ -1,226 +1,525 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Inputhook management for GUI event loop integration.
4 Inputhook management for GUI event loop integration.
5 """
5 """
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import ctypes
18 import ctypes
19 import sys
19 import sys
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Code
22 # Constants
23 #-----------------------------------------------------------------------------
24
25 # Constants for identifying the GUI toolkits.
26 GUI_WX = 'wx'
27 GUI_QT4 = 'qt4'
28 GUI_GTK = 'gtk'
29 GUI_TK = 'tk'
30
31 #-----------------------------------------------------------------------------
32 # Utility classes
33 #-----------------------------------------------------------------------------
34
35
36 class _DummyMainloop(object):
37 """A special manager to hijack GUI mainloops that is mostly a no-op.
38
39 We are not using this class currently as it breaks GUI code that calls
40 a mainloop function after the app has started to process pending events.
41 """
42 def __init__(self, ml, ihm, gui_type):
43 self.ml = ml
44 self.ihm = ihm
45 self.gui_type = gui_type
46
47 def __call__(self, *args, **kw):
48 if self.ihm.current_gui() == self.gui_type:
49 pass
50 else:
51 self.ml(*args, **kw)
52
53
54 #-----------------------------------------------------------------------------
55 # Appstart and spin functions
56 #-----------------------------------------------------------------------------
57
58
59 def appstart_qt4(app):
60 """Start the qt4 event loop in a way that plays with IPython.
61
62 When a qt4 app is run interactively in IPython, the event loop should
63 not be started. This function checks to see if IPython's qt4 integration
64 is activated and if so, it passes. If not, it will call the :meth:`exec_`
65 method of the main qt4 app.
66
67 This function should be used by users who want their qt4 scripts to work
68 both at the command line and in IPython. These users should put the
69 following logic at the bottom on their script, after they create a
70 :class:`QApplication` instance (called ``app`` here)::
71
72 try:
73 from IPython.lib.inputhook import appstart_qt4
74 appstart_qt4(app)
75 except ImportError:
76 app.exec_()
77 """
78 from PyQt4 import QtCore, QtGui
79
80 assert isinstance(app, QtCore.QCoreApplication)
81 if app is not None:
82 if current_gui() == GUI_QT4:
83 pass
84 else:
85 app.exec_()
86
87
88 def appstart_wx(app):
89 """Start the wx event loop in a way that plays with IPython.
90
91 When a wx app is run interactively in IPython, the event loop should
92 not be started. This function checks to see if IPython's wx integration
93 is activated and if so, it passes. If not, it will call the
94 :meth:`MainLoop` method of the main qt4 app.
95
96 This function should be used by users who want their wx scripts to work
97 both at the command line and in IPython. These users should put the
98 following logic at the bottom on their script, after they create a
99 :class:`App` instance (called ``app`` here)::
100
101 try:
102 from IPython.lib.inputhook import appstart_wx
103 appstart_wx(app)
104 except ImportError:
105 app.MainLoop()
106 """
107 import wx
108
109 assert isinstance(app, wx.App)
110 if app is not None:
111 if current_gui() == GUI_WX:
112 pass
113 else:
114 app.MainLoop()
115
116
117 def appstart_tk(app):
118 """Start the tk event loop in a way that plays with IPython.
119
120 When a tk app is run interactively in IPython, the event loop should
121 not be started. This function checks to see if IPython's tk integration
122 is activated and if so, it passes. If not, it will call the
123 :meth:`mainloop` method of the tk object passed to this method.
124
125 This function should be used by users who want their tk scripts to work
126 both at the command line and in IPython. These users should put the
127 following logic at the bottom on their script, after they create a
128 :class:`Tk` instance (called ``app`` here)::
129
130 try:
131 from IPython.lib.inputhook import appstart_tk
132 appstart_tk(app)
133 except ImportError:
134 app.mainloop()
135 """
136 if app is not None:
137 if current_gui() == GUI_TK:
138 pass
139 else:
140 app.mainloop()
141
142 def appstart_gtk():
143 """Start the gtk event loop in a way that plays with IPython.
144
145 When a gtk app is run interactively in IPython, the event loop should
146 not be started. This function checks to see if IPython's gtk integration
147 is activated and if so, it passes. If not, it will call
148 :func:`gtk.main`. Unlike the other appstart implementations, this does
149 not take an ``app`` argument.
150
151 This function should be used by users who want their gtk scripts to work
152 both at the command line and in IPython. These users should put the
153 following logic at the bottom on their script::
154
155 try:
156 from IPython.lib.inputhook import appstart_gtk
157 appstart_gtk()
158 except ImportError:
159 gtk.main()
160 """
161 import gtk
162 if current_gui() == GUI_GTK:
163 pass
164 else:
165 gtk.main()
166
167 #-----------------------------------------------------------------------------
168 # Main InputHookManager class
23 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
24
170
25
171
26 class InputHookManager(object):
172 class InputHookManager(object):
27 """Manage PyOS_InputHook for different GUI toolkits.
173 """Manage PyOS_InputHook for different GUI toolkits.
28
174
29 This class installs various hooks under ``PyOSInputHook`` to handle
175 This class installs various hooks under ``PyOSInputHook`` to handle
30 GUI event loop integration.
176 GUI event loop integration.
31 """
177 """
32
178
33 def __init__(self):
179 def __init__(self):
34 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
180 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
181 self._apps = {}
182 self._spinner_dict = {
183 GUI_QT4 : self._spin_qt4,
184 GUI_WX : self._spin_wx,
185 GUI_GTK : self._spin_gtk,
186 GUI_TK : self._spin_tk}
35 self._reset()
187 self._reset()
36
188
37 def _reset(self):
189 def _reset(self):
38 self._callback_pyfunctype = None
190 self._callback_pyfunctype = None
39 self._callback = None
191 self._callback = None
40 self._installed = False
192 self._installed = False
41 self._current_gui = None
193 self._current_gui = None
42
194
43 def get_pyos_inputhook(self):
195 def _hijack_wx(self):
44 """Return the current PyOS_InputHook as a ctypes.c_void_p.
196 """Hijack the wx mainloop so a user calling it won't cause badness.
197
198 We are not currently using this as it breaks GUI code that calls a
199 mainloop at anytime but startup.
200 """
201 import wx
202 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
203 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
204 else: raise AttributeError('Could not find wx core module')
205 orig_mainloop = core.PyApp_MainLoop
206 core.PyApp_MainLoop = _DummyMainloop
207 return orig_mainloop
208
209 def _hijack_qt4(self):
210 """Hijack the qt4 mainloop so a user calling it won't cause badness.
211
212 We are not currently using this as it breaks GUI code that calls a
213 mainloop at anytime but startup.
214 """
215 from PyQt4 import QtGui, QtCore
216 orig_mainloop = QtGui.qApp.exec_
217 dumb_ml = _DummyMainloop(orig_mainloop, self, GUI_QT4)
218 QtGui.qApp.exec_ = dumb_ml
219 QtGui.QApplication.exec_ = dumb_ml
220 QtCore.QCoreApplication.exec_ = dumb_ml
221 return orig_mainloop
222
223 def _hijack_gtk(self):
224 """Hijack the gtk mainloop so a user calling it won't cause badness.
225
226 We are not currently using this as it breaks GUI code that calls a
227 mainloop at anytime but startup.
228 """
229 import gtk
230 orig_mainloop = gtk.main
231 dumb_ml = _DummyMainloop(orig_mainloop, self, GUI_GTK)
232 gtk.mainloop = dumb_ml
233 gtk.main = dumb_ml
234 return orig_mainloop
235
236 def _hijack_tk(self):
237 """Hijack the tk mainloop so a user calling it won't cause badness.
238
239 We are not currently using this as it breaks GUI code that calls a
240 mainloop at anytime but startup.
241 """
242 import Tkinter
243 orig_mainloop = gtk.main
244 dumb_ml = _DummyMainloop(orig_mainloop, self, GUI_TK)
245 Tkinter.Misc.mainloop = dumb_ml
246 Tkinter.mainloop = dumb_ml
247
248 def _spin_qt4(self):
249 """Process all pending events in the qt4 event loop.
250
251 This is for internal IPython use only and user code should not call this.
252 Instead, they should issue the raw GUI calls themselves.
253 """
254 from PyQt4 import QtCore, QtGui
255
256 app = QtCore.QCoreApplication.instance()
257 if app is not None:
258 QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents)
259
260 def _spin_wx(self):
261 """Process all pending events in the wx event loop.
262
263 This is for internal IPython use only and user code should not call this.
264 Instead, they should issue the raw GUI calls themselves.
265 """
266 import wx
267 app = wx.GetApp()
268 if app is not None and wx.Thread_IsMain():
269 evtloop = wx.EventLoop()
270 ea = wx.EventLoopActivator(evtloop)
271 while evtloop.Pending():
272 evtloop.Dispatch()
273 app.ProcessIdle()
274 del ea
275
276 def _spin_gtk(self):
277 """Process all pending events in the gtk event loop.
278
279 This is for internal IPython use only and user code should not call this.
280 Instead, they should issue the raw GUI calls themselves.
281 """
282 import gtk
283 gtk.gdk.threads_enter()
284 while gtk.events_pending():
285 gtk.main_iteration(False)
286 gtk.gdk.flush()
287 gtk.gdk.threads_leave()
288
289 def _spin_tk(self):
290 """Process all pending events in the tk event loop.
291
292 This is for internal IPython use only and user code should not call this.
293 Instead, they should issue the raw GUI calls themselves.
45 """
294 """
295 app = self._apps.get(GUI_TK)
296 if app is not None:
297 app.update()
298
299 def spin(self):
300 """Process pending events in the current gui.
301
302 This method is just provided for IPython to use internally if needed
303 for things like testing. Third party projects should not call this
304 method, but instead should call the underlying GUI toolkit methods
305 that we are calling.
306 """
307 spinner = self._spinner_dict.get(self._current_gui, lambda: None)
308 spinner()
309
310 def get_pyos_inputhook(self):
311 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
46 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
312 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
47
313
48 def get_pyos_inputhook_as_func(self):
314 def get_pyos_inputhook_as_func(self):
49 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE.
315 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
50 """
51 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
316 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
52
317
53 def set_inputhook(self, callback):
318 def set_inputhook(self, callback):
54 """Set PyOS_InputHook to callback and return the previous one.
319 """Set PyOS_InputHook to callback and return the previous one."""
55 """
56 self._callback = callback
320 self._callback = callback
57 self._callback_pyfunctype = self.PYFUNC(callback)
321 self._callback_pyfunctype = self.PYFUNC(callback)
58 pyos_inputhook_ptr = self.get_pyos_inputhook()
322 pyos_inputhook_ptr = self.get_pyos_inputhook()
59 original = self.get_pyos_inputhook_as_func()
323 original = self.get_pyos_inputhook_as_func()
60 pyos_inputhook_ptr.value = \
324 pyos_inputhook_ptr.value = \
61 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
325 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
62 self._installed = True
326 self._installed = True
63 return original
327 return original
64
328
65 def clear_inputhook(self):
329 def clear_inputhook(self):
66 """Set PyOS_InputHook to NULL and return the previous one.
330 """Set PyOS_InputHook to NULL and return the previous one."""
67 """
68 pyos_inputhook_ptr = self.get_pyos_inputhook()
331 pyos_inputhook_ptr = self.get_pyos_inputhook()
69 original = self.get_pyos_inputhook_as_func()
332 original = self.get_pyos_inputhook_as_func()
70 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
333 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
71 self._reset()
334 self._reset()
72 return original
335 return original
73
336
337 def clear_app_refs(self, gui=None):
338 """Clear IPython's internal reference to an application instance.
339
340 Whenever we create an app for a user on qt4 or wx, we hold a
341 reference to the app. This is needed because in some cases bad things
342 can happen if a user doesn't hold a reference themselves. This
343 method is provided to clear the references we are holding.
344
345 Parameters
346 ----------
347 gui : None or str
348 If None, clear all app references. If ('wx', 'qt4') clear
349 the app for that toolkit. References are not held for gtk or tk
350 as those toolkits don't have the notion of an app.
351 """
352 if gui is None:
353 self._apps = {}
354 elif self._apps.has_key(gui):
355 del self._apps[gui]
356
74 def enable_wx(self, app=False):
357 def enable_wx(self, app=False):
75 """Enable event loop integration with wxPython.
358 """Enable event loop integration with wxPython.
76
359
77 Parameters
360 Parameters
78 ----------
361 ----------
79 app : bool
362 app : bool
80 Create a running application object or not.
363 Create a running application object or not.
81
364
82 Notes
365 Notes
83 -----
366 -----
84 This methods sets the PyOS_InputHook for wxPython, which allows
367 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
85 the wxPython to integrate with terminal based applications like
368 the wxPython to integrate with terminal based applications like
86 IPython.
369 IPython.
87
370
88 Once this has been called, you can use wx interactively by doing::
371 If ``app`` is True, we create an :class:`wx.App` as follows::
89
372
90 >>> import wx
373 import wx
91 >>> app = wx.App(redirect=False, clearSigInt=False)
374 app = wx.App(redirect=False, clearSigInt=False)
92
375
93 Both options this constructor are important for things to work
376 Both options this constructor are important for things to work
94 properly in an interactive context.
377 properly in an interactive context.
95
378
96 But, *don't start the event loop*. That is handled automatically by
379 But, we first check to see if an application has already been
97 PyOS_InputHook.
380 created. If so, we simply return that instance.
98 """
381 """
99 from IPython.lib.inputhookwx import inputhook_wx
382 from IPython.lib.inputhookwx import inputhook_wx
100 self.set_inputhook(inputhook_wx)
383 self.set_inputhook(inputhook_wx)
101 self._current_gui = 'wx'
384 self._current_gui = GUI_WX
102 if app:
385 if app:
103 import wx
386 import wx
104 app = wx.App(redirect=False, clearSigInt=False)
387 app = wx.GetApp()
388 if app is None:
389 app = wx.App(redirect=False, clearSigInt=False)
390 self._apps[GUI_WX] = app
105 return app
391 return app
106
392
107 def disable_wx(self):
393 def disable_wx(self):
108 """Disable event loop integration with wxPython.
394 """Disable event loop integration with wxPython.
109
395
110 This merely sets PyOS_InputHook to NULL.
396 This merely sets PyOS_InputHook to NULL.
111 """
397 """
112 self.clear_inputhook()
398 self.clear_inputhook()
113
399
114 def enable_qt4(self, app=False):
400 def enable_qt4(self, app=False):
115 """Enable event loop integration with PyQt4.
401 """Enable event loop integration with PyQt4.
116
402
117 Parameters
403 Parameters
118 ----------
404 ----------
119 app : bool
405 app : bool
120 Create a running application object or not.
406 Create a running application object or not.
121
407
122 Notes
408 Notes
123 -----
409 -----
124 This methods sets the PyOS_InputHook for wxPython, which allows
410 This methods sets the PyOS_InputHook for PyQt4, which allows
125 the PyQt4 to integrate with terminal based applications like
411 the PyQt4 to integrate with terminal based applications like
126 IPython.
412 IPython.
127
413
128 Once this has been called, you can simply create a QApplication and
414 If ``app`` is True, we create an :class:`QApplication` as follows::
129 use it. But, *don't start the event loop*. That is handled
415
130 automatically by PyOS_InputHook.
416 from PyQt4 import QtCore
417 app = QtGui.QApplication(sys.argv)
418
419 But, we first check to see if an application has already been
420 created. If so, we simply return that instance.
131 """
421 """
132 from PyQt4 import QtCore
422 from PyQt4 import QtCore
133 # PyQt4 has had this since 4.3.1. In version 4.2, PyOS_InputHook
423 # PyQt4 has had this since 4.3.1. In version 4.2, PyOS_InputHook
134 # was set when QtCore was imported, but if it ever got removed,
424 # was set when QtCore was imported, but if it ever got removed,
135 # you couldn't reset it. For earlier versions we can
425 # you couldn't reset it. For earlier versions we can
136 # probably implement a ctypes version.
426 # probably implement a ctypes version.
137 try:
427 try:
138 QtCore.pyqtRestoreInputHook()
428 QtCore.pyqtRestoreInputHook()
139 except AttributeError:
429 except AttributeError:
140 pass
430 pass
141 self._current_gui = 'qt4'
431 self._current_gui = GUI_QT4
142 if app:
432 if app:
143 from PyQt4 import QtGui
433 from PyQt4 import QtGui
144 app = QtGui.QApplication(sys.argv)
434 app = QtCore.QCoreApplication.instance()
435 if app is None:
436 app = QtGui.QApplication(sys.argv)
437 self._apps[GUI_QT4] = app
145 return app
438 return app
146
439
147 def disable_qt4(self):
440 def disable_qt4(self):
148 """Disable event loop integration with PyQt4.
441 """Disable event loop integration with PyQt4.
149
442
150 This merely sets PyOS_InputHook to NULL.
443 This merely sets PyOS_InputHook to NULL.
151 """
444 """
152 self.clear_inputhook()
445 self.clear_inputhook()
153
446
154 def enable_gtk(self, app=False):
447 def enable_gtk(self, app=False):
155 """Enable event loop integration with PyGTK.
448 """Enable event loop integration with PyGTK.
156
449
157 Parameters
450 Parameters
158 ----------
451 ----------
159 app : bool
452 app : bool
160 Create a running application object or not.
453 Create a running application object or not. Because gtk does't
454 have an app class, this does nothing.
161
455
162 Notes
456 Notes
163 -----
457 -----
164 This methods sets the PyOS_InputHook for PyGTK, which allows
458 This methods sets the PyOS_InputHook for PyGTK, which allows
165 the PyGTK to integrate with terminal based applications like
459 the PyGTK to integrate with terminal based applications like
166 IPython.
460 IPython.
167
168 Once this has been called, you can simple create PyGTK objects and
169 use them. But, *don't start the event loop*. That is handled
170 automatically by PyOS_InputHook.
171 """
461 """
172 import gtk
462 import gtk
173 try:
463 try:
174 gtk.set_interactive(True)
464 gtk.set_interactive(True)
175 self._current_gui = 'gtk'
465 self._current_gui = GUI_GTK
176 except AttributeError:
466 except AttributeError:
177 # For older versions of gtk, use our own ctypes version
467 # For older versions of gtk, use our own ctypes version
178 from IPython.lib.inputhookgtk import inputhook_gtk
468 from IPython.lib.inputhookgtk import inputhook_gtk
179 add_inputhook(inputhook_gtk)
469 self.set_inputhook(inputhook_gtk)
470 self._current_gui = GUI_GTK
180
471
181 def disable_gtk(self):
472 def disable_gtk(self):
182 """Disable event loop integration with PyGTK.
473 """Disable event loop integration with PyGTK.
183
474
184 This merely sets PyOS_InputHook to NULL.
475 This merely sets PyOS_InputHook to NULL.
185 """
476 """
186 self.clear_inputhook()
477 self.clear_inputhook()
187
478
188 def enable_tk(self, app=False):
479 def enable_tk(self, app=False):
189 """Enable event loop integration with Tk.
480 """Enable event loop integration with Tk.
190
481
191 Parameters
482 Parameters
192 ----------
483 ----------
193 app : bool
484 app : bool
194 Create a running application object or not.
485 Create a running application object or not.
195
486
196 Notes
487 Notes
197 -----
488 -----
198 Currently this is a no-op as creating a :class:`Tkinter.Tk` object
489 Currently this is a no-op as creating a :class:`Tkinter.Tk` object
199 sets ``PyOS_InputHook``.
490 sets ``PyOS_InputHook``.
200 """
491 """
201 self._current_gui = 'tk'
492 self._current_gui = GUI_TK
493 if app:
494 import Tkinter
495 app = Tkinter.Tk()
496 app.withdraw()
497 self._apps[GUI_TK] = app
498 return app
202
499
203 def disable_tk(self):
500 def disable_tk(self):
204 """Disable event loop integration with Tkinter.
501 """Disable event loop integration with Tkinter.
205
502
206 This merely sets PyOS_InputHook to NULL.
503 This merely sets PyOS_InputHook to NULL.
207 """
504 """
208 self.clear_inputhook()
505 self.clear_inputhook()
209
506
210 def current_gui(self):
507 def current_gui(self):
211 """Return a string indicating the currently active GUI or None."""
508 """Return a string indicating the currently active GUI or None."""
212 return self._current_gui
509 return self._current_gui
213
510
214 inputhook_manager = InputHookManager()
511 inputhook_manager = InputHookManager()
215
512
216 enable_wx = inputhook_manager.enable_wx
513 enable_wx = inputhook_manager.enable_wx
217 disable_wx = inputhook_manager.disable_wx
514 disable_wx = inputhook_manager.disable_wx
218 enable_qt4 = inputhook_manager.enable_qt4
515 enable_qt4 = inputhook_manager.enable_qt4
219 disable_qt4 = inputhook_manager.disable_qt4
516 disable_qt4 = inputhook_manager.disable_qt4
220 enable_gtk = inputhook_manager.enable_gtk
517 enable_gtk = inputhook_manager.enable_gtk
221 disable_gtk = inputhook_manager.disable_gtk
518 disable_gtk = inputhook_manager.disable_gtk
222 enable_tk = inputhook_manager.enable_tk
519 enable_tk = inputhook_manager.enable_tk
223 disable_tk = inputhook_manager.disable_tk
520 disable_tk = inputhook_manager.disable_tk
224 clear_inputhook = inputhook_manager.clear_inputhook
521 clear_inputhook = inputhook_manager.clear_inputhook
225 set_inputhook = inputhook_manager.set_inputhook
522 set_inputhook = inputhook_manager.set_inputhook
226 current_gui = inputhook_manager.current_gui No newline at end of file
523 current_gui = inputhook_manager.current_gui
524 clear_app_refs = inputhook_manager.clear_app_refs
525 spin = inputhook_manager.spin
@@ -1,153 +1,162 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 """
4 """
5 Enable wxPython to be used interacive by setting PyOS_InputHook.
5 Enable wxPython to be used interacive by setting PyOS_InputHook.
6
6
7 Authors: Robin Dunn, Brian Granger, Ondrej Certik
7 Authors: Robin Dunn, Brian Granger, Ondrej Certik
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2008-2009 The IPython Development Team
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 import os
21 import os
22 import signal
22 import sys
23 import sys
23 import time
24 import time
24 from timeit import default_timer as clock
25 from timeit import default_timer as clock
25 import wx
26 import wx
26
27
27 if os.name == 'posix':
28 if os.name == 'posix':
28 import select
29 import select
29 elif sys.platform == 'win32':
30 elif sys.platform == 'win32':
30 import msvcrt
31 import msvcrt
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
33 # Code
34 # Code
34 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
35
36
36 def stdin_ready():
37 def stdin_ready():
37 if os.name == 'posix':
38 if os.name == 'posix':
38 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
39 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
39 if infds:
40 if infds:
40 return True
41 return True
41 else:
42 else:
42 return False
43 return False
43 elif sys.platform == 'win32':
44 elif sys.platform == 'win32':
44 return msvcrt.kbhit()
45 return msvcrt.kbhit()
45
46
46
47
47 def inputhook_wx1():
48 def inputhook_wx1():
48 """Run the wx event loop by processing pending events only.
49 """Run the wx event loop by processing pending events only.
49
50
50 This approach seems to work, but its performance is not great as it
51 This approach seems to work, but its performance is not great as it
51 relies on having PyOS_InputHook called regularly.
52 relies on having PyOS_InputHook called regularly.
52 """
53 """
53 app = wx.GetApp()
54 app = wx.GetApp()
54 if app is not None:
55 if app is not None:
55 assert wx.Thread_IsMain()
56 assert wx.Thread_IsMain()
56
57
57 # Make a temporary event loop and process system events until
58 # Make a temporary event loop and process system events until
58 # there are no more waiting, then allow idle events (which
59 # there are no more waiting, then allow idle events (which
59 # will also deal with pending or posted wx events.)
60 # will also deal with pending or posted wx events.)
60 evtloop = wx.EventLoop()
61 evtloop = wx.EventLoop()
61 ea = wx.EventLoopActivator(evtloop)
62 ea = wx.EventLoopActivator(evtloop)
62 while evtloop.Pending():
63 while evtloop.Pending():
63 evtloop.Dispatch()
64 evtloop.Dispatch()
64 app.ProcessIdle()
65 app.ProcessIdle()
65 del ea
66 del ea
66 return 0
67 return 0
67
68
68 class EventLoopTimer(wx.Timer):
69 class EventLoopTimer(wx.Timer):
69
70
70 def __init__(self, func):
71 def __init__(self, func):
71 self.func = func
72 self.func = func
72 wx.Timer.__init__(self)
73 wx.Timer.__init__(self)
73
74
74 def Notify(self):
75 def Notify(self):
75 self.func()
76 self.func()
76
77
77 class EventLoopRunner(object):
78 class EventLoopRunner(object):
78
79
79 def Run(self, time):
80 def Run(self, time):
80 self.evtloop = wx.EventLoop()
81 self.evtloop = wx.EventLoop()
81 self.timer = EventLoopTimer(self.check_stdin)
82 self.timer = EventLoopTimer(self.check_stdin)
82 self.timer.Start(time)
83 self.timer.Start(time)
83 self.evtloop.Run()
84 self.evtloop.Run()
84
85
85 def check_stdin(self):
86 def check_stdin(self):
86 if stdin_ready():
87 if stdin_ready():
87 self.timer.Stop()
88 self.timer.Stop()
88 self.evtloop.Exit()
89 self.evtloop.Exit()
89
90
90 def inputhook_wx2():
91 def inputhook_wx2():
91 """Run the wx event loop, polling for stdin.
92 """Run the wx event loop, polling for stdin.
92
93
93 This version runs the wx eventloop for an undetermined amount of time,
94 This version runs the wx eventloop for an undetermined amount of time,
94 during which it periodically checks to see if anything is ready on
95 during which it periodically checks to see if anything is ready on
95 stdin. If anything is ready on stdin, the event loop exits.
96 stdin. If anything is ready on stdin, the event loop exits.
96
97
97 The argument to elr.Run controls how often the event loop looks at stdin.
98 The argument to elr.Run controls how often the event loop looks at stdin.
98 This determines the responsiveness at the keyboard. A setting of 1000
99 This determines the responsiveness at the keyboard. A setting of 1000
99 enables a user to type at most 1 char per second. I have found that a
100 enables a user to type at most 1 char per second. I have found that a
100 setting of 10 gives good keyboard response. We can shorten it further,
101 setting of 10 gives good keyboard response. We can shorten it further,
101 but eventually performance would suffer from calling select/kbhit too
102 but eventually performance would suffer from calling select/kbhit too
102 often.
103 often.
103 """
104 """
104 app = wx.GetApp()
105 app = wx.GetApp()
105 if app is not None:
106 if app is not None:
106 assert wx.Thread_IsMain()
107 assert wx.Thread_IsMain()
107 elr = EventLoopRunner()
108 elr = EventLoopRunner()
108 # As this time is made shorter, keyboard response improves, but idle
109 # As this time is made shorter, keyboard response improves, but idle
109 # CPU load goes up. 10 ms seems like a good compromise.
110 # CPU load goes up. 10 ms seems like a good compromise.
110 elr.Run(time=10) # CHANGE time here to control polling interval
111 elr.Run(time=10) # CHANGE time here to control polling interval
111 return 0
112 return 0
112
113
113 def inputhook_wx3():
114 def inputhook_wx3():
114 """Run the wx event loop by processing pending events only.
115 """Run the wx event loop by processing pending events only.
115
116
116 This is like inputhook_wx1, but it keeps processing pending events
117 This is like inputhook_wx1, but it keeps processing pending events
117 until stdin is ready. After processing all pending events, a call to
118 until stdin is ready. After processing all pending events, a call to
118 time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
119 time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
119 This sleep time should be tuned though for best performance.
120 This sleep time should be tuned though for best performance.
120 """
121 """
121 app = wx.GetApp()
122 app = wx.GetApp()
122 if app is not None:
123 if app is not None:
123 assert wx.Thread_IsMain()
124 assert wx.Thread_IsMain()
124
125
126 # The import of wx on Linux sets the handler for signal.SIGINT
127 # to 0. This is a bug in wx or gtk. We fix by just setting it
128 # back to the Python default.
129 if not callable(signal.getsignal(signal.SIGINT)):
130 signal.signal(signal.SIGINT, signal.default_int_handler)
131
125 evtloop = wx.EventLoop()
132 evtloop = wx.EventLoop()
126 ea = wx.EventLoopActivator(evtloop)
133 ea = wx.EventLoopActivator(evtloop)
127 t = clock()
134 t = clock()
128 while not stdin_ready():
135 while not stdin_ready():
129 while evtloop.Pending():
136 while evtloop.Pending():
130 t = clock()
137 t = clock()
131 evtloop.Dispatch()
138 evtloop.Dispatch()
132 app.ProcessIdle()
139 app.ProcessIdle()
133 # We need to sleep at this point to keep the idle CPU load
140 # We need to sleep at this point to keep the idle CPU load
134 # low. However, if sleep to long, GUI response is poor. As
141 # low. However, if sleep to long, GUI response is poor. As
135 # a compromise, we watch how often GUI events are being processed
142 # a compromise, we watch how often GUI events are being processed
136 # and switch between a short and long sleep time. Here are some
143 # and switch between a short and long sleep time. Here are some
137 # stats useful in helping to tune this.
144 # stats useful in helping to tune this.
138 # time CPU load
145 # time CPU load
139 # 0.001 13%
146 # 0.001 13%
140 # 0.005 3%
147 # 0.005 3%
141 # 0.01 1.5%
148 # 0.01 1.5%
142 # 0.05 0.5%
149 # 0.05 0.5%
150 if clock()-t > 1.0:
151 time.sleep(1.0)
143 if clock()-t > 0.1:
152 if clock()-t > 0.1:
144 # Few GUI events coming in, so we can sleep longer
153 # Few GUI events coming in, so we can sleep longer
145 time.sleep(0.05)
154 time.sleep(0.05)
146 else:
155 else:
147 # Many GUI events coming in, so sleep only very little
156 # Many GUI events coming in, so sleep only very little
148 time.sleep(0.001)
157 time.sleep(0.001)
149 del ea
158 del ea
150 return 0
159 return 0
151
160
152 # This is our default implementation
161 # This is our default implementation
153 inputhook_wx = inputhook_wx3 No newline at end of file
162 inputhook_wx = inputhook_wx3
@@ -1,1539 +1,1542 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. _command_line_options:
5 .. _command_line_options:
6
6
7 Command-line usage
7 Command-line usage
8 ==================
8 ==================
9
9
10 You start IPython with the command::
10 You start IPython with the command::
11
11
12 $ ipython [options] files
12 $ ipython [options] files
13
13
14 If invoked with no options, it executes all the files listed in sequence
14 If invoked with no options, it executes all the files listed in sequence
15 and drops you into the interpreter while still acknowledging any options
15 and drops you into the interpreter while still acknowledging any options
16 you may have set in your ipythonrc file. This behavior is different from
16 you may have set in your ipythonrc file. This behavior is different from
17 standard Python, which when called as python -i will only execute one
17 standard Python, which when called as python -i will only execute one
18 file and ignore your configuration setup.
18 file and ignore your configuration setup.
19
19
20 Please note that some of the configuration options are not available at
20 Please note that some of the configuration options are not available at
21 the command line, simply because they are not practical here. Look into
21 the command line, simply because they are not practical here. Look into
22 your ipythonrc configuration file for details on those. This file
22 your ipythonrc configuration file for details on those. This file
23 typically installed in the $HOME/.ipython directory. For Windows users,
23 typically installed in the $HOME/.ipython directory. For Windows users,
24 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
24 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
25 instances. In the rest of this text, we will refer to this directory as
25 instances. In the rest of this text, we will refer to this directory as
26 IPYTHONDIR.
26 IPYTHONDIR.
27
27
28
28
29
29
30 Special Threading Options
30 Special Threading Options
31 -------------------------
31 -------------------------
32
32
33 Previously IPython had command line options for controlling GUI event loop
33 Previously IPython had command line options for controlling GUI event loop
34 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
34 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
35 version 0.11, these have been deprecated. Please see the new ``%gui``
35 version 0.11, these have been deprecated. Please see the new ``%gui``
36 magic command or :ref:`this section <gui_support>` for details on the new
36 magic command or :ref:`this section <gui_support>` for details on the new
37 interface.
37 interface.
38
38
39 Regular Options
39 Regular Options
40 ---------------
40 ---------------
41
41
42 After the above threading options have been given, regular options can
42 After the above threading options have been given, regular options can
43 follow in any order. All options can be abbreviated to their shortest
43 follow in any order. All options can be abbreviated to their shortest
44 non-ambiguous form and are case-sensitive. One or two dashes can be
44 non-ambiguous form and are case-sensitive. One or two dashes can be
45 used. Some options have an alternate short form, indicated after a ``|``.
45 used. Some options have an alternate short form, indicated after a ``|``.
46
46
47 Most options can also be set from your ipythonrc configuration file. See
47 Most options can also be set from your ipythonrc configuration file. See
48 the provided example for more details on what the options do. Options
48 the provided example for more details on what the options do. Options
49 given at the command line override the values set in the ipythonrc file.
49 given at the command line override the values set in the ipythonrc file.
50
50
51 All options with a [no] prepended can be specified in negated form
51 All options with a [no] prepended can be specified in negated form
52 (-nooption instead of -option) to turn the feature off.
52 (-nooption instead of -option) to turn the feature off.
53
53
54 -help print a help message and exit.
54 -help print a help message and exit.
55
55
56 -pylab
56 -pylab
57 Deprecated. See :ref:`Matplotlib support <matplotlib_support>`
57 Deprecated. See :ref:`Matplotlib support <matplotlib_support>`
58 for more details.
58 for more details.
59
59
60 -autocall <val>
60 -autocall <val>
61 Make IPython automatically call any callable object even if you
61 Make IPython automatically call any callable object even if you
62 didn't type explicit parentheses. For example, 'str 43' becomes
62 didn't type explicit parentheses. For example, 'str 43' becomes
63 'str(43)' automatically. The value can be '0' to disable the feature,
63 'str(43)' automatically. The value can be '0' to disable the feature,
64 '1' for smart autocall, where it is not applied if there are no more
64 '1' for smart autocall, where it is not applied if there are no more
65 arguments on the line, and '2' for full autocall, where all callable
65 arguments on the line, and '2' for full autocall, where all callable
66 objects are automatically called (even if no arguments are
66 objects are automatically called (even if no arguments are
67 present). The default is '1'.
67 present). The default is '1'.
68
68
69 -[no]autoindent
69 -[no]autoindent
70 Turn automatic indentation on/off.
70 Turn automatic indentation on/off.
71
71
72 -[no]automagic
72 -[no]automagic
73 make magic commands automatic (without needing their first character
73 make magic commands automatic (without needing their first character
74 to be %). Type %magic at the IPython prompt for more information.
74 to be %). Type %magic at the IPython prompt for more information.
75
75
76 -[no]autoedit_syntax
76 -[no]autoedit_syntax
77 When a syntax error occurs after editing a file, automatically
77 When a syntax error occurs after editing a file, automatically
78 open the file to the trouble causing line for convenient
78 open the file to the trouble causing line for convenient
79 fixing.
79 fixing.
80
80
81 -[no]banner Print the initial information banner (default on).
81 -[no]banner Print the initial information banner (default on).
82
82
83 -c <command>
83 -c <command>
84 execute the given command string. This is similar to the -c
84 execute the given command string. This is similar to the -c
85 option in the normal Python interpreter.
85 option in the normal Python interpreter.
86
86
87 -cache_size, cs <n>
87 -cache_size, cs <n>
88 size of the output cache (maximum number of entries to hold in
88 size of the output cache (maximum number of entries to hold in
89 memory). The default is 1000, you can change it permanently in your
89 memory). The default is 1000, you can change it permanently in your
90 config file. Setting it to 0 completely disables the caching system,
90 config file. Setting it to 0 completely disables the caching system,
91 and the minimum value accepted is 20 (if you provide a value less than
91 and the minimum value accepted is 20 (if you provide a value less than
92 20, it is reset to 0 and a warning is issued) This limit is defined
92 20, it is reset to 0 and a warning is issued) This limit is defined
93 because otherwise you'll spend more time re-flushing a too small cache
93 because otherwise you'll spend more time re-flushing a too small cache
94 than working.
94 than working.
95
95
96 -classic, cl
96 -classic, cl
97 Gives IPython a similar feel to the classic Python
97 Gives IPython a similar feel to the classic Python
98 prompt.
98 prompt.
99
99
100 -colors <scheme>
100 -colors <scheme>
101 Color scheme for prompts and exception reporting. Currently
101 Color scheme for prompts and exception reporting. Currently
102 implemented: NoColor, Linux and LightBG.
102 implemented: NoColor, Linux and LightBG.
103
103
104 -[no]color_info
104 -[no]color_info
105 IPython can display information about objects via a set of functions,
105 IPython can display information about objects via a set of functions,
106 and optionally can use colors for this, syntax highlighting source
106 and optionally can use colors for this, syntax highlighting source
107 code and various other elements. However, because this information is
107 code and various other elements. However, because this information is
108 passed through a pager (like 'less') and many pagers get confused with
108 passed through a pager (like 'less') and many pagers get confused with
109 color codes, this option is off by default. You can test it and turn
109 color codes, this option is off by default. You can test it and turn
110 it on permanently in your ipythonrc file if it works for you. As a
110 it on permanently in your ipythonrc file if it works for you. As a
111 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
111 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
112 that in RedHat 7.2 doesn't.
112 that in RedHat 7.2 doesn't.
113
113
114 Test it and turn it on permanently if it works with your
114 Test it and turn it on permanently if it works with your
115 system. The magic function %color_info allows you to toggle this
115 system. The magic function %color_info allows you to toggle this
116 interactively for testing.
116 interactively for testing.
117
117
118 -[no]debug
118 -[no]debug
119 Show information about the loading process. Very useful to pin down
119 Show information about the loading process. Very useful to pin down
120 problems with your configuration files or to get details about
120 problems with your configuration files or to get details about
121 session restores.
121 session restores.
122
122
123 -[no]deep_reload:
123 -[no]deep_reload:
124 IPython can use the deep_reload module which reloads changes in
124 IPython can use the deep_reload module which reloads changes in
125 modules recursively (it replaces the reload() function, so you don't
125 modules recursively (it replaces the reload() function, so you don't
126 need to change anything to use it). deep_reload() forces a full
126 need to change anything to use it). deep_reload() forces a full
127 reload of modules whose code may have changed, which the default
127 reload of modules whose code may have changed, which the default
128 reload() function does not.
128 reload() function does not.
129
129
130 When deep_reload is off, IPython will use the normal reload(),
130 When deep_reload is off, IPython will use the normal reload(),
131 but deep_reload will still be available as dreload(). This
131 but deep_reload will still be available as dreload(). This
132 feature is off by default [which means that you have both
132 feature is off by default [which means that you have both
133 normal reload() and dreload()].
133 normal reload() and dreload()].
134
134
135 -editor <name>
135 -editor <name>
136 Which editor to use with the %edit command. By default,
136 Which editor to use with the %edit command. By default,
137 IPython will honor your EDITOR environment variable (if not
137 IPython will honor your EDITOR environment variable (if not
138 set, vi is the Unix default and notepad the Windows one).
138 set, vi is the Unix default and notepad the Windows one).
139 Since this editor is invoked on the fly by IPython and is
139 Since this editor is invoked on the fly by IPython and is
140 meant for editing small code snippets, you may want to use a
140 meant for editing small code snippets, you may want to use a
141 small, lightweight editor here (in case your default EDITOR is
141 small, lightweight editor here (in case your default EDITOR is
142 something like Emacs).
142 something like Emacs).
143
143
144 -ipythondir <name>
144 -ipythondir <name>
145 name of your IPython configuration directory IPYTHONDIR. This
145 name of your IPython configuration directory IPYTHONDIR. This
146 can also be specified through the environment variable
146 can also be specified through the environment variable
147 IPYTHONDIR.
147 IPYTHONDIR.
148
148
149 -log, l
149 -log, l
150 generate a log file of all input. The file is named
150 generate a log file of all input. The file is named
151 ipython_log.py in your current directory (which prevents logs
151 ipython_log.py in your current directory (which prevents logs
152 from multiple IPython sessions from trampling each other). You
152 from multiple IPython sessions from trampling each other). You
153 can use this to later restore a session by loading your
153 can use this to later restore a session by loading your
154 logfile as a file to be executed with option -logplay (see
154 logfile as a file to be executed with option -logplay (see
155 below).
155 below).
156
156
157 -logfile, lf <name> specify the name of your logfile.
157 -logfile, lf <name> specify the name of your logfile.
158
158
159 -logplay, lp <name>
159 -logplay, lp <name>
160
160
161 you can replay a previous log. For restoring a session as close as
161 you can replay a previous log. For restoring a session as close as
162 possible to the state you left it in, use this option (don't just run
162 possible to the state you left it in, use this option (don't just run
163 the logfile). With -logplay, IPython will try to reconstruct the
163 the logfile). With -logplay, IPython will try to reconstruct the
164 previous working environment in full, not just execute the commands in
164 previous working environment in full, not just execute the commands in
165 the logfile.
165 the logfile.
166
166
167 When a session is restored, logging is automatically turned on
167 When a session is restored, logging is automatically turned on
168 again with the name of the logfile it was invoked with (it is
168 again with the name of the logfile it was invoked with (it is
169 read from the log header). So once you've turned logging on for
169 read from the log header). So once you've turned logging on for
170 a session, you can quit IPython and reload it as many times as
170 a session, you can quit IPython and reload it as many times as
171 you want and it will continue to log its history and restore
171 you want and it will continue to log its history and restore
172 from the beginning every time.
172 from the beginning every time.
173
173
174 Caveats: there are limitations in this option. The history
174 Caveats: there are limitations in this option. The history
175 variables _i*,_* and _dh don't get restored properly. In the
175 variables _i*,_* and _dh don't get restored properly. In the
176 future we will try to implement full session saving by writing
176 future we will try to implement full session saving by writing
177 and retrieving a 'snapshot' of the memory state of IPython. But
177 and retrieving a 'snapshot' of the memory state of IPython. But
178 our first attempts failed because of inherent limitations of
178 our first attempts failed because of inherent limitations of
179 Python's Pickle module, so this may have to wait.
179 Python's Pickle module, so this may have to wait.
180
180
181 -[no]messages
181 -[no]messages
182 Print messages which IPython collects about its startup
182 Print messages which IPython collects about its startup
183 process (default on).
183 process (default on).
184
184
185 -[no]pdb
185 -[no]pdb
186 Automatically call the pdb debugger after every uncaught
186 Automatically call the pdb debugger after every uncaught
187 exception. If you are used to debugging using pdb, this puts
187 exception. If you are used to debugging using pdb, this puts
188 you automatically inside of it after any call (either in
188 you automatically inside of it after any call (either in
189 IPython or in code called by it) which triggers an exception
189 IPython or in code called by it) which triggers an exception
190 which goes uncaught.
190 which goes uncaught.
191
191
192 -pydb
192 -pydb
193 Makes IPython use the third party "pydb" package as debugger,
193 Makes IPython use the third party "pydb" package as debugger,
194 instead of pdb. Requires that pydb is installed.
194 instead of pdb. Requires that pydb is installed.
195
195
196 -[no]pprint
196 -[no]pprint
197 ipython can optionally use the pprint (pretty printer) module
197 ipython can optionally use the pprint (pretty printer) module
198 for displaying results. pprint tends to give a nicer display
198 for displaying results. pprint tends to give a nicer display
199 of nested data structures. If you like it, you can turn it on
199 of nested data structures. If you like it, you can turn it on
200 permanently in your config file (default off).
200 permanently in your config file (default off).
201
201
202 -profile, p <name>
202 -profile, p <name>
203
203
204 assume that your config file is ipythonrc-<name> or
204 assume that your config file is ipythonrc-<name> or
205 ipy_profile_<name>.py (looks in current dir first, then in
205 ipy_profile_<name>.py (looks in current dir first, then in
206 IPYTHONDIR). This is a quick way to keep and load multiple
206 IPYTHONDIR). This is a quick way to keep and load multiple
207 config files for different tasks, especially if you use the
207 config files for different tasks, especially if you use the
208 include option of config files. You can keep a basic
208 include option of config files. You can keep a basic
209 IPYTHONDIR/ipythonrc file and then have other 'profiles' which
209 IPYTHONDIR/ipythonrc file and then have other 'profiles' which
210 include this one and load extra things for particular
210 include this one and load extra things for particular
211 tasks. For example:
211 tasks. For example:
212
212
213 1. $HOME/.ipython/ipythonrc : load basic things you always want.
213 1. $HOME/.ipython/ipythonrc : load basic things you always want.
214 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules.
214 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules.
215 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules.
215 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules.
216
216
217 Since it is possible to create an endless loop by having
217 Since it is possible to create an endless loop by having
218 circular file inclusions, IPython will stop if it reaches 15
218 circular file inclusions, IPython will stop if it reaches 15
219 recursive inclusions.
219 recursive inclusions.
220
220
221 -prompt_in1, pi1 <string>
221 -prompt_in1, pi1 <string>
222
222
223 Specify the string used for input prompts. Note that if you are using
223 Specify the string used for input prompts. Note that if you are using
224 numbered prompts, the number is represented with a '\#' in the
224 numbered prompts, the number is represented with a '\#' in the
225 string. Don't forget to quote strings with spaces embedded in
225 string. Don't forget to quote strings with spaces embedded in
226 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
226 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
227 discusses in detail all the available escapes to customize your
227 discusses in detail all the available escapes to customize your
228 prompts.
228 prompts.
229
229
230 -prompt_in2, pi2 <string>
230 -prompt_in2, pi2 <string>
231 Similar to the previous option, but used for the continuation
231 Similar to the previous option, but used for the continuation
232 prompts. The special sequence '\D' is similar to '\#', but
232 prompts. The special sequence '\D' is similar to '\#', but
233 with all digits replaced dots (so you can have your
233 with all digits replaced dots (so you can have your
234 continuation prompt aligned with your input prompt). Default:
234 continuation prompt aligned with your input prompt). Default:
235 ' .\D.:' (note three spaces at the start for alignment with
235 ' .\D.:' (note three spaces at the start for alignment with
236 'In [\#]').
236 'In [\#]').
237
237
238 -prompt_out,po <string>
238 -prompt_out,po <string>
239 String used for output prompts, also uses numbers like
239 String used for output prompts, also uses numbers like
240 prompt_in1. Default: 'Out[\#]:'
240 prompt_in1. Default: 'Out[\#]:'
241
241
242 -quick start in bare bones mode (no config file loaded).
242 -quick start in bare bones mode (no config file loaded).
243
243
244 -rcfile <name>
244 -rcfile <name>
245 name of your IPython resource configuration file. Normally
245 name of your IPython resource configuration file. Normally
246 IPython loads ipythonrc (from current directory) or
246 IPython loads ipythonrc (from current directory) or
247 IPYTHONDIR/ipythonrc.
247 IPYTHONDIR/ipythonrc.
248
248
249 If the loading of your config file fails, IPython starts with
249 If the loading of your config file fails, IPython starts with
250 a bare bones configuration (no modules loaded at all).
250 a bare bones configuration (no modules loaded at all).
251
251
252 -[no]readline
252 -[no]readline
253 use the readline library, which is needed to support name
253 use the readline library, which is needed to support name
254 completion and command history, among other things. It is
254 completion and command history, among other things. It is
255 enabled by default, but may cause problems for users of
255 enabled by default, but may cause problems for users of
256 X/Emacs in Python comint or shell buffers.
256 X/Emacs in Python comint or shell buffers.
257
257
258 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
258 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
259 IPython's readline and syntax coloring fine, only 'emacs' (M-x
259 IPython's readline and syntax coloring fine, only 'emacs' (M-x
260 shell and C-c !) buffers do not.
260 shell and C-c !) buffers do not.
261
261
262 -screen_length, sl <n>
262 -screen_length, sl <n>
263 number of lines of your screen. This is used to control
263 number of lines of your screen. This is used to control
264 printing of very long strings. Strings longer than this number
264 printing of very long strings. Strings longer than this number
265 of lines will be sent through a pager instead of directly
265 of lines will be sent through a pager instead of directly
266 printed.
266 printed.
267
267
268 The default value for this is 0, which means IPython will
268 The default value for this is 0, which means IPython will
269 auto-detect your screen size every time it needs to print certain
269 auto-detect your screen size every time it needs to print certain
270 potentially long strings (this doesn't change the behavior of the
270 potentially long strings (this doesn't change the behavior of the
271 'print' keyword, it's only triggered internally). If for some
271 'print' keyword, it's only triggered internally). If for some
272 reason this isn't working well (it needs curses support), specify
272 reason this isn't working well (it needs curses support), specify
273 it yourself. Otherwise don't change the default.
273 it yourself. Otherwise don't change the default.
274
274
275 -separate_in, si <string>
275 -separate_in, si <string>
276
276
277 separator before input prompts.
277 separator before input prompts.
278 Default: '\n'
278 Default: '\n'
279
279
280 -separate_out, so <string>
280 -separate_out, so <string>
281 separator before output prompts.
281 separator before output prompts.
282 Default: nothing.
282 Default: nothing.
283
283
284 -separate_out2, so2
284 -separate_out2, so2
285 separator after output prompts.
285 separator after output prompts.
286 Default: nothing.
286 Default: nothing.
287 For these three options, use the value 0 to specify no separator.
287 For these three options, use the value 0 to specify no separator.
288
288
289 -nosep
289 -nosep
290 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
290 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
291 0'. Simply removes all input/output separators.
291 0'. Simply removes all input/output separators.
292
292
293 -upgrade
293 -upgrade
294 allows you to upgrade your IPYTHONDIR configuration when you
294 allows you to upgrade your IPYTHONDIR configuration when you
295 install a new version of IPython. Since new versions may
295 install a new version of IPython. Since new versions may
296 include new command line options or example files, this copies
296 include new command line options or example files, this copies
297 updated ipythonrc-type files. However, it backs up (with a
297 updated ipythonrc-type files. However, it backs up (with a
298 .old extension) all files which it overwrites so that you can
298 .old extension) all files which it overwrites so that you can
299 merge back any customizations you might have in your personal
299 merge back any customizations you might have in your personal
300 files. Note that you should probably use %upgrade instead,
300 files. Note that you should probably use %upgrade instead,
301 it's a safer alternative.
301 it's a safer alternative.
302
302
303
303
304 -Version print version information and exit.
304 -Version print version information and exit.
305
305
306 -wxversion <string>
306 -wxversion <string>
307 Deprecated.
307 Deprecated.
308
308
309 -xmode <modename>
309 -xmode <modename>
310
310
311 Mode for exception reporting.
311 Mode for exception reporting.
312
312
313 Valid modes: Plain, Context and Verbose.
313 Valid modes: Plain, Context and Verbose.
314
314
315 * Plain: similar to python's normal traceback printing.
315 * Plain: similar to python's normal traceback printing.
316 * Context: prints 5 lines of context source code around each
316 * Context: prints 5 lines of context source code around each
317 line in the traceback.
317 line in the traceback.
318 * Verbose: similar to Context, but additionally prints the
318 * Verbose: similar to Context, but additionally prints the
319 variables currently visible where the exception happened
319 variables currently visible where the exception happened
320 (shortening their strings if too long). This can potentially be
320 (shortening their strings if too long). This can potentially be
321 very slow, if you happen to have a huge data structure whose
321 very slow, if you happen to have a huge data structure whose
322 string representation is complex to compute. Your computer may
322 string representation is complex to compute. Your computer may
323 appear to freeze for a while with cpu usage at 100%. If this
323 appear to freeze for a while with cpu usage at 100%. If this
324 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
324 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
325 more than once).
325 more than once).
326
326
327 Interactive use
327 Interactive use
328 ===============
328 ===============
329
329
330 Warning: IPython relies on the existence of a global variable called
330 Warning: IPython relies on the existence of a global variable called
331 _ip which controls the shell itself. If you redefine _ip to anything,
331 _ip which controls the shell itself. If you redefine _ip to anything,
332 bizarre behavior will quickly occur.
332 bizarre behavior will quickly occur.
333
333
334 Other than the above warning, IPython is meant to work as a drop-in
334 Other than the above warning, IPython is meant to work as a drop-in
335 replacement for the standard interactive interpreter. As such, any code
335 replacement for the standard interactive interpreter. As such, any code
336 which is valid python should execute normally under IPython (cases where
336 which is valid python should execute normally under IPython (cases where
337 this is not true should be reported as bugs). It does, however, offer
337 this is not true should be reported as bugs). It does, however, offer
338 many features which are not available at a standard python prompt. What
338 many features which are not available at a standard python prompt. What
339 follows is a list of these.
339 follows is a list of these.
340
340
341
341
342 Caution for Windows users
342 Caution for Windows users
343 -------------------------
343 -------------------------
344
344
345 Windows, unfortunately, uses the '\' character as a path
345 Windows, unfortunately, uses the '\' character as a path
346 separator. This is a terrible choice, because '\' also represents the
346 separator. This is a terrible choice, because '\' also represents the
347 escape character in most modern programming languages, including
347 escape character in most modern programming languages, including
348 Python. For this reason, using '/' character is recommended if you
348 Python. For this reason, using '/' character is recommended if you
349 have problems with ``\``. However, in Windows commands '/' flags
349 have problems with ``\``. However, in Windows commands '/' flags
350 options, so you can not use it for the root directory. This means that
350 options, so you can not use it for the root directory. This means that
351 paths beginning at the root must be typed in a contrived manner like:
351 paths beginning at the root must be typed in a contrived manner like:
352 ``%copy \opt/foo/bar.txt \tmp``
352 ``%copy \opt/foo/bar.txt \tmp``
353
353
354 .. _magic:
354 .. _magic:
355
355
356 Magic command system
356 Magic command system
357 --------------------
357 --------------------
358
358
359 IPython will treat any line whose first character is a % as a special
359 IPython will treat any line whose first character is a % as a special
360 call to a 'magic' function. These allow you to control the behavior of
360 call to a 'magic' function. These allow you to control the behavior of
361 IPython itself, plus a lot of system-type features. They are all
361 IPython itself, plus a lot of system-type features. They are all
362 prefixed with a % character, but parameters are given without
362 prefixed with a % character, but parameters are given without
363 parentheses or quotes.
363 parentheses or quotes.
364
364
365 Example: typing '%cd mydir' (without the quotes) changes you working
365 Example: typing '%cd mydir' (without the quotes) changes you working
366 directory to 'mydir', if it exists.
366 directory to 'mydir', if it exists.
367
367
368 If you have 'automagic' enabled (in your ipythonrc file, via the command
368 If you have 'automagic' enabled (in your ipythonrc file, via the command
369 line option -automagic or with the %automagic function), you don't need
369 line option -automagic or with the %automagic function), you don't need
370 to type in the % explicitly. IPython will scan its internal list of
370 to type in the % explicitly. IPython will scan its internal list of
371 magic functions and call one if it exists. With automagic on you can
371 magic functions and call one if it exists. With automagic on you can
372 then just type 'cd mydir' to go to directory 'mydir'. The automagic
372 then just type 'cd mydir' to go to directory 'mydir'. The automagic
373 system has the lowest possible precedence in name searches, so defining
373 system has the lowest possible precedence in name searches, so defining
374 an identifier with the same name as an existing magic function will
374 an identifier with the same name as an existing magic function will
375 shadow it for automagic use. You can still access the shadowed magic
375 shadow it for automagic use. You can still access the shadowed magic
376 function by explicitly using the % character at the beginning of the line.
376 function by explicitly using the % character at the beginning of the line.
377
377
378 An example (with automagic on) should clarify all this::
378 An example (with automagic on) should clarify all this::
379
379
380 In [1]: cd ipython # %cd is called by automagic
380 In [1]: cd ipython # %cd is called by automagic
381
381
382 /home/fperez/ipython
382 /home/fperez/ipython
383
383
384 In [2]: cd=1 # now cd is just a variable
384 In [2]: cd=1 # now cd is just a variable
385
385
386 In [3]: cd .. # and doesn't work as a function anymore
386 In [3]: cd .. # and doesn't work as a function anymore
387
387
388 ------------------------------
388 ------------------------------
389
389
390 File "<console>", line 1
390 File "<console>", line 1
391
391
392 cd ..
392 cd ..
393
393
394 ^
394 ^
395
395
396 SyntaxError: invalid syntax
396 SyntaxError: invalid syntax
397
397
398 In [4]: %cd .. # but %cd always works
398 In [4]: %cd .. # but %cd always works
399
399
400 /home/fperez
400 /home/fperez
401
401
402 In [5]: del cd # if you remove the cd variable
402 In [5]: del cd # if you remove the cd variable
403
403
404 In [6]: cd ipython # automagic can work again
404 In [6]: cd ipython # automagic can work again
405
405
406 /home/fperez/ipython
406 /home/fperez/ipython
407
407
408 You can define your own magic functions to extend the system. The
408 You can define your own magic functions to extend the system. The
409 following example defines a new magic command, %impall::
409 following example defines a new magic command, %impall::
410
410
411 import IPython.ipapi
411 import IPython.ipapi
412
412
413 ip = IPython.ipapi.get()
413 ip = IPython.ipapi.get()
414
414
415 def doimp(self, arg):
415 def doimp(self, arg):
416
416
417 ip = self.api
417 ip = self.api
418
418
419 ip.ex("import %s; reload(%s); from %s import *" % (
419 ip.ex("import %s; reload(%s); from %s import *" % (
420
420
421 arg,arg,arg)
421 arg,arg,arg)
422
422
423 )
423 )
424
424
425 ip.expose_magic('impall', doimp)
425 ip.expose_magic('impall', doimp)
426
426
427 You can also define your own aliased names for magic functions. In your
427 You can also define your own aliased names for magic functions. In your
428 ipythonrc file, placing a line like::
428 ipythonrc file, placing a line like::
429
429
430 execute __IP.magic_cl = __IP.magic_clear
430 execute __IP.magic_cl = __IP.magic_clear
431
431
432 will define %cl as a new name for %clear.
432 will define %cl as a new name for %clear.
433
433
434 Type %magic for more information, including a list of all available
434 Type %magic for more information, including a list of all available
435 magic functions at any time and their docstrings. You can also type
435 magic functions at any time and their docstrings. You can also type
436 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
436 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
437 information on the '?' system) to get information about any particular
437 information on the '?' system) to get information about any particular
438 magic function you are interested in.
438 magic function you are interested in.
439
439
440 The API documentation for the :mod:`IPython.Magic` module contains the full
440 The API documentation for the :mod:`IPython.Magic` module contains the full
441 docstrings of all currently available magic commands.
441 docstrings of all currently available magic commands.
442
442
443
443
444 Access to the standard Python help
444 Access to the standard Python help
445 ----------------------------------
445 ----------------------------------
446
446
447 As of Python 2.1, a help system is available with access to object docstrings
447 As of Python 2.1, a help system is available with access to object docstrings
448 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
448 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
449 also type help(object) to obtain information about a given object, and
449 also type help(object) to obtain information about a given object, and
450 help('keyword') for information on a keyword. As noted :ref:`here
450 help('keyword') for information on a keyword. As noted :ref:`here
451 <accessing_help>`, you need to properly configure your environment variable
451 <accessing_help>`, you need to properly configure your environment variable
452 PYTHONDOCS for this feature to work correctly.
452 PYTHONDOCS for this feature to work correctly.
453
453
454 .. _dynamic_object_info:
454 .. _dynamic_object_info:
455
455
456 Dynamic object information
456 Dynamic object information
457 --------------------------
457 --------------------------
458
458
459 Typing ?word or word? prints detailed information about an object. If
459 Typing ?word or word? prints detailed information about an object. If
460 certain strings in the object are too long (docstrings, code, etc.) they
460 certain strings in the object are too long (docstrings, code, etc.) they
461 get snipped in the center for brevity. This system gives access variable
461 get snipped in the center for brevity. This system gives access variable
462 types and values, full source code for any object (if available),
462 types and values, full source code for any object (if available),
463 function prototypes and other useful information.
463 function prototypes and other useful information.
464
464
465 Typing ??word or word?? gives access to the full information without
465 Typing ??word or word?? gives access to the full information without
466 snipping long strings. Long strings are sent to the screen through the
466 snipping long strings. Long strings are sent to the screen through the
467 less pager if longer than the screen and printed otherwise. On systems
467 less pager if longer than the screen and printed otherwise. On systems
468 lacking the less command, IPython uses a very basic internal pager.
468 lacking the less command, IPython uses a very basic internal pager.
469
469
470 The following magic functions are particularly useful for gathering
470 The following magic functions are particularly useful for gathering
471 information about your working environment. You can get more details by
471 information about your working environment. You can get more details by
472 typing %magic or querying them individually (use %function_name? with or
472 typing %magic or querying them individually (use %function_name? with or
473 without the %), this is just a summary:
473 without the %), this is just a summary:
474
474
475 * **%pdoc <object>**: Print (or run through a pager if too long) the
475 * **%pdoc <object>**: Print (or run through a pager if too long) the
476 docstring for an object. If the given object is a class, it will
476 docstring for an object. If the given object is a class, it will
477 print both the class and the constructor docstrings.
477 print both the class and the constructor docstrings.
478 * **%pdef <object>**: Print the definition header for any callable
478 * **%pdef <object>**: Print the definition header for any callable
479 object. If the object is a class, print the constructor information.
479 object. If the object is a class, print the constructor information.
480 * **%psource <object>**: Print (or run through a pager if too long)
480 * **%psource <object>**: Print (or run through a pager if too long)
481 the source code for an object.
481 the source code for an object.
482 * **%pfile <object>**: Show the entire source file where an object was
482 * **%pfile <object>**: Show the entire source file where an object was
483 defined via a pager, opening it at the line where the object
483 defined via a pager, opening it at the line where the object
484 definition begins.
484 definition begins.
485 * **%who/%whos**: These functions give information about identifiers
485 * **%who/%whos**: These functions give information about identifiers
486 you have defined interactively (not things you loaded or defined
486 you have defined interactively (not things you loaded or defined
487 in your configuration files). %who just prints a list of
487 in your configuration files). %who just prints a list of
488 identifiers and %whos prints a table with some basic details about
488 identifiers and %whos prints a table with some basic details about
489 each identifier.
489 each identifier.
490
490
491 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
491 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
492 %pdef, %psource) give you access to documentation even on things which
492 %pdef, %psource) give you access to documentation even on things which
493 are not really defined as separate identifiers. Try for example typing
493 are not really defined as separate identifiers. Try for example typing
494 {}.get? or after doing import os, type os.path.abspath??.
494 {}.get? or after doing import os, type os.path.abspath??.
495
495
496
496
497 .. _readline:
497 .. _readline:
498
498
499 Readline-based features
499 Readline-based features
500 -----------------------
500 -----------------------
501
501
502 These features require the GNU readline library, so they won't work if
502 These features require the GNU readline library, so they won't work if
503 your Python installation lacks readline support. We will first describe
503 your Python installation lacks readline support. We will first describe
504 the default behavior IPython uses, and then how to change it to suit
504 the default behavior IPython uses, and then how to change it to suit
505 your preferences.
505 your preferences.
506
506
507
507
508 Command line completion
508 Command line completion
509 +++++++++++++++++++++++
509 +++++++++++++++++++++++
510
510
511 At any time, hitting TAB will complete any available python commands or
511 At any time, hitting TAB will complete any available python commands or
512 variable names, and show you a list of the possible completions if
512 variable names, and show you a list of the possible completions if
513 there's no unambiguous one. It will also complete filenames in the
513 there's no unambiguous one. It will also complete filenames in the
514 current directory if no python names match what you've typed so far.
514 current directory if no python names match what you've typed so far.
515
515
516
516
517 Search command history
517 Search command history
518 ++++++++++++++++++++++
518 ++++++++++++++++++++++
519
519
520 IPython provides two ways for searching through previous input and thus
520 IPython provides two ways for searching through previous input and thus
521 reduce the need for repetitive typing:
521 reduce the need for repetitive typing:
522
522
523 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
523 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
524 (next,down) to search through only the history items that match
524 (next,down) to search through only the history items that match
525 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
525 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
526 prompt, they just behave like normal arrow keys.
526 prompt, they just behave like normal arrow keys.
527 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
527 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
528 searches your history for lines that contain what you've typed so
528 searches your history for lines that contain what you've typed so
529 far, completing as much as it can.
529 far, completing as much as it can.
530
530
531
531
532 Persistent command history across sessions
532 Persistent command history across sessions
533 ++++++++++++++++++++++++++++++++++++++++++
533 ++++++++++++++++++++++++++++++++++++++++++
534
534
535 IPython will save your input history when it leaves and reload it next
535 IPython will save your input history when it leaves and reload it next
536 time you restart it. By default, the history file is named
536 time you restart it. By default, the history file is named
537 $IPYTHONDIR/history, but if you've loaded a named profile,
537 $IPYTHONDIR/history, but if you've loaded a named profile,
538 '-PROFILE_NAME' is appended to the name. This allows you to keep
538 '-PROFILE_NAME' is appended to the name. This allows you to keep
539 separate histories related to various tasks: commands related to
539 separate histories related to various tasks: commands related to
540 numerical work will not be clobbered by a system shell history, for
540 numerical work will not be clobbered by a system shell history, for
541 example.
541 example.
542
542
543
543
544 Autoindent
544 Autoindent
545 ++++++++++
545 ++++++++++
546
546
547 IPython can recognize lines ending in ':' and indent the next line,
547 IPython can recognize lines ending in ':' and indent the next line,
548 while also un-indenting automatically after 'raise' or 'return'.
548 while also un-indenting automatically after 'raise' or 'return'.
549
549
550 This feature uses the readline library, so it will honor your ~/.inputrc
550 This feature uses the readline library, so it will honor your ~/.inputrc
551 configuration (or whatever file your INPUTRC variable points to). Adding
551 configuration (or whatever file your INPUTRC variable points to). Adding
552 the following lines to your .inputrc file can make indenting/unindenting
552 the following lines to your .inputrc file can make indenting/unindenting
553 more convenient (M-i indents, M-u unindents)::
553 more convenient (M-i indents, M-u unindents)::
554
554
555 $if Python
555 $if Python
556 "\M-i": " "
556 "\M-i": " "
557 "\M-u": "\d\d\d\d"
557 "\M-u": "\d\d\d\d"
558 $endif
558 $endif
559
559
560 Note that there are 4 spaces between the quote marks after "M-i" above.
560 Note that there are 4 spaces between the quote marks after "M-i" above.
561
561
562 Warning: this feature is ON by default, but it can cause problems with
562 Warning: this feature is ON by default, but it can cause problems with
563 the pasting of multi-line indented code (the pasted code gets
563 the pasting of multi-line indented code (the pasted code gets
564 re-indented on each line). A magic function %autoindent allows you to
564 re-indented on each line). A magic function %autoindent allows you to
565 toggle it on/off at runtime. You can also disable it permanently on in
565 toggle it on/off at runtime. You can also disable it permanently on in
566 your ipythonrc file (set autoindent 0).
566 your ipythonrc file (set autoindent 0).
567
567
568
568
569 Customizing readline behavior
569 Customizing readline behavior
570 +++++++++++++++++++++++++++++
570 +++++++++++++++++++++++++++++
571
571
572 All these features are based on the GNU readline library, which has an
572 All these features are based on the GNU readline library, which has an
573 extremely customizable interface. Normally, readline is configured via a
573 extremely customizable interface. Normally, readline is configured via a
574 file which defines the behavior of the library; the details of the
574 file which defines the behavior of the library; the details of the
575 syntax for this can be found in the readline documentation available
575 syntax for this can be found in the readline documentation available
576 with your system or on the Internet. IPython doesn't read this file (if
576 with your system or on the Internet. IPython doesn't read this file (if
577 it exists) directly, but it does support passing to readline valid
577 it exists) directly, but it does support passing to readline valid
578 options via a simple interface. In brief, you can customize readline by
578 options via a simple interface. In brief, you can customize readline by
579 setting the following options in your ipythonrc configuration file (note
579 setting the following options in your ipythonrc configuration file (note
580 that these options can not be specified at the command line):
580 that these options can not be specified at the command line):
581
581
582 * **readline_parse_and_bind**: this option can appear as many times as
582 * **readline_parse_and_bind**: this option can appear as many times as
583 you want, each time defining a string to be executed via a
583 you want, each time defining a string to be executed via a
584 readline.parse_and_bind() command. The syntax for valid commands
584 readline.parse_and_bind() command. The syntax for valid commands
585 of this kind can be found by reading the documentation for the GNU
585 of this kind can be found by reading the documentation for the GNU
586 readline library, as these commands are of the kind which readline
586 readline library, as these commands are of the kind which readline
587 accepts in its configuration file.
587 accepts in its configuration file.
588 * **readline_remove_delims**: a string of characters to be removed
588 * **readline_remove_delims**: a string of characters to be removed
589 from the default word-delimiters list used by readline, so that
589 from the default word-delimiters list used by readline, so that
590 completions may be performed on strings which contain them. Do not
590 completions may be performed on strings which contain them. Do not
591 change the default value unless you know what you're doing.
591 change the default value unless you know what you're doing.
592 * **readline_omit__names**: when tab-completion is enabled, hitting
592 * **readline_omit__names**: when tab-completion is enabled, hitting
593 <tab> after a '.' in a name will complete all attributes of an
593 <tab> after a '.' in a name will complete all attributes of an
594 object, including all the special methods whose names include
594 object, including all the special methods whose names include
595 double underscores (like __getitem__ or __class__). If you'd
595 double underscores (like __getitem__ or __class__). If you'd
596 rather not see these names by default, you can set this option to
596 rather not see these names by default, you can set this option to
597 1. Note that even when this option is set, you can still see those
597 1. Note that even when this option is set, you can still see those
598 names by explicitly typing a _ after the period and hitting <tab>:
598 names by explicitly typing a _ after the period and hitting <tab>:
599 'name._<tab>' will always complete attribute names starting with '_'.
599 'name._<tab>' will always complete attribute names starting with '_'.
600
600
601 This option is off by default so that new users see all
601 This option is off by default so that new users see all
602 attributes of any objects they are dealing with.
602 attributes of any objects they are dealing with.
603
603
604 You will find the default values along with a corresponding detailed
604 You will find the default values along with a corresponding detailed
605 explanation in your ipythonrc file.
605 explanation in your ipythonrc file.
606
606
607
607
608 Session logging and restoring
608 Session logging and restoring
609 -----------------------------
609 -----------------------------
610
610
611 You can log all input from a session either by starting IPython with the
611 You can log all input from a session either by starting IPython with the
612 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
612 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
613 or by activating the logging at any moment with the magic function %logstart.
613 or by activating the logging at any moment with the magic function %logstart.
614
614
615 Log files can later be reloaded with the -logplay option and IPython
615 Log files can later be reloaded with the -logplay option and IPython
616 will attempt to 'replay' the log by executing all the lines in it, thus
616 will attempt to 'replay' the log by executing all the lines in it, thus
617 restoring the state of a previous session. This feature is not quite
617 restoring the state of a previous session. This feature is not quite
618 perfect, but can still be useful in many cases.
618 perfect, but can still be useful in many cases.
619
619
620 The log files can also be used as a way to have a permanent record of
620 The log files can also be used as a way to have a permanent record of
621 any code you wrote while experimenting. Log files are regular text files
621 any code you wrote while experimenting. Log files are regular text files
622 which you can later open in your favorite text editor to extract code or
622 which you can later open in your favorite text editor to extract code or
623 to 'clean them up' before using them to replay a session.
623 to 'clean them up' before using them to replay a session.
624
624
625 The %logstart function for activating logging in mid-session is used as
625 The %logstart function for activating logging in mid-session is used as
626 follows:
626 follows:
627
627
628 %logstart [log_name [log_mode]]
628 %logstart [log_name [log_mode]]
629
629
630 If no name is given, it defaults to a file named 'log' in your
630 If no name is given, it defaults to a file named 'log' in your
631 IPYTHONDIR directory, in 'rotate' mode (see below).
631 IPYTHONDIR directory, in 'rotate' mode (see below).
632
632
633 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
633 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
634 history up to that point and then continues logging.
634 history up to that point and then continues logging.
635
635
636 %logstart takes a second optional parameter: logging mode. This can be
636 %logstart takes a second optional parameter: logging mode. This can be
637 one of (note that the modes are given unquoted):
637 one of (note that the modes are given unquoted):
638
638
639 * [over:] overwrite existing log_name.
639 * [over:] overwrite existing log_name.
640 * [backup:] rename (if exists) to log_name~ and start log_name.
640 * [backup:] rename (if exists) to log_name~ and start log_name.
641 * [append:] well, that says it.
641 * [append:] well, that says it.
642 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
642 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
643
643
644 The %logoff and %logon functions allow you to temporarily stop and
644 The %logoff and %logon functions allow you to temporarily stop and
645 resume logging to a file which had previously been started with
645 resume logging to a file which had previously been started with
646 %logstart. They will fail (with an explanation) if you try to use them
646 %logstart. They will fail (with an explanation) if you try to use them
647 before logging has been started.
647 before logging has been started.
648
648
649 .. _system_shell_access:
649 .. _system_shell_access:
650
650
651 System shell access
651 System shell access
652 -------------------
652 -------------------
653
653
654 Any input line beginning with a ! character is passed verbatim (minus
654 Any input line beginning with a ! character is passed verbatim (minus
655 the !, of course) to the underlying operating system. For example,
655 the !, of course) to the underlying operating system. For example,
656 typing !ls will run 'ls' in the current directory.
656 typing !ls will run 'ls' in the current directory.
657
657
658 Manual capture of command output
658 Manual capture of command output
659 --------------------------------
659 --------------------------------
660
660
661 If the input line begins with two exclamation marks, !!, the command is
661 If the input line begins with two exclamation marks, !!, the command is
662 executed but its output is captured and returned as a python list, split
662 executed but its output is captured and returned as a python list, split
663 on newlines. Any output sent by the subprocess to standard error is
663 on newlines. Any output sent by the subprocess to standard error is
664 printed separately, so that the resulting list only captures standard
664 printed separately, so that the resulting list only captures standard
665 output. The !! syntax is a shorthand for the %sx magic command.
665 output. The !! syntax is a shorthand for the %sx magic command.
666
666
667 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
667 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
668 but allowing more fine-grained control of the capture details, and
668 but allowing more fine-grained control of the capture details, and
669 storing the result directly into a named variable. The direct use of
669 storing the result directly into a named variable. The direct use of
670 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
670 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
671 instead.
671 instead.
672
672
673 IPython also allows you to expand the value of python variables when
673 IPython also allows you to expand the value of python variables when
674 making system calls. Any python variable or expression which you prepend
674 making system calls. Any python variable or expression which you prepend
675 with $ will get expanded before the system call is made::
675 with $ will get expanded before the system call is made::
676
676
677 In [1]: pyvar='Hello world'
677 In [1]: pyvar='Hello world'
678 In [2]: !echo "A python variable: $pyvar"
678 In [2]: !echo "A python variable: $pyvar"
679 A python variable: Hello world
679 A python variable: Hello world
680
680
681 If you want the shell to actually see a literal $, you need to type it
681 If you want the shell to actually see a literal $, you need to type it
682 twice::
682 twice::
683
683
684 In [3]: !echo "A system variable: $$HOME"
684 In [3]: !echo "A system variable: $$HOME"
685 A system variable: /home/fperez
685 A system variable: /home/fperez
686
686
687 You can pass arbitrary expressions, though you'll need to delimit them
687 You can pass arbitrary expressions, though you'll need to delimit them
688 with {} if there is ambiguity as to the extent of the expression::
688 with {} if there is ambiguity as to the extent of the expression::
689
689
690 In [5]: x=10
690 In [5]: x=10
691 In [6]: y=20
691 In [6]: y=20
692 In [13]: !echo $x+y
692 In [13]: !echo $x+y
693 10+y
693 10+y
694 In [7]: !echo ${x+y}
694 In [7]: !echo ${x+y}
695 30
695 30
696
696
697 Even object attributes can be expanded::
697 Even object attributes can be expanded::
698
698
699 In [12]: !echo $sys.argv
699 In [12]: !echo $sys.argv
700 [/home/fperez/usr/bin/ipython]
700 [/home/fperez/usr/bin/ipython]
701
701
702
702
703 System command aliases
703 System command aliases
704 ----------------------
704 ----------------------
705
705
706 The %alias magic function and the alias option in the ipythonrc
706 The %alias magic function and the alias option in the ipythonrc
707 configuration file allow you to define magic functions which are in fact
707 configuration file allow you to define magic functions which are in fact
708 system shell commands. These aliases can have parameters.
708 system shell commands. These aliases can have parameters.
709
709
710 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
710 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
711
711
712 Then, typing '%alias_name params' will execute the system command 'cmd
712 Then, typing '%alias_name params' will execute the system command 'cmd
713 params' (from your underlying operating system).
713 params' (from your underlying operating system).
714
714
715 You can also define aliases with parameters using %s specifiers (one per
715 You can also define aliases with parameters using %s specifiers (one per
716 parameter). The following example defines the %parts function as an
716 parameter). The following example defines the %parts function as an
717 alias to the command 'echo first %s second %s' where each %s will be
717 alias to the command 'echo first %s second %s' where each %s will be
718 replaced by a positional parameter to the call to %parts::
718 replaced by a positional parameter to the call to %parts::
719
719
720 In [1]: alias parts echo first %s second %s
720 In [1]: alias parts echo first %s second %s
721 In [2]: %parts A B
721 In [2]: %parts A B
722 first A second B
722 first A second B
723 In [3]: %parts A
723 In [3]: %parts A
724 Incorrect number of arguments: 2 expected.
724 Incorrect number of arguments: 2 expected.
725 parts is an alias to: 'echo first %s second %s'
725 parts is an alias to: 'echo first %s second %s'
726
726
727 If called with no parameters, %alias prints the table of currently
727 If called with no parameters, %alias prints the table of currently
728 defined aliases.
728 defined aliases.
729
729
730 The %rehash/rehashx magics allow you to load your entire $PATH as
730 The %rehash/rehashx magics allow you to load your entire $PATH as
731 ipython aliases. See their respective docstrings (or sec. 6.2
731 ipython aliases. See their respective docstrings (or sec. 6.2
732 <#sec:magic> for further details).
732 <#sec:magic> for further details).
733
733
734
734
735 .. _dreload:
735 .. _dreload:
736
736
737 Recursive reload
737 Recursive reload
738 ----------------
738 ----------------
739
739
740 The dreload function does a recursive reload of a module: changes made
740 The dreload function does a recursive reload of a module: changes made
741 to the module since you imported will actually be available without
741 to the module since you imported will actually be available without
742 having to exit.
742 having to exit.
743
743
744
744
745 Verbose and colored exception traceback printouts
745 Verbose and colored exception traceback printouts
746 -------------------------------------------------
746 -------------------------------------------------
747
747
748 IPython provides the option to see very detailed exception tracebacks,
748 IPython provides the option to see very detailed exception tracebacks,
749 which can be especially useful when debugging large programs. You can
749 which can be especially useful when debugging large programs. You can
750 run any Python file with the %run function to benefit from these
750 run any Python file with the %run function to benefit from these
751 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
751 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
752 be colored (if your terminal supports it) which makes them much easier
752 be colored (if your terminal supports it) which makes them much easier
753 to parse visually.
753 to parse visually.
754
754
755 See the magic xmode and colors functions for details (just type %magic).
755 See the magic xmode and colors functions for details (just type %magic).
756
756
757 These features are basically a terminal version of Ka-Ping Yee's cgitb
757 These features are basically a terminal version of Ka-Ping Yee's cgitb
758 module, now part of the standard Python library.
758 module, now part of the standard Python library.
759
759
760
760
761 .. _input_caching:
761 .. _input_caching:
762
762
763 Input caching system
763 Input caching system
764 --------------------
764 --------------------
765
765
766 IPython offers numbered prompts (In/Out) with input and output caching
766 IPython offers numbered prompts (In/Out) with input and output caching
767 (also referred to as 'input history'). All input is saved and can be
767 (also referred to as 'input history'). All input is saved and can be
768 retrieved as variables (besides the usual arrow key recall), in
768 retrieved as variables (besides the usual arrow key recall), in
769 addition to the %rep magic command that brings a history entry
769 addition to the %rep magic command that brings a history entry
770 up for editing on the next command line.
770 up for editing on the next command line.
771
771
772 The following GLOBAL variables always exist (so don't overwrite them!):
772 The following GLOBAL variables always exist (so don't overwrite them!):
773 _i: stores previous input. _ii: next previous. _iii: next-next previous.
773 _i: stores previous input. _ii: next previous. _iii: next-next previous.
774 _ih : a list of all input _ih[n] is the input from line n and this list
774 _ih : a list of all input _ih[n] is the input from line n and this list
775 is aliased to the global variable In. If you overwrite In with a
775 is aliased to the global variable In. If you overwrite In with a
776 variable of your own, you can remake the assignment to the internal list
776 variable of your own, you can remake the assignment to the internal list
777 with a simple 'In=_ih'.
777 with a simple 'In=_ih'.
778
778
779 Additionally, global variables named _i<n> are dynamically created (<n>
779 Additionally, global variables named _i<n> are dynamically created (<n>
780 being the prompt counter), such that
780 being the prompt counter), such that
781 _i<n> == _ih[<n>] == In[<n>].
781 _i<n> == _ih[<n>] == In[<n>].
782
782
783 For example, what you typed at prompt 14 is available as _i14, _ih[14]
783 For example, what you typed at prompt 14 is available as _i14, _ih[14]
784 and In[14].
784 and In[14].
785
785
786 This allows you to easily cut and paste multi line interactive prompts
786 This allows you to easily cut and paste multi line interactive prompts
787 by printing them out: they print like a clean string, without prompt
787 by printing them out: they print like a clean string, without prompt
788 characters. You can also manipulate them like regular variables (they
788 characters. You can also manipulate them like regular variables (they
789 are strings), modify or exec them (typing 'exec _i9' will re-execute the
789 are strings), modify or exec them (typing 'exec _i9' will re-execute the
790 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
790 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
791 9 through 13 and line 18).
791 9 through 13 and line 18).
792
792
793 You can also re-execute multiple lines of input easily by using the
793 You can also re-execute multiple lines of input easily by using the
794 magic %macro function (which automates the process and allows
794 magic %macro function (which automates the process and allows
795 re-execution without having to type 'exec' every time). The macro system
795 re-execution without having to type 'exec' every time). The macro system
796 also allows you to re-execute previous lines which include magic
796 also allows you to re-execute previous lines which include magic
797 function calls (which require special processing). Type %macro? or see
797 function calls (which require special processing). Type %macro? or see
798 sec. 6.2 <#sec:magic> for more details on the macro system.
798 sec. 6.2 <#sec:magic> for more details on the macro system.
799
799
800 A history function %hist allows you to see any part of your input
800 A history function %hist allows you to see any part of your input
801 history by printing a range of the _i variables.
801 history by printing a range of the _i variables.
802
802
803 You can also search ('grep') through your history by typing
803 You can also search ('grep') through your history by typing
804 '%hist -g somestring'. This also searches through the so called *shadow history*,
804 '%hist -g somestring'. This also searches through the so called *shadow history*,
805 which remembers all the commands (apart from multiline code blocks)
805 which remembers all the commands (apart from multiline code blocks)
806 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
806 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
807 etc. You can bring shadow history entries listed by '%hist -g' up for editing
807 etc. You can bring shadow history entries listed by '%hist -g' up for editing
808 (or re-execution by just pressing ENTER) with %rep command. Shadow history
808 (or re-execution by just pressing ENTER) with %rep command. Shadow history
809 entries are not available as _iNUMBER variables, and they are identified by
809 entries are not available as _iNUMBER variables, and they are identified by
810 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
810 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
811 history entry, but 0231 is a shadow history entry.
811 history entry, but 0231 is a shadow history entry.
812
812
813 Shadow history was added because the readline history is inherently very
813 Shadow history was added because the readline history is inherently very
814 unsafe - if you have multiple IPython sessions open, the last session
814 unsafe - if you have multiple IPython sessions open, the last session
815 to close will overwrite the history of previountly closed session. Likewise,
815 to close will overwrite the history of previountly closed session. Likewise,
816 if a crash occurs, history is never saved, whereas shadow history entries
816 if a crash occurs, history is never saved, whereas shadow history entries
817 are added after entering every command (so a command executed
817 are added after entering every command (so a command executed
818 in another IPython session is immediately available in other IPython
818 in another IPython session is immediately available in other IPython
819 sessions that are open).
819 sessions that are open).
820
820
821 To conserve space, a command can exist in shadow history only once - it doesn't
821 To conserve space, a command can exist in shadow history only once - it doesn't
822 make sense to store a common line like "cd .." a thousand times. The idea is
822 make sense to store a common line like "cd .." a thousand times. The idea is
823 mainly to provide a reliable place where valuable, hard-to-remember commands can
823 mainly to provide a reliable place where valuable, hard-to-remember commands can
824 always be retrieved, as opposed to providing an exact sequence of commands
824 always be retrieved, as opposed to providing an exact sequence of commands
825 you have entered in actual order.
825 you have entered in actual order.
826
826
827 Because shadow history has all the commands you have ever executed,
827 Because shadow history has all the commands you have ever executed,
828 time taken by %hist -g will increase oven time. If it ever starts to take
828 time taken by %hist -g will increase oven time. If it ever starts to take
829 too long (or it ends up containing sensitive information like passwords),
829 too long (or it ends up containing sensitive information like passwords),
830 clear the shadow history by `%clear shadow_nuke`.
830 clear the shadow history by `%clear shadow_nuke`.
831
831
832 Time taken to add entries to shadow history should be negligible, but
832 Time taken to add entries to shadow history should be negligible, but
833 in any case, if you start noticing performance degradation after using
833 in any case, if you start noticing performance degradation after using
834 IPython for a long time (or running a script that floods the shadow history!),
834 IPython for a long time (or running a script that floods the shadow history!),
835 you can 'compress' the shadow history by executing
835 you can 'compress' the shadow history by executing
836 `%clear shadow_compress`. In practice, this should never be necessary
836 `%clear shadow_compress`. In practice, this should never be necessary
837 in normal use.
837 in normal use.
838
838
839 .. _output_caching:
839 .. _output_caching:
840
840
841 Output caching system
841 Output caching system
842 ---------------------
842 ---------------------
843
843
844 For output that is returned from actions, a system similar to the input
844 For output that is returned from actions, a system similar to the input
845 cache exists but using _ instead of _i. Only actions that produce a
845 cache exists but using _ instead of _i. Only actions that produce a
846 result (NOT assignments, for example) are cached. If you are familiar
846 result (NOT assignments, for example) are cached. If you are familiar
847 with Mathematica, IPython's _ variables behave exactly like
847 with Mathematica, IPython's _ variables behave exactly like
848 Mathematica's % variables.
848 Mathematica's % variables.
849
849
850 The following GLOBAL variables always exist (so don't overwrite them!):
850 The following GLOBAL variables always exist (so don't overwrite them!):
851
851
852 * [_] (a single underscore) : stores previous output, like Python's
852 * [_] (a single underscore) : stores previous output, like Python's
853 default interpreter.
853 default interpreter.
854 * [__] (two underscores): next previous.
854 * [__] (two underscores): next previous.
855 * [___] (three underscores): next-next previous.
855 * [___] (three underscores): next-next previous.
856
856
857 Additionally, global variables named _<n> are dynamically created (<n>
857 Additionally, global variables named _<n> are dynamically created (<n>
858 being the prompt counter), such that the result of output <n> is always
858 being the prompt counter), such that the result of output <n> is always
859 available as _<n> (don't use the angle brackets, just the number, e.g.
859 available as _<n> (don't use the angle brackets, just the number, e.g.
860 _21).
860 _21).
861
861
862 These global variables are all stored in a global dictionary (not a
862 These global variables are all stored in a global dictionary (not a
863 list, since it only has entries for lines which returned a result)
863 list, since it only has entries for lines which returned a result)
864 available under the names _oh and Out (similar to _ih and In). So the
864 available under the names _oh and Out (similar to _ih and In). So the
865 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
865 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
866 accidentally overwrite the Out variable you can recover it by typing
866 accidentally overwrite the Out variable you can recover it by typing
867 'Out=_oh' at the prompt.
867 'Out=_oh' at the prompt.
868
868
869 This system obviously can potentially put heavy memory demands on your
869 This system obviously can potentially put heavy memory demands on your
870 system, since it prevents Python's garbage collector from removing any
870 system, since it prevents Python's garbage collector from removing any
871 previously computed results. You can control how many results are kept
871 previously computed results. You can control how many results are kept
872 in memory with the option (at the command line or in your ipythonrc
872 in memory with the option (at the command line or in your ipythonrc
873 file) cache_size. If you set it to 0, the whole system is completely
873 file) cache_size. If you set it to 0, the whole system is completely
874 disabled and the prompts revert to the classic '>>>' of normal Python.
874 disabled and the prompts revert to the classic '>>>' of normal Python.
875
875
876
876
877 Directory history
877 Directory history
878 -----------------
878 -----------------
879
879
880 Your history of visited directories is kept in the global list _dh, and
880 Your history of visited directories is kept in the global list _dh, and
881 the magic %cd command can be used to go to any entry in that list. The
881 the magic %cd command can be used to go to any entry in that list. The
882 %dhist command allows you to view this history. Do ``cd -<TAB`` to
882 %dhist command allows you to view this history. Do ``cd -<TAB`` to
883 conventiently view the directory history.
883 conventiently view the directory history.
884
884
885
885
886 Automatic parentheses and quotes
886 Automatic parentheses and quotes
887 --------------------------------
887 --------------------------------
888
888
889 These features were adapted from Nathan Gray's LazyPython. They are
889 These features were adapted from Nathan Gray's LazyPython. They are
890 meant to allow less typing for common situations.
890 meant to allow less typing for common situations.
891
891
892
892
893 Automatic parentheses
893 Automatic parentheses
894 ---------------------
894 ---------------------
895
895
896 Callable objects (i.e. functions, methods, etc) can be invoked like this
896 Callable objects (i.e. functions, methods, etc) can be invoked like this
897 (notice the commas between the arguments)::
897 (notice the commas between the arguments)::
898
898
899 >>> callable_ob arg1, arg2, arg3
899 >>> callable_ob arg1, arg2, arg3
900
900
901 and the input will be translated to this::
901 and the input will be translated to this::
902
902
903 -> callable_ob(arg1, arg2, arg3)
903 -> callable_ob(arg1, arg2, arg3)
904
904
905 You can force automatic parentheses by using '/' as the first character
905 You can force automatic parentheses by using '/' as the first character
906 of a line. For example::
906 of a line. For example::
907
907
908 >>> /globals # becomes 'globals()'
908 >>> /globals # becomes 'globals()'
909
909
910 Note that the '/' MUST be the first character on the line! This won't work::
910 Note that the '/' MUST be the first character on the line! This won't work::
911
911
912 >>> print /globals # syntax error
912 >>> print /globals # syntax error
913
913
914 In most cases the automatic algorithm should work, so you should rarely
914 In most cases the automatic algorithm should work, so you should rarely
915 need to explicitly invoke /. One notable exception is if you are trying
915 need to explicitly invoke /. One notable exception is if you are trying
916 to call a function with a list of tuples as arguments (the parenthesis
916 to call a function with a list of tuples as arguments (the parenthesis
917 will confuse IPython)::
917 will confuse IPython)::
918
918
919 In [1]: zip (1,2,3),(4,5,6) # won't work
919 In [1]: zip (1,2,3),(4,5,6) # won't work
920
920
921 but this will work::
921 but this will work::
922
922
923 In [2]: /zip (1,2,3),(4,5,6)
923 In [2]: /zip (1,2,3),(4,5,6)
924 ---> zip ((1,2,3),(4,5,6))
924 ---> zip ((1,2,3),(4,5,6))
925 Out[2]= [(1, 4), (2, 5), (3, 6)]
925 Out[2]= [(1, 4), (2, 5), (3, 6)]
926
926
927 IPython tells you that it has altered your command line by displaying
927 IPython tells you that it has altered your command line by displaying
928 the new command line preceded by ->. e.g.::
928 the new command line preceded by ->. e.g.::
929
929
930 In [18]: callable list
930 In [18]: callable list
931 ----> callable (list)
931 ----> callable (list)
932
932
933
933
934 Automatic quoting
934 Automatic quoting
935 -----------------
935 -----------------
936
936
937 You can force automatic quoting of a function's arguments by using ','
937 You can force automatic quoting of a function's arguments by using ','
938 or ';' as the first character of a line. For example::
938 or ';' as the first character of a line. For example::
939
939
940 >>> ,my_function /home/me # becomes my_function("/home/me")
940 >>> ,my_function /home/me # becomes my_function("/home/me")
941
941
942 If you use ';' instead, the whole argument is quoted as a single string
942 If you use ';' instead, the whole argument is quoted as a single string
943 (while ',' splits on whitespace)::
943 (while ',' splits on whitespace)::
944
944
945 >>> ,my_function a b c # becomes my_function("a","b","c")
945 >>> ,my_function a b c # becomes my_function("a","b","c")
946
946
947 >>> ;my_function a b c # becomes my_function("a b c")
947 >>> ;my_function a b c # becomes my_function("a b c")
948
948
949 Note that the ',' or ';' MUST be the first character on the line! This
949 Note that the ',' or ';' MUST be the first character on the line! This
950 won't work::
950 won't work::
951
951
952 >>> x = ,my_function /home/me # syntax error
952 >>> x = ,my_function /home/me # syntax error
953
953
954 IPython as your default Python environment
954 IPython as your default Python environment
955 ==========================================
955 ==========================================
956
956
957 Python honors the environment variable PYTHONSTARTUP and will execute at
957 Python honors the environment variable PYTHONSTARTUP and will execute at
958 startup the file referenced by this variable. If you put at the end of
958 startup the file referenced by this variable. If you put at the end of
959 this file the following two lines of code::
959 this file the following two lines of code::
960
960
961 import IPython
961 import IPython
962 IPython.Shell.IPShell().mainloop(sys_exit=1)
962 IPython.Shell.IPShell().mainloop(sys_exit=1)
963
963
964 then IPython will be your working environment anytime you start Python.
964 then IPython will be your working environment anytime you start Python.
965 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
965 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
966 it finishes, otherwise you'll be back at the normal Python '>>>'
966 it finishes, otherwise you'll be back at the normal Python '>>>'
967 prompt.
967 prompt.
968
968
969 This is probably useful to developers who manage multiple Python
969 This is probably useful to developers who manage multiple Python
970 versions and don't want to have correspondingly multiple IPython
970 versions and don't want to have correspondingly multiple IPython
971 versions. Note that in this mode, there is no way to pass IPython any
971 versions. Note that in this mode, there is no way to pass IPython any
972 command-line options, as those are trapped first by Python itself.
972 command-line options, as those are trapped first by Python itself.
973
973
974 .. _Embedding:
974 .. _Embedding:
975
975
976 Embedding IPython
976 Embedding IPython
977 =================
977 =================
978
978
979 It is possible to start an IPython instance inside your own Python
979 It is possible to start an IPython instance inside your own Python
980 programs. This allows you to evaluate dynamically the state of your
980 programs. This allows you to evaluate dynamically the state of your
981 code, operate with your variables, analyze them, etc. Note however that
981 code, operate with your variables, analyze them, etc. Note however that
982 any changes you make to values while in the shell do not propagate back
982 any changes you make to values while in the shell do not propagate back
983 to the running code, so it is safe to modify your values because you
983 to the running code, so it is safe to modify your values because you
984 won't break your code in bizarre ways by doing so.
984 won't break your code in bizarre ways by doing so.
985
985
986 This feature allows you to easily have a fully functional python
986 This feature allows you to easily have a fully functional python
987 environment for doing object introspection anywhere in your code with a
987 environment for doing object introspection anywhere in your code with a
988 simple function call. In some cases a simple print statement is enough,
988 simple function call. In some cases a simple print statement is enough,
989 but if you need to do more detailed analysis of a code fragment this
989 but if you need to do more detailed analysis of a code fragment this
990 feature can be very valuable.
990 feature can be very valuable.
991
991
992 It can also be useful in scientific computing situations where it is
992 It can also be useful in scientific computing situations where it is
993 common to need to do some automatic, computationally intensive part and
993 common to need to do some automatic, computationally intensive part and
994 then stop to look at data, plots, etc.
994 then stop to look at data, plots, etc.
995 Opening an IPython instance will give you full access to your data and
995 Opening an IPython instance will give you full access to your data and
996 functions, and you can resume program execution once you are done with
996 functions, and you can resume program execution once you are done with
997 the interactive part (perhaps to stop again later, as many times as
997 the interactive part (perhaps to stop again later, as many times as
998 needed).
998 needed).
999
999
1000 The following code snippet is the bare minimum you need to include in
1000 The following code snippet is the bare minimum you need to include in
1001 your Python programs for this to work (detailed examples follow later)::
1001 your Python programs for this to work (detailed examples follow later)::
1002
1002
1003 from IPython.Shell import IPShellEmbed
1003 from IPython.Shell import IPShellEmbed
1004
1004
1005 ipshell = IPShellEmbed()
1005 ipshell = IPShellEmbed()
1006
1006
1007 ipshell() # this call anywhere in your program will start IPython
1007 ipshell() # this call anywhere in your program will start IPython
1008
1008
1009 You can run embedded instances even in code which is itself being run at
1009 You can run embedded instances even in code which is itself being run at
1010 the IPython interactive prompt with '%run <filename>'. Since it's easy
1010 the IPython interactive prompt with '%run <filename>'. Since it's easy
1011 to get lost as to where you are (in your top-level IPython or in your
1011 to get lost as to where you are (in your top-level IPython or in your
1012 embedded one), it's a good idea in such cases to set the in/out prompts
1012 embedded one), it's a good idea in such cases to set the in/out prompts
1013 to something different for the embedded instances. The code examples
1013 to something different for the embedded instances. The code examples
1014 below illustrate this.
1014 below illustrate this.
1015
1015
1016 You can also have multiple IPython instances in your program and open
1016 You can also have multiple IPython instances in your program and open
1017 them separately, for example with different options for data
1017 them separately, for example with different options for data
1018 presentation. If you close and open the same instance multiple times,
1018 presentation. If you close and open the same instance multiple times,
1019 its prompt counters simply continue from each execution to the next.
1019 its prompt counters simply continue from each execution to the next.
1020
1020
1021 Please look at the docstrings in the Shell.py module for more details on
1021 Please look at the docstrings in the Shell.py module for more details on
1022 the use of this system.
1022 the use of this system.
1023
1023
1024 The following sample file illustrating how to use the embedding
1024 The following sample file illustrating how to use the embedding
1025 functionality is provided in the examples directory as example-embed.py.
1025 functionality is provided in the examples directory as example-embed.py.
1026 It should be fairly self-explanatory::
1026 It should be fairly self-explanatory::
1027
1027
1028
1028
1029 #!/usr/bin/env python
1029 #!/usr/bin/env python
1030
1030
1031 """An example of how to embed an IPython shell into a running program.
1031 """An example of how to embed an IPython shell into a running program.
1032
1032
1033 Please see the documentation in the IPython.Shell module for more details.
1033 Please see the documentation in the IPython.Shell module for more details.
1034
1034
1035 The accompanying file example-embed-short.py has quick code fragments for
1035 The accompanying file example-embed-short.py has quick code fragments for
1036 embedding which you can cut and paste in your code once you understand how
1036 embedding which you can cut and paste in your code once you understand how
1037 things work.
1037 things work.
1038
1038
1039 The code in this file is deliberately extra-verbose, meant for learning."""
1039 The code in this file is deliberately extra-verbose, meant for learning."""
1040
1040
1041 # The basics to get you going:
1041 # The basics to get you going:
1042
1042
1043 # IPython sets the __IPYTHON__ variable so you can know if you have nested
1043 # IPython sets the __IPYTHON__ variable so you can know if you have nested
1044 # copies running.
1044 # copies running.
1045
1045
1046 # Try running this code both at the command line and from inside IPython (with
1046 # Try running this code both at the command line and from inside IPython (with
1047 # %run example-embed.py)
1047 # %run example-embed.py)
1048 try:
1048 try:
1049 __IPYTHON__
1049 __IPYTHON__
1050 except NameError:
1050 except NameError:
1051 nested = 0
1051 nested = 0
1052 args = ['']
1052 args = ['']
1053 else:
1053 else:
1054 print "Running nested copies of IPython."
1054 print "Running nested copies of IPython."
1055 print "The prompts for the nested copy have been modified"
1055 print "The prompts for the nested copy have been modified"
1056 nested = 1
1056 nested = 1
1057 # what the embedded instance will see as sys.argv:
1057 # what the embedded instance will see as sys.argv:
1058 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
1058 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
1059 '-po','Out<\\#>: ','-nosep']
1059 '-po','Out<\\#>: ','-nosep']
1060
1060
1061 # First import the embeddable shell class
1061 # First import the embeddable shell class
1062 from IPython.Shell import IPShellEmbed
1062 from IPython.Shell import IPShellEmbed
1063
1063
1064 # Now create an instance of the embeddable shell. The first argument is a
1064 # Now create an instance of the embeddable shell. The first argument is a
1065 # string with options exactly as you would type them if you were starting
1065 # string with options exactly as you would type them if you were starting
1066 # IPython at the system command line. Any parameters you want to define for
1066 # IPython at the system command line. Any parameters you want to define for
1067 # configuration can thus be specified here.
1067 # configuration can thus be specified here.
1068 ipshell = IPShellEmbed(args,
1068 ipshell = IPShellEmbed(args,
1069 banner = 'Dropping into IPython',
1069 banner = 'Dropping into IPython',
1070 exit_msg = 'Leaving Interpreter, back to program.')
1070 exit_msg = 'Leaving Interpreter, back to program.')
1071
1071
1072 # Make a second instance, you can have as many as you want.
1072 # Make a second instance, you can have as many as you want.
1073 if nested:
1073 if nested:
1074 args[1] = 'In2<\\#>'
1074 args[1] = 'In2<\\#>'
1075 else:
1075 else:
1076 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
1076 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
1077 '-po','Out<\\#>: ','-nosep']
1077 '-po','Out<\\#>: ','-nosep']
1078 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
1078 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
1079
1079
1080 print '\nHello. This is printed from the main controller program.\n'
1080 print '\nHello. This is printed from the main controller program.\n'
1081
1081
1082 # You can then call ipshell() anywhere you need it (with an optional
1082 # You can then call ipshell() anywhere you need it (with an optional
1083 # message):
1083 # message):
1084 ipshell('***Called from top level. '
1084 ipshell('***Called from top level. '
1085 'Hit Ctrl-D to exit interpreter and continue program.\n'
1085 'Hit Ctrl-D to exit interpreter and continue program.\n'
1086 'Note that if you use %kill_embedded, you can fully deactivate\n'
1086 'Note that if you use %kill_embedded, you can fully deactivate\n'
1087 'This embedded instance so it will never turn on again')
1087 'This embedded instance so it will never turn on again')
1088
1088
1089 print '\nBack in caller program, moving along...\n'
1089 print '\nBack in caller program, moving along...\n'
1090
1090
1091 #---------------------------------------------------------------------------
1091 #---------------------------------------------------------------------------
1092 # More details:
1092 # More details:
1093
1093
1094 # IPShellEmbed instances don't print the standard system banner and
1094 # IPShellEmbed instances don't print the standard system banner and
1095 # messages. The IPython banner (which actually may contain initialization
1095 # messages. The IPython banner (which actually may contain initialization
1096 # messages) is available as <instance>.IP.BANNER in case you want it.
1096 # messages) is available as <instance>.IP.BANNER in case you want it.
1097
1097
1098 # IPShellEmbed instances print the following information everytime they
1098 # IPShellEmbed instances print the following information everytime they
1099 # start:
1099 # start:
1100
1100
1101 # - A global startup banner.
1101 # - A global startup banner.
1102
1102
1103 # - A call-specific header string, which you can use to indicate where in the
1103 # - A call-specific header string, which you can use to indicate where in the
1104 # execution flow the shell is starting.
1104 # execution flow the shell is starting.
1105
1105
1106 # They also print an exit message every time they exit.
1106 # They also print an exit message every time they exit.
1107
1107
1108 # Both the startup banner and the exit message default to None, and can be set
1108 # Both the startup banner and the exit message default to None, and can be set
1109 # either at the instance constructor or at any other time with the
1109 # either at the instance constructor or at any other time with the
1110 # set_banner() and set_exit_msg() methods.
1110 # set_banner() and set_exit_msg() methods.
1111
1111
1112 # The shell instance can be also put in 'dummy' mode globally or on a per-call
1112 # The shell instance can be also put in 'dummy' mode globally or on a per-call
1113 # basis. This gives you fine control for debugging without having to change
1113 # basis. This gives you fine control for debugging without having to change
1114 # code all over the place.
1114 # code all over the place.
1115
1115
1116 # The code below illustrates all this.
1116 # The code below illustrates all this.
1117
1117
1118
1118
1119 # This is how the global banner and exit_msg can be reset at any point
1119 # This is how the global banner and exit_msg can be reset at any point
1120 ipshell.set_banner('Entering interpreter - New Banner')
1120 ipshell.set_banner('Entering interpreter - New Banner')
1121 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
1121 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
1122
1122
1123 def foo(m):
1123 def foo(m):
1124 s = 'spam'
1124 s = 'spam'
1125 ipshell('***In foo(). Try @whos, or print s or m:')
1125 ipshell('***In foo(). Try @whos, or print s or m:')
1126 print 'foo says m = ',m
1126 print 'foo says m = ',m
1127
1127
1128 def bar(n):
1128 def bar(n):
1129 s = 'eggs'
1129 s = 'eggs'
1130 ipshell('***In bar(). Try @whos, or print s or n:')
1130 ipshell('***In bar(). Try @whos, or print s or n:')
1131 print 'bar says n = ',n
1131 print 'bar says n = ',n
1132
1132
1133 # Some calls to the above functions which will trigger IPython:
1133 # Some calls to the above functions which will trigger IPython:
1134 print 'Main program calling foo("eggs")\n'
1134 print 'Main program calling foo("eggs")\n'
1135 foo('eggs')
1135 foo('eggs')
1136
1136
1137 # The shell can be put in 'dummy' mode where calls to it silently return. This
1137 # The shell can be put in 'dummy' mode where calls to it silently return. This
1138 # allows you, for example, to globally turn off debugging for a program with a
1138 # allows you, for example, to globally turn off debugging for a program with a
1139 # single call.
1139 # single call.
1140 ipshell.set_dummy_mode(1)
1140 ipshell.set_dummy_mode(1)
1141 print '\nTrying to call IPython which is now "dummy":'
1141 print '\nTrying to call IPython which is now "dummy":'
1142 ipshell()
1142 ipshell()
1143 print 'Nothing happened...'
1143 print 'Nothing happened...'
1144 # The global 'dummy' mode can still be overridden for a single call
1144 # The global 'dummy' mode can still be overridden for a single call
1145 print '\nOverriding dummy mode manually:'
1145 print '\nOverriding dummy mode manually:'
1146 ipshell(dummy=0)
1146 ipshell(dummy=0)
1147
1147
1148 # Reactivate the IPython shell
1148 # Reactivate the IPython shell
1149 ipshell.set_dummy_mode(0)
1149 ipshell.set_dummy_mode(0)
1150
1150
1151 print 'You can even have multiple embedded instances:'
1151 print 'You can even have multiple embedded instances:'
1152 ipshell2()
1152 ipshell2()
1153
1153
1154 print '\nMain program calling bar("spam")\n'
1154 print '\nMain program calling bar("spam")\n'
1155 bar('spam')
1155 bar('spam')
1156
1156
1157 print 'Main program finished. Bye!'
1157 print 'Main program finished. Bye!'
1158
1158
1159 #********************** End of file <example-embed.py> ***********************
1159 #********************** End of file <example-embed.py> ***********************
1160
1160
1161 Once you understand how the system functions, you can use the following
1161 Once you understand how the system functions, you can use the following
1162 code fragments in your programs which are ready for cut and paste::
1162 code fragments in your programs which are ready for cut and paste::
1163
1163
1164
1164
1165 """Quick code snippets for embedding IPython into other programs.
1165 """Quick code snippets for embedding IPython into other programs.
1166
1166
1167 See example-embed.py for full details, this file has the bare minimum code for
1167 See example-embed.py for full details, this file has the bare minimum code for
1168 cut and paste use once you understand how to use the system."""
1168 cut and paste use once you understand how to use the system."""
1169
1169
1170 #---------------------------------------------------------------------------
1170 #---------------------------------------------------------------------------
1171 # This code loads IPython but modifies a few things if it detects it's running
1171 # This code loads IPython but modifies a few things if it detects it's running
1172 # embedded in another IPython session (helps avoid confusion)
1172 # embedded in another IPython session (helps avoid confusion)
1173
1173
1174 try:
1174 try:
1175 __IPYTHON__
1175 __IPYTHON__
1176 except NameError:
1176 except NameError:
1177 argv = ['']
1177 argv = ['']
1178 banner = exit_msg = ''
1178 banner = exit_msg = ''
1179 else:
1179 else:
1180 # Command-line options for IPython (a list like sys.argv)
1180 # Command-line options for IPython (a list like sys.argv)
1181 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
1181 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
1182 banner = '*** Nested interpreter ***'
1182 banner = '*** Nested interpreter ***'
1183 exit_msg = '*** Back in main IPython ***'
1183 exit_msg = '*** Back in main IPython ***'
1184
1184
1185 # First import the embeddable shell class
1185 # First import the embeddable shell class
1186 from IPython.Shell import IPShellEmbed
1186 from IPython.Shell import IPShellEmbed
1187 # Now create the IPython shell instance. Put ipshell() anywhere in your code
1187 # Now create the IPython shell instance. Put ipshell() anywhere in your code
1188 # where you want it to open.
1188 # where you want it to open.
1189 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
1189 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
1190
1190
1191 #---------------------------------------------------------------------------
1191 #---------------------------------------------------------------------------
1192 # This code will load an embeddable IPython shell always with no changes for
1192 # This code will load an embeddable IPython shell always with no changes for
1193 # nested embededings.
1193 # nested embededings.
1194
1194
1195 from IPython.Shell import IPShellEmbed
1195 from IPython.Shell import IPShellEmbed
1196 ipshell = IPShellEmbed()
1196 ipshell = IPShellEmbed()
1197 # Now ipshell() will open IPython anywhere in the code.
1197 # Now ipshell() will open IPython anywhere in the code.
1198
1198
1199 #---------------------------------------------------------------------------
1199 #---------------------------------------------------------------------------
1200 # This code loads an embeddable shell only if NOT running inside
1200 # This code loads an embeddable shell only if NOT running inside
1201 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
1201 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
1202 # dummy function.
1202 # dummy function.
1203
1203
1204 try:
1204 try:
1205 __IPYTHON__
1205 __IPYTHON__
1206 except NameError:
1206 except NameError:
1207 from IPython.Shell import IPShellEmbed
1207 from IPython.Shell import IPShellEmbed
1208 ipshell = IPShellEmbed()
1208 ipshell = IPShellEmbed()
1209 # Now ipshell() will open IPython anywhere in the code
1209 # Now ipshell() will open IPython anywhere in the code
1210 else:
1210 else:
1211 # Define a dummy ipshell() so the same code doesn't crash inside an
1211 # Define a dummy ipshell() so the same code doesn't crash inside an
1212 # interactive IPython
1212 # interactive IPython
1213 def ipshell(): pass
1213 def ipshell(): pass
1214
1214
1215 #******************* End of file <example-embed-short.py> ********************
1215 #******************* End of file <example-embed-short.py> ********************
1216
1216
1217 Using the Python debugger (pdb)
1217 Using the Python debugger (pdb)
1218 ===============================
1218 ===============================
1219
1219
1220 Running entire programs via pdb
1220 Running entire programs via pdb
1221 -------------------------------
1221 -------------------------------
1222
1222
1223 pdb, the Python debugger, is a powerful interactive debugger which
1223 pdb, the Python debugger, is a powerful interactive debugger which
1224 allows you to step through code, set breakpoints, watch variables,
1224 allows you to step through code, set breakpoints, watch variables,
1225 etc. IPython makes it very easy to start any script under the control
1225 etc. IPython makes it very easy to start any script under the control
1226 of pdb, regardless of whether you have wrapped it into a 'main()'
1226 of pdb, regardless of whether you have wrapped it into a 'main()'
1227 function or not. For this, simply type '%run -d myscript' at an
1227 function or not. For this, simply type '%run -d myscript' at an
1228 IPython prompt. See the %run command's documentation (via '%run?' or
1228 IPython prompt. See the %run command's documentation (via '%run?' or
1229 in Sec. magic_ for more details, including how to control where pdb
1229 in Sec. magic_ for more details, including how to control where pdb
1230 will stop execution first.
1230 will stop execution first.
1231
1231
1232 For more information on the use of the pdb debugger, read the included
1232 For more information on the use of the pdb debugger, read the included
1233 pdb.doc file (part of the standard Python distribution). On a stock
1233 pdb.doc file (part of the standard Python distribution). On a stock
1234 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1234 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1235 easiest way to read it is by using the help() function of the pdb module
1235 easiest way to read it is by using the help() function of the pdb module
1236 as follows (in an IPython prompt):
1236 as follows (in an IPython prompt):
1237
1237
1238 In [1]: import pdb
1238 In [1]: import pdb
1239 In [2]: pdb.help()
1239 In [2]: pdb.help()
1240
1240
1241 This will load the pdb.doc document in a file viewer for you automatically.
1241 This will load the pdb.doc document in a file viewer for you automatically.
1242
1242
1243
1243
1244 Automatic invocation of pdb on exceptions
1244 Automatic invocation of pdb on exceptions
1245 -----------------------------------------
1245 -----------------------------------------
1246
1246
1247 IPython, if started with the -pdb option (or if the option is set in
1247 IPython, if started with the -pdb option (or if the option is set in
1248 your rc file) can call the Python pdb debugger every time your code
1248 your rc file) can call the Python pdb debugger every time your code
1249 triggers an uncaught exception. This feature
1249 triggers an uncaught exception. This feature
1250 can also be toggled at any time with the %pdb magic command. This can be
1250 can also be toggled at any time with the %pdb magic command. This can be
1251 extremely useful in order to find the origin of subtle bugs, because pdb
1251 extremely useful in order to find the origin of subtle bugs, because pdb
1252 opens up at the point in your code which triggered the exception, and
1252 opens up at the point in your code which triggered the exception, and
1253 while your program is at this point 'dead', all the data is still
1253 while your program is at this point 'dead', all the data is still
1254 available and you can walk up and down the stack frame and understand
1254 available and you can walk up and down the stack frame and understand
1255 the origin of the problem.
1255 the origin of the problem.
1256
1256
1257 Furthermore, you can use these debugging facilities both with the
1257 Furthermore, you can use these debugging facilities both with the
1258 embedded IPython mode and without IPython at all. For an embedded shell
1258 embedded IPython mode and without IPython at all. For an embedded shell
1259 (see sec. Embedding_), simply call the constructor with
1259 (see sec. Embedding_), simply call the constructor with
1260 '-pdb' in the argument string and automatically pdb will be called if an
1260 '-pdb' in the argument string and automatically pdb will be called if an
1261 uncaught exception is triggered by your code.
1261 uncaught exception is triggered by your code.
1262
1262
1263 For stand-alone use of the feature in your programs which do not use
1263 For stand-alone use of the feature in your programs which do not use
1264 IPython at all, put the following lines toward the top of your 'main'
1264 IPython at all, put the following lines toward the top of your 'main'
1265 routine::
1265 routine::
1266
1266
1267 import sys
1267 import sys
1268 from IPython.core import ultratb
1268 from IPython.core import ultratb
1269 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1269 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1270 color_scheme='Linux', call_pdb=1)
1270 color_scheme='Linux', call_pdb=1)
1271
1271
1272 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1272 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1273 detailed or normal tracebacks respectively. The color_scheme keyword can
1273 detailed or normal tracebacks respectively. The color_scheme keyword can
1274 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1274 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1275 options which can be set in IPython with -colors and -xmode.
1275 options which can be set in IPython with -colors and -xmode.
1276
1276
1277 This will give any of your programs detailed, colored tracebacks with
1277 This will give any of your programs detailed, colored tracebacks with
1278 automatic invocation of pdb.
1278 automatic invocation of pdb.
1279
1279
1280
1280
1281 Extensions for syntax processing
1281 Extensions for syntax processing
1282 ================================
1282 ================================
1283
1283
1284 This isn't for the faint of heart, because the potential for breaking
1284 This isn't for the faint of heart, because the potential for breaking
1285 things is quite high. But it can be a very powerful and useful feature.
1285 things is quite high. But it can be a very powerful and useful feature.
1286 In a nutshell, you can redefine the way IPython processes the user input
1286 In a nutshell, you can redefine the way IPython processes the user input
1287 line to accept new, special extensions to the syntax without needing to
1287 line to accept new, special extensions to the syntax without needing to
1288 change any of IPython's own code.
1288 change any of IPython's own code.
1289
1289
1290 In the IPython/extensions directory you will find some examples
1290 In the IPython/extensions directory you will find some examples
1291 supplied, which we will briefly describe now. These can be used 'as is'
1291 supplied, which we will briefly describe now. These can be used 'as is'
1292 (and both provide very useful functionality), or you can use them as a
1292 (and both provide very useful functionality), or you can use them as a
1293 starting point for writing your own extensions.
1293 starting point for writing your own extensions.
1294
1294
1295
1295
1296 Pasting of code starting with '>>> ' or '... '
1296 Pasting of code starting with '>>> ' or '... '
1297 ----------------------------------------------
1297 ----------------------------------------------
1298
1298
1299 In the python tutorial it is common to find code examples which have
1299 In the python tutorial it is common to find code examples which have
1300 been taken from real python sessions. The problem with those is that all
1300 been taken from real python sessions. The problem with those is that all
1301 the lines begin with either '>>> ' or '... ', which makes it impossible
1301 the lines begin with either '>>> ' or '... ', which makes it impossible
1302 to paste them all at once. One must instead do a line by line manual
1302 to paste them all at once. One must instead do a line by line manual
1303 copying, carefully removing the leading extraneous characters.
1303 copying, carefully removing the leading extraneous characters.
1304
1304
1305 This extension identifies those starting characters and removes them
1305 This extension identifies those starting characters and removes them
1306 from the input automatically, so that one can paste multi-line examples
1306 from the input automatically, so that one can paste multi-line examples
1307 directly into IPython, saving a lot of time. Please look at the file
1307 directly into IPython, saving a lot of time. Please look at the file
1308 InterpreterPasteInput.py in the IPython/extensions directory for details
1308 InterpreterPasteInput.py in the IPython/extensions directory for details
1309 on how this is done.
1309 on how this is done.
1310
1310
1311 IPython comes with a special profile enabling this feature, called
1311 IPython comes with a special profile enabling this feature, called
1312 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1312 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1313 will be available. In a normal IPython session you can activate the
1313 will be available. In a normal IPython session you can activate the
1314 feature by importing the corresponding module with:
1314 feature by importing the corresponding module with:
1315 In [1]: import IPython.extensions.InterpreterPasteInput
1315 In [1]: import IPython.extensions.InterpreterPasteInput
1316
1316
1317 The following is a 'screenshot' of how things work when this extension
1317 The following is a 'screenshot' of how things work when this extension
1318 is on, copying an example from the standard tutorial::
1318 is on, copying an example from the standard tutorial::
1319
1319
1320 IPython profile: tutorial
1320 IPython profile: tutorial
1321
1321
1322 *** Pasting of code with ">>>" or "..." has been enabled.
1322 *** Pasting of code with ">>>" or "..." has been enabled.
1323
1323
1324 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1324 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1325 ...: ... """Return a list containing the Fibonacci series up to
1325 ...: ... """Return a list containing the Fibonacci series up to
1326 n."""
1326 n."""
1327 ...: ... result = []
1327 ...: ... result = []
1328 ...: ... a, b = 0, 1
1328 ...: ... a, b = 0, 1
1329 ...: ... while b < n:
1329 ...: ... while b < n:
1330 ...: ... result.append(b) # see below
1330 ...: ... result.append(b) # see below
1331 ...: ... a, b = b, a+b
1331 ...: ... a, b = b, a+b
1332 ...: ... return result
1332 ...: ... return result
1333 ...:
1333 ...:
1334
1334
1335 In [2]: fib2(10)
1335 In [2]: fib2(10)
1336 Out[2]: [1, 1, 2, 3, 5, 8]
1336 Out[2]: [1, 1, 2, 3, 5, 8]
1337
1337
1338 Note that as currently written, this extension does not recognize
1338 Note that as currently written, this extension does not recognize
1339 IPython's prompts for pasting. Those are more complicated, since the
1339 IPython's prompts for pasting. Those are more complicated, since the
1340 user can change them very easily, they involve numbers and can vary in
1340 user can change them very easily, they involve numbers and can vary in
1341 length. One could however extract all the relevant information from the
1341 length. One could however extract all the relevant information from the
1342 IPython instance and build an appropriate regular expression. This is
1342 IPython instance and build an appropriate regular expression. This is
1343 left as an exercise for the reader.
1343 left as an exercise for the reader.
1344
1344
1345
1345
1346 Input of physical quantities with units
1346 Input of physical quantities with units
1347 ---------------------------------------
1347 ---------------------------------------
1348
1348
1349 The module PhysicalQInput allows a simplified form of input for physical
1349 The module PhysicalQInput allows a simplified form of input for physical
1350 quantities with units. This file is meant to be used in conjunction with
1350 quantities with units. This file is meant to be used in conjunction with
1351 the PhysicalQInteractive module (in the same directory) and
1351 the PhysicalQInteractive module (in the same directory) and
1352 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1352 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1353 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1353 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1354
1354
1355 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1355 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1356 but these must be declared as instances of a class. For example, to
1356 but these must be declared as instances of a class. For example, to
1357 define v as a velocity of 3 m/s, normally you would write::
1357 define v as a velocity of 3 m/s, normally you would write::
1358
1358
1359 In [1]: v = PhysicalQuantity(3,'m/s')
1359 In [1]: v = PhysicalQuantity(3,'m/s')
1360
1360
1361 Using the PhysicalQ_Input extension this can be input instead as:
1361 Using the PhysicalQ_Input extension this can be input instead as:
1362 In [1]: v = 3 m/s
1362 In [1]: v = 3 m/s
1363 which is much more convenient for interactive use (even though it is
1363 which is much more convenient for interactive use (even though it is
1364 blatantly invalid Python syntax).
1364 blatantly invalid Python syntax).
1365
1365
1366 The physics profile supplied with IPython (enabled via 'ipython -p
1366 The physics profile supplied with IPython (enabled via 'ipython -p
1367 physics') uses these extensions, which you can also activate with:
1367 physics') uses these extensions, which you can also activate with:
1368
1368
1369 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1369 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1370 from IPython.extensions.PhysicalQInteractive import *
1370 from IPython.extensions.PhysicalQInteractive import *
1371 import IPython.extensions.PhysicalQInput
1371 import IPython.extensions.PhysicalQInput
1372
1372
1373 .. _gui_support:
1373 .. _gui_support:
1374
1374
1375 GUI event loop support support
1375 GUI event loop support support
1376 ==============================
1376 ==============================
1377
1377
1378 .. versionadded:: 0.11
1378 .. versionadded:: 0.11
1379 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1379 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1380
1380
1381 IPython has excellent support for working interactively with Graphical User
1381 IPython has excellent support for working interactively with Graphical User
1382 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1382 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1383 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1383 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1384 is extremely robust compared to our previous threaded based version. The
1384 is extremely robust compared to our previous threaded based version. The
1385 advantages of
1385 advantages of
1386
1386
1387 * GUIs can be enabled and disabled dynamically at runtime.
1387 * GUIs can be enabled and disabled dynamically at runtime.
1388 * The active GUI can be switched dynamically at runtime.
1388 * The active GUI can be switched dynamically at runtime.
1389 * In some cases, multiple GUIs can run simultaneously with no problems.
1389 * In some cases, multiple GUIs can run simultaneously with no problems.
1390 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1390 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1391 all of these things.
1391 all of these things.
1392
1392
1393 For users, enabling GUI event loop integration is simple. You simple use the
1393 For users, enabling GUI event loop integration is simple. You simple use the
1394 ``%gui`` magic as follows::
1394 ``%gui`` magic as follows::
1395
1395
1396 %gui [-a] [GUINAME]
1396 %gui [-a] [GUINAME]
1397
1397
1398 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1398 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1399 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1399 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1400 create and return a running application object for the selected GUI toolkit.
1400 create and return a running application object for the selected GUI toolkit.
1401
1401
1402 This to use wxPython interactively and create a running :class:`wx.App`
1402 This to use wxPython interactively and create a running :class:`wx.App`
1403 object, do::
1403 object, do::
1404
1404
1405 %gui -a wx
1405 %gui -a wx
1406
1406
1407 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1407 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1408 see :ref:`this section <matplotlib_support>`.
1408 see :ref:`this section <matplotlib_support>`.
1409
1409
1410 For developers that want to use IPython's GUI event loop integration in
1410 For developers that want to use IPython's GUI event loop integration in
1411 the form of a library, the capabilities are exposed in library form
1411 the form of a library, the capabilities are exposed in library form
1412 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1412 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1413 module docstrings for more information.
1413 module docstrings for more information.
1414
1414
1415 In addition, we also have a number of examples in our source directory
1416 :file:`docs/examples/lib` that demonstrate these capabilities.
1417
1415 .. _matplotlib_support:
1418 .. _matplotlib_support:
1416
1419
1417 Plotting with matplotlib
1420 Plotting with matplotlib
1418 ========================
1421 ========================
1419
1422
1420
1423
1421 `Matplotlib`_ provides high quality 2D and
1424 `Matplotlib`_ provides high quality 2D and
1422 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1425 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1423 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1426 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1424 number of commands useful for scientific computing, all with a syntax
1427 number of commands useful for scientific computing, all with a syntax
1425 compatible with that of the popular Matlab program.
1428 compatible with that of the popular Matlab program.
1426
1429
1427 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1430 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1428 automates the integration of Matplotlib with IPython. We are still in the
1431 automates the integration of Matplotlib with IPython. We are still in the
1429 process of working with the Matplotlib developers to finalize the new pylab
1432 process of working with the Matplotlib developers to finalize the new pylab
1430 API, but for now you can use Matplotlib interactively using the following
1433 API, but for now you can use Matplotlib interactively using the following
1431 commands::
1434 commands::
1432
1435
1433 %gui -a wx
1436 %gui -a wx
1434 import matplotlib
1437 import matplotlib
1435 matplotlib.use('wxagg')
1438 matplotlib.use('wxagg')
1436 from matplotlib import pylab
1439 from matplotlib import pylab
1437 pylab.interactive(True)
1440 pylab.interactive(True)
1438
1441
1439 All of this will soon be automated as Matplotlib beings to include
1442 All of this will soon be automated as Matplotlib beings to include
1440 new logic that uses our new GUI support.
1443 new logic that uses our new GUI support.
1441
1444
1442 .. _interactive_demos:
1445 .. _interactive_demos:
1443
1446
1444 Interactive demos with IPython
1447 Interactive demos with IPython
1445 ==============================
1448 ==============================
1446
1449
1447 IPython ships with a basic system for running scripts interactively in
1450 IPython ships with a basic system for running scripts interactively in
1448 sections, useful when presenting code to audiences. A few tags embedded
1451 sections, useful when presenting code to audiences. A few tags embedded
1449 in comments (so that the script remains valid Python code) divide a file
1452 in comments (so that the script remains valid Python code) divide a file
1450 into separate blocks, and the demo can be run one block at a time, with
1453 into separate blocks, and the demo can be run one block at a time, with
1451 IPython printing (with syntax highlighting) the block before executing
1454 IPython printing (with syntax highlighting) the block before executing
1452 it, and returning to the interactive prompt after each block. The
1455 it, and returning to the interactive prompt after each block. The
1453 interactive namespace is updated after each block is run with the
1456 interactive namespace is updated after each block is run with the
1454 contents of the demo's namespace.
1457 contents of the demo's namespace.
1455
1458
1456 This allows you to show a piece of code, run it and then execute
1459 This allows you to show a piece of code, run it and then execute
1457 interactively commands based on the variables just created. Once you
1460 interactively commands based on the variables just created. Once you
1458 want to continue, you simply execute the next block of the demo. The
1461 want to continue, you simply execute the next block of the demo. The
1459 following listing shows the markup necessary for dividing a script into
1462 following listing shows the markup necessary for dividing a script into
1460 sections for execution as a demo::
1463 sections for execution as a demo::
1461
1464
1462
1465
1463 """A simple interactive demo to illustrate the use of IPython's Demo class.
1466 """A simple interactive demo to illustrate the use of IPython's Demo class.
1464
1467
1465 Any python script can be run as a demo, but that does little more than showing
1468 Any python script can be run as a demo, but that does little more than showing
1466 it on-screen, syntax-highlighted in one shot. If you add a little simple
1469 it on-screen, syntax-highlighted in one shot. If you add a little simple
1467 markup, you can stop at specified intervals and return to the ipython prompt,
1470 markup, you can stop at specified intervals and return to the ipython prompt,
1468 resuming execution later.
1471 resuming execution later.
1469 """
1472 """
1470
1473
1471 print 'Hello, welcome to an interactive IPython demo.'
1474 print 'Hello, welcome to an interactive IPython demo.'
1472 print 'Executing this block should require confirmation before proceeding,'
1475 print 'Executing this block should require confirmation before proceeding,'
1473 print 'unless auto_all has been set to true in the demo object'
1476 print 'unless auto_all has been set to true in the demo object'
1474
1477
1475 # The mark below defines a block boundary, which is a point where IPython will
1478 # The mark below defines a block boundary, which is a point where IPython will
1476 # stop execution and return to the interactive prompt.
1479 # stop execution and return to the interactive prompt.
1477 # Note that in actual interactive execution,
1480 # Note that in actual interactive execution,
1478 # <demo> --- stop ---
1481 # <demo> --- stop ---
1479
1482
1480 x = 1
1483 x = 1
1481 y = 2
1484 y = 2
1482
1485
1483 # <demo> --- stop ---
1486 # <demo> --- stop ---
1484
1487
1485 # the mark below makes this block as silent
1488 # the mark below makes this block as silent
1486 # <demo> silent
1489 # <demo> silent
1487
1490
1488 print 'This is a silent block, which gets executed but not printed.'
1491 print 'This is a silent block, which gets executed but not printed.'
1489
1492
1490 # <demo> --- stop ---
1493 # <demo> --- stop ---
1491 # <demo> auto
1494 # <demo> auto
1492 print 'This is an automatic block.'
1495 print 'This is an automatic block.'
1493 print 'It is executed without asking for confirmation, but printed.'
1496 print 'It is executed without asking for confirmation, but printed.'
1494 z = x+y
1497 z = x+y
1495
1498
1496 print 'z=',x
1499 print 'z=',x
1497
1500
1498 # <demo> --- stop ---
1501 # <demo> --- stop ---
1499 # This is just another normal block.
1502 # This is just another normal block.
1500 print 'z is now:', z
1503 print 'z is now:', z
1501
1504
1502 print 'bye!'
1505 print 'bye!'
1503
1506
1504 In order to run a file as a demo, you must first make a Demo object out
1507 In order to run a file as a demo, you must first make a Demo object out
1505 of it. If the file is named myscript.py, the following code will make a
1508 of it. If the file is named myscript.py, the following code will make a
1506 demo::
1509 demo::
1507
1510
1508 from IPython.demo import Demo
1511 from IPython.demo import Demo
1509
1512
1510 mydemo = Demo('myscript.py')
1513 mydemo = Demo('myscript.py')
1511
1514
1512 This creates the mydemo object, whose blocks you run one at a time by
1515 This creates the mydemo object, whose blocks you run one at a time by
1513 simply calling the object with no arguments. If you have autocall active
1516 simply calling the object with no arguments. If you have autocall active
1514 in IPython (the default), all you need to do is type::
1517 in IPython (the default), all you need to do is type::
1515
1518
1516 mydemo
1519 mydemo
1517
1520
1518 and IPython will call it, executing each block. Demo objects can be
1521 and IPython will call it, executing each block. Demo objects can be
1519 restarted, you can move forward or back skipping blocks, re-execute the
1522 restarted, you can move forward or back skipping blocks, re-execute the
1520 last block, etc. Simply use the Tab key on a demo object to see its
1523 last block, etc. Simply use the Tab key on a demo object to see its
1521 methods, and call '?' on them to see their docstrings for more usage
1524 methods, and call '?' on them to see their docstrings for more usage
1522 details. In addition, the demo module itself contains a comprehensive
1525 details. In addition, the demo module itself contains a comprehensive
1523 docstring, which you can access via::
1526 docstring, which you can access via::
1524
1527
1525 from IPython import demo
1528 from IPython import demo
1526
1529
1527 demo?
1530 demo?
1528
1531
1529 Limitations: It is important to note that these demos are limited to
1532 Limitations: It is important to note that these demos are limited to
1530 fairly simple uses. In particular, you can not put division marks in
1533 fairly simple uses. In particular, you can not put division marks in
1531 indented code (loops, if statements, function definitions, etc.)
1534 indented code (loops, if statements, function definitions, etc.)
1532 Supporting something like this would basically require tracking the
1535 Supporting something like this would basically require tracking the
1533 internal execution state of the Python interpreter, so only top-level
1536 internal execution state of the Python interpreter, so only top-level
1534 divisions are allowed. If you want to be able to open an IPython
1537 divisions are allowed. If you want to be able to open an IPython
1535 instance at an arbitrary point in a program, you can use IPython's
1538 instance at an arbitrary point in a program, you can use IPython's
1536 embedding facilities, described in detail in Sec. 9
1539 embedding facilities, described in detail in Sec. 9
1537
1540
1538 .. [Matplotlib] Matplotlib. http://matplotlib.sourceforge.net
1541 .. [Matplotlib] Matplotlib. http://matplotlib.sourceforge.net
1539
1542
General Comments 0
You need to be logged in to leave comments. Login now