##// END OF EJS Templates
Merge pull request #10727 from blueForestIcarus/master...
Thomas Kluyver -
r23830:268a3774 merge
parent child Browse files
Show More
@@ -0,0 +1,22 b''
1 """Quick snippet explaining how to set config options when using start_ipython."""
2
3 # First create a config object from the traitlets library
4 from traitlets.config import Config
5 c = Config()
6
7 # Now we can set options as we would in a config file:
8 # c.Class.config_value = value
9 # For example, we can set the exec_lines option of the InteractiveShellApp
10 # class to run some code when the IPython REPL starts
11 c.InteractiveShellApp.exec_lines = [
12 'print("\\nimporting some things\\n")',
13 'import math',
14 "math"
15 ]
16 c.InteractiveShell.colors = 'LightBG'
17 c.InteractiveShell.confirm_exit = False
18 c.TerminalIPythonApp.display_banner = False
19
20 # Now we start ipython with our configuration
21 import IPython
22 IPython.start_ipython(config=c)
@@ -1,153 +1,166 b''
1 =====================================
1 =====================================
2 Introduction to IPython configuration
2 Introduction to IPython configuration
3 =====================================
3 =====================================
4
4
5 .. _setting_config:
5 .. _setting_config:
6
6
7 Setting configurable options
7 Setting configurable options
8 ============================
8 ============================
9
9
10 Many of IPython's classes have configurable attributes (see
10 Many of IPython's classes have configurable attributes (see
11 :doc:`options/index` for the list). These can be
11 :doc:`options/index` for the list). These can be
12 configured in several ways.
12 configured in several ways.
13
13
14 Python config files
14 Python config files
15 -------------------
15 -------------------
16
16
17 To create the blank config files, run::
17 To create the blank config files, run::
18
18
19 ipython profile create [profilename]
19 ipython profile create [profilename]
20
20
21 If you leave out the profile name, the files will be created for the
21 If you leave out the profile name, the files will be created for the
22 ``default`` profile (see :ref:`profiles`). These will typically be
22 ``default`` profile (see :ref:`profiles`). These will typically be
23 located in :file:`~/.ipython/profile_default/`, and will be named
23 located in :file:`~/.ipython/profile_default/`, and will be named
24 :file:`ipython_config.py`, :file:`ipython_notebook_config.py`, etc.
24 :file:`ipython_config.py`, :file:`ipython_notebook_config.py`, etc.
25 The settings in :file:`ipython_config.py` apply to all IPython commands.
25 The settings in :file:`ipython_config.py` apply to all IPython commands.
26
26
27 The files typically start by getting the root config object::
27 The files typically start by getting the root config object::
28
28
29 c = get_config()
29 c = get_config()
30
30
31 You can then configure class attributes like this::
31 You can then configure class attributes like this::
32
32
33 c.InteractiveShell.automagic = False
33 c.InteractiveShell.automagic = False
34
34
35 Be careful with spelling--incorrect names will simply be ignored, with
35 Be careful with spelling--incorrect names will simply be ignored, with
36 no error.
36 no error.
37
37
38 To add to a collection which may have already been defined elsewhere,
38 To add to a collection which may have already been defined elsewhere,
39 you can use methods like those found on lists, dicts and sets: append,
39 you can use methods like those found on lists, dicts and sets: append,
40 extend, :meth:`~traitlets.config.LazyConfigValue.prepend` (like
40 extend, :meth:`~traitlets.config.LazyConfigValue.prepend` (like
41 extend, but at the front), add and update (which works both for dicts
41 extend, but at the front), add and update (which works both for dicts
42 and sets)::
42 and sets)::
43
43
44 c.InteractiveShellApp.extensions.append('Cython')
44 c.InteractiveShellApp.extensions.append('Cython')
45
45
46 .. versionadded:: 2.0
46 .. versionadded:: 2.0
47 list, dict and set methods for config values
47 list, dict and set methods for config values
48
48
49 Example config file
49 Example config file
50 ```````````````````
50 ```````````````````
51
51
52 ::
52 ::
53
53
54 # sample ipython_config.py
54 # sample ipython_config.py
55 c = get_config()
55 c = get_config()
56
56
57 c.TerminalIPythonApp.display_banner = True
57 c.TerminalIPythonApp.display_banner = True
58 c.InteractiveShellApp.log_level = 20
58 c.InteractiveShellApp.log_level = 20
59 c.InteractiveShellApp.extensions = [
59 c.InteractiveShellApp.extensions = [
60 'myextension'
60 'myextension'
61 ]
61 ]
62 c.InteractiveShellApp.exec_lines = [
62 c.InteractiveShellApp.exec_lines = [
63 'import numpy',
63 'import numpy',
64 'import scipy'
64 'import scipy'
65 ]
65 ]
66 c.InteractiveShellApp.exec_files = [
66 c.InteractiveShellApp.exec_files = [
67 'mycode.py',
67 'mycode.py',
68 'fancy.ipy'
68 'fancy.ipy'
69 ]
69 ]
70 c.InteractiveShell.autoindent = True
70 c.InteractiveShell.autoindent = True
71 c.InteractiveShell.colors = 'LightBG'
71 c.InteractiveShell.colors = 'LightBG'
72 c.InteractiveShell.confirm_exit = False
72 c.InteractiveShell.confirm_exit = False
73 c.InteractiveShell.editor = 'nano'
73 c.InteractiveShell.editor = 'nano'
74 c.InteractiveShell.xmode = 'Context'
74 c.InteractiveShell.xmode = 'Context'
75
75
76 c.PrefilterManager.multi_line_specials = True
76 c.PrefilterManager.multi_line_specials = True
77
77
78 c.AliasManager.user_aliases = [
78 c.AliasManager.user_aliases = [
79 ('la', 'ls -al')
79 ('la', 'ls -al')
80 ]
80 ]
81
81
82
82
83 Command line arguments
83 Command line arguments
84 ----------------------
84 ----------------------
85
85
86 Every configurable value can be set from the command line, using this
86 Every configurable value can be set from the command line, using this
87 syntax::
87 syntax::
88
88
89 ipython --ClassName.attribute=value
89 ipython --ClassName.attribute=value
90
90
91 Many frequently used options have short aliases and flags, such as
91 Many frequently used options have short aliases and flags, such as
92 ``--matplotlib`` (to integrate with a matplotlib GUI event loop) or
92 ``--matplotlib`` (to integrate with a matplotlib GUI event loop) or
93 ``--pdb`` (automatic post-mortem debugging of exceptions).
93 ``--pdb`` (automatic post-mortem debugging of exceptions).
94
94
95 To see all of these abbreviated options, run::
95 To see all of these abbreviated options, run::
96
96
97 ipython --help
97 ipython --help
98 ipython notebook --help
98 ipython notebook --help
99 # etc.
99 # etc.
100
100
101 Options specified at the command line, in either format, override
101 Options specified at the command line, in either format, override
102 options set in a configuration file.
102 options set in a configuration file.
103
103
104 The config magic
104 The config magic
105 ----------------
105 ----------------
106
106
107 You can also modify config from inside IPython, using a magic command::
107 You can also modify config from inside IPython, using a magic command::
108
108
109 %config IPCompleter.greedy = True
109 %config IPCompleter.greedy = True
110
110
111 At present, this only affects the current session - changes you make to
111 At present, this only affects the current session - changes you make to
112 config are not saved anywhere. Also, some options are only read when
112 config are not saved anywhere. Also, some options are only read when
113 IPython starts, so they can't be changed like this.
113 IPython starts, so they can't be changed like this.
114
114
115 .. _configure_start_ipython:
116
117 Running IPython from Python
118 ----------------------------
119
120 If you are using :ref:`embedding` to start IPython from a normal
121 python file, you can set configuration options the same way as in a
122 config file by creating a traitlets config object and passing it to
123 start_ipython like in the example below.
124
125 .. literalinclude:: ../../../examples/Embedding/start_ipython_config.py
126 :language: python
127
115 .. _profiles:
128 .. _profiles:
116
129
117 Profiles
130 Profiles
118 ========
131 ========
119
132
120 IPython can use multiple profiles, with separate configuration and
133 IPython can use multiple profiles, with separate configuration and
121 history. By default, if you don't specify a profile, IPython always runs
134 history. By default, if you don't specify a profile, IPython always runs
122 in the ``default`` profile. To use a new profile::
135 in the ``default`` profile. To use a new profile::
123
136
124 ipython profile create foo # create the profile foo
137 ipython profile create foo # create the profile foo
125 ipython --profile=foo # start IPython using the new profile
138 ipython --profile=foo # start IPython using the new profile
126
139
127 Profiles are typically stored in :ref:`ipythondir`, but you can also keep
140 Profiles are typically stored in :ref:`ipythondir`, but you can also keep
128 a profile in the current working directory, for example to distribute it
141 a profile in the current working directory, for example to distribute it
129 with a project. To find a profile directory on the filesystem::
142 with a project. To find a profile directory on the filesystem::
130
143
131 ipython locate profile foo
144 ipython locate profile foo
132
145
133 .. _ipythondir:
146 .. _ipythondir:
134
147
135 The IPython directory
148 The IPython directory
136 =====================
149 =====================
137
150
138 IPython stores its files---config, command history and extensions---in
151 IPython stores its files---config, command history and extensions---in
139 the directory :file:`~/.ipython/` by default.
152 the directory :file:`~/.ipython/` by default.
140
153
141 .. envvar:: IPYTHONDIR
154 .. envvar:: IPYTHONDIR
142
155
143 If set, this environment variable should be the path to a directory,
156 If set, this environment variable should be the path to a directory,
144 which IPython will use for user data. IPython will create it if it
157 which IPython will use for user data. IPython will create it if it
145 does not exist.
158 does not exist.
146
159
147 .. option:: --ipython-dir=<path>
160 .. option:: --ipython-dir=<path>
148
161
149 This command line option can also be used to override the default
162 This command line option can also be used to override the default
150 IPython directory.
163 IPython directory.
151
164
152 To see where IPython is looking for the IPython directory, use the command
165 To see where IPython is looking for the IPython directory, use the command
153 ``ipython locate``, or the Python function :func:`IPython.paths.get_ipython_dir`.
166 ``ipython locate``, or the Python function :func:`IPython.paths.get_ipython_dir`.
@@ -1,981 +1,983 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 and
14 If invoked with no options, it executes all the files listed in sequence and
15 exits. If you add the ``-i`` flag, it drops you into the interpreter while still
15 exits. If you add the ``-i`` flag, it drops you into the interpreter while still
16 acknowledging any options you may have set in your ``ipython_config.py``. This
16 acknowledging any options you may have set in your ``ipython_config.py``. This
17 behavior is different from standard Python, which when called as python ``-i``
17 behavior is different from standard Python, which when called as python ``-i``
18 will only execute one file and ignore your configuration setup.
18 will only execute one file and ignore your configuration setup.
19
19
20 Please note that some of the configuration options are not available at the
20 Please note that some of the configuration options are not available at the
21 command line, simply because they are not practical here. Look into your
21 command line, simply because they are not practical here. Look into your
22 configuration files for details on those. There are separate configuration files
22 configuration files for details on those. There are separate configuration files
23 for each profile, and the files look like :file:`ipython_config.py` or
23 for each profile, and the files look like :file:`ipython_config.py` or
24 :file:`ipython_config_{frontendname}.py`. Profile directories look like
24 :file:`ipython_config_{frontendname}.py`. Profile directories look like
25 :file:`profile_{profilename}` and are typically installed in the
25 :file:`profile_{profilename}` and are typically installed in the
26 :envvar:`IPYTHONDIR` directory, which defaults to :file:`$HOME/.ipython`. For
26 :envvar:`IPYTHONDIR` directory, which defaults to :file:`$HOME/.ipython`. For
27 Windows users, :envvar:`HOME` resolves to :file:`C:\\Users\\{YourUserName}` in
27 Windows users, :envvar:`HOME` resolves to :file:`C:\\Users\\{YourUserName}` in
28 most instances.
28 most instances.
29
29
30 Command-line Options
30 Command-line Options
31 --------------------
31 --------------------
32
32
33 To see the options IPython accepts, use ``ipython --help`` (and you probably
33 To see the options IPython accepts, use ``ipython --help`` (and you probably
34 should run the output through a pager such as ``ipython --help | less`` for
34 should run the output through a pager such as ``ipython --help | less`` for
35 more convenient reading). This shows all the options that have a single-word
35 more convenient reading). This shows all the options that have a single-word
36 alias to control them, but IPython lets you configure all of its objects from
36 alias to control them, but IPython lets you configure all of its objects from
37 the command-line by passing the full class name and a corresponding value; type
37 the command-line by passing the full class name and a corresponding value; type
38 ``ipython --help-all`` to see this full list. For example::
38 ``ipython --help-all`` to see this full list. For example::
39
39
40 $ ipython --help-all
40 $ ipython --help-all
41 <...snip...>
41 <...snip...>
42 --matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
42 --matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
43 Default: None
43 Default: None
44 Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
44 Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
45 Configure matplotlib for interactive use with the default matplotlib
45 Configure matplotlib for interactive use with the default matplotlib
46 backend.
46 backend.
47 <...snip...>
47 <...snip...>
48
48
49
49
50 Indicate that the following::
50 Indicate that the following::
51
51
52 $ ipython --matplotlib qt
52 $ ipython --matplotlib qt
53
53
54
54
55 is equivalent to::
55 is equivalent to::
56
56
57 $ ipython --TerminalIPythonApp.matplotlib='qt'
57 $ ipython --TerminalIPythonApp.matplotlib='qt'
58
58
59 Note that in the second form, you *must* use the equal sign, as the expression
59 Note that in the second form, you *must* use the equal sign, as the expression
60 is evaluated as an actual Python assignment. While in the above example the
60 is evaluated as an actual Python assignment. While in the above example the
61 short form is more convenient, only the most common options have a short form,
61 short form is more convenient, only the most common options have a short form,
62 while any configurable variable in IPython can be set at the command-line by
62 while any configurable variable in IPython can be set at the command-line by
63 using the long form. This long form is the same syntax used in the
63 using the long form. This long form is the same syntax used in the
64 configuration files, if you want to set these options permanently.
64 configuration files, if you want to set these options permanently.
65
65
66
66
67 Interactive use
67 Interactive use
68 ===============
68 ===============
69
69
70 IPython is meant to work as a drop-in replacement for the standard interactive
70 IPython is meant to work as a drop-in replacement for the standard interactive
71 interpreter. As such, any code which is valid python should execute normally
71 interpreter. As such, any code which is valid python should execute normally
72 under IPython (cases where this is not true should be reported as bugs). It
72 under IPython (cases where this is not true should be reported as bugs). It
73 does, however, offer many features which are not available at a standard python
73 does, however, offer many features which are not available at a standard python
74 prompt. What follows is a list of these.
74 prompt. What follows is a list of these.
75
75
76
76
77 Caution for Windows users
77 Caution for Windows users
78 -------------------------
78 -------------------------
79
79
80 Windows, unfortunately, uses the '\\' character as a path separator. This is a
80 Windows, unfortunately, uses the '\\' character as a path separator. This is a
81 terrible choice, because '\\' also represents the escape character in most
81 terrible choice, because '\\' also represents the escape character in most
82 modern programming languages, including Python. For this reason, using '/'
82 modern programming languages, including Python. For this reason, using '/'
83 character is recommended if you have problems with ``\``. However, in Windows
83 character is recommended if you have problems with ``\``. However, in Windows
84 commands '/' flags options, so you can not use it for the root directory. This
84 commands '/' flags options, so you can not use it for the root directory. This
85 means that paths beginning at the root must be typed in a contrived manner
85 means that paths beginning at the root must be typed in a contrived manner
86 like: ``%copy \opt/foo/bar.txt \tmp``
86 like: ``%copy \opt/foo/bar.txt \tmp``
87
87
88 .. _magic:
88 .. _magic:
89
89
90 Magic command system
90 Magic command system
91 --------------------
91 --------------------
92
92
93 IPython will treat any line whose first character is a % as a special
93 IPython will treat any line whose first character is a % as a special
94 call to a 'magic' function. These allow you to control the behavior of
94 call to a 'magic' function. These allow you to control the behavior of
95 IPython itself, plus a lot of system-type features. They are all
95 IPython itself, plus a lot of system-type features. They are all
96 prefixed with a % character, but parameters are given without
96 prefixed with a % character, but parameters are given without
97 parentheses or quotes.
97 parentheses or quotes.
98
98
99 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
99 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
100 only the rest of the current line, but all lines below them as well, in the
100 only the rest of the current line, but all lines below them as well, in the
101 current execution block. Cell magics can in fact make arbitrary modifications
101 current execution block. Cell magics can in fact make arbitrary modifications
102 to the input they receive, which need not even be valid Python code at all.
102 to the input they receive, which need not even be valid Python code at all.
103 They receive the whole block as a single string.
103 They receive the whole block as a single string.
104
104
105 As a line magic example, the :magic:`cd` magic works just like the OS command of
105 As a line magic example, the :magic:`cd` magic works just like the OS command of
106 the same name::
106 the same name::
107
107
108 In [8]: %cd
108 In [8]: %cd
109 /home/fperez
109 /home/fperez
110
110
111 The following uses the builtin :magic:`timeit` in cell mode::
111 The following uses the builtin :magic:`timeit` in cell mode::
112
112
113 In [10]: %%timeit x = range(10000)
113 In [10]: %%timeit x = range(10000)
114 ...: min(x)
114 ...: min(x)
115 ...: max(x)
115 ...: max(x)
116 ...:
116 ...:
117 1000 loops, best of 3: 438 us per loop
117 1000 loops, best of 3: 438 us per loop
118
118
119 In this case, ``x = range(10000)`` is called as the line argument, and the
119 In this case, ``x = range(10000)`` is called as the line argument, and the
120 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
120 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
121 :magic:`timeit` magic receives both.
121 :magic:`timeit` magic receives both.
122
122
123 If you have 'automagic' enabled (as it is by default), you don't need to type in
123 If you have 'automagic' enabled (as it is by default), you don't need to type in
124 the single ``%`` explicitly for line magics; IPython will scan its internal
124 the single ``%`` explicitly for line magics; IPython will scan its internal
125 list of magic functions and call one if it exists. With automagic on you can
125 list of magic functions and call one if it exists. With automagic on you can
126 then just type ``cd mydir`` to go to directory 'mydir'::
126 then just type ``cd mydir`` to go to directory 'mydir'::
127
127
128 In [9]: cd mydir
128 In [9]: cd mydir
129 /home/fperez/mydir
129 /home/fperez/mydir
130
130
131 Cell magics *always* require an explicit ``%%`` prefix, automagic
131 Cell magics *always* require an explicit ``%%`` prefix, automagic
132 calling only works for line magics.
132 calling only works for line magics.
133
133
134 The automagic system has the lowest possible precedence in name searches, so
134 The automagic system has the lowest possible precedence in name searches, so
135 you can freely use variables with the same names as magic commands. If a magic
135 you can freely use variables with the same names as magic commands. If a magic
136 command is 'shadowed' by a variable, you will need the explicit ``%`` prefix to
136 command is 'shadowed' by a variable, you will need the explicit ``%`` prefix to
137 use it:
137 use it:
138
138
139 .. sourcecode:: ipython
139 .. sourcecode:: ipython
140
140
141 In [1]: cd ipython # %cd is called by automagic
141 In [1]: cd ipython # %cd is called by automagic
142 /home/fperez/ipython
142 /home/fperez/ipython
143
143
144 In [2]: cd=1 # now cd is just a variable
144 In [2]: cd=1 # now cd is just a variable
145
145
146 In [3]: cd .. # and doesn't work as a function anymore
146 In [3]: cd .. # and doesn't work as a function anymore
147 File "<ipython-input-3-9fedb3aff56c>", line 1
147 File "<ipython-input-3-9fedb3aff56c>", line 1
148 cd ..
148 cd ..
149 ^
149 ^
150 SyntaxError: invalid syntax
150 SyntaxError: invalid syntax
151
151
152
152
153 In [4]: %cd .. # but %cd always works
153 In [4]: %cd .. # but %cd always works
154 /home/fperez
154 /home/fperez
155
155
156 In [5]: del cd # if you remove the cd variable, automagic works again
156 In [5]: del cd # if you remove the cd variable, automagic works again
157
157
158 In [6]: cd ipython
158 In [6]: cd ipython
159
159
160 /home/fperez/ipython
160 /home/fperez/ipython
161
161
162 Line magics, if they return a value, can be assigned to a variable using the
162 Line magics, if they return a value, can be assigned to a variable using the
163 syntax ``l = %sx ls`` (which in this particular case returns the result of `ls`
163 syntax ``l = %sx ls`` (which in this particular case returns the result of `ls`
164 as a python list). See :ref:`below <manual_capture>` for more information.
164 as a python list). See :ref:`below <manual_capture>` for more information.
165
165
166 Type ``%magic`` for more information, including a list of all available magic
166 Type ``%magic`` for more information, including a list of all available magic
167 functions at any time and their docstrings. You can also type
167 functions at any time and their docstrings. You can also type
168 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
168 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
169 information on the '?' system) to get information about any particular magic
169 information on the '?' system) to get information about any particular magic
170 function you are interested in.
170 function you are interested in.
171
171
172 The API documentation for the :mod:`IPython.core.magic` module contains the full
172 The API documentation for the :mod:`IPython.core.magic` module contains the full
173 docstrings of all currently available magic commands.
173 docstrings of all currently available magic commands.
174
174
175 .. seealso::
175 .. seealso::
176
176
177 :doc:`magics`
177 :doc:`magics`
178 A list of the line and cell magics available in IPython by default
178 A list of the line and cell magics available in IPython by default
179
179
180 :ref:`defining_magics`
180 :ref:`defining_magics`
181 How to define and register additional magic functions
181 How to define and register additional magic functions
182
182
183
183
184 Access to the standard Python help
184 Access to the standard Python help
185 ----------------------------------
185 ----------------------------------
186
186
187 Simply type ``help()`` to access Python's standard help system. You can
187 Simply type ``help()`` to access Python's standard help system. You can
188 also type ``help(object)`` for information about a given object, or
188 also type ``help(object)`` for information about a given object, or
189 ``help('keyword')`` for information on a keyword. You may need to configure your
189 ``help('keyword')`` for information on a keyword. You may need to configure your
190 PYTHONDOCS environment variable for this feature to work correctly.
190 PYTHONDOCS environment variable for this feature to work correctly.
191
191
192 .. _dynamic_object_info:
192 .. _dynamic_object_info:
193
193
194 Dynamic object information
194 Dynamic object information
195 --------------------------
195 --------------------------
196
196
197 Typing ``?word`` or ``word?`` prints detailed information about an object. If
197 Typing ``?word`` or ``word?`` prints detailed information about an object. If
198 certain strings in the object are too long (e.g. function signatures) they get
198 certain strings in the object are too long (e.g. function signatures) they get
199 snipped in the center for brevity. This system gives access variable types and
199 snipped in the center for brevity. This system gives access variable types and
200 values, docstrings, function prototypes and other useful information.
200 values, docstrings, function prototypes and other useful information.
201
201
202 If the information will not fit in the terminal, it is displayed in a pager
202 If the information will not fit in the terminal, it is displayed in a pager
203 (``less`` if available, otherwise a basic internal pager).
203 (``less`` if available, otherwise a basic internal pager).
204
204
205 Typing ``??word`` or ``word??`` gives access to the full information, including
205 Typing ``??word`` or ``word??`` gives access to the full information, including
206 the source code where possible. Long strings are not snipped.
206 the source code where possible. Long strings are not snipped.
207
207
208 The following magic functions are particularly useful for gathering
208 The following magic functions are particularly useful for gathering
209 information about your working environment:
209 information about your working environment:
210
210
211 * :magic:`pdoc` **<object>**: Print (or run through a pager if too long) the
211 * :magic:`pdoc` **<object>**: Print (or run through a pager if too long) the
212 docstring for an object. If the given object is a class, it will
212 docstring for an object. If the given object is a class, it will
213 print both the class and the constructor docstrings.
213 print both the class and the constructor docstrings.
214 * :magic:`pdef` **<object>**: Print the call signature for any callable
214 * :magic:`pdef` **<object>**: Print the call signature for any callable
215 object. If the object is a class, print the constructor information.
215 object. If the object is a class, print the constructor information.
216 * :magic:`psource` **<object>**: Print (or run through a pager if too long)
216 * :magic:`psource` **<object>**: Print (or run through a pager if too long)
217 the source code for an object.
217 the source code for an object.
218 * :magic:`pfile` **<object>**: Show the entire source file where an object was
218 * :magic:`pfile` **<object>**: Show the entire source file where an object was
219 defined via a pager, opening it at the line where the object
219 defined via a pager, opening it at the line where the object
220 definition begins.
220 definition begins.
221 * :magic:`who`/:magic:`whos`: These functions give information about identifiers
221 * :magic:`who`/:magic:`whos`: These functions give information about identifiers
222 you have defined interactively (not things you loaded or defined
222 you have defined interactively (not things you loaded or defined
223 in your configuration files). %who just prints a list of
223 in your configuration files). %who just prints a list of
224 identifiers and %whos prints a table with some basic details about
224 identifiers and %whos prints a table with some basic details about
225 each identifier.
225 each identifier.
226
226
227 The dynamic object information functions (?/??, ``%pdoc``,
227 The dynamic object information functions (?/??, ``%pdoc``,
228 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
228 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
229 directly on variables. For example, after doing ``import os``, you can use
229 directly on variables. For example, after doing ``import os``, you can use
230 ``os.path.abspath??``.
230 ``os.path.abspath??``.
231
231
232
232
233 Command line completion
233 Command line completion
234 +++++++++++++++++++++++
234 +++++++++++++++++++++++
235
235
236 At any time, hitting TAB will complete any available python commands or
236 At any time, hitting TAB will complete any available python commands or
237 variable names, and show you a list of the possible completions if
237 variable names, and show you a list of the possible completions if
238 there's no unambiguous one. It will also complete filenames in the
238 there's no unambiguous one. It will also complete filenames in the
239 current directory if no python names match what you've typed so far.
239 current directory if no python names match what you've typed so far.
240
240
241
241
242 Search command history
242 Search command history
243 ++++++++++++++++++++++
243 ++++++++++++++++++++++
244
244
245 IPython provides two ways for searching through previous input and thus
245 IPython provides two ways for searching through previous input and thus
246 reduce the need for repetitive typing:
246 reduce the need for repetitive typing:
247
247
248 1. Start typing, and then use the up and down arrow keys (or :kbd:`Ctrl-p`
248 1. Start typing, and then use the up and down arrow keys (or :kbd:`Ctrl-p`
249 and :kbd:`Ctrl-n`) to search through only the history items that match
249 and :kbd:`Ctrl-n`) to search through only the history items that match
250 what you've typed so far.
250 what you've typed so far.
251 2. Hit :kbd:`Ctrl-r`: to open a search prompt. Begin typing and the system
251 2. Hit :kbd:`Ctrl-r`: to open a search prompt. Begin typing and the system
252 searches your history for lines that contain what you've typed so
252 searches your history for lines that contain what you've typed so
253 far, completing as much as it can.
253 far, completing as much as it can.
254
254
255 IPython will save your input history when it leaves and reload it next
255 IPython will save your input history when it leaves and reload it next
256 time you restart it. By default, the history file is named
256 time you restart it. By default, the history file is named
257 :file:`.ipython/profile_{name}/history.sqlite`.
257 :file:`.ipython/profile_{name}/history.sqlite`.
258
258
259 Autoindent
259 Autoindent
260 ++++++++++
260 ++++++++++
261
261
262 Starting with 5.0, IPython uses `prompt_toolkit` in place of ``readline``,
262 Starting with 5.0, IPython uses `prompt_toolkit` in place of ``readline``,
263 it thus can recognize lines ending in ':' and indent the next line,
263 it thus can recognize lines ending in ':' and indent the next line,
264 while also un-indenting automatically after 'raise' or 'return',
264 while also un-indenting automatically after 'raise' or 'return',
265 and support real multi-line editing as well as syntactic coloration
265 and support real multi-line editing as well as syntactic coloration
266 during edition.
266 during edition.
267
267
268 This feature does not use the ``readline`` library anymore, so it will
268 This feature does not use the ``readline`` library anymore, so it will
269 not honor your :file:`~/.inputrc` configuration (or whatever
269 not honor your :file:`~/.inputrc` configuration (or whatever
270 file your :envvar:`INPUTRC` environment variable points to).
270 file your :envvar:`INPUTRC` environment variable points to).
271
271
272 In particular if you want to change the input mode to ``vi``, you will need to
272 In particular if you want to change the input mode to ``vi``, you will need to
273 set the ``TerminalInteractiveShell.editing_mode`` configuration option of IPython.
273 set the ``TerminalInteractiveShell.editing_mode`` configuration option of IPython.
274
274
275 Session logging and restoring
275 Session logging and restoring
276 -----------------------------
276 -----------------------------
277
277
278 You can log all input from a session either by starting IPython with the
278 You can log all input from a session either by starting IPython with the
279 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
279 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
280 or by activating the logging at any moment with the magic function :magic:`logstart`.
280 or by activating the logging at any moment with the magic function :magic:`logstart`.
281
281
282 Log files can later be reloaded by running them as scripts and IPython
282 Log files can later be reloaded by running them as scripts and IPython
283 will attempt to 'replay' the log by executing all the lines in it, thus
283 will attempt to 'replay' the log by executing all the lines in it, thus
284 restoring the state of a previous session. This feature is not quite
284 restoring the state of a previous session. This feature is not quite
285 perfect, but can still be useful in many cases.
285 perfect, but can still be useful in many cases.
286
286
287 The log files can also be used as a way to have a permanent record of
287 The log files can also be used as a way to have a permanent record of
288 any code you wrote while experimenting. Log files are regular text files
288 any code you wrote while experimenting. Log files are regular text files
289 which you can later open in your favorite text editor to extract code or
289 which you can later open in your favorite text editor to extract code or
290 to 'clean them up' before using them to replay a session.
290 to 'clean them up' before using them to replay a session.
291
291
292 The :magic:`logstart` function for activating logging in mid-session is used as
292 The :magic:`logstart` function for activating logging in mid-session is used as
293 follows::
293 follows::
294
294
295 %logstart [log_name [log_mode]]
295 %logstart [log_name [log_mode]]
296
296
297 If no name is given, it defaults to a file named 'ipython_log.py' in your
297 If no name is given, it defaults to a file named 'ipython_log.py' in your
298 current working directory, in 'rotate' mode (see below).
298 current working directory, in 'rotate' mode (see below).
299
299
300 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
300 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
301 history up to that point and then continues logging.
301 history up to that point and then continues logging.
302
302
303 %logstart takes a second optional parameter: logging mode. This can be
303 %logstart takes a second optional parameter: logging mode. This can be
304 one of (note that the modes are given unquoted):
304 one of (note that the modes are given unquoted):
305
305
306 * [over:] overwrite existing log_name.
306 * [over:] overwrite existing log_name.
307 * [backup:] rename (if exists) to log_name~ and start log_name.
307 * [backup:] rename (if exists) to log_name~ and start log_name.
308 * [append:] well, that says it.
308 * [append:] well, that says it.
309 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
309 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
310
310
311 The :magic:`logoff` and :magic:`logon` functions allow you to temporarily stop and
311 The :magic:`logoff` and :magic:`logon` functions allow you to temporarily stop and
312 resume logging to a file which had previously been started with
312 resume logging to a file which had previously been started with
313 %logstart. They will fail (with an explanation) if you try to use them
313 %logstart. They will fail (with an explanation) if you try to use them
314 before logging has been started.
314 before logging has been started.
315
315
316 .. _system_shell_access:
316 .. _system_shell_access:
317
317
318 System shell access
318 System shell access
319 -------------------
319 -------------------
320
320
321 Any input line beginning with a ``!`` character is passed verbatim (minus
321 Any input line beginning with a ``!`` character is passed verbatim (minus
322 the ``!``, of course) to the underlying operating system. For example,
322 the ``!``, of course) to the underlying operating system. For example,
323 typing ``!ls`` will run 'ls' in the current directory.
323 typing ``!ls`` will run 'ls' in the current directory.
324
324
325 .. _manual_capture:
325 .. _manual_capture:
326
326
327 Manual capture of command output and magic output
327 Manual capture of command output and magic output
328 -------------------------------------------------
328 -------------------------------------------------
329
329
330 You can assign the result of a system command to a Python variable with the
330 You can assign the result of a system command to a Python variable with the
331 syntax ``myfiles = !ls``. Similarly, the result of a magic (as long as it returns
331 syntax ``myfiles = !ls``. Similarly, the result of a magic (as long as it returns
332 a value) can be assigned to a variable. For example, the syntax ``myfiles = %sx ls``
332 a value) can be assigned to a variable. For example, the syntax ``myfiles = %sx ls``
333 is equivalent to the above system command example (the :magic:`sx` magic runs a shell command
333 is equivalent to the above system command example (the :magic:`sx` magic runs a shell command
334 and captures the output). Each of these gets machine
334 and captures the output). Each of these gets machine
335 readable output from stdout (e.g. without colours), and splits on newlines. To
335 readable output from stdout (e.g. without colours), and splits on newlines. To
336 explicitly get this sort of output without assigning to a variable, use two
336 explicitly get this sort of output without assigning to a variable, use two
337 exclamation marks (``!!ls``) or the :magic:`sx` magic command without an assignment.
337 exclamation marks (``!!ls``) or the :magic:`sx` magic command without an assignment.
338 (However, ``!!`` commands cannot be assigned to a variable.)
338 (However, ``!!`` commands cannot be assigned to a variable.)
339
339
340 The captured list in this example has some convenience features. ``myfiles.n`` or ``myfiles.s``
340 The captured list in this example has some convenience features. ``myfiles.n`` or ``myfiles.s``
341 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
341 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
342 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
342 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
343 See :ref:`string_lists` for details.
343 See :ref:`string_lists` for details.
344
344
345 IPython also allows you to expand the value of python variables when
345 IPython also allows you to expand the value of python variables when
346 making system calls. Wrap variables or expressions in {braces}::
346 making system calls. Wrap variables or expressions in {braces}::
347
347
348 In [1]: pyvar = 'Hello world'
348 In [1]: pyvar = 'Hello world'
349 In [2]: !echo "A python variable: {pyvar}"
349 In [2]: !echo "A python variable: {pyvar}"
350 A python variable: Hello world
350 A python variable: Hello world
351 In [3]: import math
351 In [3]: import math
352 In [4]: x = 8
352 In [4]: x = 8
353 In [5]: !echo {math.factorial(x)}
353 In [5]: !echo {math.factorial(x)}
354 40320
354 40320
355
355
356 For simple cases, you can alternatively prepend $ to a variable name::
356 For simple cases, you can alternatively prepend $ to a variable name::
357
357
358 In [6]: !echo $sys.argv
358 In [6]: !echo $sys.argv
359 [/home/fperez/usr/bin/ipython]
359 [/home/fperez/usr/bin/ipython]
360 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
360 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
361 A system variable: /home/fperez
361 A system variable: /home/fperez
362
362
363 Note that `$$` is used to represent a literal `$`.
363 Note that `$$` is used to represent a literal `$`.
364
364
365 System command aliases
365 System command aliases
366 ----------------------
366 ----------------------
367
367
368 The :magic:`alias` magic function allows you to define magic functions which are in fact
368 The :magic:`alias` magic function allows you to define magic functions which are in fact
369 system shell commands. These aliases can have parameters.
369 system shell commands. These aliases can have parameters.
370
370
371 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
371 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
372
372
373 Then, typing ``alias_name params`` will execute the system command 'cmd
373 Then, typing ``alias_name params`` will execute the system command 'cmd
374 params' (from your underlying operating system).
374 params' (from your underlying operating system).
375
375
376 You can also define aliases with parameters using ``%s`` specifiers (one per
376 You can also define aliases with parameters using ``%s`` specifiers (one per
377 parameter). The following example defines the parts function as an
377 parameter). The following example defines the parts function as an
378 alias to the command ``echo first %s second %s`` where each ``%s`` will be
378 alias to the command ``echo first %s second %s`` where each ``%s`` will be
379 replaced by a positional parameter to the call to %parts::
379 replaced by a positional parameter to the call to %parts::
380
380
381 In [1]: %alias parts echo first %s second %s
381 In [1]: %alias parts echo first %s second %s
382 In [2]: parts A B
382 In [2]: parts A B
383 first A second B
383 first A second B
384 In [3]: parts A
384 In [3]: parts A
385 ERROR: Alias <parts> requires 2 arguments, 1 given.
385 ERROR: Alias <parts> requires 2 arguments, 1 given.
386
386
387 If called with no parameters, :magic:`alias` prints the table of currently
387 If called with no parameters, :magic:`alias` prints the table of currently
388 defined aliases.
388 defined aliases.
389
389
390 The :magic:`rehashx` magic allows you to load your entire $PATH as
390 The :magic:`rehashx` magic allows you to load your entire $PATH as
391 ipython aliases. See its docstring for further details.
391 ipython aliases. See its docstring for further details.
392
392
393
393
394 .. _dreload:
394 .. _dreload:
395
395
396 Recursive reload
396 Recursive reload
397 ----------------
397 ----------------
398
398
399 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
399 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
400 module: changes made to any of its dependencies will be reloaded without
400 module: changes made to any of its dependencies will be reloaded without
401 having to exit. To start using it, do::
401 having to exit. To start using it, do::
402
402
403 from IPython.lib.deepreload import reload as dreload
403 from IPython.lib.deepreload import reload as dreload
404
404
405
405
406 Verbose and colored exception traceback printouts
406 Verbose and colored exception traceback printouts
407 -------------------------------------------------
407 -------------------------------------------------
408
408
409 IPython provides the option to see very detailed exception tracebacks,
409 IPython provides the option to see very detailed exception tracebacks,
410 which can be especially useful when debugging large programs. You can
410 which can be especially useful when debugging large programs. You can
411 run any Python file with the %run function to benefit from these
411 run any Python file with the %run function to benefit from these
412 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
412 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
413 be colored (if your terminal supports it) which makes them much easier
413 be colored (if your terminal supports it) which makes them much easier
414 to parse visually.
414 to parse visually.
415
415
416 See the magic :magic:`xmode` and :magic:`colors` functions for details.
416 See the magic :magic:`xmode` and :magic:`colors` functions for details.
417
417
418 These features are basically a terminal version of Ka-Ping Yee's cgitb
418 These features are basically a terminal version of Ka-Ping Yee's cgitb
419 module, now part of the standard Python library.
419 module, now part of the standard Python library.
420
420
421
421
422 .. _input_caching:
422 .. _input_caching:
423
423
424 Input caching system
424 Input caching system
425 --------------------
425 --------------------
426
426
427 IPython offers numbered prompts (In/Out) with input and output caching
427 IPython offers numbered prompts (In/Out) with input and output caching
428 (also referred to as 'input history'). All input is saved and can be
428 (also referred to as 'input history'). All input is saved and can be
429 retrieved as variables (besides the usual arrow key recall), in
429 retrieved as variables (besides the usual arrow key recall), in
430 addition to the :magic:`rep` magic command that brings a history entry
430 addition to the :magic:`rep` magic command that brings a history entry
431 up for editing on the next command line.
431 up for editing on the next command line.
432
432
433 The following variables always exist:
433 The following variables always exist:
434
434
435 * ``_i``, ``_ii``, ``_iii``: store previous, next previous and next-next
435 * ``_i``, ``_ii``, ``_iii``: store previous, next previous and next-next
436 previous inputs.
436 previous inputs.
437
437
438 * ``In``, ``_ih`` : a list of all inputs; ``_ih[n]`` is the input from line
438 * ``In``, ``_ih`` : a list of all inputs; ``_ih[n]`` is the input from line
439 ``n``. If you overwrite In with a variable of your own, you can remake the
439 ``n``. If you overwrite In with a variable of your own, you can remake the
440 assignment to the internal list with a simple ``In=_ih``.
440 assignment to the internal list with a simple ``In=_ih``.
441
441
442 Additionally, global variables named ``_i<n>`` are dynamically created (``<n>``
442 Additionally, global variables named ``_i<n>`` are dynamically created (``<n>``
443 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
443 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
444
444
445 For example, what you typed at prompt 14 is available as ``_i14``, ``_ih[14]``
445 For example, what you typed at prompt 14 is available as ``_i14``, ``_ih[14]``
446 and ``In[14]``.
446 and ``In[14]``.
447
447
448 This allows you to easily cut and paste multi line interactive prompts
448 This allows you to easily cut and paste multi line interactive prompts
449 by printing them out: they print like a clean string, without prompt
449 by printing them out: they print like a clean string, without prompt
450 characters. You can also manipulate them like regular variables (they
450 characters. You can also manipulate them like regular variables (they
451 are strings), modify or exec them.
451 are strings), modify or exec them.
452
452
453 You can also re-execute multiple lines of input easily by using the magic
453 You can also re-execute multiple lines of input easily by using the magic
454 :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to
454 :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to
455 re-execute previous lines which include magic function calls (which require
455 re-execute previous lines which include magic function calls (which require
456 special processing). Type %macro? for more details on the macro system.
456 special processing). Type %macro? for more details on the macro system.
457
457
458 A history function :magic:`history` allows you to see any part of your input
458 A history function :magic:`history` allows you to see any part of your input
459 history by printing a range of the _i variables.
459 history by printing a range of the _i variables.
460
460
461 You can also search ('grep') through your history by typing
461 You can also search ('grep') through your history by typing
462 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
462 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
463 etc. You can bring history entries listed by '%hist -g' up for editing
463 etc. You can bring history entries listed by '%hist -g' up for editing
464 with the %recall command, or run them immediately with :magic:`rerun`.
464 with the %recall command, or run them immediately with :magic:`rerun`.
465
465
466 .. _output_caching:
466 .. _output_caching:
467
467
468 Output caching system
468 Output caching system
469 ---------------------
469 ---------------------
470
470
471 For output that is returned from actions, a system similar to the input
471 For output that is returned from actions, a system similar to the input
472 cache exists but using _ instead of _i. Only actions that produce a
472 cache exists but using _ instead of _i. Only actions that produce a
473 result (NOT assignments, for example) are cached. If you are familiar
473 result (NOT assignments, for example) are cached. If you are familiar
474 with Mathematica, IPython's _ variables behave exactly like
474 with Mathematica, IPython's _ variables behave exactly like
475 Mathematica's % variables.
475 Mathematica's % variables.
476
476
477 The following variables always exist:
477 The following variables always exist:
478
478
479 * [_] (a single underscore): stores previous output, like Python's
479 * [_] (a single underscore): stores previous output, like Python's
480 default interpreter.
480 default interpreter.
481 * [__] (two underscores): next previous.
481 * [__] (two underscores): next previous.
482 * [___] (three underscores): next-next previous.
482 * [___] (three underscores): next-next previous.
483
483
484 Additionally, global variables named _<n> are dynamically created (<n>
484 Additionally, global variables named _<n> are dynamically created (<n>
485 being the prompt counter), such that the result of output <n> is always
485 being the prompt counter), such that the result of output <n> is always
486 available as _<n> (don't use the angle brackets, just the number, e.g.
486 available as _<n> (don't use the angle brackets, just the number, e.g.
487 ``_21``).
487 ``_21``).
488
488
489 These variables are also stored in a global dictionary (not a
489 These variables are also stored in a global dictionary (not a
490 list, since it only has entries for lines which returned a result)
490 list, since it only has entries for lines which returned a result)
491 available under the names _oh and Out (similar to _ih and In). So the
491 available under the names _oh and Out (similar to _ih and In). So the
492 output from line 12 can be obtained as ``_12``, ``Out[12]`` or ``_oh[12]``. If you
492 output from line 12 can be obtained as ``_12``, ``Out[12]`` or ``_oh[12]``. If you
493 accidentally overwrite the Out variable you can recover it by typing
493 accidentally overwrite the Out variable you can recover it by typing
494 ``Out=_oh`` at the prompt.
494 ``Out=_oh`` at the prompt.
495
495
496 This system obviously can potentially put heavy memory demands on your
496 This system obviously can potentially put heavy memory demands on your
497 system, since it prevents Python's garbage collector from removing any
497 system, since it prevents Python's garbage collector from removing any
498 previously computed results. You can control how many results are kept
498 previously computed results. You can control how many results are kept
499 in memory with the configuration option ``InteractiveShell.cache_size``.
499 in memory with the configuration option ``InteractiveShell.cache_size``.
500 If you set it to 0, output caching is disabled. You can also use the :magic:`reset`
500 If you set it to 0, output caching is disabled. You can also use the :magic:`reset`
501 and :magic:`xdel` magics to clear large items from memory.
501 and :magic:`xdel` magics to clear large items from memory.
502
502
503 Directory history
503 Directory history
504 -----------------
504 -----------------
505
505
506 Your history of visited directories is kept in the global list _dh, and
506 Your history of visited directories is kept in the global list _dh, and
507 the magic :magic:`cd` command can be used to go to any entry in that list. The
507 the magic :magic:`cd` command can be used to go to any entry in that list. The
508 :magic:`dhist` command allows you to view this history. Do ``cd -<TAB>`` to
508 :magic:`dhist` command allows you to view this history. Do ``cd -<TAB>`` to
509 conveniently view the directory history.
509 conveniently view the directory history.
510
510
511
511
512 Automatic parentheses and quotes
512 Automatic parentheses and quotes
513 --------------------------------
513 --------------------------------
514
514
515 These features were adapted from Nathan Gray's LazyPython. They are
515 These features were adapted from Nathan Gray's LazyPython. They are
516 meant to allow less typing for common situations.
516 meant to allow less typing for common situations.
517
517
518 Callable objects (i.e. functions, methods, etc) can be invoked like this
518 Callable objects (i.e. functions, methods, etc) can be invoked like this
519 (notice the commas between the arguments)::
519 (notice the commas between the arguments)::
520
520
521 In [1]: callable_ob arg1, arg2, arg3
521 In [1]: callable_ob arg1, arg2, arg3
522 ------> callable_ob(arg1, arg2, arg3)
522 ------> callable_ob(arg1, arg2, arg3)
523
523
524 .. note::
524 .. note::
525 This feature is disabled by default. To enable it, use the ``%autocall``
525 This feature is disabled by default. To enable it, use the ``%autocall``
526 magic command. The commands below with special prefixes will always work,
526 magic command. The commands below with special prefixes will always work,
527 however.
527 however.
528
528
529 You can force automatic parentheses by using '/' as the first character
529 You can force automatic parentheses by using '/' as the first character
530 of a line. For example::
530 of a line. For example::
531
531
532 In [2]: /globals # becomes 'globals()'
532 In [2]: /globals # becomes 'globals()'
533
533
534 Note that the '/' MUST be the first character on the line! This won't work::
534 Note that the '/' MUST be the first character on the line! This won't work::
535
535
536 In [3]: print /globals # syntax error
536 In [3]: print /globals # syntax error
537
537
538 In most cases the automatic algorithm should work, so you should rarely
538 In most cases the automatic algorithm should work, so you should rarely
539 need to explicitly invoke /. One notable exception is if you are trying
539 need to explicitly invoke /. One notable exception is if you are trying
540 to call a function with a list of tuples as arguments (the parenthesis
540 to call a function with a list of tuples as arguments (the parenthesis
541 will confuse IPython)::
541 will confuse IPython)::
542
542
543 In [4]: zip (1,2,3),(4,5,6) # won't work
543 In [4]: zip (1,2,3),(4,5,6) # won't work
544
544
545 but this will work::
545 but this will work::
546
546
547 In [5]: /zip (1,2,3),(4,5,6)
547 In [5]: /zip (1,2,3),(4,5,6)
548 ------> zip ((1,2,3),(4,5,6))
548 ------> zip ((1,2,3),(4,5,6))
549 Out[5]: [(1, 4), (2, 5), (3, 6)]
549 Out[5]: [(1, 4), (2, 5), (3, 6)]
550
550
551 IPython tells you that it has altered your command line by displaying
551 IPython tells you that it has altered your command line by displaying
552 the new command line preceded by ``--->``.
552 the new command line preceded by ``--->``.
553
553
554 You can force automatic quoting of a function's arguments by using ``,``
554 You can force automatic quoting of a function's arguments by using ``,``
555 or ``;`` as the first character of a line. For example::
555 or ``;`` as the first character of a line. For example::
556
556
557 In [1]: ,my_function /home/me # becomes my_function("/home/me")
557 In [1]: ,my_function /home/me # becomes my_function("/home/me")
558
558
559 If you use ';' the whole argument is quoted as a single string, while ',' splits
559 If you use ';' the whole argument is quoted as a single string, while ',' splits
560 on whitespace::
560 on whitespace::
561
561
562 In [2]: ,my_function a b c # becomes my_function("a","b","c")
562 In [2]: ,my_function a b c # becomes my_function("a","b","c")
563
563
564 In [3]: ;my_function a b c # becomes my_function("a b c")
564 In [3]: ;my_function a b c # becomes my_function("a b c")
565
565
566 Note that the ',' or ';' MUST be the first character on the line! This
566 Note that the ',' or ';' MUST be the first character on the line! This
567 won't work::
567 won't work::
568
568
569 In [4]: x = ,my_function /home/me # syntax error
569 In [4]: x = ,my_function /home/me # syntax error
570
570
571 IPython as your default Python environment
571 IPython as your default Python environment
572 ==========================================
572 ==========================================
573
573
574 Python honors the environment variable :envvar:`PYTHONSTARTUP` and will
574 Python honors the environment variable :envvar:`PYTHONSTARTUP` and will
575 execute at startup the file referenced by this variable. If you put the
575 execute at startup the file referenced by this variable. If you put the
576 following code at the end of that file, then IPython will be your working
576 following code at the end of that file, then IPython will be your working
577 environment anytime you start Python::
577 environment anytime you start Python::
578
578
579 import os, IPython
579 import os, IPython
580 os.environ['PYTHONSTARTUP'] = '' # Prevent running this again
580 os.environ['PYTHONSTARTUP'] = '' # Prevent running this again
581 IPython.start_ipython()
581 IPython.start_ipython()
582 raise SystemExit
582 raise SystemExit
583
583
584 The ``raise SystemExit`` is needed to exit Python when
584 The ``raise SystemExit`` is needed to exit Python when
585 it finishes, otherwise you'll be back at the normal Python ``>>>``
585 it finishes, otherwise you'll be back at the normal Python ``>>>``
586 prompt.
586 prompt.
587
587
588 This is probably useful to developers who manage multiple Python
588 This is probably useful to developers who manage multiple Python
589 versions and don't want to have correspondingly multiple IPython
589 versions and don't want to have correspondingly multiple IPython
590 versions. Note that in this mode, there is no way to pass IPython any
590 versions. Note that in this mode, there is no way to pass IPython any
591 command-line options, as those are trapped first by Python itself.
591 command-line options, as those are trapped first by Python itself.
592
592
593 .. _Embedding:
593 .. _Embedding:
594
594
595 Embedding IPython
595 Embedding IPython
596 =================
596 =================
597
597
598 You can start a regular IPython session with
598 You can start a regular IPython session with
599
599
600 .. sourcecode:: python
600 .. sourcecode:: python
601
601
602 import IPython
602 import IPython
603 IPython.start_ipython(argv=[])
603 IPython.start_ipython(argv=[])
604
604
605 at any point in your program. This will load IPython configuration,
605 at any point in your program. This will load IPython configuration,
606 startup files, and everything, just as if it were a normal IPython session.
606 startup files, and everything, just as if it were a normal IPython session.
607 For information on setting configuration options when running IPython from
608 python, see :ref:`configure_start_ipython`.
607
609
608 It is also possible to embed an IPython shell in a namespace in your Python code.
610 It is also possible to embed an IPython shell in a namespace in your Python code.
609 This allows you to evaluate dynamically the state of your code,
611 This allows you to evaluate dynamically the state of your code,
610 operate with your variables, analyze them, etc. Note however that
612 operate with your variables, analyze them, etc. Note however that
611 any changes you make to values while in the shell do not propagate back
613 any changes you make to values while in the shell do not propagate back
612 to the running code, so it is safe to modify your values because you
614 to the running code, so it is safe to modify your values because you
613 won't break your code in bizarre ways by doing so.
615 won't break your code in bizarre ways by doing so.
614
616
615 .. note::
617 .. note::
616
618
617 At present, embedding IPython cannot be done from inside IPython.
619 At present, embedding IPython cannot be done from inside IPython.
618 Run the code samples below outside IPython.
620 Run the code samples below outside IPython.
619
621
620 This feature allows you to easily have a fully functional python
622 This feature allows you to easily have a fully functional python
621 environment for doing object introspection anywhere in your code with a
623 environment for doing object introspection anywhere in your code with a
622 simple function call. In some cases a simple print statement is enough,
624 simple function call. In some cases a simple print statement is enough,
623 but if you need to do more detailed analysis of a code fragment this
625 but if you need to do more detailed analysis of a code fragment this
624 feature can be very valuable.
626 feature can be very valuable.
625
627
626 It can also be useful in scientific computing situations where it is
628 It can also be useful in scientific computing situations where it is
627 common to need to do some automatic, computationally intensive part and
629 common to need to do some automatic, computationally intensive part and
628 then stop to look at data, plots, etc.
630 then stop to look at data, plots, etc.
629 Opening an IPython instance will give you full access to your data and
631 Opening an IPython instance will give you full access to your data and
630 functions, and you can resume program execution once you are done with
632 functions, and you can resume program execution once you are done with
631 the interactive part (perhaps to stop again later, as many times as
633 the interactive part (perhaps to stop again later, as many times as
632 needed).
634 needed).
633
635
634 The following code snippet is the bare minimum you need to include in
636 The following code snippet is the bare minimum you need to include in
635 your Python programs for this to work (detailed examples follow later)::
637 your Python programs for this to work (detailed examples follow later)::
636
638
637 from IPython import embed
639 from IPython import embed
638
640
639 embed() # this call anywhere in your program will start IPython
641 embed() # this call anywhere in your program will start IPython
640
642
641 You can also embed an IPython *kernel*, for use with qtconsole, etc. via
643 You can also embed an IPython *kernel*, for use with qtconsole, etc. via
642 ``IPython.embed_kernel()``. This should function work the same way, but you can
644 ``IPython.embed_kernel()``. This should function work the same way, but you can
643 connect an external frontend (``ipython qtconsole`` or ``ipython console``),
645 connect an external frontend (``ipython qtconsole`` or ``ipython console``),
644 rather than interacting with it in the terminal.
646 rather than interacting with it in the terminal.
645
647
646 You can run embedded instances even in code which is itself being run at
648 You can run embedded instances even in code which is itself being run at
647 the IPython interactive prompt with '%run <filename>'. Since it's easy
649 the IPython interactive prompt with '%run <filename>'. Since it's easy
648 to get lost as to where you are (in your top-level IPython or in your
650 to get lost as to where you are (in your top-level IPython or in your
649 embedded one), it's a good idea in such cases to set the in/out prompts
651 embedded one), it's a good idea in such cases to set the in/out prompts
650 to something different for the embedded instances. The code examples
652 to something different for the embedded instances. The code examples
651 below illustrate this.
653 below illustrate this.
652
654
653 You can also have multiple IPython instances in your program and open
655 You can also have multiple IPython instances in your program and open
654 them separately, for example with different options for data
656 them separately, for example with different options for data
655 presentation. If you close and open the same instance multiple times,
657 presentation. If you close and open the same instance multiple times,
656 its prompt counters simply continue from each execution to the next.
658 its prompt counters simply continue from each execution to the next.
657
659
658 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
660 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
659 module for more details on the use of this system.
661 module for more details on the use of this system.
660
662
661 The following sample file illustrating how to use the embedding
663 The following sample file illustrating how to use the embedding
662 functionality is provided in the examples directory as embed_class_long.py.
664 functionality is provided in the examples directory as embed_class_long.py.
663 It should be fairly self-explanatory:
665 It should be fairly self-explanatory:
664
666
665 .. literalinclude:: ../../../examples/Embedding/embed_class_long.py
667 .. literalinclude:: ../../../examples/Embedding/embed_class_long.py
666 :language: python
668 :language: python
667
669
668 Once you understand how the system functions, you can use the following
670 Once you understand how the system functions, you can use the following
669 code fragments in your programs which are ready for cut and paste:
671 code fragments in your programs which are ready for cut and paste:
670
672
671 .. literalinclude:: ../../../examples/Embedding/embed_class_short.py
673 .. literalinclude:: ../../../examples/Embedding/embed_class_short.py
672 :language: python
674 :language: python
673
675
674 Using the Python debugger (pdb)
676 Using the Python debugger (pdb)
675 ===============================
677 ===============================
676
678
677 Running entire programs via pdb
679 Running entire programs via pdb
678 -------------------------------
680 -------------------------------
679
681
680 pdb, the Python debugger, is a powerful interactive debugger which
682 pdb, the Python debugger, is a powerful interactive debugger which
681 allows you to step through code, set breakpoints, watch variables,
683 allows you to step through code, set breakpoints, watch variables,
682 etc. IPython makes it very easy to start any script under the control
684 etc. IPython makes it very easy to start any script under the control
683 of pdb, regardless of whether you have wrapped it into a 'main()'
685 of pdb, regardless of whether you have wrapped it into a 'main()'
684 function or not. For this, simply type ``%run -d myscript`` at an
686 function or not. For this, simply type ``%run -d myscript`` at an
685 IPython prompt. See the :magic:`run` command's documentation for more details, including
687 IPython prompt. See the :magic:`run` command's documentation for more details, including
686 how to control where pdb will stop execution first.
688 how to control where pdb will stop execution first.
687
689
688 For more information on the use of the pdb debugger, see :ref:`debugger-commands`
690 For more information on the use of the pdb debugger, see :ref:`debugger-commands`
689 in the Python documentation.
691 in the Python documentation.
690
692
691 IPython extends the debugger with a few useful additions, like coloring of
693 IPython extends the debugger with a few useful additions, like coloring of
692 tracebacks. The debugger will adopt the color scheme selected for IPython.
694 tracebacks. The debugger will adopt the color scheme selected for IPython.
693
695
694 The ``where`` command has also been extended to take as argument the number of
696 The ``where`` command has also been extended to take as argument the number of
695 context line to show. This allows to a many line of context on shallow stack trace:
697 context line to show. This allows to a many line of context on shallow stack trace:
696
698
697 .. code::
699 .. code::
698
700
699 In [5]: def foo(x):
701 In [5]: def foo(x):
700 ...: 1
702 ...: 1
701 ...: 2
703 ...: 2
702 ...: 3
704 ...: 3
703 ...: return 1/x+foo(x-1)
705 ...: return 1/x+foo(x-1)
704 ...: 5
706 ...: 5
705 ...: 6
707 ...: 6
706 ...: 7
708 ...: 7
707 ...:
709 ...:
708
710
709 In[6]: foo(1)
711 In[6]: foo(1)
710 # ...
712 # ...
711 ipdb> where 8
713 ipdb> where 8
712 <ipython-input-6-9e45007b2b59>(1)<module>()
714 <ipython-input-6-9e45007b2b59>(1)<module>()
713 ----> 1 foo(1)
715 ----> 1 foo(1)
714
716
715 <ipython-input-5-7baadc3d1465>(5)foo()
717 <ipython-input-5-7baadc3d1465>(5)foo()
716 1 def foo(x):
718 1 def foo(x):
717 2 1
719 2 1
718 3 2
720 3 2
719 4 3
721 4 3
720 ----> 5 return 1/x+foo(x-1)
722 ----> 5 return 1/x+foo(x-1)
721 6 5
723 6 5
722 7 6
724 7 6
723 8 7
725 8 7
724
726
725 > <ipython-input-5-7baadc3d1465>(5)foo()
727 > <ipython-input-5-7baadc3d1465>(5)foo()
726 1 def foo(x):
728 1 def foo(x):
727 2 1
729 2 1
728 3 2
730 3 2
729 4 3
731 4 3
730 ----> 5 return 1/x+foo(x-1)
732 ----> 5 return 1/x+foo(x-1)
731 6 5
733 6 5
732 7 6
734 7 6
733 8 7
735 8 7
734
736
735
737
736 And less context on shallower Stack Trace:
738 And less context on shallower Stack Trace:
737
739
738 .. code::
740 .. code::
739
741
740 ipdb> where 1
742 ipdb> where 1
741 <ipython-input-13-afa180a57233>(1)<module>()
743 <ipython-input-13-afa180a57233>(1)<module>()
742 ----> 1 foo(7)
744 ----> 1 foo(7)
743
745
744 <ipython-input-5-7baadc3d1465>(5)foo()
746 <ipython-input-5-7baadc3d1465>(5)foo()
745 ----> 5 return 1/x+foo(x-1)
747 ----> 5 return 1/x+foo(x-1)
746
748
747 <ipython-input-5-7baadc3d1465>(5)foo()
749 <ipython-input-5-7baadc3d1465>(5)foo()
748 ----> 5 return 1/x+foo(x-1)
750 ----> 5 return 1/x+foo(x-1)
749
751
750 <ipython-input-5-7baadc3d1465>(5)foo()
752 <ipython-input-5-7baadc3d1465>(5)foo()
751 ----> 5 return 1/x+foo(x-1)
753 ----> 5 return 1/x+foo(x-1)
752
754
753 <ipython-input-5-7baadc3d1465>(5)foo()
755 <ipython-input-5-7baadc3d1465>(5)foo()
754 ----> 5 return 1/x+foo(x-1)
756 ----> 5 return 1/x+foo(x-1)
755
757
756
758
757 Post-mortem debugging
759 Post-mortem debugging
758 ---------------------
760 ---------------------
759
761
760 Going into a debugger when an exception occurs can be
762 Going into a debugger when an exception occurs can be
761 extremely useful in order to find the origin of subtle bugs, because pdb
763 extremely useful in order to find the origin of subtle bugs, because pdb
762 opens up at the point in your code which triggered the exception, and
764 opens up at the point in your code which triggered the exception, and
763 while your program is at this point 'dead', all the data is still
765 while your program is at this point 'dead', all the data is still
764 available and you can walk up and down the stack frame and understand
766 available and you can walk up and down the stack frame and understand
765 the origin of the problem.
767 the origin of the problem.
766
768
767 You can use the :magic:`debug` magic after an exception has occurred to start
769 You can use the :magic:`debug` magic after an exception has occurred to start
768 post-mortem debugging. IPython can also call debugger every time your code
770 post-mortem debugging. IPython can also call debugger every time your code
769 triggers an uncaught exception. This feature can be toggled with the :magic:`pdb` magic
771 triggers an uncaught exception. This feature can be toggled with the :magic:`pdb` magic
770 command, or you can start IPython with the ``--pdb`` option.
772 command, or you can start IPython with the ``--pdb`` option.
771
773
772 For a post-mortem debugger in your programs outside IPython,
774 For a post-mortem debugger in your programs outside IPython,
773 put the following lines toward the top of your 'main' routine::
775 put the following lines toward the top of your 'main' routine::
774
776
775 import sys
777 import sys
776 from IPython.core import ultratb
778 from IPython.core import ultratb
777 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
779 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
778 color_scheme='Linux', call_pdb=1)
780 color_scheme='Linux', call_pdb=1)
779
781
780 The mode keyword can be either 'Verbose' or 'Plain', giving either very
782 The mode keyword can be either 'Verbose' or 'Plain', giving either very
781 detailed or normal tracebacks respectively. The color_scheme keyword can
783 detailed or normal tracebacks respectively. The color_scheme keyword can
782 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
784 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
783 options which can be set in IPython with ``--colors`` and ``--xmode``.
785 options which can be set in IPython with ``--colors`` and ``--xmode``.
784
786
785 This will give any of your programs detailed, colored tracebacks with
787 This will give any of your programs detailed, colored tracebacks with
786 automatic invocation of pdb.
788 automatic invocation of pdb.
787
789
788 .. _pasting_with_prompts:
790 .. _pasting_with_prompts:
789
791
790 Pasting of code starting with Python or IPython prompts
792 Pasting of code starting with Python or IPython prompts
791 =======================================================
793 =======================================================
792
794
793 IPython is smart enough to filter out input prompts, be they plain Python ones
795 IPython is smart enough to filter out input prompts, be they plain Python ones
794 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
796 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
795 therefore copy and paste from existing interactive sessions without worry.
797 therefore copy and paste from existing interactive sessions without worry.
796
798
797 The following is a 'screenshot' of how things work, copying an example from the
799 The following is a 'screenshot' of how things work, copying an example from the
798 standard Python tutorial::
800 standard Python tutorial::
799
801
800 In [1]: >>> # Fibonacci series:
802 In [1]: >>> # Fibonacci series:
801
803
802 In [2]: ... # the sum of two elements defines the next
804 In [2]: ... # the sum of two elements defines the next
803
805
804 In [3]: ... a, b = 0, 1
806 In [3]: ... a, b = 0, 1
805
807
806 In [4]: >>> while b < 10:
808 In [4]: >>> while b < 10:
807 ...: ... print(b)
809 ...: ... print(b)
808 ...: ... a, b = b, a+b
810 ...: ... a, b = b, a+b
809 ...:
811 ...:
810 1
812 1
811 1
813 1
812 2
814 2
813 3
815 3
814 5
816 5
815 8
817 8
816
818
817 And pasting from IPython sessions works equally well::
819 And pasting from IPython sessions works equally well::
818
820
819 In [1]: In [5]: def f(x):
821 In [1]: In [5]: def f(x):
820 ...: ...: "A simple function"
822 ...: ...: "A simple function"
821 ...: ...: return x**2
823 ...: ...: return x**2
822 ...: ...:
824 ...: ...:
823
825
824 In [2]: f(3)
826 In [2]: f(3)
825 Out[2]: 9
827 Out[2]: 9
826
828
827 .. _gui_support:
829 .. _gui_support:
828
830
829 GUI event loop support
831 GUI event loop support
830 ======================
832 ======================
831
833
832 IPython has excellent support for working interactively with Graphical User
834 IPython has excellent support for working interactively with Graphical User
833 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
835 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
834 implemented by running the toolkit's event loop while IPython is waiting for
836 implemented by running the toolkit's event loop while IPython is waiting for
835 input.
837 input.
836
838
837 For users, enabling GUI event loop integration is simple. You simple use the
839 For users, enabling GUI event loop integration is simple. You simple use the
838 :magic:`gui` magic as follows::
840 :magic:`gui` magic as follows::
839
841
840 %gui [GUINAME]
842 %gui [GUINAME]
841
843
842 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
844 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
843 arguments include ``wx``, ``qt``, ``qt5``, ``gtk``, ``gtk3`` and ``tk``.
845 arguments include ``wx``, ``qt``, ``qt5``, ``gtk``, ``gtk3`` and ``tk``.
844
846
845 Thus, to use wxPython interactively and create a running :class:`wx.App`
847 Thus, to use wxPython interactively and create a running :class:`wx.App`
846 object, do::
848 object, do::
847
849
848 %gui wx
850 %gui wx
849
851
850 You can also start IPython with an event loop set up using the `--gui`
852 You can also start IPython with an event loop set up using the `--gui`
851 flag::
853 flag::
852
854
853 $ ipython --gui=qt
855 $ ipython --gui=qt
854
856
855 For information on IPython's matplotlib_ integration (and the ``matplotlib``
857 For information on IPython's matplotlib_ integration (and the ``matplotlib``
856 mode) see :ref:`this section <matplotlib_support>`.
858 mode) see :ref:`this section <matplotlib_support>`.
857
859
858 For developers that want to integrate additional event loops with IPython, see
860 For developers that want to integrate additional event loops with IPython, see
859 :doc:`/config/eventloops`.
861 :doc:`/config/eventloops`.
860
862
861 When running inside IPython with an integrated event loop, a GUI application
863 When running inside IPython with an integrated event loop, a GUI application
862 should *not* start its own event loop. This means that applications that are
864 should *not* start its own event loop. This means that applications that are
863 meant to be used both
865 meant to be used both
864 in IPython and as standalone apps need to have special code to detects how the
866 in IPython and as standalone apps need to have special code to detects how the
865 application is being run. We highly recommend using IPython's support for this.
867 application is being run. We highly recommend using IPython's support for this.
866 Since the details vary slightly between toolkits, we point you to the various
868 Since the details vary slightly between toolkits, we point you to the various
867 examples in our source directory :file:`examples/IPython Kernel/gui/` that
869 examples in our source directory :file:`examples/IPython Kernel/gui/` that
868 demonstrate these capabilities.
870 demonstrate these capabilities.
869
871
870 PyQt and PySide
872 PyQt and PySide
871 ---------------
873 ---------------
872
874
873 .. attempt at explanation of the complete mess that is Qt support
875 .. attempt at explanation of the complete mess that is Qt support
874
876
875 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
877 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
876 PyQt4 or PySide. There are three options for configuration here, because
878 PyQt4 or PySide. There are three options for configuration here, because
877 PyQt4 has two APIs for QString and QVariant: v1, which is the default on
879 PyQt4 has two APIs for QString and QVariant: v1, which is the default on
878 Python 2, and the more natural v2, which is the only API supported by PySide.
880 Python 2, and the more natural v2, which is the only API supported by PySide.
879 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
881 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
880 uses v2, but you can still use any interface in your code, since the
882 uses v2, but you can still use any interface in your code, since the
881 Qt frontend is in a different process.
883 Qt frontend is in a different process.
882
884
883 The default will be to import PyQt4 without configuration of the APIs, thus
885 The default will be to import PyQt4 without configuration of the APIs, thus
884 matching what most applications would expect. It will fall back to PySide if
886 matching what most applications would expect. It will fall back to PySide if
885 PyQt4 is unavailable.
887 PyQt4 is unavailable.
886
888
887 If specified, IPython will respect the environment variable ``QT_API`` used
889 If specified, IPython will respect the environment variable ``QT_API`` used
888 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
890 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
889 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
891 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
890 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
892 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
891 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
893 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
892
894
893 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
895 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
894 then IPython will ask matplotlib which Qt library to use (only if QT_API is
896 then IPython will ask matplotlib which Qt library to use (only if QT_API is
895 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
897 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
896 older, then IPython will always use PyQt4 without setting the v2 APIs, since
898 older, then IPython will always use PyQt4 without setting the v2 APIs, since
897 neither v2 PyQt nor PySide work.
899 neither v2 PyQt nor PySide work.
898
900
899 .. warning::
901 .. warning::
900
902
901 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
903 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
902 to work with IPython's qt integration, because otherwise PyQt4 will be
904 to work with IPython's qt integration, because otherwise PyQt4 will be
903 loaded in an incompatible mode.
905 loaded in an incompatible mode.
904
906
905 It also means that you must *not* have ``QT_API`` set if you want to
907 It also means that you must *not* have ``QT_API`` set if you want to
906 use ``--gui=qt`` with code that requires PyQt4 API v1.
908 use ``--gui=qt`` with code that requires PyQt4 API v1.
907
909
908
910
909 .. _matplotlib_support:
911 .. _matplotlib_support:
910
912
911 Plotting with matplotlib
913 Plotting with matplotlib
912 ========================
914 ========================
913
915
914 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
916 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
915 can produce plots on screen using a variety of GUI toolkits, including Tk,
917 can produce plots on screen using a variety of GUI toolkits, including Tk,
916 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
918 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
917 scientific computing, all with a syntax compatible with that of the popular
919 scientific computing, all with a syntax compatible with that of the popular
918 Matlab program.
920 Matlab program.
919
921
920 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
922 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
921 IPython is already running, you can run the :magic:`matplotlib` magic. If no
923 IPython is already running, you can run the :magic:`matplotlib` magic. If no
922 arguments are given, IPython will automatically detect your choice of
924 arguments are given, IPython will automatically detect your choice of
923 matplotlib backend. You can also request a specific backend with
925 matplotlib backend. You can also request a specific backend with
924 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
926 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
925 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
927 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
926 backend value, which produces static figures inlined inside the application
928 backend value, which produces static figures inlined inside the application
927 window instead of matplotlib's interactive figures that live in separate
929 window instead of matplotlib's interactive figures that live in separate
928 windows.
930 windows.
929
931
930 .. _interactive_demos:
932 .. _interactive_demos:
931
933
932 Interactive demos with IPython
934 Interactive demos with IPython
933 ==============================
935 ==============================
934
936
935 IPython ships with a basic system for running scripts interactively in
937 IPython ships with a basic system for running scripts interactively in
936 sections, useful when presenting code to audiences. A few tags embedded
938 sections, useful when presenting code to audiences. A few tags embedded
937 in comments (so that the script remains valid Python code) divide a file
939 in comments (so that the script remains valid Python code) divide a file
938 into separate blocks, and the demo can be run one block at a time, with
940 into separate blocks, and the demo can be run one block at a time, with
939 IPython printing (with syntax highlighting) the block before executing
941 IPython printing (with syntax highlighting) the block before executing
940 it, and returning to the interactive prompt after each block. The
942 it, and returning to the interactive prompt after each block. The
941 interactive namespace is updated after each block is run with the
943 interactive namespace is updated after each block is run with the
942 contents of the demo's namespace.
944 contents of the demo's namespace.
943
945
944 This allows you to show a piece of code, run it and then execute
946 This allows you to show a piece of code, run it and then execute
945 interactively commands based on the variables just created. Once you
947 interactively commands based on the variables just created. Once you
946 want to continue, you simply execute the next block of the demo. The
948 want to continue, you simply execute the next block of the demo. The
947 following listing shows the markup necessary for dividing a script into
949 following listing shows the markup necessary for dividing a script into
948 sections for execution as a demo:
950 sections for execution as a demo:
949
951
950 .. literalinclude:: ../../../examples/IPython Kernel/example-demo.py
952 .. literalinclude:: ../../../examples/IPython Kernel/example-demo.py
951 :language: python
953 :language: python
952
954
953 In order to run a file as a demo, you must first make a Demo object out
955 In order to run a file as a demo, you must first make a Demo object out
954 of it. If the file is named myscript.py, the following code will make a
956 of it. If the file is named myscript.py, the following code will make a
955 demo::
957 demo::
956
958
957 from IPython.lib.demo import Demo
959 from IPython.lib.demo import Demo
958
960
959 mydemo = Demo('myscript.py')
961 mydemo = Demo('myscript.py')
960
962
961 This creates the mydemo object, whose blocks you run one at a time by
963 This creates the mydemo object, whose blocks you run one at a time by
962 simply calling the object with no arguments. Then call it to run each step
964 simply calling the object with no arguments. Then call it to run each step
963 of the demo::
965 of the demo::
964
966
965 mydemo()
967 mydemo()
966
968
967 Demo objects can be
969 Demo objects can be
968 restarted, you can move forward or back skipping blocks, re-execute the
970 restarted, you can move forward or back skipping blocks, re-execute the
969 last block, etc. See the :mod:`IPython.lib.demo` module and the
971 last block, etc. See the :mod:`IPython.lib.demo` module and the
970 :class:`~IPython.lib.demo.Demo` class for details.
972 :class:`~IPython.lib.demo.Demo` class for details.
971
973
972 Limitations: These demos are limited to
974 Limitations: These demos are limited to
973 fairly simple uses. In particular, you cannot break up sections within
975 fairly simple uses. In particular, you cannot break up sections within
974 indented code (loops, if statements, function definitions, etc.)
976 indented code (loops, if statements, function definitions, etc.)
975 Supporting something like this would basically require tracking the
977 Supporting something like this would basically require tracking the
976 internal execution state of the Python interpreter, so only top-level
978 internal execution state of the Python interpreter, so only top-level
977 divisions are allowed. If you want to be able to open an IPython
979 divisions are allowed. If you want to be able to open an IPython
978 instance at an arbitrary point in a program, you can use IPython's
980 instance at an arbitrary point in a program, you can use IPython's
979 :ref:`embedding facilities <Embedding>`.
981 :ref:`embedding facilities <Embedding>`.
980
982
981 .. include:: ../links.txt
983 .. include:: ../links.txt
General Comments 0
You need to be logged in to leave comments. Login now