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