##// END OF EJS Templates
fix docs&examples pointing to appstart_ methods renamed to enable_
MinRK -
Show More
@@ -1,43 +1,43 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Simple GTK example to manually test event loop integration.
2 """Simple GTK example to manually test event loop integration.
3
3
4 This is meant to run tests manually in ipython as:
4 This is meant to run tests manually in ipython as:
5
5
6 In [5]: %gui gtk
6 In [5]: %gui gtk
7
7
8 In [6]: %run gui-gtk.py
8 In [6]: %run gui-gtk.py
9 """
9 """
10
10
11
11
12 import pygtk
12 import pygtk
13 pygtk.require('2.0')
13 pygtk.require('2.0')
14 import gtk
14 import gtk
15
15
16
16
17 def hello_world(wigdet, data=None):
17 def hello_world(wigdet, data=None):
18 print "Hello World"
18 print "Hello World"
19
19
20 def delete_event(widget, event, data=None):
20 def delete_event(widget, event, data=None):
21 return False
21 return False
22
22
23 def destroy(widget, data=None):
23 def destroy(widget, data=None):
24 gtk.main_quit()
24 gtk.main_quit()
25
25
26 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
26 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
27 window.connect("delete_event", delete_event)
27 window.connect("delete_event", delete_event)
28 window.connect("destroy", destroy)
28 window.connect("destroy", destroy)
29 button = gtk.Button("Hello World")
29 button = gtk.Button("Hello World")
30 button.connect("clicked", hello_world, None)
30 button.connect("clicked", hello_world, None)
31
31
32 window.add(button)
32 window.add(button)
33 button.show()
33 button.show()
34 window.show()
34 window.show()
35
35
36 try:
36 try:
37 from IPython.lib.inputhook import appstart_gtk
37 from IPython.lib.inputhook import enable_gtk
38 appstart_gtk()
38 enable_gtk()
39 except ImportError:
39 except ImportError:
40 gtk.main()
40 gtk.main()
41
41
42
42
43
43
@@ -1,40 +1,40 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Simple Qt4 example to manually test event loop integration.
2 """Simple Qt4 example to manually test event loop integration.
3
3
4 This is meant to run tests manually in ipython as:
4 This is meant to run tests manually in ipython as:
5
5
6 In [5]: %gui qt
6 In [5]: %gui qt
7
7
8 In [6]: %run gui-qt.py
8 In [6]: %run gui-qt.py
9
9
10 Ref: Modified from http://zetcode.com/tutorials/pyqt4/firstprograms/
10 Ref: Modified from http://zetcode.com/tutorials/pyqt4/firstprograms/
11 """
11 """
12
12
13 import sys
13 import sys
14 from PyQt4 import QtGui, QtCore
14 from PyQt4 import QtGui, QtCore
15
15
16 class SimpleWindow(QtGui.QWidget):
16 class SimpleWindow(QtGui.QWidget):
17 def __init__(self, parent=None):
17 def __init__(self, parent=None):
18 QtGui.QWidget.__init__(self, parent)
18 QtGui.QWidget.__init__(self, parent)
19
19
20 self.setGeometry(300, 300, 200, 80)
20 self.setGeometry(300, 300, 200, 80)
21 self.setWindowTitle('Hello World')
21 self.setWindowTitle('Hello World')
22
22
23 quit = QtGui.QPushButton('Close', self)
23 quit = QtGui.QPushButton('Close', self)
24 quit.setGeometry(10, 10, 60, 35)
24 quit.setGeometry(10, 10, 60, 35)
25
25
26 self.connect(quit, QtCore.SIGNAL('clicked()'),
26 self.connect(quit, QtCore.SIGNAL('clicked()'),
27 self, QtCore.SLOT('close()'))
27 self, QtCore.SLOT('close()'))
28
28
29 if __name__ == '__main__':
29 if __name__ == '__main__':
30 app = QtCore.QCoreApplication.instance()
30 app = QtCore.QCoreApplication.instance()
31 if app is None:
31 if app is None:
32 app = QtGui.QApplication([])
32 app = QtGui.QApplication([])
33
33
34 sw = SimpleWindow()
34 sw = SimpleWindow()
35 sw.show()
35 sw.show()
36
36
37 try:
37 try:
38 from IPython import appstart_qt4; appstart_qt4(app)
38 from IPython import enable_qt4; enable_qt4(app)
39 except ImportError:
39 except ImportError:
40 app.exec_()
40 app.exec_()
@@ -1,32 +1,32 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Simple Tk example to manually test event loop integration.
2 """Simple Tk example to manually test event loop integration.
3
3
4 This is meant to run tests manually in ipython as:
4 This is meant to run tests manually in ipython as:
5
5
6 In [5]: %gui tk
6 In [5]: %gui tk
7
7
8 In [6]: %run gui-tk.py
8 In [6]: %run gui-tk.py
9 """
9 """
10
10
11 from Tkinter import *
11 from Tkinter import *
12
12
13 class MyApp:
13 class MyApp:
14
14
15 def __init__(self, root):
15 def __init__(self, root):
16 frame = Frame(root)
16 frame = Frame(root)
17 frame.pack()
17 frame.pack()
18
18
19 self.button = Button(frame, text="Hello", command=self.hello_world)
19 self.button = Button(frame, text="Hello", command=self.hello_world)
20 self.button.pack(side=LEFT)
20 self.button.pack(side=LEFT)
21
21
22 def hello_world(self):
22 def hello_world(self):
23 print "Hello World!"
23 print "Hello World!"
24
24
25 root = Tk()
25 root = Tk()
26
26
27 app = MyApp(root)
27 app = MyApp(root)
28
28
29 try:
29 try:
30 from IPython import appstart_tk; appstart_tk(root)
30 from IPython import enable_tk; enable_tk(root)
31 except ImportError:
31 except ImportError:
32 root.mainloop()
32 root.mainloop()
@@ -1,109 +1,109 b''
1 """A Simple wx example to test IPython's event loop integration.
1 """A Simple wx example to test IPython's event loop integration.
2
2
3 To run this do:
3 To run this do:
4
4
5 In [5]: %gui wx
5 In [5]: %gui wx
6
6
7 In [6]: %run gui-wx.py
7 In [6]: %run gui-wx.py
8
8
9 Ref: Modified from wxPython source code wxPython/samples/simple/simple.py
9 Ref: Modified from wxPython source code wxPython/samples/simple/simple.py
10
10
11 This example can only be run once in a given IPython session because when
11 This example can only be run once in a given IPython session because when
12 the frame is closed, wx goes through its shutdown sequence, killing further
12 the frame is closed, wx goes through its shutdown sequence, killing further
13 attempts. I am sure someone who knows wx can fix this issue.
13 attempts. I am sure someone who knows wx can fix this issue.
14
14
15 Furthermore, once this example is run, the Wx event loop is mostly dead, so
15 Furthermore, once this example is run, the Wx event loop is mostly dead, so
16 even other new uses of Wx may not work correctly. If you know how to better
16 even other new uses of Wx may not work correctly. If you know how to better
17 handle this, please contact the ipython developers and let us know.
17 handle this, please contact the ipython developers and let us know.
18
18
19 Note however that we will work with the Matplotlib and Enthought developers so
19 Note however that we will work with the Matplotlib and Enthought developers so
20 that the main interactive uses of Wx we are aware of, namely these tools, will
20 that the main interactive uses of Wx we are aware of, namely these tools, will
21 continue to work well with IPython interactively.
21 continue to work well with IPython interactively.
22 """
22 """
23
23
24 import wx
24 import wx
25
25
26
26
27 class MyFrame(wx.Frame):
27 class MyFrame(wx.Frame):
28 """
28 """
29 This is MyFrame. It just shows a few controls on a wxPanel,
29 This is MyFrame. It just shows a few controls on a wxPanel,
30 and has a simple menu.
30 and has a simple menu.
31 """
31 """
32 def __init__(self, parent, title):
32 def __init__(self, parent, title):
33 wx.Frame.__init__(self, parent, -1, title,
33 wx.Frame.__init__(self, parent, -1, title,
34 pos=(150, 150), size=(350, 200))
34 pos=(150, 150), size=(350, 200))
35
35
36 # Create the menubar
36 # Create the menubar
37 menuBar = wx.MenuBar()
37 menuBar = wx.MenuBar()
38
38
39 # and a menu
39 # and a menu
40 menu = wx.Menu()
40 menu = wx.Menu()
41
41
42 # add an item to the menu, using \tKeyName automatically
42 # add an item to the menu, using \tKeyName automatically
43 # creates an accelerator, the third param is some help text
43 # creates an accelerator, the third param is some help text
44 # that will show up in the statusbar
44 # that will show up in the statusbar
45 menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")
45 menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")
46
46
47 # bind the menu event to an event handler
47 # bind the menu event to an event handler
48 self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT)
48 self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT)
49
49
50 # and put the menu on the menubar
50 # and put the menu on the menubar
51 menuBar.Append(menu, "&File")
51 menuBar.Append(menu, "&File")
52 self.SetMenuBar(menuBar)
52 self.SetMenuBar(menuBar)
53
53
54 self.CreateStatusBar()
54 self.CreateStatusBar()
55
55
56 # Now create the Panel to put the other controls on.
56 # Now create the Panel to put the other controls on.
57 panel = wx.Panel(self)
57 panel = wx.Panel(self)
58
58
59 # and a few controls
59 # and a few controls
60 text = wx.StaticText(panel, -1, "Hello World!")
60 text = wx.StaticText(panel, -1, "Hello World!")
61 text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
61 text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
62 text.SetSize(text.GetBestSize())
62 text.SetSize(text.GetBestSize())
63 btn = wx.Button(panel, -1, "Close")
63 btn = wx.Button(panel, -1, "Close")
64 funbtn = wx.Button(panel, -1, "Just for fun...")
64 funbtn = wx.Button(panel, -1, "Just for fun...")
65
65
66 # bind the button events to handlers
66 # bind the button events to handlers
67 self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, btn)
67 self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, btn)
68 self.Bind(wx.EVT_BUTTON, self.OnFunButton, funbtn)
68 self.Bind(wx.EVT_BUTTON, self.OnFunButton, funbtn)
69
69
70 # Use a sizer to layout the controls, stacked vertically and with
70 # Use a sizer to layout the controls, stacked vertically and with
71 # a 10 pixel border around each
71 # a 10 pixel border around each
72 sizer = wx.BoxSizer(wx.VERTICAL)
72 sizer = wx.BoxSizer(wx.VERTICAL)
73 sizer.Add(text, 0, wx.ALL, 10)
73 sizer.Add(text, 0, wx.ALL, 10)
74 sizer.Add(btn, 0, wx.ALL, 10)
74 sizer.Add(btn, 0, wx.ALL, 10)
75 sizer.Add(funbtn, 0, wx.ALL, 10)
75 sizer.Add(funbtn, 0, wx.ALL, 10)
76 panel.SetSizer(sizer)
76 panel.SetSizer(sizer)
77 panel.Layout()
77 panel.Layout()
78
78
79
79
80 def OnTimeToClose(self, evt):
80 def OnTimeToClose(self, evt):
81 """Event handler for the button click."""
81 """Event handler for the button click."""
82 print "See ya later!"
82 print "See ya later!"
83 self.Close()
83 self.Close()
84
84
85 def OnFunButton(self, evt):
85 def OnFunButton(self, evt):
86 """Event handler for the button click."""
86 """Event handler for the button click."""
87 print "Having fun yet?"
87 print "Having fun yet?"
88
88
89
89
90 class MyApp(wx.App):
90 class MyApp(wx.App):
91 def OnInit(self):
91 def OnInit(self):
92 frame = MyFrame(None, "Simple wxPython App")
92 frame = MyFrame(None, "Simple wxPython App")
93 self.SetTopWindow(frame)
93 self.SetTopWindow(frame)
94
94
95 print "Print statements go to this stdout window by default."
95 print "Print statements go to this stdout window by default."
96
96
97 frame.Show(True)
97 frame.Show(True)
98 return True
98 return True
99
99
100 app = wx.GetApp()
100 app = wx.GetApp()
101 if app is None:
101 if app is None:
102 app = MyApp(redirect=False, clearSigInt=False)
102 app = MyApp(redirect=False, clearSigInt=False)
103
103
104 try:
104 try:
105 from IPython.lib.inputhook import appstart_wx
105 from IPython.lib.inputhook import enable_wx
106 appstart_wx(app)
106 enable_wx(app)
107 except ImportError:
107 except ImportError:
108 app.MainLoop()
108 app.MainLoop()
109
109
@@ -1,1348 +1,1348 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. warning::
5 .. warning::
6
6
7 As of the 0.11 version of IPython, some of the features and APIs
7 As of the 0.11 version of IPython, some of the features and APIs
8 described in this section have been deprecated or are broken. Our plan
8 described in this section have been deprecated or are broken. Our plan
9 is to continue to support these features, but they need to be updated
9 is to continue to support these features, but they need to be updated
10 to take advantage of recent API changes. Furthermore, this section
10 to take advantage of recent API changes. Furthermore, this section
11 of the documentation need to be updated to reflect all of these changes.
11 of the documentation need to be updated to reflect all of these changes.
12
12
13 .. _command_line_options:
13 .. _command_line_options:
14
14
15 Command-line usage
15 Command-line usage
16 ==================
16 ==================
17
17
18 You start IPython with the command::
18 You start IPython with the command::
19
19
20 $ ipython [options] files
20 $ ipython [options] files
21
21
22 If invoked with no options, it executes all the files listed in sequence
22 If invoked with no options, it executes all the files listed in sequence
23 and drops you into the interpreter while still acknowledging any options
23 and drops you into the interpreter while still acknowledging any options
24 you may have set in your ipython_config.py. This behavior is different from
24 you may have set in your ipython_config.py. This behavior is different from
25 standard Python, which when called as python -i will only execute one
25 standard Python, which when called as python -i will only execute one
26 file and ignore your configuration setup.
26 file and ignore your configuration setup.
27
27
28 Please note that some of the configuration options are not available at
28 Please note that some of the configuration options are not available at
29 the command line, simply because they are not practical here. Look into
29 the command line, simply because they are not practical here. Look into
30 your ipythonrc configuration file for details on those. This file is typically
30 your ipythonrc configuration file for details on those. This file is typically
31 installed in the IPYTHON_DIR directory. For Linux
31 installed in the IPYTHON_DIR directory. For Linux
32 users, this will be $HOME/.config/ipython, and for other users it will be
32 users, this will be $HOME/.config/ipython, and for other users it will be
33 $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
33 $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
34 Settings\\YourUserName in most instances.
34 Settings\\YourUserName in most instances.
35
35
36
36
37
37
38
38
39 Special Threading Options
39 Special Threading Options
40 -------------------------
40 -------------------------
41
41
42 Previously IPython had command line options for controlling GUI event loop
42 Previously IPython had command line options for controlling GUI event loop
43 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
43 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
44 version 0.11, these have been removed. Please see the new ``%gui``
44 version 0.11, these have been removed. Please see the new ``%gui``
45 magic command or :ref:`this section <gui_support>` for details on the new
45 magic command or :ref:`this section <gui_support>` for details on the new
46 interface, or specify the gui at the commandline::
46 interface, or specify the gui at the commandline::
47
47
48 $ ipython gui=qt
48 $ ipython gui=qt
49
49
50
50
51 Regular Options
51 Regular Options
52 ---------------
52 ---------------
53
53
54 After the above threading options have been given, regular options can
54 After the above threading options have been given, regular options can
55 follow in any order. All options can be abbreviated to their shortest
55 follow in any order. All options can be abbreviated to their shortest
56 non-ambiguous form and are case-sensitive. One or two dashes can be
56 non-ambiguous form and are case-sensitive. One or two dashes can be
57 used. Some options have an alternate short form, indicated after a ``|``.
57 used. Some options have an alternate short form, indicated after a ``|``.
58
58
59 Most options can also be set from your ipythonrc configuration file. See
59 Most options can also be set from your ipythonrc configuration file. See
60 the provided example for more details on what the options do. Options
60 the provided example for more details on what the options do. Options
61 given at the command line override the values set in the ipythonrc file.
61 given at the command line override the values set in the ipythonrc file.
62
62
63 All options with a [no] prepended can be specified in negated form
63 All options with a [no] prepended can be specified in negated form
64 (--no-option instead of --option) to turn the feature off.
64 (--no-option instead of --option) to turn the feature off.
65
65
66 -h, --help print a help message and exit.
66 -h, --help print a help message and exit.
67
67
68 --pylab, pylab=<name>
68 --pylab, pylab=<name>
69 See :ref:`Matplotlib support <matplotlib_support>`
69 See :ref:`Matplotlib support <matplotlib_support>`
70 for more details.
70 for more details.
71
71
72 autocall=<val>
72 autocall=<val>
73 Make IPython automatically call any callable object even if you
73 Make IPython automatically call any callable object even if you
74 didn't type explicit parentheses. For example, 'str 43' becomes
74 didn't type explicit parentheses. For example, 'str 43' becomes
75 'str(43)' automatically. The value can be '0' to disable the feature,
75 'str(43)' automatically. The value can be '0' to disable the feature,
76 '1' for smart autocall, where it is not applied if there are no more
76 '1' for smart autocall, where it is not applied if there are no more
77 arguments on the line, and '2' for full autocall, where all callable
77 arguments on the line, and '2' for full autocall, where all callable
78 objects are automatically called (even if no arguments are
78 objects are automatically called (even if no arguments are
79 present). The default is '1'.
79 present). The default is '1'.
80
80
81 --[no-]autoindent
81 --[no-]autoindent
82 Turn automatic indentation on/off.
82 Turn automatic indentation on/off.
83
83
84 --[no-]automagic
84 --[no-]automagic
85 make magic commands automatic (without needing their first character
85 make magic commands automatic (without needing their first character
86 to be %). Type %magic at the IPython prompt for more information.
86 to be %). Type %magic at the IPython prompt for more information.
87
87
88 --[no-]autoedit_syntax
88 --[no-]autoedit_syntax
89 When a syntax error occurs after editing a file, automatically
89 When a syntax error occurs after editing a file, automatically
90 open the file to the trouble causing line for convenient
90 open the file to the trouble causing line for convenient
91 fixing.
91 fixing.
92
92
93 --[no-]banner Print the initial information banner (default on).
93 --[no-]banner Print the initial information banner (default on).
94
94
95 c=<command>
95 c=<command>
96 execute the given command string. This is similar to the -c
96 execute the given command string. This is similar to the -c
97 option in the normal Python interpreter.
97 option in the normal Python interpreter.
98
98
99 cache_size=<n>
99 cache_size=<n>
100 size of the output cache (maximum number of entries to hold in
100 size of the output cache (maximum number of entries to hold in
101 memory). The default is 1000, you can change it permanently in your
101 memory). The default is 1000, you can change it permanently in your
102 config file. Setting it to 0 completely disables the caching system,
102 config file. Setting it to 0 completely disables the caching system,
103 and the minimum value accepted is 20 (if you provide a value less than
103 and the minimum value accepted is 20 (if you provide a value less than
104 20, it is reset to 0 and a warning is issued) This limit is defined
104 20, it is reset to 0 and a warning is issued) This limit is defined
105 because otherwise you'll spend more time re-flushing a too small cache
105 because otherwise you'll spend more time re-flushing a too small cache
106 than working.
106 than working.
107
107
108 --classic
108 --classic
109 Gives IPython a similar feel to the classic Python
109 Gives IPython a similar feel to the classic Python
110 prompt.
110 prompt.
111
111
112 colors=<scheme>
112 colors=<scheme>
113 Color scheme for prompts and exception reporting. Currently
113 Color scheme for prompts and exception reporting. Currently
114 implemented: NoColor, Linux and LightBG.
114 implemented: NoColor, Linux and LightBG.
115
115
116 --[no-]color_info
116 --[no-]color_info
117 IPython can display information about objects via a set of functions,
117 IPython can display information about objects via a set of functions,
118 and optionally can use colors for this, syntax highlighting source
118 and optionally can use colors for this, syntax highlighting source
119 code and various other elements. However, because this information is
119 code and various other elements. However, because this information is
120 passed through a pager (like 'less') and many pagers get confused with
120 passed through a pager (like 'less') and many pagers get confused with
121 color codes, this option is off by default. You can test it and turn
121 color codes, this option is off by default. You can test it and turn
122 it on permanently in your ipythonrc file if it works for you. As a
122 it on permanently in your ipythonrc file if it works for you. As a
123 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
123 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
124 that in RedHat 7.2 doesn't.
124 that in RedHat 7.2 doesn't.
125
125
126 Test it and turn it on permanently if it works with your
126 Test it and turn it on permanently if it works with your
127 system. The magic function %color_info allows you to toggle this
127 system. The magic function %color_info allows you to toggle this
128 interactively for testing.
128 interactively for testing.
129
129
130 --[no-]debug
130 --[no-]debug
131 Show information about the loading process. Very useful to pin down
131 Show information about the loading process. Very useful to pin down
132 problems with your configuration files or to get details about
132 problems with your configuration files or to get details about
133 session restores.
133 session restores.
134
134
135 --[no-]deep_reload:
135 --[no-]deep_reload:
136 IPython can use the deep_reload module which reloads changes in
136 IPython can use the deep_reload module which reloads changes in
137 modules recursively (it replaces the reload() function, so you don't
137 modules recursively (it replaces the reload() function, so you don't
138 need to change anything to use it). deep_reload() forces a full
138 need to change anything to use it). deep_reload() forces a full
139 reload of modules whose code may have changed, which the default
139 reload of modules whose code may have changed, which the default
140 reload() function does not.
140 reload() function does not.
141
141
142 When deep_reload is off, IPython will use the normal reload(),
142 When deep_reload is off, IPython will use the normal reload(),
143 but deep_reload will still be available as dreload(). This
143 but deep_reload will still be available as dreload(). This
144 feature is off by default [which means that you have both
144 feature is off by default [which means that you have both
145 normal reload() and dreload()].
145 normal reload() and dreload()].
146
146
147 editor=<name>
147 editor=<name>
148 Which editor to use with the %edit command. By default,
148 Which editor to use with the %edit command. By default,
149 IPython will honor your EDITOR environment variable (if not
149 IPython will honor your EDITOR environment variable (if not
150 set, vi is the Unix default and notepad the Windows one).
150 set, vi is the Unix default and notepad the Windows one).
151 Since this editor is invoked on the fly by IPython and is
151 Since this editor is invoked on the fly by IPython and is
152 meant for editing small code snippets, you may want to use a
152 meant for editing small code snippets, you may want to use a
153 small, lightweight editor here (in case your default EDITOR is
153 small, lightweight editor here (in case your default EDITOR is
154 something like Emacs).
154 something like Emacs).
155
155
156 ipython_dir=<name>
156 ipython_dir=<name>
157 name of your IPython configuration directory IPYTHON_DIR. This
157 name of your IPython configuration directory IPYTHON_DIR. This
158 can also be specified through the environment variable
158 can also be specified through the environment variable
159 IPYTHON_DIR.
159 IPYTHON_DIR.
160
160
161 -log, l
161 -log, l
162 generate a log file of all input. The file is named
162 generate a log file of all input. The file is named
163 ipython_log.py in your current directory (which prevents logs
163 ipython_log.py in your current directory (which prevents logs
164 from multiple IPython sessions from trampling each other). You
164 from multiple IPython sessions from trampling each other). You
165 can use this to later restore a session by loading your
165 can use this to later restore a session by loading your
166 logfile as a file to be executed with option -logplay (see
166 logfile as a file to be executed with option -logplay (see
167 below).
167 below).
168
168
169 logfile=<name> specify the name of your logfile.
169 logfile=<name> specify the name of your logfile.
170
170
171 logplay=<name>
171 logplay=<name>
172
172
173 you can replay a previous log. For restoring a session as close as
173 you can replay a previous log. For restoring a session as close as
174 possible to the state you left it in, use this option (don't just run
174 possible to the state you left it in, use this option (don't just run
175 the logfile). With -logplay, IPython will try to reconstruct the
175 the logfile). With -logplay, IPython will try to reconstruct the
176 previous working environment in full, not just execute the commands in
176 previous working environment in full, not just execute the commands in
177 the logfile.
177 the logfile.
178
178
179 When a session is restored, logging is automatically turned on
179 When a session is restored, logging is automatically turned on
180 again with the name of the logfile it was invoked with (it is
180 again with the name of the logfile it was invoked with (it is
181 read from the log header). So once you've turned logging on for
181 read from the log header). So once you've turned logging on for
182 a session, you can quit IPython and reload it as many times as
182 a session, you can quit IPython and reload it as many times as
183 you want and it will continue to log its history and restore
183 you want and it will continue to log its history and restore
184 from the beginning every time.
184 from the beginning every time.
185
185
186 Caveats: there are limitations in this option. The history
186 Caveats: there are limitations in this option. The history
187 variables _i*,_* and _dh don't get restored properly. In the
187 variables _i*,_* and _dh don't get restored properly. In the
188 future we will try to implement full session saving by writing
188 future we will try to implement full session saving by writing
189 and retrieving a 'snapshot' of the memory state of IPython. But
189 and retrieving a 'snapshot' of the memory state of IPython. But
190 our first attempts failed because of inherent limitations of
190 our first attempts failed because of inherent limitations of
191 Python's Pickle module, so this may have to wait.
191 Python's Pickle module, so this may have to wait.
192
192
193 --[no-]messages
193 --[no-]messages
194 Print messages which IPython collects about its startup
194 Print messages which IPython collects about its startup
195 process (default on).
195 process (default on).
196
196
197 --[no-]pdb
197 --[no-]pdb
198 Automatically call the pdb debugger after every uncaught
198 Automatically call the pdb debugger after every uncaught
199 exception. If you are used to debugging using pdb, this puts
199 exception. If you are used to debugging using pdb, this puts
200 you automatically inside of it after any call (either in
200 you automatically inside of it after any call (either in
201 IPython or in code called by it) which triggers an exception
201 IPython or in code called by it) which triggers an exception
202 which goes uncaught.
202 which goes uncaught.
203
203
204 --[no-]pprint
204 --[no-]pprint
205 ipython can optionally use the pprint (pretty printer) module
205 ipython can optionally use the pprint (pretty printer) module
206 for displaying results. pprint tends to give a nicer display
206 for displaying results. pprint tends to give a nicer display
207 of nested data structures. If you like it, you can turn it on
207 of nested data structures. If you like it, you can turn it on
208 permanently in your config file (default off).
208 permanently in your config file (default off).
209
209
210 profile=<name>
210 profile=<name>
211
211
212 Select the IPython profile by name.
212 Select the IPython profile by name.
213
213
214 This is a quick way to keep and load multiple
214 This is a quick way to keep and load multiple
215 config files for different tasks, especially if you use the
215 config files for different tasks, especially if you use the
216 include option of config files. You can keep a basic
216 include option of config files. You can keep a basic
217 IPYTHON_DIR/ipythonrc file and then have other 'profiles' which
217 IPYTHON_DIR/ipythonrc file and then have other 'profiles' which
218 include this one and load extra things for particular
218 include this one and load extra things for particular
219 tasks. For example:
219 tasks. For example:
220
220
221 1. $IPYTHON_DIR/profile_default : load basic things you always want.
221 1. $IPYTHON_DIR/profile_default : load basic things you always want.
222 2. $IPYTHON_DIR/profile_math : load (1) and basic math-related modules.
222 2. $IPYTHON_DIR/profile_math : load (1) and basic math-related modules.
223 3. $IPYTHON_DIR/profile_numeric : load (1) and Numeric and plotting modules.
223 3. $IPYTHON_DIR/profile_numeric : load (1) and Numeric and plotting modules.
224
224
225 Since it is possible to create an endless loop by having
225 Since it is possible to create an endless loop by having
226 circular file inclusions, IPython will stop if it reaches 15
226 circular file inclusions, IPython will stop if it reaches 15
227 recursive inclusions.
227 recursive inclusions.
228
228
229 InteractiveShell.prompt_in1=<string>
229 InteractiveShell.prompt_in1=<string>
230
230
231 Specify the string used for input prompts. Note that if you are using
231 Specify the string used for input prompts. Note that if you are using
232 numbered prompts, the number is represented with a '\#' in the
232 numbered prompts, the number is represented with a '\#' in the
233 string. Don't forget to quote strings with spaces embedded in
233 string. Don't forget to quote strings with spaces embedded in
234 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
234 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
235 discusses in detail all the available escapes to customize your
235 discusses in detail all the available escapes to customize your
236 prompts.
236 prompts.
237
237
238 InteractiveShell.prompt_in2=<string>
238 InteractiveShell.prompt_in2=<string>
239 Similar to the previous option, but used for the continuation
239 Similar to the previous option, but used for the continuation
240 prompts. The special sequence '\D' is similar to '\#', but
240 prompts. The special sequence '\D' is similar to '\#', but
241 with all digits replaced dots (so you can have your
241 with all digits replaced dots (so you can have your
242 continuation prompt aligned with your input prompt). Default:
242 continuation prompt aligned with your input prompt). Default:
243 ' .\D.:' (note three spaces at the start for alignment with
243 ' .\D.:' (note three spaces at the start for alignment with
244 'In [\#]').
244 'In [\#]').
245
245
246 InteractiveShell.prompt_out=<string>
246 InteractiveShell.prompt_out=<string>
247 String used for output prompts, also uses numbers like
247 String used for output prompts, also uses numbers like
248 prompt_in1. Default: 'Out[\#]:'
248 prompt_in1. Default: 'Out[\#]:'
249
249
250 --quick
250 --quick
251 start in bare bones mode (no config file loaded).
251 start in bare bones mode (no config file loaded).
252
252
253 config_file=<name>
253 config_file=<name>
254 name of your IPython resource configuration file. Normally
254 name of your IPython resource configuration file. Normally
255 IPython loads ipython_config.py (from current directory) or
255 IPython loads ipython_config.py (from current directory) or
256 IPYTHON_DIR/profile_default.
256 IPYTHON_DIR/profile_default.
257
257
258 If the loading of your config file fails, IPython starts with
258 If the loading of your config file fails, IPython starts with
259 a bare bones configuration (no modules loaded at all).
259 a bare bones configuration (no modules loaded at all).
260
260
261 --[no-]readline
261 --[no-]readline
262 use the readline library, which is needed to support name
262 use the readline library, which is needed to support name
263 completion and command history, among other things. It is
263 completion and command history, among other things. It is
264 enabled by default, but may cause problems for users of
264 enabled by default, but may cause problems for users of
265 X/Emacs in Python comint or shell buffers.
265 X/Emacs in Python comint or shell buffers.
266
266
267 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
267 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
268 IPython's readline and syntax coloring fine, only 'emacs' (M-x
268 IPython's readline and syntax coloring fine, only 'emacs' (M-x
269 shell and C-c !) buffers do not.
269 shell and C-c !) buffers do not.
270
270
271 TerminalInteractiveShell.screen_length=<n>
271 TerminalInteractiveShell.screen_length=<n>
272 number of lines of your screen. This is used to control
272 number of lines of your screen. This is used to control
273 printing of very long strings. Strings longer than this number
273 printing of very long strings. Strings longer than this number
274 of lines will be sent through a pager instead of directly
274 of lines will be sent through a pager instead of directly
275 printed.
275 printed.
276
276
277 The default value for this is 0, which means IPython will
277 The default value for this is 0, which means IPython will
278 auto-detect your screen size every time it needs to print certain
278 auto-detect your screen size every time it needs to print certain
279 potentially long strings (this doesn't change the behavior of the
279 potentially long strings (this doesn't change the behavior of the
280 'print' keyword, it's only triggered internally). If for some
280 'print' keyword, it's only triggered internally). If for some
281 reason this isn't working well (it needs curses support), specify
281 reason this isn't working well (it needs curses support), specify
282 it yourself. Otherwise don't change the default.
282 it yourself. Otherwise don't change the default.
283
283
284 TerminalInteractiveShell.separate_in=<string>
284 TerminalInteractiveShell.separate_in=<string>
285
285
286 separator before input prompts.
286 separator before input prompts.
287 Default: '\n'
287 Default: '\n'
288
288
289 TerminalInteractiveShell.separate_out=<string>
289 TerminalInteractiveShell.separate_out=<string>
290 separator before output prompts.
290 separator before output prompts.
291 Default: nothing.
291 Default: nothing.
292
292
293 TerminalInteractiveShell.separate_out2=<string>
293 TerminalInteractiveShell.separate_out2=<string>
294 separator after output prompts.
294 separator after output prompts.
295 Default: nothing.
295 Default: nothing.
296 For these three options, use the value 0 to specify no separator.
296 For these three options, use the value 0 to specify no separator.
297
297
298 --nosep
298 --nosep
299 shorthand for setting the above separators to empty strings.
299 shorthand for setting the above separators to empty strings.
300
300
301 Simply removes all input/output separators.
301 Simply removes all input/output separators.
302
302
303 --init
303 --init
304 allows you to initialize a profile dir for configuration when you
304 allows you to initialize a profile dir for configuration when you
305 install a new version of IPython or want to use a new profile.
305 install a new version of IPython or want to use a new profile.
306 Since new versions may include new command line options or example
306 Since new versions may include new command line options or example
307 files, this copies updated config files. Note that you should probably
307 files, this copies updated config files. Note that you should probably
308 use %upgrade instead,it's a safer alternative.
308 use %upgrade instead,it's a safer alternative.
309
309
310 --version print version information and exit.
310 --version print version information and exit.
311
311
312 xmode=<modename>
312 xmode=<modename>
313
313
314 Mode for exception reporting.
314 Mode for exception reporting.
315
315
316 Valid modes: Plain, Context and Verbose.
316 Valid modes: Plain, Context and Verbose.
317
317
318 * Plain: similar to python's normal traceback printing.
318 * Plain: similar to python's normal traceback printing.
319 * Context: prints 5 lines of context source code around each
319 * Context: prints 5 lines of context source code around each
320 line in the traceback.
320 line in the traceback.
321 * Verbose: similar to Context, but additionally prints the
321 * Verbose: similar to Context, but additionally prints the
322 variables currently visible where the exception happened
322 variables currently visible where the exception happened
323 (shortening their strings if too long). This can potentially be
323 (shortening their strings if too long). This can potentially be
324 very slow, if you happen to have a huge data structure whose
324 very slow, if you happen to have a huge data structure whose
325 string representation is complex to compute. Your computer may
325 string representation is complex to compute. Your computer may
326 appear to freeze for a while with cpu usage at 100%. If this
326 appear to freeze for a while with cpu usage at 100%. If this
327 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
327 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
328 more than once).
328 more than once).
329
329
330 Interactive use
330 Interactive use
331 ===============
331 ===============
332
332
333 IPython is meant to work as a drop-in
333 IPython is meant to work as a drop-in
334 replacement for the standard interactive interpreter. As such, any code
334 replacement for the standard interactive interpreter. As such, any code
335 which is valid python should execute normally under IPython (cases where
335 which is valid python should execute normally under IPython (cases where
336 this is not true should be reported as bugs). It does, however, offer
336 this is not true should be reported as bugs). It does, however, offer
337 many features which are not available at a standard python prompt. What
337 many features which are not available at a standard python prompt. What
338 follows is a list of these.
338 follows is a list of these.
339
339
340
340
341 Caution for Windows users
341 Caution for Windows users
342 -------------------------
342 -------------------------
343
343
344 Windows, unfortunately, uses the '\\' character as a path
344 Windows, unfortunately, uses the '\\' character as a path
345 separator. This is a terrible choice, because '\\' also represents the
345 separator. This is a terrible choice, because '\\' also represents the
346 escape character in most modern programming languages, including
346 escape character in most modern programming languages, including
347 Python. For this reason, using '/' character is recommended if you
347 Python. For this reason, using '/' character is recommended if you
348 have problems with ``\``. However, in Windows commands '/' flags
348 have problems with ``\``. However, in Windows commands '/' flags
349 options, so you can not use it for the root directory. This means that
349 options, so you can not use it for the root directory. This means that
350 paths beginning at the root must be typed in a contrived manner like:
350 paths beginning at the root must be typed in a contrived manner like:
351 ``%copy \opt/foo/bar.txt \tmp``
351 ``%copy \opt/foo/bar.txt \tmp``
352
352
353 .. _magic:
353 .. _magic:
354
354
355 Magic command system
355 Magic command system
356 --------------------
356 --------------------
357
357
358 IPython will treat any line whose first character is a % as a special
358 IPython will treat any line whose first character is a % as a special
359 call to a 'magic' function. These allow you to control the behavior of
359 call to a 'magic' function. These allow you to control the behavior of
360 IPython itself, plus a lot of system-type features. They are all
360 IPython itself, plus a lot of system-type features. They are all
361 prefixed with a % character, but parameters are given without
361 prefixed with a % character, but parameters are given without
362 parentheses or quotes.
362 parentheses or quotes.
363
363
364 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
364 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
365 exists.
365 exists.
366
366
367 If you have 'automagic' enabled (as it by default), you don't need
367 If you have 'automagic' enabled (as it by default), you don't need
368 to type in the % explicitly. IPython will scan its internal list of
368 to type in the % explicitly. IPython will scan its internal list of
369 magic functions and call one if it exists. With automagic on you can
369 magic functions and call one if it exists. With automagic on you can
370 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
370 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
371 system has the lowest possible precedence in name searches, so defining
371 system has the lowest possible precedence in name searches, so defining
372 an identifier with the same name as an existing magic function will
372 an identifier with the same name as an existing magic function will
373 shadow it for automagic use. You can still access the shadowed magic
373 shadow it for automagic use. You can still access the shadowed magic
374 function by explicitly using the % character at the beginning of the line.
374 function by explicitly using the % character at the beginning of the line.
375
375
376 An example (with automagic on) should clarify all this:
376 An example (with automagic on) should clarify all this:
377
377
378 .. sourcecode:: ipython
378 .. sourcecode:: ipython
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 .. sourcecode:: python
411 .. sourcecode:: python
412
412
413 ip = get_ipython()
413 ip = get_ipython()
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 Type %magic for more information, including a list of all available
427 Type %magic for more information, including a list of all available
428 magic functions at any time and their docstrings. You can also type
428 magic functions at any time and their docstrings. You can also type
429 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
429 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
430 information on the '?' system) to get information about any particular
430 information on the '?' system) to get information about any particular
431 magic function you are interested in.
431 magic function you are interested in.
432
432
433 The API documentation for the :mod:`IPython.core.magic` module contains the full
433 The API documentation for the :mod:`IPython.core.magic` module contains the full
434 docstrings of all currently available magic commands.
434 docstrings of all currently available magic commands.
435
435
436
436
437 Access to the standard Python help
437 Access to the standard Python help
438 ----------------------------------
438 ----------------------------------
439
439
440 As of Python 2.1, a help system is available with access to object docstrings
440 As of Python 2.1, a help system is available with access to object docstrings
441 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
441 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
442 also type help(object) to obtain information about a given object, and
442 also type help(object) to obtain information about a given object, and
443 help('keyword') for information on a keyword. As noted :ref:`here
443 help('keyword') for information on a keyword. As noted :ref:`here
444 <accessing_help>`, you need to properly configure your environment variable
444 <accessing_help>`, you need to properly configure your environment variable
445 PYTHONDOCS for this feature to work correctly.
445 PYTHONDOCS for this feature to work correctly.
446
446
447 .. _dynamic_object_info:
447 .. _dynamic_object_info:
448
448
449 Dynamic object information
449 Dynamic object information
450 --------------------------
450 --------------------------
451
451
452 Typing ?word or word? prints detailed information about an object. If
452 Typing ?word or word? prints detailed information about an object. If
453 certain strings in the object are too long (docstrings, code, etc.) they
453 certain strings in the object are too long (docstrings, code, etc.) they
454 get snipped in the center for brevity. This system gives access variable
454 get snipped in the center for brevity. This system gives access variable
455 types and values, full source code for any object (if available),
455 types and values, full source code for any object (if available),
456 function prototypes and other useful information.
456 function prototypes and other useful information.
457
457
458 Typing ??word or word?? gives access to the full information without
458 Typing ??word or word?? gives access to the full information without
459 snipping long strings. Long strings are sent to the screen through the
459 snipping long strings. Long strings are sent to the screen through the
460 less pager if longer than the screen and printed otherwise. On systems
460 less pager if longer than the screen and printed otherwise. On systems
461 lacking the less command, IPython uses a very basic internal pager.
461 lacking the less command, IPython uses a very basic internal pager.
462
462
463 The following magic functions are particularly useful for gathering
463 The following magic functions are particularly useful for gathering
464 information about your working environment. You can get more details by
464 information about your working environment. You can get more details by
465 typing %magic or querying them individually (use %function_name? with or
465 typing %magic or querying them individually (use %function_name? with or
466 without the %), this is just a summary:
466 without the %), this is just a summary:
467
467
468 * **%pdoc <object>**: Print (or run through a pager if too long) the
468 * **%pdoc <object>**: Print (or run through a pager if too long) the
469 docstring for an object. If the given object is a class, it will
469 docstring for an object. If the given object is a class, it will
470 print both the class and the constructor docstrings.
470 print both the class and the constructor docstrings.
471 * **%pdef <object>**: Print the definition header for any callable
471 * **%pdef <object>**: Print the definition header for any callable
472 object. If the object is a class, print the constructor information.
472 object. If the object is a class, print the constructor information.
473 * **%psource <object>**: Print (or run through a pager if too long)
473 * **%psource <object>**: Print (or run through a pager if too long)
474 the source code for an object.
474 the source code for an object.
475 * **%pfile <object>**: Show the entire source file where an object was
475 * **%pfile <object>**: Show the entire source file where an object was
476 defined via a pager, opening it at the line where the object
476 defined via a pager, opening it at the line where the object
477 definition begins.
477 definition begins.
478 * **%who/%whos**: These functions give information about identifiers
478 * **%who/%whos**: These functions give information about identifiers
479 you have defined interactively (not things you loaded or defined
479 you have defined interactively (not things you loaded or defined
480 in your configuration files). %who just prints a list of
480 in your configuration files). %who just prints a list of
481 identifiers and %whos prints a table with some basic details about
481 identifiers and %whos prints a table with some basic details about
482 each identifier.
482 each identifier.
483
483
484 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
484 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
485 %pdef, %psource) give you access to documentation even on things which
485 %pdef, %psource) give you access to documentation even on things which
486 are not really defined as separate identifiers. Try for example typing
486 are not really defined as separate identifiers. Try for example typing
487 {}.get? or after doing import os, type os.path.abspath??.
487 {}.get? or after doing import os, type os.path.abspath??.
488
488
489
489
490 .. _readline:
490 .. _readline:
491
491
492 Readline-based features
492 Readline-based features
493 -----------------------
493 -----------------------
494
494
495 These features require the GNU readline library, so they won't work if
495 These features require the GNU readline library, so they won't work if
496 your Python installation lacks readline support. We will first describe
496 your Python installation lacks readline support. We will first describe
497 the default behavior IPython uses, and then how to change it to suit
497 the default behavior IPython uses, and then how to change it to suit
498 your preferences.
498 your preferences.
499
499
500
500
501 Command line completion
501 Command line completion
502 +++++++++++++++++++++++
502 +++++++++++++++++++++++
503
503
504 At any time, hitting TAB will complete any available python commands or
504 At any time, hitting TAB will complete any available python commands or
505 variable names, and show you a list of the possible completions if
505 variable names, and show you a list of the possible completions if
506 there's no unambiguous one. It will also complete filenames in the
506 there's no unambiguous one. It will also complete filenames in the
507 current directory if no python names match what you've typed so far.
507 current directory if no python names match what you've typed so far.
508
508
509
509
510 Search command history
510 Search command history
511 ++++++++++++++++++++++
511 ++++++++++++++++++++++
512
512
513 IPython provides two ways for searching through previous input and thus
513 IPython provides two ways for searching through previous input and thus
514 reduce the need for repetitive typing:
514 reduce the need for repetitive typing:
515
515
516 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
516 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
517 (next,down) to search through only the history items that match
517 (next,down) to search through only the history items that match
518 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
518 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
519 prompt, they just behave like normal arrow keys.
519 prompt, they just behave like normal arrow keys.
520 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
520 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
521 searches your history for lines that contain what you've typed so
521 searches your history for lines that contain what you've typed so
522 far, completing as much as it can.
522 far, completing as much as it can.
523
523
524
524
525 Persistent command history across sessions
525 Persistent command history across sessions
526 ++++++++++++++++++++++++++++++++++++++++++
526 ++++++++++++++++++++++++++++++++++++++++++
527
527
528 IPython will save your input history when it leaves and reload it next
528 IPython will save your input history when it leaves and reload it next
529 time you restart it. By default, the history file is named
529 time you restart it. By default, the history file is named
530 $IPYTHON_DIR/profile_<name>/history.sqlite. This allows you to keep
530 $IPYTHON_DIR/profile_<name>/history.sqlite. This allows you to keep
531 separate histories related to various tasks: commands related to
531 separate histories related to various tasks: commands related to
532 numerical work will not be clobbered by a system shell history, for
532 numerical work will not be clobbered by a system shell history, for
533 example.
533 example.
534
534
535
535
536 Autoindent
536 Autoindent
537 ++++++++++
537 ++++++++++
538
538
539 IPython can recognize lines ending in ':' and indent the next line,
539 IPython can recognize lines ending in ':' and indent the next line,
540 while also un-indenting automatically after 'raise' or 'return'.
540 while also un-indenting automatically after 'raise' or 'return'.
541
541
542 This feature uses the readline library, so it will honor your ~/.inputrc
542 This feature uses the readline library, so it will honor your ~/.inputrc
543 configuration (or whatever file your INPUTRC variable points to). Adding
543 configuration (or whatever file your INPUTRC variable points to). Adding
544 the following lines to your .inputrc file can make indenting/unindenting
544 the following lines to your .inputrc file can make indenting/unindenting
545 more convenient (M-i indents, M-u unindents)::
545 more convenient (M-i indents, M-u unindents)::
546
546
547 $if Python
547 $if Python
548 "\M-i": " "
548 "\M-i": " "
549 "\M-u": "\d\d\d\d"
549 "\M-u": "\d\d\d\d"
550 $endif
550 $endif
551
551
552 Note that there are 4 spaces between the quote marks after "M-i" above.
552 Note that there are 4 spaces between the quote marks after "M-i" above.
553
553
554 .. warning::
554 .. warning::
555
555
556 Setting the above indents will cause problems with unicode text entry in the terminal.
556 Setting the above indents will cause problems with unicode text entry in the terminal.
557
557
558 .. warning::
558 .. warning::
559
559
560 This feature is ON by default, but it can cause problems with
560 This feature is ON by default, but it can cause problems with
561 the pasting of multi-line indented code (the pasted code gets
561 the pasting of multi-line indented code (the pasted code gets
562 re-indented on each line). A magic function %autoindent allows you to
562 re-indented on each line). A magic function %autoindent allows you to
563 toggle it on/off at runtime. You can also disable it permanently on in
563 toggle it on/off at runtime. You can also disable it permanently on in
564 your :file:`ipython_config.py` file (set TerminalInteractiveShell.autoindent=False).
564 your :file:`ipython_config.py` file (set TerminalInteractiveShell.autoindent=False).
565
565
566
566
567 Customizing readline behavior
567 Customizing readline behavior
568 +++++++++++++++++++++++++++++
568 +++++++++++++++++++++++++++++
569
569
570 All these features are based on the GNU readline library, which has an
570 All these features are based on the GNU readline library, which has an
571 extremely customizable interface. Normally, readline is configured via a
571 extremely customizable interface. Normally, readline is configured via a
572 file which defines the behavior of the library; the details of the
572 file which defines the behavior of the library; the details of the
573 syntax for this can be found in the readline documentation available
573 syntax for this can be found in the readline documentation available
574 with your system or on the Internet. IPython doesn't read this file (if
574 with your system or on the Internet. IPython doesn't read this file (if
575 it exists) directly, but it does support passing to readline valid
575 it exists) directly, but it does support passing to readline valid
576 options via a simple interface. In brief, you can customize readline by
576 options via a simple interface. In brief, you can customize readline by
577 setting the following options in your ipythonrc configuration file (note
577 setting the following options in your ipythonrc configuration file (note
578 that these options can not be specified at the command line):
578 that these options can not be specified at the command line):
579
579
580 * **readline_parse_and_bind**: this option can appear as many times as
580 * **readline_parse_and_bind**: this option can appear as many times as
581 you want, each time defining a string to be executed via a
581 you want, each time defining a string to be executed via a
582 readline.parse_and_bind() command. The syntax for valid commands
582 readline.parse_and_bind() command. The syntax for valid commands
583 of this kind can be found by reading the documentation for the GNU
583 of this kind can be found by reading the documentation for the GNU
584 readline library, as these commands are of the kind which readline
584 readline library, as these commands are of the kind which readline
585 accepts in its configuration file.
585 accepts in its configuration file.
586 * **readline_remove_delims**: a string of characters to be removed
586 * **readline_remove_delims**: a string of characters to be removed
587 from the default word-delimiters list used by readline, so that
587 from the default word-delimiters list used by readline, so that
588 completions may be performed on strings which contain them. Do not
588 completions may be performed on strings which contain them. Do not
589 change the default value unless you know what you're doing.
589 change the default value unless you know what you're doing.
590 * **readline_omit__names**: when tab-completion is enabled, hitting
590 * **readline_omit__names**: when tab-completion is enabled, hitting
591 <tab> after a '.' in a name will complete all attributes of an
591 <tab> after a '.' in a name will complete all attributes of an
592 object, including all the special methods whose names include
592 object, including all the special methods whose names include
593 double underscores (like __getitem__ or __class__). If you'd
593 double underscores (like __getitem__ or __class__). If you'd
594 rather not see these names by default, you can set this option to
594 rather not see these names by default, you can set this option to
595 1. Note that even when this option is set, you can still see those
595 1. Note that even when this option is set, you can still see those
596 names by explicitly typing a _ after the period and hitting <tab>:
596 names by explicitly typing a _ after the period and hitting <tab>:
597 'name._<tab>' will always complete attribute names starting with '_'.
597 'name._<tab>' will always complete attribute names starting with '_'.
598
598
599 This option is off by default so that new users see all
599 This option is off by default so that new users see all
600 attributes of any objects they are dealing with.
600 attributes of any objects they are dealing with.
601
601
602 You will find the default values along with a corresponding detailed
602 You will find the default values along with a corresponding detailed
603 explanation in your ipythonrc file.
603 explanation in your ipythonrc file.
604
604
605
605
606 Session logging and restoring
606 Session logging and restoring
607 -----------------------------
607 -----------------------------
608
608
609 You can log all input from a session either by starting IPython with the
609 You can log all input from a session either by starting IPython with the
610 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
610 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
611 or by activating the logging at any moment with the magic function %logstart.
611 or by activating the logging at any moment with the magic function %logstart.
612
612
613 Log files can later be reloaded with the -logplay option and IPython
613 Log files can later be reloaded with the -logplay option and IPython
614 will attempt to 'replay' the log by executing all the lines in it, thus
614 will attempt to 'replay' the log by executing all the lines in it, thus
615 restoring the state of a previous session. This feature is not quite
615 restoring the state of a previous session. This feature is not quite
616 perfect, but can still be useful in many cases.
616 perfect, but can still be useful in many cases.
617
617
618 The log files can also be used as a way to have a permanent record of
618 The log files can also be used as a way to have a permanent record of
619 any code you wrote while experimenting. Log files are regular text files
619 any code you wrote while experimenting. Log files are regular text files
620 which you can later open in your favorite text editor to extract code or
620 which you can later open in your favorite text editor to extract code or
621 to 'clean them up' before using them to replay a session.
621 to 'clean them up' before using them to replay a session.
622
622
623 The %logstart function for activating logging in mid-session is used as
623 The %logstart function for activating logging in mid-session is used as
624 follows:
624 follows:
625
625
626 %logstart [log_name [log_mode]]
626 %logstart [log_name [log_mode]]
627
627
628 If no name is given, it defaults to a file named 'log' in your
628 If no name is given, it defaults to a file named 'log' in your
629 IPYTHON_DIR directory, in 'rotate' mode (see below).
629 IPYTHON_DIR directory, in 'rotate' mode (see below).
630
630
631 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
631 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
632 history up to that point and then continues logging.
632 history up to that point and then continues logging.
633
633
634 %logstart takes a second optional parameter: logging mode. This can be
634 %logstart takes a second optional parameter: logging mode. This can be
635 one of (note that the modes are given unquoted):
635 one of (note that the modes are given unquoted):
636
636
637 * [over:] overwrite existing log_name.
637 * [over:] overwrite existing log_name.
638 * [backup:] rename (if exists) to log_name~ and start log_name.
638 * [backup:] rename (if exists) to log_name~ and start log_name.
639 * [append:] well, that says it.
639 * [append:] well, that says it.
640 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
640 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
641
641
642 The %logoff and %logon functions allow you to temporarily stop and
642 The %logoff and %logon functions allow you to temporarily stop and
643 resume logging to a file which had previously been started with
643 resume logging to a file which had previously been started with
644 %logstart. They will fail (with an explanation) if you try to use them
644 %logstart. They will fail (with an explanation) if you try to use them
645 before logging has been started.
645 before logging has been started.
646
646
647 .. _system_shell_access:
647 .. _system_shell_access:
648
648
649 System shell access
649 System shell access
650 -------------------
650 -------------------
651
651
652 Any input line beginning with a ! character is passed verbatim (minus
652 Any input line beginning with a ! character is passed verbatim (minus
653 the !, of course) to the underlying operating system. For example,
653 the !, of course) to the underlying operating system. For example,
654 typing !ls will run 'ls' in the current directory.
654 typing !ls will run 'ls' in the current directory.
655
655
656 Manual capture of command output
656 Manual capture of command output
657 --------------------------------
657 --------------------------------
658
658
659 If the input line begins with two exclamation marks, !!, the command is
659 If the input line begins with two exclamation marks, !!, the command is
660 executed but its output is captured and returned as a python list, split
660 executed but its output is captured and returned as a python list, split
661 on newlines. Any output sent by the subprocess to standard error is
661 on newlines. Any output sent by the subprocess to standard error is
662 printed separately, so that the resulting list only captures standard
662 printed separately, so that the resulting list only captures standard
663 output. The !! syntax is a shorthand for the %sx magic command.
663 output. The !! syntax is a shorthand for the %sx magic command.
664
664
665 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
665 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
666 but allowing more fine-grained control of the capture details, and
666 but allowing more fine-grained control of the capture details, and
667 storing the result directly into a named variable. The direct use of
667 storing the result directly into a named variable. The direct use of
668 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
668 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
669 instead.
669 instead.
670
670
671 IPython also allows you to expand the value of python variables when
671 IPython also allows you to expand the value of python variables when
672 making system calls. Any python variable or expression which you prepend
672 making system calls. Any python variable or expression which you prepend
673 with $ will get expanded before the system call is made::
673 with $ will get expanded before the system call is made::
674
674
675 In [1]: pyvar='Hello world'
675 In [1]: pyvar='Hello world'
676 In [2]: !echo "A python variable: $pyvar"
676 In [2]: !echo "A python variable: $pyvar"
677 A python variable: Hello world
677 A python variable: Hello world
678
678
679 If you want the shell to actually see a literal $, you need to type it
679 If you want the shell to actually see a literal $, you need to type it
680 twice::
680 twice::
681
681
682 In [3]: !echo "A system variable: $$HOME"
682 In [3]: !echo "A system variable: $$HOME"
683 A system variable: /home/fperez
683 A system variable: /home/fperez
684
684
685 You can pass arbitrary expressions, though you'll need to delimit them
685 You can pass arbitrary expressions, though you'll need to delimit them
686 with {} if there is ambiguity as to the extent of the expression::
686 with {} if there is ambiguity as to the extent of the expression::
687
687
688 In [5]: x=10
688 In [5]: x=10
689 In [6]: y=20
689 In [6]: y=20
690 In [13]: !echo $x+y
690 In [13]: !echo $x+y
691 10+y
691 10+y
692 In [7]: !echo ${x+y}
692 In [7]: !echo ${x+y}
693 30
693 30
694
694
695 Even object attributes can be expanded::
695 Even object attributes can be expanded::
696
696
697 In [12]: !echo $sys.argv
697 In [12]: !echo $sys.argv
698 [/home/fperez/usr/bin/ipython]
698 [/home/fperez/usr/bin/ipython]
699
699
700
700
701 System command aliases
701 System command aliases
702 ----------------------
702 ----------------------
703
703
704 The %alias magic function and the alias option in the ipythonrc
704 The %alias magic function and the alias option in the ipythonrc
705 configuration file allow you to define magic functions which are in fact
705 configuration file allow you to define magic functions which are in fact
706 system shell commands. These aliases can have parameters.
706 system shell commands. These aliases can have parameters.
707
707
708 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
708 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
709
709
710 Then, typing '%alias_name params' will execute the system command 'cmd
710 Then, typing '%alias_name params' will execute the system command 'cmd
711 params' (from your underlying operating system).
711 params' (from your underlying operating system).
712
712
713 You can also define aliases with parameters using %s specifiers (one per
713 You can also define aliases with parameters using %s specifiers (one per
714 parameter). The following example defines the %parts function as an
714 parameter). The following example defines the %parts function as an
715 alias to the command 'echo first %s second %s' where each %s will be
715 alias to the command 'echo first %s second %s' where each %s will be
716 replaced by a positional parameter to the call to %parts::
716 replaced by a positional parameter to the call to %parts::
717
717
718 In [1]: alias parts echo first %s second %s
718 In [1]: alias parts echo first %s second %s
719 In [2]: %parts A B
719 In [2]: %parts A B
720 first A second B
720 first A second B
721 In [3]: %parts A
721 In [3]: %parts A
722 Incorrect number of arguments: 2 expected.
722 Incorrect number of arguments: 2 expected.
723 parts is an alias to: 'echo first %s second %s'
723 parts is an alias to: 'echo first %s second %s'
724
724
725 If called with no parameters, %alias prints the table of currently
725 If called with no parameters, %alias prints the table of currently
726 defined aliases.
726 defined aliases.
727
727
728 The %rehash/rehashx magics allow you to load your entire $PATH as
728 The %rehash/rehashx magics allow you to load your entire $PATH as
729 ipython aliases. See their respective docstrings (or sec. 6.2
729 ipython aliases. See their respective docstrings (or sec. 6.2
730 <#sec:magic> for further details).
730 <#sec:magic> for further details).
731
731
732
732
733 .. _dreload:
733 .. _dreload:
734
734
735 Recursive reload
735 Recursive reload
736 ----------------
736 ----------------
737
737
738 The dreload function does a recursive reload of a module: changes made
738 The dreload function does a recursive reload of a module: changes made
739 to the module since you imported will actually be available without
739 to the module since you imported will actually be available without
740 having to exit.
740 having to exit.
741
741
742
742
743 Verbose and colored exception traceback printouts
743 Verbose and colored exception traceback printouts
744 -------------------------------------------------
744 -------------------------------------------------
745
745
746 IPython provides the option to see very detailed exception tracebacks,
746 IPython provides the option to see very detailed exception tracebacks,
747 which can be especially useful when debugging large programs. You can
747 which can be especially useful when debugging large programs. You can
748 run any Python file with the %run function to benefit from these
748 run any Python file with the %run function to benefit from these
749 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
749 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
750 be colored (if your terminal supports it) which makes them much easier
750 be colored (if your terminal supports it) which makes them much easier
751 to parse visually.
751 to parse visually.
752
752
753 See the magic xmode and colors functions for details (just type %magic).
753 See the magic xmode and colors functions for details (just type %magic).
754
754
755 These features are basically a terminal version of Ka-Ping Yee's cgitb
755 These features are basically a terminal version of Ka-Ping Yee's cgitb
756 module, now part of the standard Python library.
756 module, now part of the standard Python library.
757
757
758
758
759 .. _input_caching:
759 .. _input_caching:
760
760
761 Input caching system
761 Input caching system
762 --------------------
762 --------------------
763
763
764 IPython offers numbered prompts (In/Out) with input and output caching
764 IPython offers numbered prompts (In/Out) with input and output caching
765 (also referred to as 'input history'). All input is saved and can be
765 (also referred to as 'input history'). All input is saved and can be
766 retrieved as variables (besides the usual arrow key recall), in
766 retrieved as variables (besides the usual arrow key recall), in
767 addition to the %rep magic command that brings a history entry
767 addition to the %rep magic command that brings a history entry
768 up for editing on the next command line.
768 up for editing on the next command line.
769
769
770 The following GLOBAL variables always exist (so don't overwrite them!):
770 The following GLOBAL variables always exist (so don't overwrite them!):
771 _i: stores previous input. _ii: next previous. _iii: next-next previous.
771 _i: stores previous input. _ii: next previous. _iii: next-next previous.
772 _ih : a list of all input _ih[n] is the input from line n and this list
772 _ih : a list of all input _ih[n] is the input from line n and this list
773 is aliased to the global variable In. If you overwrite In with a
773 is aliased to the global variable In. If you overwrite In with a
774 variable of your own, you can remake the assignment to the internal list
774 variable of your own, you can remake the assignment to the internal list
775 with a simple 'In=_ih'.
775 with a simple 'In=_ih'.
776
776
777 Additionally, global variables named _i<n> are dynamically created (<n>
777 Additionally, global variables named _i<n> are dynamically created (<n>
778 being the prompt counter), such that
778 being the prompt counter), such that
779 _i<n> == _ih[<n>] == In[<n>].
779 _i<n> == _ih[<n>] == In[<n>].
780
780
781 For example, what you typed at prompt 14 is available as _i14, _ih[14]
781 For example, what you typed at prompt 14 is available as _i14, _ih[14]
782 and In[14].
782 and In[14].
783
783
784 This allows you to easily cut and paste multi line interactive prompts
784 This allows you to easily cut and paste multi line interactive prompts
785 by printing them out: they print like a clean string, without prompt
785 by printing them out: they print like a clean string, without prompt
786 characters. You can also manipulate them like regular variables (they
786 characters. You can also manipulate them like regular variables (they
787 are strings), modify or exec them (typing 'exec _i9' will re-execute the
787 are strings), modify or exec them (typing 'exec _i9' will re-execute the
788 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
788 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
789 9 through 13 and line 18).
789 9 through 13 and line 18).
790
790
791 You can also re-execute multiple lines of input easily by using the
791 You can also re-execute multiple lines of input easily by using the
792 magic %macro function (which automates the process and allows
792 magic %macro function (which automates the process and allows
793 re-execution without having to type 'exec' every time). The macro system
793 re-execution without having to type 'exec' every time). The macro system
794 also allows you to re-execute previous lines which include magic
794 also allows you to re-execute previous lines which include magic
795 function calls (which require special processing). Type %macro? or see
795 function calls (which require special processing). Type %macro? or see
796 sec. 6.2 <#sec:magic> for more details on the macro system.
796 sec. 6.2 <#sec:magic> for more details on the macro system.
797
797
798 A history function %hist allows you to see any part of your input
798 A history function %hist allows you to see any part of your input
799 history by printing a range of the _i variables.
799 history by printing a range of the _i variables.
800
800
801 You can also search ('grep') through your history by typing
801 You can also search ('grep') through your history by typing
802 '%hist -g somestring'. This also searches through the so called *shadow history*,
802 '%hist -g somestring'. This also searches through the so called *shadow history*,
803 which remembers all the commands (apart from multiline code blocks)
803 which remembers all the commands (apart from multiline code blocks)
804 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
804 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
805 etc. You can bring shadow history entries listed by '%hist -g' up for editing
805 etc. You can bring shadow history entries listed by '%hist -g' up for editing
806 (or re-execution by just pressing ENTER) with %rep command. Shadow history
806 (or re-execution by just pressing ENTER) with %rep command. Shadow history
807 entries are not available as _iNUMBER variables, and they are identified by
807 entries are not available as _iNUMBER variables, and they are identified by
808 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
808 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
809 history entry, but 0231 is a shadow history entry.
809 history entry, but 0231 is a shadow history entry.
810
810
811 Shadow history was added because the readline history is inherently very
811 Shadow history was added because the readline history is inherently very
812 unsafe - if you have multiple IPython sessions open, the last session
812 unsafe - if you have multiple IPython sessions open, the last session
813 to close will overwrite the history of previountly closed session. Likewise,
813 to close will overwrite the history of previountly closed session. Likewise,
814 if a crash occurs, history is never saved, whereas shadow history entries
814 if a crash occurs, history is never saved, whereas shadow history entries
815 are added after entering every command (so a command executed
815 are added after entering every command (so a command executed
816 in another IPython session is immediately available in other IPython
816 in another IPython session is immediately available in other IPython
817 sessions that are open).
817 sessions that are open).
818
818
819 To conserve space, a command can exist in shadow history only once - it doesn't
819 To conserve space, a command can exist in shadow history only once - it doesn't
820 make sense to store a common line like "cd .." a thousand times. The idea is
820 make sense to store a common line like "cd .." a thousand times. The idea is
821 mainly to provide a reliable place where valuable, hard-to-remember commands can
821 mainly to provide a reliable place where valuable, hard-to-remember commands can
822 always be retrieved, as opposed to providing an exact sequence of commands
822 always be retrieved, as opposed to providing an exact sequence of commands
823 you have entered in actual order.
823 you have entered in actual order.
824
824
825 Because shadow history has all the commands you have ever executed,
825 Because shadow history has all the commands you have ever executed,
826 time taken by %hist -g will increase oven time. If it ever starts to take
826 time taken by %hist -g will increase oven time. If it ever starts to take
827 too long (or it ends up containing sensitive information like passwords),
827 too long (or it ends up containing sensitive information like passwords),
828 clear the shadow history by `%clear shadow_nuke`.
828 clear the shadow history by `%clear shadow_nuke`.
829
829
830 Time taken to add entries to shadow history should be negligible, but
830 Time taken to add entries to shadow history should be negligible, but
831 in any case, if you start noticing performance degradation after using
831 in any case, if you start noticing performance degradation after using
832 IPython for a long time (or running a script that floods the shadow history!),
832 IPython for a long time (or running a script that floods the shadow history!),
833 you can 'compress' the shadow history by executing
833 you can 'compress' the shadow history by executing
834 `%clear shadow_compress`. In practice, this should never be necessary
834 `%clear shadow_compress`. In practice, this should never be necessary
835 in normal use.
835 in normal use.
836
836
837 .. _output_caching:
837 .. _output_caching:
838
838
839 Output caching system
839 Output caching system
840 ---------------------
840 ---------------------
841
841
842 For output that is returned from actions, a system similar to the input
842 For output that is returned from actions, a system similar to the input
843 cache exists but using _ instead of _i. Only actions that produce a
843 cache exists but using _ instead of _i. Only actions that produce a
844 result (NOT assignments, for example) are cached. If you are familiar
844 result (NOT assignments, for example) are cached. If you are familiar
845 with Mathematica, IPython's _ variables behave exactly like
845 with Mathematica, IPython's _ variables behave exactly like
846 Mathematica's % variables.
846 Mathematica's % variables.
847
847
848 The following GLOBAL variables always exist (so don't overwrite them!):
848 The following GLOBAL variables always exist (so don't overwrite them!):
849
849
850 * [_] (a single underscore) : stores previous output, like Python's
850 * [_] (a single underscore) : stores previous output, like Python's
851 default interpreter.
851 default interpreter.
852 * [__] (two underscores): next previous.
852 * [__] (two underscores): next previous.
853 * [___] (three underscores): next-next previous.
853 * [___] (three underscores): next-next previous.
854
854
855 Additionally, global variables named _<n> are dynamically created (<n>
855 Additionally, global variables named _<n> are dynamically created (<n>
856 being the prompt counter), such that the result of output <n> is always
856 being the prompt counter), such that the result of output <n> is always
857 available as _<n> (don't use the angle brackets, just the number, e.g.
857 available as _<n> (don't use the angle brackets, just the number, e.g.
858 _21).
858 _21).
859
859
860 These global variables are all stored in a global dictionary (not a
860 These global variables are all stored in a global dictionary (not a
861 list, since it only has entries for lines which returned a result)
861 list, since it only has entries for lines which returned a result)
862 available under the names _oh and Out (similar to _ih and In). So the
862 available under the names _oh and Out (similar to _ih and In). So the
863 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
863 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
864 accidentally overwrite the Out variable you can recover it by typing
864 accidentally overwrite the Out variable you can recover it by typing
865 'Out=_oh' at the prompt.
865 'Out=_oh' at the prompt.
866
866
867 This system obviously can potentially put heavy memory demands on your
867 This system obviously can potentially put heavy memory demands on your
868 system, since it prevents Python's garbage collector from removing any
868 system, since it prevents Python's garbage collector from removing any
869 previously computed results. You can control how many results are kept
869 previously computed results. You can control how many results are kept
870 in memory with the option (at the command line or in your ipythonrc
870 in memory with the option (at the command line or in your ipythonrc
871 file) cache_size. If you set it to 0, the whole system is completely
871 file) cache_size. If you set it to 0, the whole system is completely
872 disabled and the prompts revert to the classic '>>>' of normal Python.
872 disabled and the prompts revert to the classic '>>>' of normal Python.
873
873
874
874
875 Directory history
875 Directory history
876 -----------------
876 -----------------
877
877
878 Your history of visited directories is kept in the global list _dh, and
878 Your history of visited directories is kept in the global list _dh, and
879 the magic %cd command can be used to go to any entry in that list. The
879 the magic %cd command can be used to go to any entry in that list. The
880 %dhist command allows you to view this history. Do ``cd -<TAB`` to
880 %dhist command allows you to view this history. Do ``cd -<TAB`` to
881 conventiently view the directory history.
881 conventiently view the directory history.
882
882
883
883
884 Automatic parentheses and quotes
884 Automatic parentheses and quotes
885 --------------------------------
885 --------------------------------
886
886
887 These features were adapted from Nathan Gray's LazyPython. They are
887 These features were adapted from Nathan Gray's LazyPython. They are
888 meant to allow less typing for common situations.
888 meant to allow less typing for common situations.
889
889
890
890
891 Automatic parentheses
891 Automatic parentheses
892 ---------------------
892 ---------------------
893
893
894 Callable objects (i.e. functions, methods, etc) can be invoked like this
894 Callable objects (i.e. functions, methods, etc) can be invoked like this
895 (notice the commas between the arguments)::
895 (notice the commas between the arguments)::
896
896
897 >>> callable_ob arg1, arg2, arg3
897 >>> callable_ob arg1, arg2, arg3
898
898
899 and the input will be translated to this::
899 and the input will be translated to this::
900
900
901 -> callable_ob(arg1, arg2, arg3)
901 -> callable_ob(arg1, arg2, arg3)
902
902
903 You can force automatic parentheses by using '/' as the first character
903 You can force automatic parentheses by using '/' as the first character
904 of a line. For example::
904 of a line. For example::
905
905
906 >>> /globals # becomes 'globals()'
906 >>> /globals # becomes 'globals()'
907
907
908 Note that the '/' MUST be the first character on the line! This won't work::
908 Note that the '/' MUST be the first character on the line! This won't work::
909
909
910 >>> print /globals # syntax error
910 >>> print /globals # syntax error
911
911
912 In most cases the automatic algorithm should work, so you should rarely
912 In most cases the automatic algorithm should work, so you should rarely
913 need to explicitly invoke /. One notable exception is if you are trying
913 need to explicitly invoke /. One notable exception is if you are trying
914 to call a function with a list of tuples as arguments (the parenthesis
914 to call a function with a list of tuples as arguments (the parenthesis
915 will confuse IPython)::
915 will confuse IPython)::
916
916
917 In [1]: zip (1,2,3),(4,5,6) # won't work
917 In [1]: zip (1,2,3),(4,5,6) # won't work
918
918
919 but this will work::
919 but this will work::
920
920
921 In [2]: /zip (1,2,3),(4,5,6)
921 In [2]: /zip (1,2,3),(4,5,6)
922 ---> zip ((1,2,3),(4,5,6))
922 ---> zip ((1,2,3),(4,5,6))
923 Out[2]= [(1, 4), (2, 5), (3, 6)]
923 Out[2]= [(1, 4), (2, 5), (3, 6)]
924
924
925 IPython tells you that it has altered your command line by displaying
925 IPython tells you that it has altered your command line by displaying
926 the new command line preceded by ->. e.g.::
926 the new command line preceded by ->. e.g.::
927
927
928 In [18]: callable list
928 In [18]: callable list
929 ----> callable (list)
929 ----> callable (list)
930
930
931
931
932 Automatic quoting
932 Automatic quoting
933 -----------------
933 -----------------
934
934
935 You can force automatic quoting of a function's arguments by using ','
935 You can force automatic quoting of a function's arguments by using ','
936 or ';' as the first character of a line. For example::
936 or ';' as the first character of a line. For example::
937
937
938 >>> ,my_function /home/me # becomes my_function("/home/me")
938 >>> ,my_function /home/me # becomes my_function("/home/me")
939
939
940 If you use ';' instead, the whole argument is quoted as a single string
940 If you use ';' instead, the whole argument is quoted as a single string
941 (while ',' splits on whitespace)::
941 (while ',' splits on whitespace)::
942
942
943 >>> ,my_function a b c # becomes my_function("a","b","c")
943 >>> ,my_function a b c # becomes my_function("a","b","c")
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 Note that the ',' or ';' MUST be the first character on the line! This
947 Note that the ',' or ';' MUST be the first character on the line! This
948 won't work::
948 won't work::
949
949
950 >>> x = ,my_function /home/me # syntax error
950 >>> x = ,my_function /home/me # syntax error
951
951
952 IPython as your default Python environment
952 IPython as your default Python environment
953 ==========================================
953 ==========================================
954
954
955 Python honors the environment variable PYTHONSTARTUP and will execute at
955 Python honors the environment variable PYTHONSTARTUP and will execute at
956 startup the file referenced by this variable. If you put at the end of
956 startup the file referenced by this variable. If you put at the end of
957 this file the following two lines of code::
957 this file the following two lines of code::
958
958
959 from IPython.frontend.terminal.ipapp import launch_new_instance
959 from IPython.frontend.terminal.ipapp import launch_new_instance
960 launch_new_instance()
960 launch_new_instance()
961 raise SystemExit
961 raise SystemExit
962
962
963 then IPython will be your working environment anytime you start Python.
963 then IPython will be your working environment anytime you start Python.
964 The ``raise SystemExit`` is needed to exit Python when
964 The ``raise SystemExit`` is needed to exit Python when
965 it finishes, otherwise you'll be back at the normal Python '>>>'
965 it finishes, otherwise you'll be back at the normal Python '>>>'
966 prompt.
966 prompt.
967
967
968 This is probably useful to developers who manage multiple Python
968 This is probably useful to developers who manage multiple Python
969 versions and don't want to have correspondingly multiple IPython
969 versions and don't want to have correspondingly multiple IPython
970 versions. Note that in this mode, there is no way to pass IPython any
970 versions. Note that in this mode, there is no way to pass IPython any
971 command-line options, as those are trapped first by Python itself.
971 command-line options, as those are trapped first by Python itself.
972
972
973 .. _Embedding:
973 .. _Embedding:
974
974
975 Embedding IPython
975 Embedding IPython
976 =================
976 =================
977
977
978 It is possible to start an IPython instance inside your own Python
978 It is possible to start an IPython instance inside your own Python
979 programs. This allows you to evaluate dynamically the state of your
979 programs. This allows you to evaluate dynamically the state of your
980 code, operate with your variables, analyze them, etc. Note however that
980 code, operate with your variables, analyze them, etc. Note however that
981 any changes you make to values while in the shell do not propagate back
981 any changes you make to values while in the shell do not propagate back
982 to the running code, so it is safe to modify your values because you
982 to the running code, so it is safe to modify your values because you
983 won't break your code in bizarre ways by doing so.
983 won't break your code in bizarre ways by doing so.
984
984
985 This feature allows you to easily have a fully functional python
985 This feature allows you to easily have a fully functional python
986 environment for doing object introspection anywhere in your code with a
986 environment for doing object introspection anywhere in your code with a
987 simple function call. In some cases a simple print statement is enough,
987 simple function call. In some cases a simple print statement is enough,
988 but if you need to do more detailed analysis of a code fragment this
988 but if you need to do more detailed analysis of a code fragment this
989 feature can be very valuable.
989 feature can be very valuable.
990
990
991 It can also be useful in scientific computing situations where it is
991 It can also be useful in scientific computing situations where it is
992 common to need to do some automatic, computationally intensive part and
992 common to need to do some automatic, computationally intensive part and
993 then stop to look at data, plots, etc.
993 then stop to look at data, plots, etc.
994 Opening an IPython instance will give you full access to your data and
994 Opening an IPython instance will give you full access to your data and
995 functions, and you can resume program execution once you are done with
995 functions, and you can resume program execution once you are done with
996 the interactive part (perhaps to stop again later, as many times as
996 the interactive part (perhaps to stop again later, as many times as
997 needed).
997 needed).
998
998
999 The following code snippet is the bare minimum you need to include in
999 The following code snippet is the bare minimum you need to include in
1000 your Python programs for this to work (detailed examples follow later)::
1000 your Python programs for this to work (detailed examples follow later)::
1001
1001
1002 from IPython import embed
1002 from IPython import embed
1003
1003
1004 embed() # this call anywhere in your program will start IPython
1004 embed() # this call anywhere in your program will start IPython
1005
1005
1006 You can run embedded instances even in code which is itself being run at
1006 You can run embedded instances even in code which is itself being run at
1007 the IPython interactive prompt with '%run <filename>'. Since it's easy
1007 the IPython interactive prompt with '%run <filename>'. Since it's easy
1008 to get lost as to where you are (in your top-level IPython or in your
1008 to get lost as to where you are (in your top-level IPython or in your
1009 embedded one), it's a good idea in such cases to set the in/out prompts
1009 embedded one), it's a good idea in such cases to set the in/out prompts
1010 to something different for the embedded instances. The code examples
1010 to something different for the embedded instances. The code examples
1011 below illustrate this.
1011 below illustrate this.
1012
1012
1013 You can also have multiple IPython instances in your program and open
1013 You can also have multiple IPython instances in your program and open
1014 them separately, for example with different options for data
1014 them separately, for example with different options for data
1015 presentation. If you close and open the same instance multiple times,
1015 presentation. If you close and open the same instance multiple times,
1016 its prompt counters simply continue from each execution to the next.
1016 its prompt counters simply continue from each execution to the next.
1017
1017
1018 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
1018 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
1019 module for more details on the use of this system.
1019 module for more details on the use of this system.
1020
1020
1021 The following sample file illustrating how to use the embedding
1021 The following sample file illustrating how to use the embedding
1022 functionality is provided in the examples directory as example-embed.py.
1022 functionality is provided in the examples directory as example-embed.py.
1023 It should be fairly self-explanatory:
1023 It should be fairly self-explanatory:
1024
1024
1025 .. literalinclude:: ../../examples/core/example-embed.py
1025 .. literalinclude:: ../../examples/core/example-embed.py
1026 :language: python
1026 :language: python
1027
1027
1028 Once you understand how the system functions, you can use the following
1028 Once you understand how the system functions, you can use the following
1029 code fragments in your programs which are ready for cut and paste:
1029 code fragments in your programs which are ready for cut and paste:
1030
1030
1031 .. literalinclude:: ../../examples/core/example-embed-short.py
1031 .. literalinclude:: ../../examples/core/example-embed-short.py
1032 :language: python
1032 :language: python
1033
1033
1034 Using the Python debugger (pdb)
1034 Using the Python debugger (pdb)
1035 ===============================
1035 ===============================
1036
1036
1037 Running entire programs via pdb
1037 Running entire programs via pdb
1038 -------------------------------
1038 -------------------------------
1039
1039
1040 pdb, the Python debugger, is a powerful interactive debugger which
1040 pdb, the Python debugger, is a powerful interactive debugger which
1041 allows you to step through code, set breakpoints, watch variables,
1041 allows you to step through code, set breakpoints, watch variables,
1042 etc. IPython makes it very easy to start any script under the control
1042 etc. IPython makes it very easy to start any script under the control
1043 of pdb, regardless of whether you have wrapped it into a 'main()'
1043 of pdb, regardless of whether you have wrapped it into a 'main()'
1044 function or not. For this, simply type '%run -d myscript' at an
1044 function or not. For this, simply type '%run -d myscript' at an
1045 IPython prompt. See the %run command's documentation (via '%run?' or
1045 IPython prompt. See the %run command's documentation (via '%run?' or
1046 in Sec. magic_ for more details, including how to control where pdb
1046 in Sec. magic_ for more details, including how to control where pdb
1047 will stop execution first.
1047 will stop execution first.
1048
1048
1049 For more information on the use of the pdb debugger, read the included
1049 For more information on the use of the pdb debugger, read the included
1050 pdb.doc file (part of the standard Python distribution). On a stock
1050 pdb.doc file (part of the standard Python distribution). On a stock
1051 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1051 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1052 easiest way to read it is by using the help() function of the pdb module
1052 easiest way to read it is by using the help() function of the pdb module
1053 as follows (in an IPython prompt)::
1053 as follows (in an IPython prompt)::
1054
1054
1055 In [1]: import pdb
1055 In [1]: import pdb
1056 In [2]: pdb.help()
1056 In [2]: pdb.help()
1057
1057
1058 This will load the pdb.doc document in a file viewer for you automatically.
1058 This will load the pdb.doc document in a file viewer for you automatically.
1059
1059
1060
1060
1061 Automatic invocation of pdb on exceptions
1061 Automatic invocation of pdb on exceptions
1062 -----------------------------------------
1062 -----------------------------------------
1063
1063
1064 IPython, if started with the -pdb option (or if the option is set in
1064 IPython, if started with the -pdb option (or if the option is set in
1065 your rc file) can call the Python pdb debugger every time your code
1065 your rc file) can call the Python pdb debugger every time your code
1066 triggers an uncaught exception. This feature
1066 triggers an uncaught exception. This feature
1067 can also be toggled at any time with the %pdb magic command. This can be
1067 can also be toggled at any time with the %pdb magic command. This can be
1068 extremely useful in order to find the origin of subtle bugs, because pdb
1068 extremely useful in order to find the origin of subtle bugs, because pdb
1069 opens up at the point in your code which triggered the exception, and
1069 opens up at the point in your code which triggered the exception, and
1070 while your program is at this point 'dead', all the data is still
1070 while your program is at this point 'dead', all the data is still
1071 available and you can walk up and down the stack frame and understand
1071 available and you can walk up and down the stack frame and understand
1072 the origin of the problem.
1072 the origin of the problem.
1073
1073
1074 Furthermore, you can use these debugging facilities both with the
1074 Furthermore, you can use these debugging facilities both with the
1075 embedded IPython mode and without IPython at all. For an embedded shell
1075 embedded IPython mode and without IPython at all. For an embedded shell
1076 (see sec. Embedding_), simply call the constructor with
1076 (see sec. Embedding_), simply call the constructor with
1077 '--pdb' in the argument string and automatically pdb will be called if an
1077 '--pdb' in the argument string and automatically pdb will be called if an
1078 uncaught exception is triggered by your code.
1078 uncaught exception is triggered by your code.
1079
1079
1080 For stand-alone use of the feature in your programs which do not use
1080 For stand-alone use of the feature in your programs which do not use
1081 IPython at all, put the following lines toward the top of your 'main'
1081 IPython at all, put the following lines toward the top of your 'main'
1082 routine::
1082 routine::
1083
1083
1084 import sys
1084 import sys
1085 from IPython.core import ultratb
1085 from IPython.core import ultratb
1086 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1086 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1087 color_scheme='Linux', call_pdb=1)
1087 color_scheme='Linux', call_pdb=1)
1088
1088
1089 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1089 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1090 detailed or normal tracebacks respectively. The color_scheme keyword can
1090 detailed or normal tracebacks respectively. The color_scheme keyword can
1091 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1091 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1092 options which can be set in IPython with -colors and -xmode.
1092 options which can be set in IPython with -colors and -xmode.
1093
1093
1094 This will give any of your programs detailed, colored tracebacks with
1094 This will give any of your programs detailed, colored tracebacks with
1095 automatic invocation of pdb.
1095 automatic invocation of pdb.
1096
1096
1097
1097
1098 Extensions for syntax processing
1098 Extensions for syntax processing
1099 ================================
1099 ================================
1100
1100
1101 This isn't for the faint of heart, because the potential for breaking
1101 This isn't for the faint of heart, because the potential for breaking
1102 things is quite high. But it can be a very powerful and useful feature.
1102 things is quite high. But it can be a very powerful and useful feature.
1103 In a nutshell, you can redefine the way IPython processes the user input
1103 In a nutshell, you can redefine the way IPython processes the user input
1104 line to accept new, special extensions to the syntax without needing to
1104 line to accept new, special extensions to the syntax without needing to
1105 change any of IPython's own code.
1105 change any of IPython's own code.
1106
1106
1107 In the IPython/extensions directory you will find some examples
1107 In the IPython/extensions directory you will find some examples
1108 supplied, which we will briefly describe now. These can be used 'as is'
1108 supplied, which we will briefly describe now. These can be used 'as is'
1109 (and both provide very useful functionality), or you can use them as a
1109 (and both provide very useful functionality), or you can use them as a
1110 starting point for writing your own extensions.
1110 starting point for writing your own extensions.
1111
1111
1112
1112
1113 Pasting of code starting with '>>> ' or '... '
1113 Pasting of code starting with '>>> ' or '... '
1114 ----------------------------------------------
1114 ----------------------------------------------
1115
1115
1116 In the python tutorial it is common to find code examples which have
1116 In the python tutorial it is common to find code examples which have
1117 been taken from real python sessions. The problem with those is that all
1117 been taken from real python sessions. The problem with those is that all
1118 the lines begin with either '>>> ' or '... ', which makes it impossible
1118 the lines begin with either '>>> ' or '... ', which makes it impossible
1119 to paste them all at once. One must instead do a line by line manual
1119 to paste them all at once. One must instead do a line by line manual
1120 copying, carefully removing the leading extraneous characters.
1120 copying, carefully removing the leading extraneous characters.
1121
1121
1122 This extension identifies those starting characters and removes them
1122 This extension identifies those starting characters and removes them
1123 from the input automatically, so that one can paste multi-line examples
1123 from the input automatically, so that one can paste multi-line examples
1124 directly into IPython, saving a lot of time. Please look at the file
1124 directly into IPython, saving a lot of time. Please look at the file
1125 InterpreterPasteInput.py in the IPython/extensions directory for details
1125 InterpreterPasteInput.py in the IPython/extensions directory for details
1126 on how this is done.
1126 on how this is done.
1127
1127
1128 IPython comes with a special profile enabling this feature, called
1128 IPython comes with a special profile enabling this feature, called
1129 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1129 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1130 will be available. In a normal IPython session you can activate the
1130 will be available. In a normal IPython session you can activate the
1131 feature by importing the corresponding module with:
1131 feature by importing the corresponding module with:
1132 In [1]: import IPython.extensions.InterpreterPasteInput
1132 In [1]: import IPython.extensions.InterpreterPasteInput
1133
1133
1134 The following is a 'screenshot' of how things work when this extension
1134 The following is a 'screenshot' of how things work when this extension
1135 is on, copying an example from the standard tutorial::
1135 is on, copying an example from the standard tutorial::
1136
1136
1137 IPython profile: tutorial
1137 IPython profile: tutorial
1138
1138
1139 *** Pasting of code with ">>>" or "..." has been enabled.
1139 *** Pasting of code with ">>>" or "..." has been enabled.
1140
1140
1141 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1141 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1142 ...: ... """Return a list containing the Fibonacci series up to
1142 ...: ... """Return a list containing the Fibonacci series up to
1143 n."""
1143 n."""
1144 ...: ... result = []
1144 ...: ... result = []
1145 ...: ... a, b = 0, 1
1145 ...: ... a, b = 0, 1
1146 ...: ... while b < n:
1146 ...: ... while b < n:
1147 ...: ... result.append(b) # see below
1147 ...: ... result.append(b) # see below
1148 ...: ... a, b = b, a+b
1148 ...: ... a, b = b, a+b
1149 ...: ... return result
1149 ...: ... return result
1150 ...:
1150 ...:
1151
1151
1152 In [2]: fib2(10)
1152 In [2]: fib2(10)
1153 Out[2]: [1, 1, 2, 3, 5, 8]
1153 Out[2]: [1, 1, 2, 3, 5, 8]
1154
1154
1155 Note that as currently written, this extension does not recognize
1155 Note that as currently written, this extension does not recognize
1156 IPython's prompts for pasting. Those are more complicated, since the
1156 IPython's prompts for pasting. Those are more complicated, since the
1157 user can change them very easily, they involve numbers and can vary in
1157 user can change them very easily, they involve numbers and can vary in
1158 length. One could however extract all the relevant information from the
1158 length. One could however extract all the relevant information from the
1159 IPython instance and build an appropriate regular expression. This is
1159 IPython instance and build an appropriate regular expression. This is
1160 left as an exercise for the reader.
1160 left as an exercise for the reader.
1161
1161
1162
1162
1163 Input of physical quantities with units
1163 Input of physical quantities with units
1164 ---------------------------------------
1164 ---------------------------------------
1165
1165
1166 The module PhysicalQInput allows a simplified form of input for physical
1166 The module PhysicalQInput allows a simplified form of input for physical
1167 quantities with units. This file is meant to be used in conjunction with
1167 quantities with units. This file is meant to be used in conjunction with
1168 the PhysicalQInteractive module (in the same directory) and
1168 the PhysicalQInteractive module (in the same directory) and
1169 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1169 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1170 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1170 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1171
1171
1172 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1172 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1173 but these must be declared as instances of a class. For example, to
1173 but these must be declared as instances of a class. For example, to
1174 define v as a velocity of 3 m/s, normally you would write::
1174 define v as a velocity of 3 m/s, normally you would write::
1175
1175
1176 In [1]: v = PhysicalQuantity(3,'m/s')
1176 In [1]: v = PhysicalQuantity(3,'m/s')
1177
1177
1178 Using the PhysicalQ_Input extension this can be input instead as:
1178 Using the PhysicalQ_Input extension this can be input instead as:
1179 In [1]: v = 3 m/s
1179 In [1]: v = 3 m/s
1180 which is much more convenient for interactive use (even though it is
1180 which is much more convenient for interactive use (even though it is
1181 blatantly invalid Python syntax).
1181 blatantly invalid Python syntax).
1182
1182
1183 The physics profile supplied with IPython (enabled via 'ipython -p
1183 The physics profile supplied with IPython (enabled via 'ipython -p
1184 physics') uses these extensions, which you can also activate with:
1184 physics') uses these extensions, which you can also activate with:
1185
1185
1186 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1186 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1187 from IPython.extensions.PhysicalQInteractive import *
1187 from IPython.extensions.PhysicalQInteractive import *
1188 import IPython.extensions.PhysicalQInput
1188 import IPython.extensions.PhysicalQInput
1189
1189
1190 .. _gui_support:
1190 .. _gui_support:
1191
1191
1192 GUI event loop support support
1192 GUI event loop support support
1193 ==============================
1193 ==============================
1194
1194
1195 .. versionadded:: 0.11
1195 .. versionadded:: 0.11
1196 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1196 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1197
1197
1198 IPython has excellent support for working interactively with Graphical User
1198 IPython has excellent support for working interactively with Graphical User
1199 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1199 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1200 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1200 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1201 is extremely robust compared to our previous threaded based version. The
1201 is extremely robust compared to our previous threaded based version. The
1202 advantages of this are:
1202 advantages of this are:
1203
1203
1204 * GUIs can be enabled and disabled dynamically at runtime.
1204 * GUIs can be enabled and disabled dynamically at runtime.
1205 * The active GUI can be switched dynamically at runtime.
1205 * The active GUI can be switched dynamically at runtime.
1206 * In some cases, multiple GUIs can run simultaneously with no problems.
1206 * In some cases, multiple GUIs can run simultaneously with no problems.
1207 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1207 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1208 all of these things.
1208 all of these things.
1209
1209
1210 For users, enabling GUI event loop integration is simple. You simple use the
1210 For users, enabling GUI event loop integration is simple. You simple use the
1211 ``%gui`` magic as follows::
1211 ``%gui`` magic as follows::
1212
1212
1213 %gui [-a] [GUINAME]
1213 %gui [-a] [GUINAME]
1214
1214
1215 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1215 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1216 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1216 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1217 create and return a running application object for the selected GUI toolkit.
1217 create and return a running application object for the selected GUI toolkit.
1218
1218
1219 Thus, to use wxPython interactively and create a running :class:`wx.App`
1219 Thus, to use wxPython interactively and create a running :class:`wx.App`
1220 object, do::
1220 object, do::
1221
1221
1222 %gui -a wx
1222 %gui -a wx
1223
1223
1224 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1224 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1225 see :ref:`this section <matplotlib_support>`.
1225 see :ref:`this section <matplotlib_support>`.
1226
1226
1227 For developers that want to use IPython's GUI event loop integration in
1227 For developers that want to use IPython's GUI event loop integration in
1228 the form of a library, these capabilities are exposed in library form
1228 the form of a library, these capabilities are exposed in library form
1229 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1229 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1230 module docstrings for more information, but there are a few points that
1230 module docstrings for more information, but there are a few points that
1231 should be mentioned here.
1231 should be mentioned here.
1232
1232
1233 First, the ``PyOSInputHook`` approach only works in command line settings
1233 First, the ``PyOSInputHook`` approach only works in command line settings
1234 where readline is activated.
1234 where readline is activated.
1235
1235
1236 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1236 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1237 *not* start its event loop. Instead all of this is handled by the
1237 *not* start its event loop. Instead all of this is handled by the
1238 ``PyOSInputHook``. This means that applications that are meant to be used both
1238 ``PyOSInputHook``. This means that applications that are meant to be used both
1239 in IPython and as standalone apps need to have special code to detects how the
1239 in IPython and as standalone apps need to have special code to detects how the
1240 application is being run. We highly recommend using IPython's
1240 application is being run. We highly recommend using IPython's
1241 :func:`appstart_` functions for this. Here is a simple example that shows the
1241 :func:`enable_foo` functions for this. Here is a simple example that shows the
1242 recommended code that should be at the bottom of a wxPython using GUI
1242 recommended code that should be at the bottom of a wxPython using GUI
1243 application::
1243 application::
1244
1244
1245 try:
1245 try:
1246 from IPython import appstart_wx
1246 from IPython.lib.inputhook import enable_wx
1247 appstart_wx(app)
1247 enable_wx(app)
1248 except ImportError:
1248 except ImportError:
1249 app.MainLoop()
1249 app.MainLoop()
1250
1250
1251 This pattern should be used instead of the simple ``app.MainLoop()`` code
1251 This pattern should be used instead of the simple ``app.MainLoop()`` code
1252 that a standalone wxPython application would have.
1252 that a standalone wxPython application would have.
1253
1253
1254 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1254 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1255 them with no-ops) the event loops. This is done to allow applications that
1255 them with no-ops) the event loops. This is done to allow applications that
1256 actually need to run the real event loops to do so. This is often needed to
1256 actually need to run the real event loops to do so. This is often needed to
1257 process pending events at critical points.
1257 process pending events at critical points.
1258
1258
1259 Finally, we also have a number of examples in our source directory
1259 Finally, we also have a number of examples in our source directory
1260 :file:`docs/examples/lib` that demonstrate these capabilities.
1260 :file:`docs/examples/lib` that demonstrate these capabilities.
1261
1261
1262 .. _matplotlib_support:
1262 .. _matplotlib_support:
1263
1263
1264 Plotting with matplotlib
1264 Plotting with matplotlib
1265 ========================
1265 ========================
1266
1266
1267
1267
1268 `Matplotlib`_ provides high quality 2D and
1268 `Matplotlib`_ provides high quality 2D and
1269 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1269 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1270 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1270 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1271 number of commands useful for scientific computing, all with a syntax
1271 number of commands useful for scientific computing, all with a syntax
1272 compatible with that of the popular Matlab program.
1272 compatible with that of the popular Matlab program.
1273
1273
1274 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1274 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1275 automates the integration of Matplotlib with IPython. We are still in the
1275 automates the integration of Matplotlib with IPython. We are still in the
1276 process of working with the Matplotlib developers to finalize the new pylab
1276 process of working with the Matplotlib developers to finalize the new pylab
1277 API, but for now you can use Matplotlib interactively using the following
1277 API, but for now you can use Matplotlib interactively using the following
1278 commands::
1278 commands::
1279
1279
1280 %gui -a wx
1280 %gui -a wx
1281 import matplotlib
1281 import matplotlib
1282 matplotlib.use('wxagg')
1282 matplotlib.use('wxagg')
1283 from matplotlib import pylab
1283 from matplotlib import pylab
1284 pylab.interactive(True)
1284 pylab.interactive(True)
1285
1285
1286 All of this will soon be automated as Matplotlib begins to include
1286 All of this will soon be automated as Matplotlib begins to include
1287 new logic that uses our new GUI support.
1287 new logic that uses our new GUI support.
1288
1288
1289 .. _Matplotlib: http://matplotlib.sourceforge.net
1289 .. _Matplotlib: http://matplotlib.sourceforge.net
1290
1290
1291 .. _interactive_demos:
1291 .. _interactive_demos:
1292
1292
1293 Interactive demos with IPython
1293 Interactive demos with IPython
1294 ==============================
1294 ==============================
1295
1295
1296 IPython ships with a basic system for running scripts interactively in
1296 IPython ships with a basic system for running scripts interactively in
1297 sections, useful when presenting code to audiences. A few tags embedded
1297 sections, useful when presenting code to audiences. A few tags embedded
1298 in comments (so that the script remains valid Python code) divide a file
1298 in comments (so that the script remains valid Python code) divide a file
1299 into separate blocks, and the demo can be run one block at a time, with
1299 into separate blocks, and the demo can be run one block at a time, with
1300 IPython printing (with syntax highlighting) the block before executing
1300 IPython printing (with syntax highlighting) the block before executing
1301 it, and returning to the interactive prompt after each block. The
1301 it, and returning to the interactive prompt after each block. The
1302 interactive namespace is updated after each block is run with the
1302 interactive namespace is updated after each block is run with the
1303 contents of the demo's namespace.
1303 contents of the demo's namespace.
1304
1304
1305 This allows you to show a piece of code, run it and then execute
1305 This allows you to show a piece of code, run it and then execute
1306 interactively commands based on the variables just created. Once you
1306 interactively commands based on the variables just created. Once you
1307 want to continue, you simply execute the next block of the demo. The
1307 want to continue, you simply execute the next block of the demo. The
1308 following listing shows the markup necessary for dividing a script into
1308 following listing shows the markup necessary for dividing a script into
1309 sections for execution as a demo:
1309 sections for execution as a demo:
1310
1310
1311 .. literalinclude:: ../../examples/lib/example-demo.py
1311 .. literalinclude:: ../../examples/lib/example-demo.py
1312 :language: python
1312 :language: python
1313
1313
1314
1314
1315 In order to run a file as a demo, you must first make a Demo object out
1315 In order to run a file as a demo, you must first make a Demo object out
1316 of it. If the file is named myscript.py, the following code will make a
1316 of it. If the file is named myscript.py, the following code will make a
1317 demo::
1317 demo::
1318
1318
1319 from IPython.lib.demo import Demo
1319 from IPython.lib.demo import Demo
1320
1320
1321 mydemo = Demo('myscript.py')
1321 mydemo = Demo('myscript.py')
1322
1322
1323 This creates the mydemo object, whose blocks you run one at a time by
1323 This creates the mydemo object, whose blocks you run one at a time by
1324 simply calling the object with no arguments. If you have autocall active
1324 simply calling the object with no arguments. If you have autocall active
1325 in IPython (the default), all you need to do is type::
1325 in IPython (the default), all you need to do is type::
1326
1326
1327 mydemo
1327 mydemo
1328
1328
1329 and IPython will call it, executing each block. Demo objects can be
1329 and IPython will call it, executing each block. Demo objects can be
1330 restarted, you can move forward or back skipping blocks, re-execute the
1330 restarted, you can move forward or back skipping blocks, re-execute the
1331 last block, etc. Simply use the Tab key on a demo object to see its
1331 last block, etc. Simply use the Tab key on a demo object to see its
1332 methods, and call '?' on them to see their docstrings for more usage
1332 methods, and call '?' on them to see their docstrings for more usage
1333 details. In addition, the demo module itself contains a comprehensive
1333 details. In addition, the demo module itself contains a comprehensive
1334 docstring, which you can access via::
1334 docstring, which you can access via::
1335
1335
1336 from IPython.lib import demo
1336 from IPython.lib import demo
1337
1337
1338 demo?
1338 demo?
1339
1339
1340 Limitations: It is important to note that these demos are limited to
1340 Limitations: It is important to note that these demos are limited to
1341 fairly simple uses. In particular, you can not put division marks in
1341 fairly simple uses. In particular, you can not put division marks in
1342 indented code (loops, if statements, function definitions, etc.)
1342 indented code (loops, if statements, function definitions, etc.)
1343 Supporting something like this would basically require tracking the
1343 Supporting something like this would basically require tracking the
1344 internal execution state of the Python interpreter, so only top-level
1344 internal execution state of the Python interpreter, so only top-level
1345 divisions are allowed. If you want to be able to open an IPython
1345 divisions are allowed. If you want to be able to open an IPython
1346 instance at an arbitrary point in a program, you can use IPython's
1346 instance at an arbitrary point in a program, you can use IPython's
1347 embedding facilities, described in detail in Sec. 9
1347 embedding facilities, described in detail in Sec. 9
1348
1348
General Comments 0
You need to be logged in to leave comments. Login now