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