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