Debian Codegraph @

docs/source/interactive/reference.rst

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