##// END OF EJS Templates
Merge pull request #9668 from Carreau/more-docs...
Matthias Bussonnier -
r22605:298936bf merge
parent child Browse files
Show More
@@ -1,284 +1,284 b''
1 1 # -*- coding: utf-8 -*-
2 2 #
3 3 # IPython documentation build configuration file.
4 4
5 5 # NOTE: This file has been edited manually from the auto-generated one from
6 6 # sphinx. Do NOT delete and re-generate. If any changes from sphinx are
7 7 # needed, generate a scratch one and merge by hand any new fields needed.
8 8
9 9 #
10 10 # This file is execfile()d with the current directory set to its containing dir.
11 11 #
12 12 # The contents of this file are pickled, so don't put values in the namespace
13 13 # that aren't pickleable (module imports are okay, they're removed automatically).
14 14 #
15 15 # All configuration values have a default value; values that are commented out
16 16 # serve to show the default value.
17 17
18 18 import sys, os
19 19
20 20 ON_RTD = os.environ.get('READTHEDOCS', None) == 'True'
21 21
22 22 if ON_RTD:
23 23 # Mock the presence of matplotlib, which we don't have on RTD
24 24 # see
25 25 # http://read-the-docs.readthedocs.io/en/latest/faq.html
26 26 tags.add('rtd')
27 27
28 28 # RTD doesn't use the Makefile, so re-run autogen_{things}.py here.
29 29 for name in ('config', 'api', 'magics'):
30 30 fname = 'autogen_{}.py'.format(name)
31 31 fpath = os.path.abspath(os.path.join('..', fname))
32 32 with open(fpath) as f:
33 33 exec(compile(f.read(), fname, 'exec'), {
34 34 '__file__': fpath,
35 35 '__name__': '__main__',
36 36 })
37 37 else:
38 38 import sphinx_rtd_theme
39 39 html_theme = "sphinx_rtd_theme"
40 40 html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
41 41
42 42 # If your extensions are in another directory, add it here. If the directory
43 43 # is relative to the documentation root, use os.path.abspath to make it
44 44 # absolute, like shown here.
45 45 sys.path.insert(0, os.path.abspath('../sphinxext'))
46 46
47 47 # We load the ipython release info into a dict by explicit execution
48 48 iprelease = {}
49 49 exec(compile(open('../../IPython/core/release.py').read(), '../../IPython/core/release.py', 'exec'),iprelease)
50 50
51 51 # General configuration
52 52 # ---------------------
53 53
54 54 # Add any Sphinx extension module names here, as strings. They can be extensions
55 55 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
56 56 extensions = [
57 57 'matplotlib.sphinxext.mathmpl',
58 58 'matplotlib.sphinxext.only_directives',
59 59 'matplotlib.sphinxext.plot_directive',
60 60 'sphinx.ext.autodoc',
61 61 'sphinx.ext.autosummary',
62 62 'sphinx.ext.doctest',
63 63 'sphinx.ext.inheritance_diagram',
64 64 'sphinx.ext.intersphinx',
65 65 'IPython.sphinxext.ipython_console_highlighting',
66 66 'IPython.sphinxext.ipython_directive',
67 67 'sphinx.ext.napoleon', # to preprocess docstrings
68 68 'github', # for easy GitHub links
69 69 'magics',
70 70 ]
71 71
72 72 if ON_RTD:
73 73 # Remove extensions not currently supported on RTD
74 74 extensions.remove('matplotlib.sphinxext.only_directives')
75 75 extensions.remove('matplotlib.sphinxext.mathmpl')
76 76 extensions.remove('matplotlib.sphinxext.plot_directive')
77 77 extensions.remove('IPython.sphinxext.ipython_directive')
78 78 extensions.remove('IPython.sphinxext.ipython_console_highlighting')
79 79
80 80 # Add any paths that contain templates here, relative to this directory.
81 81 templates_path = ['_templates']
82 82
83 83 # The suffix of source filenames.
84 84 source_suffix = '.rst'
85 85
86 86 def is_stable(extra):
87 87 for ext in {'dev', 'b', 'rc'}:
88 88 if ext in extra:
89 89 return False
90 90 return True
91 91
92 92 if is_stable(iprelease['_version_extra']):
93 93 tags.add('ipystable')
94 94 else:
95 95 tags.add('ipydev')
96 96 rst_prolog = """
97 97 .. warning::
98 98
99 99 This documentation is for a development version of IPython. There may be
100 100 significant differences from the latest stable release.
101 101
102 102 """
103 103
104 104 # The master toctree document.
105 105 master_doc = 'index'
106 106
107 107 # General substitutions.
108 108 project = 'IPython'
109 109 copyright = 'The IPython Development Team'
110 110
111 111 # ghissue config
112 112 github_project_url = "https://github.com/ipython/ipython"
113 113
114 114 # numpydoc config
115 115 numpydoc_show_class_members = False # Otherwise Sphinx emits thousands of warnings
116 116 numpydoc_class_members_toctree = False
117 117
118 118 # The default replacements for |version| and |release|, also used in various
119 119 # other places throughout the built documents.
120 120 #
121 121 # The full version, including alpha/beta/rc tags.
122 122 release = "%s" % iprelease['version']
123 123 # Just the X.Y.Z part, no '-dev'
124 124 version = iprelease['version'].split('-', 1)[0]
125 125
126 126
127 127 # There are two options for replacing |today|: either, you set today to some
128 128 # non-false value, then it is used:
129 129 #today = ''
130 130 # Else, today_fmt is used as the format for a strftime call.
131 131 today_fmt = '%B %d, %Y'
132 132
133 133 # List of documents that shouldn't be included in the build.
134 134 #unused_docs = []
135 135
136 136 # Exclude these glob-style patterns when looking for source files. They are
137 137 # relative to the source/ directory.
138 138 exclude_patterns = ['whatsnew/pr']
139 139
140 140
141 141 # If true, '()' will be appended to :func: etc. cross-reference text.
142 142 #add_function_parentheses = True
143 143
144 144 # If true, the current module name will be prepended to all description
145 145 # unit titles (such as .. function::).
146 146 #add_module_names = True
147 147
148 148 # If true, sectionauthor and moduleauthor directives will be shown in the
149 149 # output. They are ignored by default.
150 150 #show_authors = False
151 151
152 152 # The name of the Pygments (syntax highlighting) style to use.
153 153 pygments_style = 'sphinx'
154 154
155 155 # Set the default role so we can use `foo` instead of ``foo``
156 156 default_role = 'literal'
157 157
158 158 # Options for HTML output
159 159 # -----------------------
160 160
161 161 # The style sheet to use for HTML and HTML Help pages. A file of that name
162 162 # must exist either in Sphinx' static/ path, or in one of the custom paths
163 163 # given in html_static_path.
164 164 # html_style = 'default.css'
165 165
166 166
167 167 # The name for this set of Sphinx documents. If None, it defaults to
168 168 # "<project> v<release> documentation".
169 169 #html_title = None
170 170
171 171 # The name of an image file (within the static path) to place at the top of
172 172 # the sidebar.
173 173 #html_logo = None
174 174
175 175 # Add any paths that contain custom static files (such as style sheets) here,
176 176 # relative to this directory. They are copied after the builtin static files,
177 177 # so a file named "default.css" will overwrite the builtin "default.css".
178 178 html_static_path = ['_static']
179 179
180 180 # Favicon needs the directory name
181 181 html_favicon = '_static/favicon.ico'
182 182 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
183 183 # using the given strftime format.
184 184 html_last_updated_fmt = '%b %d, %Y'
185 185
186 186 # If true, SmartyPants will be used to convert quotes and dashes to
187 187 # typographically correct entities.
188 188 #html_use_smartypants = True
189 189
190 190 # Custom sidebar templates, maps document names to template names.
191 191 #html_sidebars = {}
192 192
193 193 # Additional templates that should be rendered to pages, maps page names to
194 194 # template names.
195 195 html_additional_pages = {
196 196 'interactive/htmlnotebook': 'notebook_redirect.html',
197 197 'interactive/notebook': 'notebook_redirect.html',
198 198 'interactive/nbconvert': 'notebook_redirect.html',
199 199 'interactive/public_server': 'notebook_redirect.html',
200 200 }
201 201
202 202 # If false, no module index is generated.
203 203 #html_use_modindex = True
204 204
205 205 # If true, the reST sources are included in the HTML build as _sources/<name>.
206 206 #html_copy_source = True
207 207
208 208 # If true, an OpenSearch description file will be output, and all pages will
209 209 # contain a <link> tag referring to it. The value of this option must be the
210 210 # base URL from which the finished HTML is served.
211 211 #html_use_opensearch = ''
212 212
213 213 # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
214 214 #html_file_suffix = ''
215 215
216 216 # Output file base name for HTML help builder.
217 217 htmlhelp_basename = 'ipythondoc'
218 218
219 intersphinx_mapping = {'python': ('http://docs.python.org/3/', None),
220 'rpy2': ('http://rpy.sourceforge.net/rpy2/doc-2.4/html/', None),
221 'traitlets': ('http://traitlets.readthedocs.io/en/latest/', None),
222 'jupyterclient': ('http://jupyter-client.readthedocs.io/en/latest/', None),
223 'ipyparallel': ('http://ipyparallel.readthedocs.io/en/latest/', None),
224 'jupyter': ('http://jupyter.readthedocs.io/en/latest/', None),
219 intersphinx_mapping = {'python': ('https://docs.python.org/3/', None),
220 'rpy2': ('https://rpy2.readthedocs.io/en/version_2.8.x/', None),
221 'traitlets': ('https://traitlets.readthedocs.io/en/latest/', None),
222 'jupyterclient': ('https://jupyter-client.readthedocs.io/en/latest/', None),
223 'ipyparallel': ('https://ipyparallel.readthedocs.io/en/latest/', None),
224 'jupyter': ('https://jupyter.readthedocs.io/en/latest/', None),
225 225 }
226 226
227 227 # Options for LaTeX output
228 228 # ------------------------
229 229
230 230 # The paper size ('letter' or 'a4').
231 231 latex_paper_size = 'letter'
232 232
233 233 # The font size ('10pt', '11pt' or '12pt').
234 234 latex_font_size = '11pt'
235 235
236 236 # Grouping the document tree into LaTeX files. List of tuples
237 237 # (source start file, target name, title, author, document class [howto/manual]).
238 238
239 239 latex_documents = [
240 240 ('index', 'ipython.tex', 'IPython Documentation',
241 241 u"""The IPython Development Team""", 'manual', True),
242 242 ('parallel/winhpc_index', 'winhpc_whitepaper.tex',
243 243 'Using IPython on Windows HPC Server 2008',
244 244 u"Brian E. Granger", 'manual', True)
245 245 ]
246 246
247 247 # The name of an image file (relative to this directory) to place at the top of
248 248 # the title page.
249 249 #latex_logo = None
250 250
251 251 # For "manual" documents, if this is true, then toplevel headings are parts,
252 252 # not chapters.
253 253 #latex_use_parts = False
254 254
255 255 # Additional stuff for the LaTeX preamble.
256 256 #latex_preamble = ''
257 257
258 258 # Documents to append as an appendix to all manuals.
259 259 #latex_appendices = []
260 260
261 261 # If false, no module index is generated.
262 262 latex_use_modindex = True
263 263
264 264
265 265 # Options for texinfo output
266 266 # --------------------------
267 267
268 268 texinfo_documents = [
269 269 (master_doc, 'ipython', 'IPython Documentation',
270 270 'The IPython Development Team',
271 271 'IPython',
272 272 'IPython Documentation',
273 273 'Programming',
274 274 1),
275 275 ]
276 276
277 277 modindex_common_prefix = ['IPython.']
278 278
279 279
280 280 # Cleanup
281 281 # -------
282 282 # delete release info to avoid pickling errors from sphinx
283 283
284 284 del iprelease
@@ -1,19 +1,31 b''
1 1 ==================================
2 2 Using IPython for interactive work
3 3 ==================================
4 4
5 This section of IPython documentation walk you through most of the IPython
6 functionality. You do not need to have any deep knowledge of Python to read this
7 tutorial, though some section might make slightly more sens if you have already
8 done some work in the REPL.
9
10 .. note::
11
12 Some part of this documentation are more than a decade old so might be out
13 of date, we welcome any report of inacuracy, and Pull Requests that make
14 that up to date.
15
5 16 .. toctree::
6 17 :maxdepth: 2
18 :hidden:
7 19
8 20 tutorial
9 magics
10 21 plotting
11 22 reference
12 23 shell
13 24 tips
14 25 python-ipython-diff
26 magics
15 27
16 28 .. seealso::
17 29
18 30 `A Qt Console for Jupyter <http://jupyter.org/qtconsole/>`__
19 31 `The Jupyter Notebook <http://jupyter-notebook.readthedocs.io/en/latest/>`__
@@ -1,5 +1,23 b''
1 1 =======================
2 2 Built-in magic commands
3 3 =======================
4 4
5 .. note::
6
7 To Jupyter users: Magics are specific to and provided by the IPython kernel.
8 Whether magics are available on a kernel is a decision that is made by
9 the kernel developer on a per-kernel basis. To work properly, Magics must
10 use a syntax element which is not valid in the underlying language. For
11 example, the IPython kernel uses the `%` syntax element for magics as `%`
12 is not a valid unary operator in Python. While, the syntax element has
13 meaning in other languages.
14
15 Here is the help auto generated from the docstrings of all the available magics
16 function that IPython ships with.
17
18 You can create an register your own magics with IPython. You can find many user
19 defined magics on `PyPI <https://pypi.io>`_. Feel free to publish your own and
20 use the ``Framework :: IPython`` trove classifier.
21
22
5 23 .. include:: magics-generated.txt
@@ -1,36 +1,42 b''
1 1 .. _plotting:
2 2
3 3 Plotting
4 4 --------
5 5 One major feature of the IPython kernel is the ability to display plots that
6 6 are the output of running code cells. The IPython kernel is designed to work
7 7 seamlessly with the matplotlib_ plotting library to provide this functionality.
8 8
9 To set this up, before any plotting is performed you must execute the
10 ``%matplotlib`` :ref:`magic command <magics_explained>`. This performs the
11 necessary behind-the-scenes setup for IPython to work correctly hand in hand
12 with ``matplotlib``; it does *not*, however, actually execute any Python
13 ``import`` commands, that is, no names are added to the namespace.
9 To set this up, before any plotting or import of matplotlib is performed you
10 must execute the ``%matplotlib`` :ref:`magic command <magics_explained>`. This
11 performs the necessary behind-the-scenes setup for IPython to work correctly
12 hand in hand with ``matplotlib``; it does *not*, however, actually execute any
13 Python ``import`` commands, that is, no names are added to the namespace.
14 14
15 15 If the ``%matplotlib`` magic is called without an argument, the
16 16 output of a plotting command is displayed using the default ``matplotlib``
17 17 backend in a separate window. Alternatively, the backend can be explicitly
18 18 requested using, for example::
19 19
20 20 %matplotlib gtk
21 21
22 22 A particularly interesting backend, provided by IPython, is the ``inline``
23 23 backend. This is available only for the Jupyter Notebook and the
24 24 Jupyter QtConsole. It can be invoked as follows::
25 25
26 26 %matplotlib inline
27 27
28 With this backend, the output of plotting commands is displayed *inline*
29 within the notebook, directly below the code cell that produced it. The
30 resulting plots will then also be stored in the notebook document.
28 With this backend, the output of plotting commands is displayed *inline* within
29 frontends like the Jupyter notebook, directly below the code cell that produced
30 it. The resulting plots will then also be stored in the notebook document.
31 31
32 32 .. seealso::
33 33
34 34 `Plotting with Matplotlib`_ example notebook
35 35
36
37 The matplotlib_ library also ships with ``%matplotlib notebook`` command that
38 allows interactive figures if your environment allows it.
39
40 See the matplotlib_ documentation for more information.
41
36 42 .. include:: ../links.txt
@@ -1,1000 +1,1007 b''
1 1 =================
2 2 IPython reference
3 3 =================
4 4
5 5 .. _command_line_options:
6 6
7 7 Command-line usage
8 8 ==================
9 9
10 10 You start IPython with the command::
11 11
12 12 $ ipython [options] files
13 13
14 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
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
18 file and ignore your configuration setup.
19
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
22 your configuration files for details on those. There are separate configuration
23 files for each profile, and the files look like :file:`ipython_config.py` or
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
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``
18 will only execute one file and ignore your configuration setup.
19
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
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
24 24 :file:`ipython_config_{frontendname}.py`. Profile directories look like
25 :file:`profile_{profilename}` and are typically installed in the :envvar:`IPYTHONDIR` directory,
26 which defaults to :file:`$HOME/.ipython`. For Windows users, :envvar:`HOME`
27 resolves to :file:`C:\\Users\\{YourUserName}` in most instances.
25 :file:`profile_{profilename}` and are typically installed in the
26 :envvar:`IPYTHONDIR` directory, which defaults to :file:`$HOME/.ipython`. For
27 Windows users, :envvar:`HOME` resolves to :file:`C:\\Users\\{YourUserName}` in
28 most instances.
28 29
29 30 Command-line Options
30 31 --------------------
31 32
32 33 To see the options IPython accepts, use ``ipython --help`` (and you probably
33 34 should run the output through a pager such as ``ipython --help | less`` for
34 35 more convenient reading). This shows all the options that have a single-word
35 36 alias to control them, but IPython lets you configure all of its objects from
36 37 the command-line by passing the full class name and a corresponding value; type
37 38 ``ipython --help-all`` to see this full list. For example::
38 39
39 ipython --matplotlib qt
40 $ ipython --help-all
41 <...snip...>
42 --matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
43 Default: None
44 Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
45 Configure matplotlib for interactive use with the default matplotlib
46 backend.
47 <...snip...>
48
49
50 Indicate that the following::
51
52 $ ipython --matplotlib qt
53
40 54
41 55 is equivalent to::
42 56
43 ipython --TerminalIPythonApp.matplotlib='qt'
57 $ ipython --TerminalIPythonApp.matplotlib='qt'
44 58
45 59 Note that in the second form, you *must* use the equal sign, as the expression
46 60 is evaluated as an actual Python assignment. While in the above example the
47 61 short form is more convenient, only the most common options have a short form,
48 62 while any configurable variable in IPython can be set at the command-line by
49 63 using the long form. This long form is the same syntax used in the
50 64 configuration files, if you want to set these options permanently.
51 65
52 66
53 67 Interactive use
54 68 ===============
55 69
56 70 IPython is meant to work as a drop-in replacement for the standard interactive
57 71 interpreter. As such, any code which is valid python should execute normally
58 72 under IPython (cases where this is not true should be reported as bugs). It
59 73 does, however, offer many features which are not available at a standard python
60 74 prompt. What follows is a list of these.
61 75
62 76
63 77 Caution for Windows users
64 78 -------------------------
65 79
66 80 Windows, unfortunately, uses the '\\' character as a path separator. This is a
67 81 terrible choice, because '\\' also represents the escape character in most
68 82 modern programming languages, including Python. For this reason, using '/'
69 83 character is recommended if you have problems with ``\``. However, in Windows
70 84 commands '/' flags options, so you can not use it for the root directory. This
71 85 means that paths beginning at the root must be typed in a contrived manner
72 86 like: ``%copy \opt/foo/bar.txt \tmp``
73 87
74 88 .. _magic:
75 89
76 90 Magic command system
77 91 --------------------
78 92
79 93 IPython will treat any line whose first character is a % as a special
80 94 call to a 'magic' function. These allow you to control the behavior of
81 95 IPython itself, plus a lot of system-type features. They are all
82 96 prefixed with a % character, but parameters are given without
83 97 parentheses or quotes.
84 98
85 99 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
86 100 only the rest of the current line, but all lines below them as well, in the
87 101 current execution block. Cell magics can in fact make arbitrary modifications
88 102 to the input they receive, which need not even be valid Python code at all.
89 103 They receive the whole block as a single string.
90 104
91 105 As a line magic example, the :magic:`cd` magic works just like the OS command of
92 106 the same name::
93 107
94 108 In [8]: %cd
95 109 /home/fperez
96 110
97 111 The following uses the builtin :magic:`timeit` in cell mode::
98 112
99 113 In [10]: %%timeit x = range(10000)
100 114 ...: min(x)
101 115 ...: max(x)
102 116 ...:
103 117 1000 loops, best of 3: 438 us per loop
104 118
105 119 In this case, ``x = range(10000)`` is called as the line argument, and the
106 120 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
107 121 :magic:`timeit` magic receives both.
108 122
109 123 If you have 'automagic' enabled (as it is by default), you don't need to type in
110 124 the single ``%`` explicitly for line magics; IPython will scan its internal
111 125 list of magic functions and call one if it exists. With automagic on you can
112 126 then just type ``cd mydir`` to go to directory 'mydir'::
113 127
114 128 In [9]: cd mydir
115 129 /home/fperez/mydir
116 130
117 131 Cell magics *always* require an explicit ``%%`` prefix, automagic
118 132 calling only works for line magics.
119 133
120 134 The automagic system has the lowest possible precedence in name searches, so
121 135 you can freely use variables with the same names as magic commands. If a magic
122 136 command is 'shadowed' by a variable, you will need the explicit ``%`` prefix to
123 137 use it:
124 138
125 139 .. sourcecode:: ipython
126 140
127 141 In [1]: cd ipython # %cd is called by automagic
128 142 /home/fperez/ipython
129 143
130 144 In [2]: cd=1 # now cd is just a variable
131 145
132 146 In [3]: cd .. # and doesn't work as a function anymore
133 147 File "<ipython-input-3-9fedb3aff56c>", line 1
134 148 cd ..
135 149 ^
136 150 SyntaxError: invalid syntax
137 151
138 152
139 153 In [4]: %cd .. # but %cd always works
140 154 /home/fperez
141 155
142 156 In [5]: del cd # if you remove the cd variable, automagic works again
143 157
144 158 In [6]: cd ipython
145 159
146 160 /home/fperez/ipython
147 161
148 Line magics, if they return a value, can be assigned to a variable using the syntax
149 ``l = %sx ls`` (which in this particular case returns the result of `ls` as a python list).
150 See :ref:`below <manual_capture>` for more information.
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`
164 as a python list). See :ref:`below <manual_capture>` for more information.
151 165
152 166 Type ``%magic`` for more information, including a list of all available magic
153 167 functions at any time and their docstrings. You can also type
154 168 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
155 169 information on the '?' system) to get information about any particular magic
156 170 function you are interested in.
157 171
158 172 The API documentation for the :mod:`IPython.core.magic` module contains the full
159 173 docstrings of all currently available magic commands.
160 174
161 175 .. seealso::
162 176
163 177 :doc:`magics`
164 178 A list of the line and cell magics available in IPython by default
165 179
166 180 :ref:`defining_magics`
167 181 How to define and register additional magic functions
168 182
169 183
170 184 Access to the standard Python help
171 185 ----------------------------------
172 186
173 187 Simply type ``help()`` to access Python's standard help system. You can
174 188 also type ``help(object)`` for information about a given object, or
175 189 ``help('keyword')`` for information on a keyword. You may need to configure your
176 190 PYTHONDOCS environment variable for this feature to work correctly.
177 191
178 192 .. _dynamic_object_info:
179 193
180 194 Dynamic object information
181 195 --------------------------
182 196
183 197 Typing ``?word`` or ``word?`` prints detailed information about an object. If
184 198 certain strings in the object are too long (e.g. function signatures) they get
185 199 snipped in the center for brevity. This system gives access variable types and
186 200 values, docstrings, function prototypes and other useful information.
187 201
188 202 If the information will not fit in the terminal, it is displayed in a pager
189 203 (``less`` if available, otherwise a basic internal pager).
190 204
191 205 Typing ``??word`` or ``word??`` gives access to the full information, including
192 206 the source code where possible. Long strings are not snipped.
193 207
194 208 The following magic functions are particularly useful for gathering
195 209 information about your working environment:
196 210
197 211 * :magic:`pdoc` **<object>**: Print (or run through a pager if too long) the
198 212 docstring for an object. If the given object is a class, it will
199 213 print both the class and the constructor docstrings.
200 214 * :magic:`pdef` **<object>**: Print the call signature for any callable
201 215 object. If the object is a class, print the constructor information.
202 216 * :magic:`psource` **<object>**: Print (or run through a pager if too long)
203 217 the source code for an object.
204 218 * :magic:`pfile` **<object>**: Show the entire source file where an object was
205 219 defined via a pager, opening it at the line where the object
206 220 definition begins.
207 221 * :magic:`who`/:magic:`whos`: These functions give information about identifiers
208 222 you have defined interactively (not things you loaded or defined
209 223 in your configuration files). %who just prints a list of
210 224 identifiers and %whos prints a table with some basic details about
211 225 each identifier.
212 226
213 227 The dynamic object information functions (?/??, ``%pdoc``,
214 228 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
215 229 directly on variables. For example, after doing ``import os``, you can use
216 230 ``os.path.abspath??``.
217 231
218 .. _readline:
219
220 Readline-based features
221 -----------------------
222
223 These features require the GNU readline library, so they won't work if your
224 Python installation lacks readline support. We will first describe the default
225 behavior IPython uses, and then how to change it to suit your preferences.
226
227 232
228 233 Command line completion
229 234 +++++++++++++++++++++++
230 235
231 236 At any time, hitting TAB will complete any available python commands or
232 237 variable names, and show you a list of the possible completions if
233 238 there's no unambiguous one. It will also complete filenames in the
234 239 current directory if no python names match what you've typed so far.
235 240
236 241
237 242 Search command history
238 243 ++++++++++++++++++++++
239 244
240 245 IPython provides two ways for searching through previous input and thus
241 246 reduce the need for repetitive typing:
242 247
243 248 1. Start typing, and then use the up and down arrow keys (or :kbd:`Ctrl-p`
244 249 and :kbd:`Ctrl-n`) to search through only the history items that match
245 250 what you've typed so far.
246 251 2. Hit :kbd:`Ctrl-r`: to open a search prompt. Begin typing and the system
247 252 searches your history for lines that contain what you've typed so
248 253 far, completing as much as it can.
249 254
250 255 IPython will save your input history when it leaves and reload it next
251 256 time you restart it. By default, the history file is named
252 257 :file:`.ipython/profile_{name}/history.sqlite`.
253 258
254 259 Autoindent
255 260 ++++++++++
256 261
257 262 Starting with 5.0, IPython uses `prompt_toolkit` in place of ``readline``,
258 263 it thus can recognize lines ending in ':' and indent the next line,
259 264 while also un-indenting automatically after 'raise' or 'return',
260 265 and support real multi-line editing as well as syntactic coloration
261 266 during edition.
262 267
263 268 This feature does not use the ``readline`` library anymore, so it will
264 269 not honor your :file:`~/.inputrc` configuration (or whatever
265 270 file your :envvar:`INPUTRC` environment variable points to).
266 271
267 272 In particular if you want to change the input mode to ``vi``, you will need to
268 273 set the ``TerminalInteractiveShell.editing_mode`` configuration option of IPython.
269 274
270 275 Session logging and restoring
271 276 -----------------------------
272 277
273 278 You can log all input from a session either by starting IPython with the
274 279 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
275 280 or by activating the logging at any moment with the magic function :magic:`logstart`.
276 281
277 282 Log files can later be reloaded by running them as scripts and IPython
278 283 will attempt to 'replay' the log by executing all the lines in it, thus
279 284 restoring the state of a previous session. This feature is not quite
280 285 perfect, but can still be useful in many cases.
281 286
282 287 The log files can also be used as a way to have a permanent record of
283 288 any code you wrote while experimenting. Log files are regular text files
284 289 which you can later open in your favorite text editor to extract code or
285 290 to 'clean them up' before using them to replay a session.
286 291
287 292 The :magic:`logstart` function for activating logging in mid-session is used as
288 293 follows::
289 294
290 295 %logstart [log_name [log_mode]]
291 296
292 297 If no name is given, it defaults to a file named 'ipython_log.py' in your
293 298 current working directory, in 'rotate' mode (see below).
294 299
295 300 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
296 301 history up to that point and then continues logging.
297 302
298 303 %logstart takes a second optional parameter: logging mode. This can be
299 304 one of (note that the modes are given unquoted):
300 305
301 306 * [over:] overwrite existing log_name.
302 307 * [backup:] rename (if exists) to log_name~ and start log_name.
303 308 * [append:] well, that says it.
304 309 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
305 310
306 311 The :magic:`logoff` and :magic:`logon` functions allow you to temporarily stop and
307 312 resume logging to a file which had previously been started with
308 313 %logstart. They will fail (with an explanation) if you try to use them
309 314 before logging has been started.
310 315
311 316 .. _system_shell_access:
312 317
313 318 System shell access
314 319 -------------------
315 320
316 Any input line beginning with a ! character is passed verbatim (minus
317 the !, of course) to the underlying operating system. For example,
321 Any input line beginning with a ``!`` character is passed verbatim (minus
322 the ``!``, of course) to the underlying operating system. For example,
318 323 typing ``!ls`` will run 'ls' in the current directory.
319 324
320 325 .. _manual_capture:
321 326
322 327 Manual capture of command output and magic output
323 328 -------------------------------------------------
324 329
325 330 You can assign the result of a system command to a Python variable with the
326 331 syntax ``myfiles = !ls``. Similarly, the result of a magic (as long as it returns
327 332 a value) can be assigned to a variable. For example, the syntax ``myfiles = %sx ls``
328 333 is equivalent to the above system command example (the :magic:`sx` magic runs a shell command
329 334 and captures the output). Each of these gets machine
330 335 readable output from stdout (e.g. without colours), and splits on newlines. To
331 336 explicitly get this sort of output without assigning to a variable, use two
332 337 exclamation marks (``!!ls``) or the :magic:`sx` magic command without an assignment.
333 338 (However, ``!!`` commands cannot be assigned to a variable.)
334 339
335 340 The captured list in this example has some convenience features. ``myfiles.n`` or ``myfiles.s``
336 341 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
337 342 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
338 343 See :ref:`string_lists` for details.
339 344
340 345 IPython also allows you to expand the value of python variables when
341 346 making system calls. Wrap variables or expressions in {braces}::
342 347
343 348 In [1]: pyvar = 'Hello world'
344 349 In [2]: !echo "A python variable: {pyvar}"
345 350 A python variable: Hello world
346 351 In [3]: import math
347 352 In [4]: x = 8
348 353 In [5]: !echo {math.factorial(x)}
349 354 40320
350 355
351 356 For simple cases, you can alternatively prepend $ to a variable name::
352 357
353 358 In [6]: !echo $sys.argv
354 359 [/home/fperez/usr/bin/ipython]
355 360 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
356 361 A system variable: /home/fperez
357 362
358 363 Note that `$$` is used to represent a literal `$`.
359 364
360 365 System command aliases
361 366 ----------------------
362 367
363 368 The :magic:`alias` magic function allows you to define magic functions which are in fact
364 369 system shell commands. These aliases can have parameters.
365 370
366 371 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
367 372
368 373 Then, typing ``alias_name params`` will execute the system command 'cmd
369 374 params' (from your underlying operating system).
370 375
371 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
372 377 parameter). The following example defines the parts function as an
373 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
374 379 replaced by a positional parameter to the call to %parts::
375 380
376 381 In [1]: %alias parts echo first %s second %s
377 382 In [2]: parts A B
378 383 first A second B
379 384 In [3]: parts A
380 385 ERROR: Alias <parts> requires 2 arguments, 1 given.
381 386
382 387 If called with no parameters, :magic:`alias` prints the table of currently
383 388 defined aliases.
384 389
385 390 The :magic:`rehashx` magic allows you to load your entire $PATH as
386 391 ipython aliases. See its docstring for further details.
387 392
388 393
389 394 .. _dreload:
390 395
391 396 Recursive reload
392 397 ----------------
393 398
394 399 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
395 400 module: changes made to any of its dependencies will be reloaded without
396 401 having to exit. To start using it, do::
397 402
398 403 from IPython.lib.deepreload import reload as dreload
399 404
400 405
401 406 Verbose and colored exception traceback printouts
402 407 -------------------------------------------------
403 408
404 409 IPython provides the option to see very detailed exception tracebacks,
405 410 which can be especially useful when debugging large programs. You can
406 411 run any Python file with the %run function to benefit from these
407 412 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
408 413 be colored (if your terminal supports it) which makes them much easier
409 414 to parse visually.
410 415
411 416 See the magic :magic:`xmode` and :magic:`colors` functions for details.
412 417
413 418 These features are basically a terminal version of Ka-Ping Yee's cgitb
414 419 module, now part of the standard Python library.
415 420
416 421
417 422 .. _input_caching:
418 423
419 424 Input caching system
420 425 --------------------
421 426
422 427 IPython offers numbered prompts (In/Out) with input and output caching
423 428 (also referred to as 'input history'). All input is saved and can be
424 429 retrieved as variables (besides the usual arrow key recall), in
425 430 addition to the :magic:`rep` magic command that brings a history entry
426 431 up for editing on the next command line.
427 432
428 433 The following variables always exist:
429 434
430 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
431 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
432 overwrite In with a variable of your own, you can remake the assignment to the
433 internal list with a simple ``In=_ih``.
435 * ``_i``, ``_ii``, ``_iii``: store previous, next previous and next-next
436 previous inputs.
437
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
440 assignment to the internal list with a simple ``In=_ih``.
434 441
435 Additionally, global variables named _i<n> are dynamically created (<n>
442 Additionally, global variables named ``_i<n>`` are dynamically created (``<n>``
436 443 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
437 444
438 445 For example, what you typed at prompt 14 is available as ``_i14``, ``_ih[14]``
439 446 and ``In[14]``.
440 447
441 448 This allows you to easily cut and paste multi line interactive prompts
442 449 by printing them out: they print like a clean string, without prompt
443 450 characters. You can also manipulate them like regular variables (they
444 451 are strings), modify or exec them.
445 452
446 You can also re-execute multiple lines of input easily by using the
447 magic :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to re-execute
448 previous lines which include magic function calls (which require special
449 processing). Type %macro? for more details on the macro system.
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
455 re-execute previous lines which include magic function calls (which require
456 special processing). Type %macro? for more details on the macro system.
450 457
451 458 A history function :magic:`history` allows you to see any part of your input
452 459 history by printing a range of the _i variables.
453 460
454 461 You can also search ('grep') through your history by typing
455 462 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
456 463 etc. You can bring history entries listed by '%hist -g' up for editing
457 464 with the %recall command, or run them immediately with :magic:`rerun`.
458 465
459 466 .. _output_caching:
460 467
461 468 Output caching system
462 469 ---------------------
463 470
464 471 For output that is returned from actions, a system similar to the input
465 472 cache exists but using _ instead of _i. Only actions that produce a
466 473 result (NOT assignments, for example) are cached. If you are familiar
467 474 with Mathematica, IPython's _ variables behave exactly like
468 475 Mathematica's % variables.
469 476
470 477 The following variables always exist:
471 478
472 479 * [_] (a single underscore): stores previous output, like Python's
473 480 default interpreter.
474 481 * [__] (two underscores): next previous.
475 482 * [___] (three underscores): next-next previous.
476 483
477 484 Additionally, global variables named _<n> are dynamically created (<n>
478 485 being the prompt counter), such that the result of output <n> is always
479 486 available as _<n> (don't use the angle brackets, just the number, e.g.
480 487 ``_21``).
481 488
482 489 These variables are also stored in a global dictionary (not a
483 490 list, since it only has entries for lines which returned a result)
484 491 available under the names _oh and Out (similar to _ih and In). So the
485 492 output from line 12 can be obtained as ``_12``, ``Out[12]`` or ``_oh[12]``. If you
486 493 accidentally overwrite the Out variable you can recover it by typing
487 494 ``Out=_oh`` at the prompt.
488 495
489 496 This system obviously can potentially put heavy memory demands on your
490 497 system, since it prevents Python's garbage collector from removing any
491 498 previously computed results. You can control how many results are kept
492 499 in memory with the configuration option ``InteractiveShell.cache_size``.
493 500 If you set it to 0, output caching is disabled. You can also use the :magic:`reset`
494 501 and :magic:`xdel` magics to clear large items from memory.
495 502
496 503 Directory history
497 504 -----------------
498 505
499 506 Your history of visited directories is kept in the global list _dh, and
500 507 the magic :magic:`cd` command can be used to go to any entry in that list. The
501 508 :magic:`dhist` command allows you to view this history. Do ``cd -<TAB>`` to
502 509 conveniently view the directory history.
503 510
504 511
505 512 Automatic parentheses and quotes
506 513 --------------------------------
507 514
508 515 These features were adapted from Nathan Gray's LazyPython. They are
509 516 meant to allow less typing for common situations.
510 517
511 518 Callable objects (i.e. functions, methods, etc) can be invoked like this
512 519 (notice the commas between the arguments)::
513 520
514 521 In [1]: callable_ob arg1, arg2, arg3
515 522 ------> callable_ob(arg1, arg2, arg3)
516 523
517 524 .. note::
518 525 This feature is disabled by default. To enable it, use the ``%autocall``
519 526 magic command. The commands below with special prefixes will always work,
520 527 however.
521 528
522 529 You can force automatic parentheses by using '/' as the first character
523 530 of a line. For example::
524 531
525 532 In [2]: /globals # becomes 'globals()'
526 533
527 534 Note that the '/' MUST be the first character on the line! This won't work::
528 535
529 536 In [3]: print /globals # syntax error
530 537
531 538 In most cases the automatic algorithm should work, so you should rarely
532 539 need to explicitly invoke /. One notable exception is if you are trying
533 540 to call a function with a list of tuples as arguments (the parenthesis
534 541 will confuse IPython)::
535 542
536 543 In [4]: zip (1,2,3),(4,5,6) # won't work
537 544
538 545 but this will work::
539 546
540 547 In [5]: /zip (1,2,3),(4,5,6)
541 548 ------> zip ((1,2,3),(4,5,6))
542 549 Out[5]: [(1, 4), (2, 5), (3, 6)]
543 550
544 551 IPython tells you that it has altered your command line by displaying
545 552 the new command line preceded by ``--->``.
546 553
547 554 You can force automatic quoting of a function's arguments by using ``,``
548 555 or ``;`` as the first character of a line. For example::
549 556
550 557 In [1]: ,my_function /home/me # becomes my_function("/home/me")
551 558
552 559 If you use ';' the whole argument is quoted as a single string, while ',' splits
553 560 on whitespace::
554 561
555 562 In [2]: ,my_function a b c # becomes my_function("a","b","c")
556 563
557 564 In [3]: ;my_function a b c # becomes my_function("a b c")
558 565
559 566 Note that the ',' or ';' MUST be the first character on the line! This
560 567 won't work::
561 568
562 569 In [4]: x = ,my_function /home/me # syntax error
563 570
564 571 IPython as your default Python environment
565 572 ==========================================
566 573
567 574 Python honors the environment variable :envvar:`PYTHONSTARTUP` and will
568 575 execute at startup the file referenced by this variable. If you put the
569 576 following code at the end of that file, then IPython will be your working
570 577 environment anytime you start Python::
571 578
572 579 import os, IPython
573 580 os.environ['PYTHONSTARTUP'] = '' # Prevent running this again
574 581 IPython.start_ipython()
575 582 raise SystemExit
576 583
577 584 The ``raise SystemExit`` is needed to exit Python when
578 585 it finishes, otherwise you'll be back at the normal Python ``>>>``
579 586 prompt.
580 587
581 588 This is probably useful to developers who manage multiple Python
582 589 versions and don't want to have correspondingly multiple IPython
583 590 versions. Note that in this mode, there is no way to pass IPython any
584 591 command-line options, as those are trapped first by Python itself.
585 592
586 593 .. _Embedding:
587 594
588 595 Embedding IPython
589 596 =================
590 597
591 598 You can start a regular IPython session with
592 599
593 600 .. sourcecode:: python
594 601
595 602 import IPython
596 603 IPython.start_ipython(argv=[])
597 604
598 605 at any point in your program. This will load IPython configuration,
599 606 startup files, and everything, just as if it were a normal IPython session.
600 607
601 608 It is also possible to embed an IPython shell in a namespace in your Python code.
602 609 This allows you to evaluate dynamically the state of your code,
603 610 operate with your variables, analyze them, etc. Note however that
604 611 any changes you make to values while in the shell do not propagate back
605 612 to the running code, so it is safe to modify your values because you
606 613 won't break your code in bizarre ways by doing so.
607 614
608 615 .. note::
609 616
610 617 At present, embedding IPython cannot be done from inside IPython.
611 618 Run the code samples below outside IPython.
612 619
613 620 This feature allows you to easily have a fully functional python
614 621 environment for doing object introspection anywhere in your code with a
615 622 simple function call. In some cases a simple print statement is enough,
616 623 but if you need to do more detailed analysis of a code fragment this
617 624 feature can be very valuable.
618 625
619 626 It can also be useful in scientific computing situations where it is
620 627 common to need to do some automatic, computationally intensive part and
621 628 then stop to look at data, plots, etc.
622 629 Opening an IPython instance will give you full access to your data and
623 630 functions, and you can resume program execution once you are done with
624 631 the interactive part (perhaps to stop again later, as many times as
625 632 needed).
626 633
627 634 The following code snippet is the bare minimum you need to include in
628 635 your Python programs for this to work (detailed examples follow later)::
629 636
630 637 from IPython import embed
631 638
632 639 embed() # this call anywhere in your program will start IPython
633 640
634 641 You can also embed an IPython *kernel*, for use with qtconsole, etc. via
635 642 ``IPython.embed_kernel()``. This should function work the same way, but you can
636 643 connect an external frontend (``ipython qtconsole`` or ``ipython console``),
637 644 rather than interacting with it in the terminal.
638 645
639 646 You can run embedded instances even in code which is itself being run at
640 647 the IPython interactive prompt with '%run <filename>'. Since it's easy
641 648 to get lost as to where you are (in your top-level IPython or in your
642 649 embedded one), it's a good idea in such cases to set the in/out prompts
643 650 to something different for the embedded instances. The code examples
644 651 below illustrate this.
645 652
646 653 You can also have multiple IPython instances in your program and open
647 654 them separately, for example with different options for data
648 655 presentation. If you close and open the same instance multiple times,
649 656 its prompt counters simply continue from each execution to the next.
650 657
651 658 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
652 659 module for more details on the use of this system.
653 660
654 661 The following sample file illustrating how to use the embedding
655 662 functionality is provided in the examples directory as embed_class_long.py.
656 663 It should be fairly self-explanatory:
657 664
658 665 .. literalinclude:: ../../../examples/Embedding/embed_class_long.py
659 666 :language: python
660 667
661 668 Once you understand how the system functions, you can use the following
662 669 code fragments in your programs which are ready for cut and paste:
663 670
664 671 .. literalinclude:: ../../../examples/Embedding/embed_class_short.py
665 672 :language: python
666 673
667 674 Using the Python debugger (pdb)
668 675 ===============================
669 676
670 677 Running entire programs via pdb
671 678 -------------------------------
672 679
673 680 pdb, the Python debugger, is a powerful interactive debugger which
674 681 allows you to step through code, set breakpoints, watch variables,
675 682 etc. IPython makes it very easy to start any script under the control
676 683 of pdb, regardless of whether you have wrapped it into a 'main()'
677 684 function or not. For this, simply type ``%run -d myscript`` at an
678 685 IPython prompt. See the :magic:`run` command's documentation for more details, including
679 686 how to control where pdb will stop execution first.
680 687
681 688 For more information on the use of the pdb debugger, see :ref:`debugger-commands`
682 689 in the Python documentation.
683 690
684 691 IPython extends the debugger with a few useful additions, like coloring of
685 692 tracebacks. The debugger will adopt the color scheme selected for IPython.
686 693
687 694 The ``where`` command has also been extended to take as argument the number of
688 695 context line to show. This allows to a many line of context on shallow stack trace:
689 696
690 697 .. code::
691 698
692 699 In [5]: def foo(x):
693 700 ...: 1
694 701 ...: 2
695 702 ...: 3
696 703 ...: return 1/x+foo(x-1)
697 704 ...: 5
698 705 ...: 6
699 706 ...: 7
700 707 ...:
701 708
702 709 In[6]: foo(1)
703 710 # ...
704 711 ipdb> where 8
705 712 <ipython-input-6-9e45007b2b59>(1)<module>()
706 713 ----> 1 foo(1)
707 714
708 715 <ipython-input-5-7baadc3d1465>(5)foo()
709 716 1 def foo(x):
710 717 2 1
711 718 3 2
712 719 4 3
713 720 ----> 5 return 1/x+foo(x-1)
714 721 6 5
715 722 7 6
716 723 8 7
717 724
718 725 > <ipython-input-5-7baadc3d1465>(5)foo()
719 726 1 def foo(x):
720 727 2 1
721 728 3 2
722 729 4 3
723 730 ----> 5 return 1/x+foo(x-1)
724 731 6 5
725 732 7 6
726 733 8 7
727 734
728 735
729 736 And less context on shallower Stack Trace:
730 737
731 738 .. code::
732 739
733 740 ipdb> where 1
734 741 <ipython-input-13-afa180a57233>(1)<module>()
735 742 ----> 1 foo(7)
736 743
737 744 <ipython-input-5-7baadc3d1465>(5)foo()
738 745 ----> 5 return 1/x+foo(x-1)
739 746
740 747 <ipython-input-5-7baadc3d1465>(5)foo()
741 748 ----> 5 return 1/x+foo(x-1)
742 749
743 750 <ipython-input-5-7baadc3d1465>(5)foo()
744 751 ----> 5 return 1/x+foo(x-1)
745 752
746 753 <ipython-input-5-7baadc3d1465>(5)foo()
747 754 ----> 5 return 1/x+foo(x-1)
748 755
749 756
750 757 Post-mortem debugging
751 758 ---------------------
752 759
753 760 Going into a debugger when an exception occurs can be
754 761 extremely useful in order to find the origin of subtle bugs, because pdb
755 762 opens up at the point in your code which triggered the exception, and
756 763 while your program is at this point 'dead', all the data is still
757 764 available and you can walk up and down the stack frame and understand
758 765 the origin of the problem.
759 766
760 767 You can use the :magic:`debug` magic after an exception has occurred to start
761 768 post-mortem debugging. IPython can also call debugger every time your code
762 769 triggers an uncaught exception. This feature can be toggled with the :magic:`pdb` magic
763 770 command, or you can start IPython with the ``--pdb`` option.
764 771
765 772 For a post-mortem debugger in your programs outside IPython,
766 773 put the following lines toward the top of your 'main' routine::
767 774
768 775 import sys
769 776 from IPython.core import ultratb
770 777 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
771 778 color_scheme='Linux', call_pdb=1)
772 779
773 780 The mode keyword can be either 'Verbose' or 'Plain', giving either very
774 781 detailed or normal tracebacks respectively. The color_scheme keyword can
775 782 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
776 783 options which can be set in IPython with ``--colors`` and ``--xmode``.
777 784
778 785 This will give any of your programs detailed, colored tracebacks with
779 786 automatic invocation of pdb.
780 787
781 788 .. _pasting_with_prompts:
782 789
783 790 Pasting of code starting with Python or IPython prompts
784 791 =======================================================
785 792
786 793 IPython is smart enough to filter out input prompts, be they plain Python ones
787 794 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
788 795 therefore copy and paste from existing interactive sessions without worry.
789 796
790 797 The following is a 'screenshot' of how things work, copying an example from the
791 798 standard Python tutorial::
792 799
793 800 In [1]: >>> # Fibonacci series:
794 801
795 802 In [2]: ... # the sum of two elements defines the next
796 803
797 804 In [3]: ... a, b = 0, 1
798 805
799 806 In [4]: >>> while b < 10:
800 807 ...: ... print(b)
801 808 ...: ... a, b = b, a+b
802 809 ...:
803 810 1
804 811 1
805 812 2
806 813 3
807 814 5
808 815 8
809 816
810 817 And pasting from IPython sessions works equally well::
811 818
812 819 In [1]: In [5]: def f(x):
813 820 ...: ...: "A simple function"
814 821 ...: ...: return x**2
815 822 ...: ...:
816 823
817 824 In [2]: f(3)
818 825 Out[2]: 9
819 826
820 827 .. _gui_support:
821 828
822 829 GUI event loop support
823 830 ======================
824 831
825 832 .. versionadded:: 0.11
826 833 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
827 834
828 835 IPython has excellent support for working interactively with Graphical User
829 836 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
830 837 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
831 838 is extremely robust compared to our previous thread-based version. The
832 839 advantages of this are:
833 840
834 841 * GUIs can be enabled and disabled dynamically at runtime.
835 842 * The active GUI can be switched dynamically at runtime.
836 843 * In some cases, multiple GUIs can run simultaneously with no problems.
837 844 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
838 845 all of these things.
839 846
840 847 For users, enabling GUI event loop integration is simple. You simple use the
841 848 :magic:`gui` magic as follows::
842 849
843 850 %gui [GUINAME]
844 851
845 852 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
846 853 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
847 854
848 855 Thus, to use wxPython interactively and create a running :class:`wx.App`
849 856 object, do::
850 857
851 858 %gui wx
852 859
853 860 You can also start IPython with an event loop set up using the `--gui`
854 861 flag::
855 862
856 863 $ ipython --gui=qt
857 864
858 865 For information on IPython's matplotlib_ integration (and the ``matplotlib``
859 866 mode) see :ref:`this section <matplotlib_support>`.
860 867
861 868 For developers that want to use IPython's GUI event loop integration in the
862 869 form of a library, these capabilities are exposed in library form in the
863 870 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
864 871 Interested developers should see the module docstrings for more information,
865 872 but there are a few points that should be mentioned here.
866 873
867 874 First, the ``PyOSInputHook`` approach only works in command line settings
868 875 where readline is activated. The integration with various eventloops
869 876 is handled somewhat differently (and more simply) when using the standalone
870 877 kernel, as in the qtconsole and notebook.
871 878
872 879 Second, when using the ``PyOSInputHook`` approach, a GUI application should
873 880 *not* start its event loop. Instead all of this is handled by the
874 881 ``PyOSInputHook``. This means that applications that are meant to be used both
875 882 in IPython and as standalone apps need to have special code to detects how the
876 883 application is being run. We highly recommend using IPython's support for this.
877 884 Since the details vary slightly between toolkits, we point you to the various
878 885 examples in our source directory :file:`examples/Embedding` that demonstrate
879 886 these capabilities.
880 887
881 888 Third, unlike previous versions of IPython, we no longer "hijack" (replace
882 889 them with no-ops) the event loops. This is done to allow applications that
883 890 actually need to run the real event loops to do so. This is often needed to
884 891 process pending events at critical points.
885 892
886 893 Finally, we also have a number of examples in our source directory
887 894 :file:`examples/Embedding` that demonstrate these capabilities.
888 895
889 896 PyQt and PySide
890 897 ---------------
891 898
892 899 .. attempt at explanation of the complete mess that is Qt support
893 900
894 901 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
895 902 PyQt4 or PySide. There are three options for configuration here, because
896 903 PyQt4 has two APIs for QString and QVariant: v1, which is the default on
897 904 Python 2, and the more natural v2, which is the only API supported by PySide.
898 905 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
899 906 uses v2, but you can still use any interface in your code, since the
900 907 Qt frontend is in a different process.
901 908
902 909 The default will be to import PyQt4 without configuration of the APIs, thus
903 910 matching what most applications would expect. It will fall back to PySide if
904 911 PyQt4 is unavailable.
905 912
906 913 If specified, IPython will respect the environment variable ``QT_API`` used
907 914 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
908 915 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
909 916 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
910 917 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
911 918
912 919 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
913 920 then IPython will ask matplotlib which Qt library to use (only if QT_API is
914 921 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
915 922 older, then IPython will always use PyQt4 without setting the v2 APIs, since
916 923 neither v2 PyQt nor PySide work.
917 924
918 925 .. warning::
919 926
920 927 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
921 928 to work with IPython's qt integration, because otherwise PyQt4 will be
922 929 loaded in an incompatible mode.
923 930
924 931 It also means that you must *not* have ``QT_API`` set if you want to
925 932 use ``--gui=qt`` with code that requires PyQt4 API v1.
926 933
927 934
928 935 .. _matplotlib_support:
929 936
930 937 Plotting with matplotlib
931 938 ========================
932 939
933 940 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
934 941 can produce plots on screen using a variety of GUI toolkits, including Tk,
935 942 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
936 943 scientific computing, all with a syntax compatible with that of the popular
937 944 Matlab program.
938 945
939 946 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
940 947 IPython is already running, you can run the :magic:`matplotlib` magic. If no
941 948 arguments are given, IPython will automatically detect your choice of
942 949 matplotlib backend. You can also request a specific backend with
943 950 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
944 951 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
945 952 backend value, which produces static figures inlined inside the application
946 953 window instead of matplotlib's interactive figures that live in separate
947 954 windows.
948 955
949 956 .. _interactive_demos:
950 957
951 958 Interactive demos with IPython
952 959 ==============================
953 960
954 961 IPython ships with a basic system for running scripts interactively in
955 962 sections, useful when presenting code to audiences. A few tags embedded
956 963 in comments (so that the script remains valid Python code) divide a file
957 964 into separate blocks, and the demo can be run one block at a time, with
958 965 IPython printing (with syntax highlighting) the block before executing
959 966 it, and returning to the interactive prompt after each block. The
960 967 interactive namespace is updated after each block is run with the
961 968 contents of the demo's namespace.
962 969
963 970 This allows you to show a piece of code, run it and then execute
964 971 interactively commands based on the variables just created. Once you
965 972 want to continue, you simply execute the next block of the demo. The
966 973 following listing shows the markup necessary for dividing a script into
967 974 sections for execution as a demo:
968 975
969 976 .. literalinclude:: ../../../examples/IPython Kernel/example-demo.py
970 977 :language: python
971 978
972 979 In order to run a file as a demo, you must first make a Demo object out
973 980 of it. If the file is named myscript.py, the following code will make a
974 981 demo::
975 982
976 983 from IPython.lib.demo import Demo
977 984
978 985 mydemo = Demo('myscript.py')
979 986
980 987 This creates the mydemo object, whose blocks you run one at a time by
981 988 simply calling the object with no arguments. Then call it to run each step
982 989 of the demo::
983 990
984 991 mydemo()
985 992
986 993 Demo objects can be
987 994 restarted, you can move forward or back skipping blocks, re-execute the
988 995 last block, etc. See the :mod:`IPython.lib.demo` module and the
989 996 :class:`~IPython.lib.demo.Demo` class for details.
990 997
991 998 Limitations: These demos are limited to
992 999 fairly simple uses. In particular, you cannot break up sections within
993 1000 indented code (loops, if statements, function definitions, etc.)
994 1001 Supporting something like this would basically require tracking the
995 1002 internal execution state of the Python interpreter, so only top-level
996 1003 divisions are allowed. If you want to be able to open an IPython
997 1004 instance at an arbitrary point in a program, you can use IPython's
998 1005 :ref:`embedding facilities <Embedding>`.
999 1006
1000 1007 .. include:: ../links.txt
@@ -1,205 +1,216 b''
1 1 .. _tutorial:
2 2
3 3 ======================
4 4 Introducing IPython
5 5 ======================
6 6
7 7 You don't need to know anything beyond Python to start using IPython – just type
8 8 commands as you would at the standard Python prompt. But IPython can do much
9 9 more than the standard prompt. Some key features are described here. For more
10 10 information, check the :ref:`tips page <tips>`, or look at examples in the
11 11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
12 12
13 13 If you've never used Python before, you might want to look at `the official
14 14 tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into
15 15 Python <http://diveintopython.net/toc/index.html>`_.
16 16
17 17 The four most helpful commands
18 18 ===============================
19 19
20 20 The four most helpful commands, as well as their brief description, is shown
21 21 to you in a banner, every time you start IPython:
22 22
23 23 ========== =========================================================
24 24 command description
25 25 ========== =========================================================
26 26 ? Introduction and overview of IPython's features.
27 27 %quickref Quick reference.
28 28 help Python's own help system.
29 29 object? Details about 'object', use 'object??' for extra details.
30 30 ========== =========================================================
31 31
32 32 Tab completion
33 33 ==============
34 34
35 35 Tab completion, especially for attributes, is a convenient way to explore the
36 36 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
37 to view the object's attributes (see :ref:`the readline section <readline>` for
38 more). Besides Python objects and keywords, tab completion also works on file
39 and directory names.
37 to view the object's attributes. Besides Python objects and keywords, tab
38 completion also works on file and directory names.
40 39
41 40 Exploring your objects
42 41 ======================
43 42
44 43 Typing ``object_name?`` will print all sorts of details about any object,
45 44 including docstrings, function definition lines (for call arguments) and
46 45 constructor details for classes. To get specific information on an object, you
47 46 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
48 47
49 48 .. _magics_explained:
50 49
51 50 Magic functions
52 51 ===============
53 52
54 53 IPython has a set of predefined 'magic functions' that you can call with a
55 54 command line style syntax. There are two kinds of magics, line-oriented and
56 cell-oriented. **Line magics** are prefixed with the ``%`` character and work much
57 like OS command-line calls: they get as an argument the rest of the line, where
58 arguments are passed without parentheses or quotes. **Cell magics** are
59 prefixed with a double ``%%``, and they are functions that get as an argument
60 not only the rest of the line, but also the lines below it in a separate
61 argument.
55 cell-oriented. **Line magics** are prefixed with the ``%`` character and work
56 much like OS command-line calls: they get as an argument the rest of the line,
57 where arguments are passed without parentheses or quotes. **Lines magics** can
58 return results and can be used in the right hand side of an assignment. **Cell
59 magics** are prefixed with a double ``%%``, and they are functions that get as
60 an argument not only the rest of the line, but also the lines below it in a
61 separate argument.
62 62
63 The following examples show how to call the builtin :magic:`timeit` magic, both in
64 line and cell mode::
63 Magics are useful as convenient functions where Python syntax is not the most
64 natural one, or when one want to embed invalid python syntax in their work flow.
65
66 The following examples show how to call the builtin :magic:`timeit` magic, both
67 in line and cell mode::
65 68
66 69 In [1]: %timeit range(1000)
67 70 100000 loops, best of 3: 7.76 us per loop
68 71
69 72 In [2]: %%timeit x = range(10000)
70 73 ...: max(x)
71 74 ...:
72 75 1000 loops, best of 3: 223 us per loop
73 76
74 77 The builtin magics include:
75 78
76 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`, :magic:`macro`,
77 :magic:`recall`, etc.
78 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`, :magic:`autoindent`,
79 :magic:`automagic`, etc.
80 - Other functions such as :magic:`reset`, :magic:`timeit`, :cellmagic:`writefile`, :magic:`load`, or
81 :magic:`paste`.
79 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`,
80 :magic:`macro`, :magic:`recall`, etc.
81
82 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`,
83 :magic:`autoindent`, :magic:`automagic`, etc.
84
85 - Other functions such as :magic:`reset`, :magic:`timeit`,
86 :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`.
82 87
83 You can always call them using the ``%`` prefix, and if you're calling a line
84 magic on a line by itself, you can omit even that::
88 You can always call magics using the ``%`` prefix, and if you're calling a line
89 magic on a line by itself, as long as the identifier is not defined in your
90 namespace, you can omit even that::
85 91
86 92 run thescript.py
87 93
88 You can toggle this behavior by running the :magic:`automagic` magic. Cell magics
89 must always have the ``%%`` prefix.
94 You can toggle this behavior by running the :magic:`automagic` magic. Cell
95 magics must always have the ``%%`` prefix.
90 96
91 97 A more detailed explanation of the magic system can be obtained by calling
92 98 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
93 99 read its docstring. To see all the available magic functions, call
94 100 ``%lsmagic``.
95 101
96 102 .. seealso::
97 103
98 :doc:`magics`
104 The :ref:`magic` section of the documentation goes more in depth into how
105 the magics works and how to define your own, and :doc:`magics` for a list of
106 built-in magics.
99 107
100 108 `Cell magics`_ example notebook
101 109
102 110 Running and Editing
103 111 -------------------
104 112
105 The :magic:`run` magic command allows you to run any python script and load all of
106 its data directly into the interactive namespace. Since the file is re-read
113 The :magic:`run` magic command allows you to run any python script and load all
114 of its data directly into the interactive namespace. Since the file is re-read
107 115 from disk each time, changes you make to it are reflected immediately (unlike
108 imported modules, which have to be specifically reloaded). IPython also
109 includes :ref:`dreload <dreload>`, a recursive reload function.
116 imported modules, which have to be specifically reloaded). IPython also includes
117 :ref:`dreload <dreload>`, a recursive reload function.
110 118
111 119 ``%run`` has special flags for timing the execution of your scripts (-t), or
112 120 for running them under the control of either Python's pdb debugger (-d) or
113 121 profiler (-p).
114 122
115 123 The :magic:`edit` command gives a reasonable approximation of multiline editing,
116 124 by invoking your favorite editor on the spot. IPython will execute the
117 code you type in there as if it were typed interactively.
125 code you type in there as if it were typed interactively. Note that for
126 :magic:`edit` to work, the call to startup your editor has to be a blocking
127 call. In a GUI environment, your editor likely will have such an option.
118 128
119 129 Debugging
120 130 ---------
121 131
122 132 After an exception occurs, you can call :magic:`debug` to jump into the Python
123 133 debugger (pdb) and examine the problem. Alternatively, if you call :magic:`pdb`,
124 134 IPython will automatically start the debugger on any uncaught exception. You can
125 print variables, see code, execute statements and even walk up and down the
126 call stack to track down the true source of the problem. This can be an efficient
127 way to develop and debug code, in many cases eliminating the need for print
135 print variables, see code, execute statements and even walk up and down the call
136 stack to track down the true source of the problem. This can be an efficient way
137 to develop and debug code, in many cases eliminating the need for print
128 138 statements or external debugging tools.
129 139
130 140 You can also step through a program from the beginning by calling
131 141 ``%run -d theprogram.py``.
132 142
133 143 History
134 144 =======
135 145
136 146 IPython stores both the commands you enter, and the results it produces. You
137 147 can easily go through previous commands with the up- and down-arrow keys, or
138 148 access your history in more sophisticated ways.
139 149
140 150 Input and output history are kept in variables called ``In`` and ``Out``, keyed
141 151 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
142 152 are also kept in variables named ``_``, ``__`` and ``___``.
143 153
144 154 You can use the ``%history`` magic function to examine past input and output.
145 155 Input history from previous sessions is saved in a database, and IPython can be
146 156 configured to save output history.
147 157
148 158 Several other magic functions can use your input history, including ``%edit``,
149 159 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
150 160 standard format to refer to lines::
151 161
152 162 %pastebin 3 18-20 ~1/1-5
153 163
154 164 This will take line 3 and lines 18 to 20 from the current session, and lines
155 165 1-5 from the previous session.
156 166
157 167 System shell commands
158 168 =====================
159 169
160 To run any command at the system shell, simply prefix it with !, e.g.::
170 To run any command at the system shell, simply prefix it with ``!``, e.g.::
161 171
162 172 !ping www.bbc.co.uk
163 173
164 174 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
165 175 the values of Python variables or expressions to system commands, prefix them
166 176 with $: ``!grep -rF $pattern ipython/*``. See :ref:`our shell section
167 177 <system_shell_access>` for more details.
168 178
169 179 Define your own system aliases
170 180 ------------------------------
171 181
172 It's convenient to have aliases to the system commands you use most often.
173 This allows you to work seamlessly from inside IPython with the same commands
174 you are used to in your system shell. IPython comes with some pre-defined
175 aliases and a complete system for changing directories, both via a stack (see
176 :magic:`pushd`, :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a history of
177 visited directories and allows you to go to any previously visited one.
182 It's convenient to have aliases to the system commands you use most often. This
183 allows you to work seamlessly from inside IPython with the same commands you are
184 used to in your system shell. IPython comes with some pre-defined aliases and a
185 complete system for changing directories, both via a stack (see :magic:`pushd`,
186 :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a
187 history of visited directories and allows you to go to any previously visited
188 one.
178 189
179 190
180 191 Configuration
181 192 =============
182 193
183 194 Much of IPython can be tweaked through :doc:`configuration </config/intro>`.
184 195 To get started, use the command ``ipython profile create`` to produce the
185 196 default config files. These will be placed in
186 197 :file:`~/.ipython/profile_default`, and contain comments explaining
187 198 what the various options do.
188 199
189 200 Profiles allow you to use IPython for different tasks, keeping separate config
190 201 files and history for each one. More details in :ref:`the profiles section
191 202 <profiles>`.
192 203
193 204 .. _startup_files:
194 205
195 206 Startup Files
196 207 -------------
197 208
198 209 If you want some code to be run at the beginning of every IPython session, the
199 210 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
200 211 :file:`profile_default/startup/` directory. Files here will be executed as soon
201 212 as the IPython shell is constructed, before any other code or scripts you have
202 213 specified. The files will be run in order of their names, so you can control the
203 214 ordering with prefixes, like ``10-myimports.py``.
204 215
205 216 .. include:: ../links.txt
General Comments 0
You need to be logged in to leave comments. Login now