##// END OF EJS Templates
ipython.rst: cleanup, add new chapters (extension api, string lists, sh profile, ipy_user_conf.py), remove some obsolete stuff
Ville M. Vainio -
r1124:fcc445dd merge
parent child Browse files
Show More
This diff has been collapsed as it changes many lines, (3768 lines changed) Show them Hide them
@@ -52,96 +52,97 b' which tries to:'
52 shell can only do this for Tkinter applications.
52 shell can only do this for Tkinter applications.
53
53
54
54
55 Main features
55 Main features
56
56 -------------
57 * Dynamic object introspection. One can access docstrings, function
57
58 definition prototypes, source code, source files and other details
58 * Dynamic object introspection. One can access docstrings, function
59 of any object accessible to the interpreter with a single
59 definition prototypes, source code, source files and other details
60 keystroke ('?', and using '??' provides additional detail).
60 of any object accessible to the interpreter with a single
61 * Searching through modules and namespaces with '*' wildcards, both
61 keystroke ('?', and using '??' provides additional detail).
62 when using the '?' system and via the %psearch command.
62 * Searching through modules and namespaces with '*' wildcards, both
63 * Completion in the local namespace, by typing TAB at the prompt.
63 when using the '?' system and via the %psearch command.
64 This works for keywords, methods, variables and files in the
64 * Completion in the local namespace, by typing TAB at the prompt.
65 current directory. This is supported via the readline library, and
65 This works for keywords, methods, variables and files in the
66 full access to configuring readline's behavior is provided.
66 current directory. This is supported via the readline library, and
67 * Numbered input/output prompts with command history (persistent
67 full access to configuring readline's behavior is provided.
68 across sessions and tied to each profile), full searching in this
68 * Numbered input/output prompts with command history (persistent
69 history and caching of all input and output.
69 across sessions and tied to each profile), full searching in this
70 * User-extensible 'magic' commands. A set of commands prefixed with
70 history and caching of all input and output.
71 % is available for controlling IPython itself and provides
71 * User-extensible 'magic' commands. A set of commands prefixed with
72 directory control, namespace information and many aliases to
72 % is available for controlling IPython itself and provides
73 common system shell commands.
73 directory control, namespace information and many aliases to
74 * Alias facility for defining your own system aliases.
74 common system shell commands.
75 * Complete system shell access. Lines starting with ! are passed
75 * Alias facility for defining your own system aliases.
76 directly to the system shell, and using !! captures shell output
76 * Complete system shell access. Lines starting with ! are passed
77 into python variables for further use.
77 directly to the system shell, and using !! captures shell output
78 * Background execution of Python commands in a separate thread.
78 into python variables for further use.
79 IPython has an internal job manager called jobs, and a
79 * Background execution of Python commands in a separate thread.
80 conveninence backgrounding magic function called %bg.
80 IPython has an internal job manager called jobs, and a
81 * The ability to expand python variables when calling the system
81 conveninence backgrounding magic function called %bg.
82 shell. In a shell command, any python variable prefixed with $ is
82 * The ability to expand python variables when calling the system
83 expanded. A double $$ allows passing a literal $ to the shell (for
83 shell. In a shell command, any python variable prefixed with $ is
84 access to shell and environment variables like $PATH).
84 expanded. A double $$ allows passing a literal $ to the shell (for
85 * Filesystem navigation, via a magic %cd command, along with a
85 access to shell and environment variables like $PATH).
86 persistent bookmark system (using %bookmark) for fast access to
86 * Filesystem navigation, via a magic %cd command, along with a
87 frequently visited directories.
87 persistent bookmark system (using %bookmark) for fast access to
88 * A lightweight persistence framework via the %store command, which
88 frequently visited directories.
89 allows you to save arbitrary Python variables. These get restored
89 * A lightweight persistence framework via the %store command, which
90 automatically when your session restarts.
90 allows you to save arbitrary Python variables. These get restored
91 * Automatic indentation (optional) of code as you type (through the
91 automatically when your session restarts.
92 readline library).
92 * Automatic indentation (optional) of code as you type (through the
93 * Macro system for quickly re-executing multiple lines of previous
93 readline library).
94 input with a single name. Macros can be stored persistently via
94 * Macro system for quickly re-executing multiple lines of previous
95 %store and edited via %edit.
95 input with a single name. Macros can be stored persistently via
96 * Session logging (you can then later use these logs as code in your
96 %store and edited via %edit.
97 programs). Logs can optionally timestamp all input, and also store
97 * Session logging (you can then later use these logs as code in your
98 session output (marked as comments, so the log remains valid
98 programs). Logs can optionally timestamp all input, and also store
99 Python source code).
99 session output (marked as comments, so the log remains valid
100 * Session restoring: logs can be replayed to restore a previous
100 Python source code).
101 session to the state where you left it.
101 * Session restoring: logs can be replayed to restore a previous
102 * Verbose and colored exception traceback printouts. Easier to parse
102 session to the state where you left it.
103 visually, and in verbose mode they produce a lot of useful
103 * Verbose and colored exception traceback printouts. Easier to parse
104 debugging information (basically a terminal version of the cgitb
104 visually, and in verbose mode they produce a lot of useful
105 module).
105 debugging information (basically a terminal version of the cgitb
106 * Auto-parentheses: callable objects can be executed without
106 module).
107 parentheses: 'sin 3' is automatically converted to 'sin(3)'.
107 * Auto-parentheses: callable objects can be executed without
108 * Auto-quoting: using ',' or ';' as the first character forces
108 parentheses: 'sin 3' is automatically converted to 'sin(3)'.
109 auto-quoting of the rest of the line: ',my_function a b' becomes
109 * Auto-quoting: using ',' or ';' as the first character forces
110 automatically 'my_function("a","b")', while ';my_function a b'
110 auto-quoting of the rest of the line: ',my_function a b' becomes
111 becomes 'my_function("a b")'.
111 automatically 'my_function("a","b")', while ';my_function a b'
112 * Extensible input syntax. You can define filters that pre-process
112 becomes 'my_function("a b")'.
113 user input to simplify input in special situations. This allows
113 * Extensible input syntax. You can define filters that pre-process
114 for example pasting multi-line code fragments which start with
114 user input to simplify input in special situations. This allows
115 '>>>' or '...' such as those from other python sessions or the
115 for example pasting multi-line code fragments which start with
116 standard Python documentation.
116 '>>>' or '...' such as those from other python sessions or the
117 * Flexible configuration system. It uses a configuration file which
117 standard Python documentation.
118 allows permanent setting of all command-line options, module
118 * Flexible configuration system. It uses a configuration file which
119 loading, code and file execution. The system allows recursive file
119 allows permanent setting of all command-line options, module
120 inclusion, so you can have a base file with defaults and layers
120 loading, code and file execution. The system allows recursive file
121 which load other customizations for particular projects.
121 inclusion, so you can have a base file with defaults and layers
122 * Embeddable. You can call IPython as a python shell inside your own
122 which load other customizations for particular projects.
123 python programs. This can be used both for debugging code or for
123 * Embeddable. You can call IPython as a python shell inside your own
124 providing interactive abilities to your programs with knowledge
124 python programs. This can be used both for debugging code or for
125 about the local namespaces (very useful in debugging and data
125 providing interactive abilities to your programs with knowledge
126 analysis situations).
126 about the local namespaces (very useful in debugging and data
127 * Easy debugger access. You can set IPython to call up an enhanced
127 analysis situations).
128 version of the Python debugger (pdb) every time there is an
128 * Easy debugger access. You can set IPython to call up an enhanced
129 uncaught exception. This drops you inside the code which triggered
129 version of the Python debugger (pdb) every time there is an
130 the exception with all the data live and it is possible to
130 uncaught exception. This drops you inside the code which triggered
131 navigate the stack to rapidly isolate the source of a bug. The
131 the exception with all the data live and it is possible to
132 %run magic command -with the -d option- can run any script under
132 navigate the stack to rapidly isolate the source of a bug. The
133 pdb's control, automatically setting initial breakpoints for you.
133 %run magic command -with the -d option- can run any script under
134 This version of pdb has IPython-specific improvements, including
134 pdb's control, automatically setting initial breakpoints for you.
135 tab-completion and traceback coloring support.
135 This version of pdb has IPython-specific improvements, including
136 * Profiler support. You can run single statements (similar to
136 tab-completion and traceback coloring support.
137 profile.run()) or complete programs under the profiler's control.
137 * Profiler support. You can run single statements (similar to
138 While this is possible with standard cProfile or profile modules,
138 profile.run()) or complete programs under the profiler's control.
139 IPython wraps this functionality with magic commands (see '%prun'
139 While this is possible with standard cProfile or profile modules,
140 and '%run -p') convenient for rapid interactive work.
140 IPython wraps this functionality with magic commands (see '%prun'
141 * Doctest support. The special %doctest_mode command toggles a mode
141 and '%run -p') convenient for rapid interactive work.
142 that allows you to paste existing doctests (with leading '>>>'
142 * Doctest support. The special %doctest_mode command toggles a mode
143 prompts and whitespace) and uses doctest-compatible prompts and
143 that allows you to paste existing doctests (with leading '>>>'
144 output, so you can use IPython sessions as doctest code.
144 prompts and whitespace) and uses doctest-compatible prompts and
145 output, so you can use IPython sessions as doctest code.
145
146
146
147
147 Portability and Python requirements
148 Portability and Python requirements
@@ -228,24 +229,31 b' manner. If you download the tar archive, the process is:'
228 ipython with the -upgrade option and it will do this automatically
229 ipython with the -upgrade option and it will do this automatically
229 for you.
230 for you.
230 3. IPython uses distutils, so you can install it by simply typing at
231 3. IPython uses distutils, so you can install it by simply typing at
231 the system prompt (don't type the $)
232 the system prompt (don't type the $)::
232 $ python setup.py install
233
234 $ python setup.py install
235
233 Note that this assumes you have root access to your machine. If
236 Note that this assumes you have root access to your machine. If
234 you don't have root access or don't want IPython to go in the
237 you don't have root access or don't want IPython to go in the
235 default python directories, you'll need to use the |--home| option
238 default python directories, you'll need to use the ``--home`` option
236 (or |--prefix|). For example:
239 (or ``--prefix``). For example::
237 |$ python setup.py install --home $HOME/local|
240
241 $ python setup.py install --home $HOME/local
242
238 will install IPython into $HOME/local and its subdirectories
243 will install IPython into $HOME/local and its subdirectories
239 (creating them if necessary).
244 (creating them if necessary).
240 You can type
245 You can type::
241 |$ python setup.py --help|
246
247 $ python setup.py --help
248
242 for more details.
249 for more details.
243 Note that if you change the default location for |--home| at
250
251 Note that if you change the default location for ``--home`` at
244 installation, IPython may end up installed at a location which is
252 installation, IPython may end up installed at a location which is
245 not part of your $PYTHONPATH environment variable. In this case,
253 not part of your $PYTHONPATH environment variable. In this case,
246 you'll need to configure this variable to include the actual
254 you'll need to configure this variable to include the actual
247 directory where the IPython/ directory ended (typically the value
255 directory where the IPython/ directory ended (typically the value
248 you give to |--home| plus /lib/python).
256 you give to ``--home`` plus /lib/python).
249
257
250
258
251 Mac OSX information
259 Mac OSX information
@@ -280,10 +288,14 b' and GTK apps. Under OSX, however, this requires that ipython is'
280 installed by calling the special pythonw script at installation time,
288 installed by calling the special pythonw script at installation time,
281 which takes care of coordinating things with Apple's graphical environment.
289 which takes care of coordinating things with Apple's graphical environment.
282
290
283 So when installing under OSX, it is best to use the following command:
291 So when installing under OSX, it is best to use the following command::
284 | $ sudo pythonw setup.py install --install-scripts=/usr/local/bin|
292
293 $ sudo pythonw setup.py install --install-scripts=/usr/local/bin
294
285 or
295 or
286 | $ sudo pythonw setup.py install --install-scripts=/usr/bin|
296
297 $ sudo pythonw setup.py install --install-scripts=/usr/bin
298
287 depending on where you like to keep hand-installed executables.
299 depending on where you like to keep hand-installed executables.
288
300
289 The resulting script will have an appropriate shebang line (the first
301 The resulting script will have an appropriate shebang line (the first
@@ -294,7 +306,7 b' does not work and has a shebang line that points to, for example, just'
294 build/scripts-<python-version> directory. Delete that directory and
306 build/scripts-<python-version> directory. Delete that directory and
295 rerun the setup.py.
307 rerun the setup.py.
296
308
297 It is also a good idea to use the special flag |--install-scripts| as
309 It is also a good idea to use the special flag ``--install-scripts`` as
298 indicated above, to ensure that the ipython scripts end up in a location
310 indicated above, to ensure that the ipython scripts end up in a location
299 which is part of your $PATH. Otherwise Apple's Python will put the
311 which is part of your $PATH. Otherwise Apple's Python will put the
300 scripts in an internal directory not available by default at the command
312 scripts in an internal directory not available by default at the command
@@ -591,10 +603,14 b' Input/Output prompts and exception tracebacks'
591 You can test whether the colored prompts and tracebacks work on your
603 You can test whether the colored prompts and tracebacks work on your
592 system interactively by typing '%colors Linux' at the prompt (use
604 system interactively by typing '%colors Linux' at the prompt (use
593 '%colors LightBG' if your terminal has a light background). If the input
605 '%colors LightBG' if your terminal has a light background). If the input
594 prompt shows garbage like:
606 prompt shows garbage like::
595 [0;32mIn [[1;32m1[0;32m]: [0;00m
607
596 instead of (in color) something like:
608 [0;32mIn [[1;32m1[0;32m]: [0;00m
597 In [1]:
609
610 instead of (in color) something like::
611
612 In [1]:
613
598 this means that your terminal doesn't properly handle color escape
614 this means that your terminal doesn't properly handle color escape
599 sequences. You can go to a 'no color' mode by typing '%colors NoColor'.
615 sequences. You can go to a 'no color' mode by typing '%colors NoColor'.
600
616
@@ -665,11 +681,11 b' the previous section, you may need to set also in your .emacs file::'
665 (setq ansi-color-for-comint-mode t)
681 (setq ansi-color-for-comint-mode t)
666
682
667
683
668 Notes::
684 Notes:
669
685
670 * There is one caveat you should be aware of: you must start the
686 * There is one caveat you should be aware of: you must start the
671 IPython shell before attempting to execute any code regions via
687 IPython shell before attempting to execute any code regions via
672 C-c |. Simply type C-c ! to start IPython before passing any code
688 ``C-c |``. Simply type C-c ! to start IPython before passing any code
673 regions to the interpreter, and you shouldn't experience any
689 regions to the interpreter, and you shouldn't experience any
674 problems.
690 problems.
675 This is due to a bug in Python itself, which has been fixed for
691 This is due to a bug in Python itself, which has been fixed for
@@ -1035,7 +1051,7 b' Regular Options'
1035 After the above threading options have been given, regular options can
1051 After the above threading options have been given, regular options can
1036 follow in any order. All options can be abbreviated to their shortest
1052 follow in any order. All options can be abbreviated to their shortest
1037 non-ambiguous form and are case-sensitive. One or two dashes can be
1053 non-ambiguous form and are case-sensitive. One or two dashes can be
1038 used. Some options have an alternate short form, indicated after a |.
1054 used. Some options have an alternate short form, indicated after a ``|``.
1039
1055
1040 Most options can also be set from your ipythonrc configuration file. See
1056 Most options can also be set from your ipythonrc configuration file. See
1041 the provided example for more details on what the options do. Options
1057 the provided example for more details on what the options do. Options
@@ -1197,1420 +1213,1422 b' All options with a [no] prepended can be specified in negated form'
1197 (M-x shell and C-c !) buffers do not.
1213 (M-x shell and C-c !) buffers do not.
1198 * [-screen_length|sl <n>:] number of lines of your screen. This is
1214 * [-screen_length|sl <n>:] number of lines of your screen. This is
1199 used to control printing of very long strings. Strings longer than
1215 used to control printing of very long strings. Strings longer than
1200 this number of lines will be sent through a pager instead of
1216 this number of lines will be sent through a pager instead of
1201 directly printed.
1217 directly printed.
1202 * [ ] The default value for this is 0, which means IPython will
1218 * [ ] The default value for this is 0, which means IPython will
1203 auto-detect your screen size every time it needs to print certain
1219 auto-detect your screen size every time it needs to print certain
1204 potentially long strings (this doesn't change the behavior of the
1220 potentially long strings (this doesn't change the behavior of the
1205 'print' keyword, it's only triggered internally). If for some
1221 'print' keyword, it's only triggered internally). If for some
1206 reason this isn't working well (it needs curses support), specify
1222 reason this isn't working well (it needs curses support), specify
1207 it yourself. Otherwise don't change the default.
1223 it yourself. Otherwise don't change the default.
1208 * [-separate_in|si <string>:] separator before input prompts.
1224 * [-separate_in|si <string>:] separator before input prompts.
1209 Default: '\n'
1225 Default: '\n'
1210 * [-separate_out|so <string>:] separator before output prompts.
1226 * [-separate_out|so <string>:] separator before output prompts.
1211 Default: nothing.
1227 Default: nothing.
1212 * [-separate_out2|so2 <string>:] separator after output prompts.
1228 * [-separate_out2|so2 <string>:] separator after output prompts.
1213 Default: nothing.
1229 Default: nothing.
1214 * [ ] For these three options, use the value 0 to specify no separator.
1230 * [ ] For these three options, use the value 0 to specify no separator.
1215 * [-nosep:] shorthand for '-SeparateIn 0 -SeparateOut 0
1231 * [-nosep:] shorthand for '-SeparateIn 0 -SeparateOut 0
1216 -SeparateOut2 0'. Simply removes all input/output separators.
1232 -SeparateOut2 0'. Simply removes all input/output separators.
1217 * [-upgrade:] allows you to upgrade your IPYTHONDIR configuration
1233 * [-upgrade:] allows you to upgrade your IPYTHONDIR configuration
1218 when you install a new version of IPython. Since new versions may
1234 when you install a new version of IPython. Since new versions may
1219 include new command line options or example files, this copies
1235 include new command line options or example files, this copies
1220 updated ipythonrc-type files. However, it backs up (with a .old
1236 updated ipythonrc-type files. However, it backs up (with a .old
1221 extension) all files which it overwrites so that you can merge
1237 extension) all files which it overwrites so that you can merge
1222 back any customizations you might have in your personal files.
1238 back any customizations you might have in your personal files.
1223 * [-Version:] print version information and exit.
1239 * [-Version:] print version information and exit.
1224 * [-wxversion <string>:] Select a specific version of wxPython (used
1240 * [-wxversion <string>:] Select a specific version of wxPython (used
1225 in conjunction with -wthread). Requires the wxversion module, part
1241 in conjunction with -wthread). Requires the wxversion module, part
1226 of recent wxPython distributions
1242 of recent wxPython distributions
1227 * [-xmode <modename>:] Mode for exception reporting.
1243 * [-xmode <modename>:] Mode for exception reporting.
1228 * [ ] Valid modes: Plain, Context and Verbose.
1244 * [ ] Valid modes: Plain, Context and Verbose.
1229 * [ ] Plain: similar to python's normal traceback printing.
1245 * [ ] Plain: similar to python's normal traceback printing.
1230 * [ ] Context: prints 5 lines of context source code around each
1246 * [ ] Context: prints 5 lines of context source code around each
1231 line in the traceback.
1247 line in the traceback.
1232 * [ ] Verbose: similar to Context, but additionally prints the
1248 * [ ] Verbose: similar to Context, but additionally prints the
1233 variables currently visible where the exception happened
1249 variables currently visible where the exception happened
1234 (shortening their strings if too long). This can potentially be
1250 (shortening their strings if too long). This can potentially be
1235 very slow, if you happen to have a huge data structure whose
1251 very slow, if you happen to have a huge data structure whose
1236 string representation is complex to compute. Your computer may
1252 string representation is complex to compute. Your computer may
1237 appear to freeze for a while with cpu usage at 100%. If this
1253 appear to freeze for a while with cpu usage at 100%. If this
1238 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
1254 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
1239 more than once).
1255 more than once).
1240
1241 Interactive use
1242 ===============
1243
1244 Warning: IPython relies on the existence of a global variable called
1245 __IP which controls the shell itself. If you redefine __IP to anything,
1246 bizarre behavior will quickly occur.
1247
1248 Other than the above warning, IPython is meant to work as a drop-in
1249 replacement for the standard interactive interpreter. As such, any code
1250 which is valid python should execute normally under IPython (cases where
1251 this is not true should be reported as bugs). It does, however, offer
1252 many features which are not available at a standard python prompt. What
1253 follows is a list of these.
1254
1255
1256 Caution for Windows users
1257 -------------------------
1258
1259 Windows, unfortunately, uses the '\' character as a path separator. This
1260 is a terrible choice, because '\' also represents the escape character
1261 in most modern programming languages, including Python. For this reason,
1262 issuing many of the commands discussed below (especially magics which
1263 affect the filesystem) with '\' in them will cause strange errors.
1264
1265 A partial solution is to use instead the '/' character as a path
1266 separator, which Windows recognizes in most situations. However, in
1267 Windows commands '/' flags options, so you can not use it for the root
1268 directory. This means that paths beginning at the root must be typed in
1269 a contrived manner like:
1270 %copy \opt/foo/bar.txt \tmp
1271
1272 There is no sensible thing IPython can do to truly work around this flaw
1273 in Windows^3 <footnode.html#foot878>.
1274
1275
1276
1277 Magic command system
1278 --------------------
1279
1280 IPython will treat any line whose first character is a % as a special
1281 call to a 'magic' function. These allow you to control the behavior of
1282 IPython itself, plus a lot of system-type features. They are all
1283 prefixed with a % character, but parameters are given without
1284 parentheses or quotes.
1285
1286 Example: typing '%cd mydir' (without the quotes) changes you working
1287 directory to 'mydir', if it exists.
1288
1289 If you have 'automagic' enabled (in your ipythonrc file, via the command
1290 line option -automagic or with the %automagic function), you don't need
1291 to type in the % explicitly. IPython will scan its internal list of
1292 magic functions and call one if it exists. With automagic on you can
1293 then just type 'cd mydir' to go to directory 'mydir'. The automagic
1294 system has the lowest possible precedence in name searches, so defining
1295 an identifier with the same name as an existing magic function will
1296 shadow it for automagic use. You can still access the shadowed magic
1297 function by explicitly using the % character at the beginning of the line.
1298
1299 An example (with automagic on) should clarify all this::
1300
1301 In [1]: cd ipython # %cd is called by automagic
1302
1303 /home/fperez/ipython
1304
1305 In [2]: cd=1 # now cd is just a variable
1306
1307 In [3]: cd .. # and doesn't work as a function anymore
1308
1309 ------------------------------
1310
1311 File "<console>", line 1
1312
1313 cd ..
1314
1315 ^
1316
1317 SyntaxError: invalid syntax
1318
1319 In [4]: %cd .. # but %cd always works
1320
1321 /home/fperez
1322
1323 In [5]: del cd # if you remove the cd variable
1324
1325 In [6]: cd ipython # automagic can work again
1326
1327 /home/fperez/ipython
1328
1329 You can define your own magic functions to extend the system. The
1330 following example defines a new magic command, %impall::
1331
1332 import IPython.ipapi
1333
1334 ip = IPython.ipapi.get()
1335
1336 def doimp(self, arg):
1337
1338 ip = self.api
1339
1340 ip.ex("import %s; reload(%s); from %s import *" % (
1341
1342 arg,arg,arg)
1343
1344 )
1345
1346 ip.expose_magic('impall', doimp)
1347
1348 You can also define your own aliased names for magic functions. In your
1349 ipythonrc file, placing a line like:
1350
1351 execute __IP.magic_cl = __IP.magic_clear
1352
1353 will define %cl as a new name for %clear.
1354
1355 Type %magic for more information, including a list of all available
1356 magic functions at any time and their docstrings. You can also type
1357 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
1358 information on the '?' system) to get information about any particular
1359 magic function you are interested in.
1360
1361
1362 Magic commands
1363 --------------
1364
1365 The rest of this section is automatically generated for each release
1366 from the docstrings in the IPython code. Therefore the formatting is
1367 somewhat minimal, but this method has the advantage of having
1368 information always in sync with the code.
1369
1370 A list of all the magic commands available in IPython's default
1371 installation follows. This is similar to what you'll see by simply
1372 typing %magic at the prompt, but that will also give you information
1373 about magic commands you may have added as part of your personal
1374 customizations.
1375
1376
1377 %Exit: Exit IPython without confirmation.
1378
1379
1380 %Pprint: Toggle pretty printing on/off.
1381
1382
1383 %alias: Define an alias for a system command.
1384
1385 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1386
1387 Then, typing 'alias_name params' will execute the system command 'cmd
1388 params' (from your underlying operating system).
1389
1390 Aliases have lower precedence than magic functions and Python normal
1391 variables, so if 'foo' is both a Python variable and an alias, the alias
1392 can not be executed until 'del foo' removes the Python variable.
1393
1394 You can use the %l specifier in an alias definition to represent the
1395 whole line when the alias is called. For example:
1396
1397 In [2]: alias all echo "Input in brackets: <%l>"
1398 In [3]: all hello world
1399 Input in brackets: <hello world>
1400
1401 You can also define aliases with parameters using %s specifiers (one per
1402 parameter):
1403
1404 In [1]: alias parts echo first %s second %s
1405 In [2]: %parts A B
1406 first A second B
1407 In [3]: %parts A
1408 Incorrect number of arguments: 2 expected.
1409 parts is an alias to: 'echo first %s second %s'
1410
1411 Note that %l and %s are mutually exclusive. You can only use one or the
1412 other in your aliases.
1413
1414 Aliases expand Python variables just like system calls using ! or !! do:
1415 all expressions prefixed with '$' get expanded. For details of the
1416 semantic rules, see PEP-215: http://www.python.org/peps/pep-0215.html.
1417 This is the library used by IPython for variable expansion. If you want
1418 to access a true shell variable, an extra $ is necessary to prevent its
1419 expansion by IPython:
1420
1421 In [6]: alias show echo
1422 In [7]: PATH='A Python string'
1423 In [8]: show $PATH
1424 A Python string
1425 In [9]: show $$PATH
1426 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1427
1428 You can use the alias facility to acess all of $PATH. See the %rehash
1429 and %rehashx functions, which automatically create aliases for the
1430 contents of your $PATH.
1431
1432 If called with no parameters, %alias prints the current alias table.
1433
1434
1435 %autocall: Make functions callable without having to type parentheses.
1436
1437 Usage:
1438
1439 %autocall [mode]
1440
1441 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
1442 value is toggled on and off (remembering the previous state).
1443
1444 In more detail, these values mean:
1445
1446 0 -> fully disabled
1447
1448 1 -> active, but do not apply if there are no arguments on the line.
1449
1450 In this mode, you get:
1451
1452 In [1]: callable Out[1]: <built-in function callable>
1453
1454 In [2]: callable 'hello' ---> callable('hello') Out[2]: False
1455
1456 2 -> Active always. Even if no arguments are present, the callable
1457 object is called:
1458
1459 In [4]: callable ---> callable()
1460
1461 Note that even with autocall off, you can still use '/' at the start of
1462 a line to treat the first argument on the command line as a function and
1463 add parentheses to it:
1464
1465 In [8]: /str 43 ---> str(43) Out[8]: '43'
1466
1467
1468 %autoindent: Toggle autoindent on/off (if available).
1469
1470
1471 %automagic: Make magic functions callable without having to type the
1472 initial %.
1473
1474 Without argumentsl toggles on/off (when off, you must call it as
1475 %automagic, of course). With arguments it sets the value, and you can
1476 use any of (case insensitive):
1477
1478 - on,1,True: to activate
1479
1480 - off,0,False: to deactivate.
1481
1482 Note that magic functions have lowest priority, so if there's a variable
1483 whose name collides with that of a magic fn, automagic won't work for
1484 that function (you get the variable instead). However, if you delete the
1485 variable (del var), the previously shadowed magic function becomes
1486 visible to automagic again.
1487
1488
1489 %bg: Run a job in the background, in a separate thread.
1490
1491 For example,
1492
1493 %bg myfunc(x,y,z=1)
1494
1495 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
1496 execution starts, a message will be printed indicating the job number.
1497 If your job number is 5, you can use
1498
1499 myvar = jobs.result(5) or myvar = jobs[5].result
1500
1501 to assign this result to variable 'myvar'.
1502
1503 IPython has a job manager, accessible via the 'jobs' object. You can
1504 type jobs? to get more information about it, and use jobs.<TAB> to see
1505 its attributes. All attributes not starting with an underscore are meant
1506 for public use.
1507
1508 In particular, look at the jobs.new() method, which is used to create
1509 new jobs. This magic %bg function is just a convenience wrapper around
1510 jobs.new(), for expression-based jobs. If you want to create a new job
1511 with an explicit function object and arguments, you must call jobs.new()
1512 directly.
1513
1514 The jobs.new docstring also describes in detail several important
1515 caveats associated with a thread-based model for background job
1516 execution. Type jobs.new? for details.
1517
1518 You can check the status of all jobs with jobs.status().
1519
1520 The jobs variable is set by IPython into the Python builtin namespace.
1521 If you ever declare a variable named 'jobs', you will shadow this name.
1522 You can either delete your global jobs variable to regain access to the
1523 job manager, or make a new name and assign it manually to the manager
1524 (stored in IPython's namespace). For example, to assign the job manager
1525 to the Jobs name, use:
1526
1527 Jobs = __builtins__.jobs
1528
1529
1530 %bookmark: Manage IPython's bookmark system.
1531
1532 %bookmark <name> - set bookmark to current dir %bookmark <name> <dir> -
1533 set bookmark to <dir> %bookmark -l - list all bookmarks %bookmark -d
1534 <name> - remove bookmark %bookmark -r - remove all bookmarks
1535
1536 You can later on access a bookmarked folder with: %cd -b <name> or
1537 simply '%cd <name>' if there is no directory called <name> AND there is
1538 such a bookmark defined.
1539
1540 Your bookmarks persist through IPython sessions, but they are associated
1541 with each profile.
1542
1543
1544 %cd: Change the current working directory.
1545
1546 This command automatically maintains an internal list of directories you
1547 visit during your IPython session, in the variable _dh. The command
1548 %dhist shows this history nicely formatted. You can also do 'cd -<tab>'
1549 to see directory history conveniently.
1550
1551 Usage:
1552
1553 cd 'dir': changes to directory 'dir'.
1554
1555 cd -: changes to the last visited directory.
1556
1557 cd -<n>: changes to the n-th directory in the directory history.
1558
1559 cd -b <bookmark_name>: jump to a bookmark set by %bookmark (note: cd
1560 <bookmark_name> is enough if there is no directory <bookmark_name>, but
1561 a bookmark with the name exists.) 'cd -b <tab>' allows you to
1562 tab-complete bookmark names.
1563
1564 Options:
1565
1566 -q: quiet. Do not print the working directory after the cd command is
1567 executed. By default IPython's cd command does print this directory,
1568 since the default prompts do not display path information.
1569
1570 Note that !cd doesn't work for this purpose because the shell where
1571 !command runs is immediately discarded after executing 'command'.
1572
1573
1574 %color_info: Toggle color_info.
1575
1576 The color_info configuration parameter controls whether colors are used
1577 for displaying object details (by things like %psource, %pfile or the
1578 '?' system). This function toggles this value with each call.
1579
1580 Note that unless you have a fairly recent pager (less works better than
1581 more) in your system, using colored object information displays will not
1582 work properly. Test it and see.
1583
1584
1585 %colors: Switch color scheme for prompts, info system and exception
1586 handlers.
1587
1588 Currently implemented schemes: NoColor, Linux, LightBG.
1589
1590 Color scheme names are not case-sensitive.
1591
1592
1593 %cpaste: Allows you to paste & execute a pre-formatted code block from
1594 clipboard
1595
1596 You must terminate the block with '-' (two minus-signs) alone on the
1597 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
1598 is the new sentinel for this operation)
1599
1600 The block is dedented prior to execution to enable execution of method
1601 definitions. '>' and '+' characters at the beginning of a line are
1602 ignored, to allow pasting directly from e-mails or diff files. The
1603 executed block is also assigned to variable named 'pasted_block' for
1604 later editing with '%edit pasted_block'.
1605
1606 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
1607 This assigns the pasted block to variable 'foo' as string, without
1608 dedenting or executing it.
1609
1610 Do not be alarmed by garbled output on Windows (it's a readline bug).
1611 Just press enter and type - (and press enter again) and the block will
1612 be what was just pasted.
1613
1614 IPython statements (magics, shell escapes) are not supported (yet).
1615
1616
1617 %debug: Activate the interactive debugger in post-mortem mode.
1618
1619 If an exception has just occurred, this lets you inspect its stack
1620 frames interactively. Note that this will always work only on the last
1621 traceback that occurred, so you must call this quickly after an
1622 exception that you wish to inspect has fired, because if another one
1623 occurs, it clobbers the previous one.
1624
1625 If you want IPython to automatically do this on every exception, see the
1626 %pdb magic for more details.
1627
1628
1629 %dhist: Print your history of visited directories.
1630
1631 %dhist -> print full history
1632 %dhist n -> print last n entries only
1633 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)
1634
1635 This history is automatically maintained by the %cd command, and always
1636 available as the global list variable _dh. You can use %cd -<n> to go to
1637 directory number <n>.
1638
1639 Note that most of time, you should view directory history by entering cd
1640 -<TAB>.
1641
1642
1643 %dirs: Return the current directory stack.
1644
1645
1646 %doctest_mode: Toggle doctest mode on and off.
1647
1648 This mode allows you to toggle the prompt behavior between normal
1649 IPython prompts and ones that are as similar to the default IPython
1650 interpreter as possible.
1651
1652 It also supports the pasting of code snippets that have leading 'Β»>' and
1653 '...' prompts in them. This means that you can paste doctests from files
1654 or docstrings (even if they have leading whitespace), and the code will
1655 execute correctly. You can then use '%history -tn' to see the translated
1656 history without line numbers; this will give you the input after removal
1657 of all the leading prompts and whitespace, which can be pasted back into
1658 an editor.
1659
1660 With these features, you can switch into this mode easily whenever you
1661 need to do testing and changes to doctests, without having to leave your
1662 existing IPython session.
1663
1664
1665 %ed: Alias to %edit.
1666
1667
1668 %edit: Bring up an editor and execute the resulting code.
1669
1670 Usage: %edit [options] [args]
1671
1672 %edit runs IPython's editor hook. The default version of this hook is
1673 set to call the __IPYTHON__.rc.editor command. This is read from your
1674 environment variable $EDITOR. If this isn't found, it will default to vi
1675 under Linux/Unix and to notepad under Windows. See the end of this
1676 docstring for how to change the editor hook.
1677
1678 You can also set the value of this editor via the command line option
1679 '-editor' or in your ipythonrc file. This is useful if you wish to use
1680 specifically for IPython an editor different from your typical default
1681 (and for Windows users who typically don't set environment variables).
1682
1683 This command allows you to conveniently edit multi-line code right in
1684 your IPython session.
1685
1686 If called without arguments, %edit opens up an empty editor with a
1687 temporary file and will execute the contents of this file when you close
1688 it (don't forget to save it!).
1689
1690 Options:
1691
1692 -n <number>: open the editor at a specified line number. By default, the
1693 IPython editor hook uses the unix syntax 'editor +N filename', but you
1694 can configure this by providing your own modified hook if your favorite
1695 editor supports line-number specifications with a different syntax.
1696
1697 -p: this will call the editor with the same data as the previous time it
1698 was used, regardless of how long ago (in your current session) it was.
1699
1700 -r: use 'raw' input. This option only applies to input taken from the
1701 user's history. By default, the 'processed' history is used, so that
1702 magics are loaded in their transformed version to valid Python. If this
1703 option is given, the raw input as typed as the command line is used
1704 instead. When you exit the editor, it will be executed by IPython's own
1705 processor.
1706
1707 -x: do not execute the edited code immediately upon exit. This is mainly
1708 useful if you are editing programs which need to be called with command
1709 line arguments, which you can then do using %run.
1710
1711 Arguments:
1712
1713 If arguments are given, the following possibilites exist:
1714
1715 - The arguments are numbers or pairs of colon-separated numbers (like 1
1716 4:8 9). These are interpreted as lines of previous input to be loaded
1717 into the editor. The syntax is the same of the %macro command.
1718
1719 - If the argument doesn't start with a number, it is evaluated as a
1720 variable and its contents loaded into the editor. You can thus edit any
1721 string which contains python code (including the result of previous edits).
1722
1723 - If the argument is the name of an object (other than a string),
1724 IPython will try to locate the file where it was defined and open the
1725 editor at the point where it is defined. You can use '%edit function' to
1726 load an editor exactly at the point where 'function' is defined, edit it
1727 and have the file be executed automatically.
1728
1729 If the object is a macro (see %macro for details), this opens up your
1730 specified editor with a temporary file containing the macro's data. Upon
1731 exit, the macro is reloaded with the contents of the file.
1732
1733 Note: opening at an exact line is only supported under Unix, and some
1734 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1735 '+NUMBER' parameter necessary for this feature. Good editors like
1736 (X)Emacs, vi, jed, pico and joe all do.
1737
1738 - If the argument is not found as a variable, IPython will look for a
1739 file with that name (adding .py if necessary) and load it into the
1740 editor. It will execute its contents with execfile() when you exit,
1741 loading any code in the file into your interactive namespace.
1742
1743 After executing your code, %edit will return as output the code you
1744 typed in the editor (except when it was an existing file). This way you
1745 can reload the code in further invocations of %edit as a variable, via
1746 _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of the
1747 output.
1748
1749 Note that %edit is also available through the alias %ed.
1750
1751 This is an example of creating a simple function inside the editor and
1752 then modifying it. First, start up the editor::
1753
1754 In [1]: ed
1755 Editing... done. Executing edited code...
1756 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
1757
1758 We can then call the function foo():
1759
1760 In [2]: foo()
1761 foo() was defined in an editing session
1762
1763 Now we edit foo. IPython automatically loads the editor with the
1764 (temporary) file where foo() was previously defined:
1765
1766 In [3]: ed foo
1767 Editing... done. Executing edited code...
1768
1769 And if we call foo() again we get the modified version:
1770
1771 In [4]: foo()
1772 foo() has now been changed!
1773
1774 Here is an example of how to edit a code snippet successive times. First
1775 we call the editor:
1776
1777 In [8]: ed
1778 Editing... done. Executing edited code...
1779 hello
1780 Out[8]: "print 'hello'\n"
1781
1782 Now we call it again with the previous output (stored in _):
1783
1784 In [9]: ed _
1785 Editing... done. Executing edited code...
1786 hello world
1787 Out[9]: "print 'hello world'\n"
1788
1789 Now we call it with the output #8 (stored in _8, also as Out[8]):
1790
1791 In [10]: ed _8
1792 Editing... done. Executing edited code...
1793 hello again
1794 Out[10]: "print 'hello again'\n"
1795
1796 Changing the default editor hook:
1797
1798 If you wish to write your own editor hook, you can put it in a
1799 configuration file which you load at startup time. The default hook is
1800 defined in the IPython.hooks module, and you can use that as a starting
1801 example for further modifications. That file also has general
1802 instructions on how to set a new hook for use once you've defined it.
1803
1804
1805 %env: List environment variables.
1806
1807
1808 %exit: Exit IPython, confirming if configured to do so.
1809
1810 You can configure whether IPython asks for confirmation upon exit by
1811 setting the confirm_exit flag in the ipythonrc file.
1812
1813
1814 %logoff: Temporarily stop logging.
1815
1816 You must have previously started logging.
1817
1818
1819 %logon: Restart logging.
1820
1821 This function is for restarting logging which you've temporarily stopped
1822 with %logoff. For starting logging for the first time, you must use the
1823 %logstart function, which allows you to specify an optional log filename.
1824
1825
1826 %logstart: Start logging anywhere in a session.
1827
1828 %logstart [-o|-r|-t] [log_name [log_mode]]
1829
1830 If no name is given, it defaults to a file named 'ipython_log.py' in
1831 your current directory, in 'rotate' mode (see below).
1832
1833 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1834 history up to that point and then continues logging.
1835
1836 %logstart takes a second optional parameter: logging mode. This can be
1837 one of (note that the modes are given unquoted):
1838 append: well, that says it.
1839 backup: rename (if exists) to name and start name.
1840 global: single logfile in your home dir, appended to.
1841 over : overwrite existing log.
1842 rotate: create rotating logs name.1 , name.2 , etc.
1843
1844 Options:
1845
1846 -o: log also IPython's output. In this mode, all commands which generate
1847 an Out[NN] prompt are recorded to the logfile, right after their
1848 corresponding input line. The output lines are always prepended with a
1849 '#[Out]# ' marker, so that the log remains valid Python code.
1850
1851 Since this marker is always the same, filtering only the output from a
1852 log is very easy, using for example a simple awk call:
1853
1854 awk -F'#
1855
1856 \begin{displaymath}Out\end{displaymath}
1857
1858 # ' 'if($2) print $2' ipython_log.py
1859
1860 -r: log 'raw' input. Normally, IPython's logs contain the processed
1861 input, so that user lines are logged in their final form, converted into
1862 valid Python. For example, %Exit is logged as '_ip.magic("Exit"). If the
1863 -r flag is given, all input is logged exactly as typed, with no
1864 transformations applied.
1865
1866 -t: put timestamps before each input line logged (these are put in
1867 comments).
1868
1869
1870 %logstate: Print the status of the logging system.
1871
1872
1873 %logstop: Fully stop logging and close log file.
1874
1875 In order to start logging again, a new %logstart call needs to be made,
1876 possibly (though not necessarily) with a new filename, mode and other
1877 options.
1878
1879
1880 %lsmagic: List currently available magic functions.
1881
1882
1883 %macro: Define a set of input lines as a macro for future re-execution.
1884
1885 Usage:
1886 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1887
1888 Options:
1889
1890 -r: use 'raw' input. By default, the 'processed' history is used, so
1891 that magics are loaded in their transformed version to valid Python. If
1892 this option is given, the raw input as typed as the command line is used
1893 instead.
1894
1895 This will define a global variable called 'name' which is a string made
1896 of joining the slices and lines you specify (n1,n2,... numbers above)
1897 from your input history into a single string. This variable acts like an
1898 automatic function which re-executes those lines as if you had typed
1899 them. You just type 'name' at the prompt and the code executes.
1900
1901 The notation for indicating number ranges is: n1-n2 means 'use line
1902 numbers n1,...n2' (the endpoint is included). That is, '5-7' means using
1903 the lines numbered 5,6 and 7.
1904
1905 Note: as a 'hidden' feature, you can also use traditional python slice
1906 notation, where N:M means numbers N through M-1.
1907
1908 For example, if your history contains (%hist prints it):
1909
1910 44: x=1
1911 45: y=3
1912 46: z=x+y
1913 47: print x
1914 48: a=5
1915 49: print 'x',x,'y',y
1916
1917 you can create a macro with lines 44 through 47 (included) and line 49
1918 called my_macro with:
1919
1920 In [51]: %macro my_macro 44-47 49
1921
1922 Now, typing 'my_macro' (without quotes) will re-execute all this code in
1923 one pass.
1924
1925 You don't need to give the line-numbers in order, and any given line
1926 number can appear multiple times. You can assemble macros with any lines
1927 from your input history in any order.
1928
1929 The macro is a simple object which holds its value in an attribute, but
1930 IPython's display system checks for macros and executes them as code
1931 instead of printing them when you type their name.
1932
1933 You can view a macro's contents by explicitly printing it with:
1934
1935 'print macro_name'.
1936
1937 For one-off cases which DON'T contain magic function calls in them you
1938 can obtain similar results by explicitly executing slices from your
1939 input history with:
1940
1941 In [60]: exec In[44:48]+In[49]
1942
1943
1944 %magic: Print information about the magic function system.
1945
1946
1947 %page: Pretty print the object and display it through a pager.
1948
1949 %page [options] OBJECT
1950
1951 If no object is given, use _ (last output).
1952
1953 Options:
1954
1955 -r: page str(object), don't pretty-print it.
1956
1957
1958 %pdb: Control the automatic calling of the pdb interactive debugger.
1959
1960 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1961 argument it works as a toggle.
1962
1963 When an exception is triggered, IPython can optionally call the
1964 interactive pdb debugger after the traceback printout. %pdb toggles this
1965 feature on and off.
1966
1967 The initial state of this feature is set in your ipythonrc configuration
1968 file (the variable is called 'pdb').
1969
1970 If you want to just activate the debugger AFTER an exception has fired,
1971 without having to type '%pdb on' and rerunning your code, you can use
1972 the %debug magic.
1973
1974
1975 %pdef: Print the definition header for any callable object.
1976
1977 If the object is a class, print the constructor information.
1978
1979
1980 %pdoc: Print the docstring for an object.
1981
1982 If the given object is a class, it will print both the class and the
1983 constructor docstrings.
1984
1985
1986 %pfile: Print (or run through pager) the file where an object is defined.
1987
1988 The file opens at the line where the object definition begins. IPython
1989 will honor the environment variable PAGER if set, and otherwise will do
1990 its best to print the file in a convenient form.
1991
1992 If the given argument is not an object currently defined, IPython will
1993 try to interpret it as a filename (automatically adding a .py extension
1994 if needed). You can thus use %pfile as a syntax highlighting code viewer.
1995
1996
1997 %pinfo: Provide detailed information about an object.
1998
1999 '%pinfo object' is just a synonym for object? or ?object.
2000
2001
2002 %popd: Change to directory popped off the top of the stack.
2003
2004
2005 %profile: Print your currently active IPyhton profile.
2006
2007
2008 %prun: Run a statement through the python code profiler.
2009
2010 Usage:
2011 %prun [options] statement
2012
2013 The given statement (which doesn't require quote marks) is run via the
2014 python profiler in a manner similar to the profile.run() function.
2015 Namespaces are internally managed to work correctly; profile.run cannot
2016 be used in IPython because it makes certain assumptions about namespaces
2017 which do not hold under IPython.
2018
2019 Options:
2020
2021 -l <limit>: you can place restrictions on what or how much of the
2022 profile gets printed. The limit value can be:
2023
2024 * A string: only information for function names containing this string
2025 is printed.
2026
2027 * An integer: only these many lines are printed.
2028
2029 * A float (between 0 and 1): this fraction of the report is printed (for
2030 example, use a limit of 0.4 to see the topmost 40% only).
2031
2032 You can combine several limits with repeated use of the option. For
2033 example, '-l __init__ -l 5' will print only the topmost 5 lines of
2034 information about class constructors.
2035
2036 -r: return the pstats.Stats object generated by the profiling. This
2037 object has all the information about the profile in it, and you can
2038 later use it for further analysis or in other functions.
2039
2040 -s <key>: sort profile by given key. You can provide more than one key
2041 by using the option several times: '-s key1 -s key2 -s key3...'. The
2042 default sorting key is 'time'.
2043
2044 The following is copied verbatim from the profile documentation
2045 referenced below:
2046
2047 When more than one key is provided, additional keys are used as
2048 secondary criteria when the there is equality in all keys selected
2049 before them.
2050
2051 Abbreviations can be used for any key names, as long as the abbreviation
2052 is unambiguous. The following are the keys currently defined:
2053
2054 Valid Arg Meaning
2055 "calls" call count
2056 "cumulative" cumulative time
2057 "file" file name
2058 "module" file name
2059 "pcalls" primitive call count
2060 "line" line number
2061 "name" function name
2062 "nfl" name/file/line
2063 "stdname" standard name
2064 "time" internal time
2065
2066 Note that all sorts on statistics are in descending order (placing most
2067 time consuming items first), where as name, file, and line number
2068 searches are in ascending order (i.e., alphabetical). The subtle
2069 distinction between "nfl" and "stdname" is that the standard name is a
2070 sort of the name as printed, which means that the embedded line numbers
2071 get compared in an odd way. For example, lines 3, 20, and 40 would (if
2072 the file names were the same) appear in the string order "20" "3" and
2073 "40". In contrast, "nfl" does a numeric compare of the line numbers. In
2074 fact, sort_stats("nfl") is the same as sort_stats("name", "file", "line").
2075
2076 -T <filename>: save profile results as shown on screen to a text file.
2077 The profile is still shown on screen.
2078
2079 -D <filename>: save (via dump_stats) profile statistics to given
2080 filename. This data is in a format understod by the pstats module, and
2081 is generated by a call to the dump_stats() method of profile objects.
2082 The profile is still shown on screen.
2083
2084 If you want to run complete programs under the profiler's control, use
2085 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
2086 contains profiler specific options as described here.
2087
2088 You can read the complete documentation for the profile module with:
2089 In [1]: import profile; profile.help()
2090
2091
2092 %psearch: Search for object in namespaces by wildcard.
2093
2094 %psearch [options] PATTERN [OBJECT TYPE]
2095
2096 Note: ? can be used as a synonym for %psearch, at the beginning or at
2097 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
2098 rest of the command line must be unchanged (options come first), so for
2099 example the following forms are equivalent
2100
2101 %psearch -i a* function -i a* function? ?-i a* function
2102
2103 Arguments:
2104
2105 PATTERN
2106
2107 where PATTERN is a string containing * as a wildcard similar to its use
2108 in a shell. The pattern is matched in all namespaces on the search path.
2109 By default objects starting with a single _ are not matched, many
2110 IPython generated objects have a single underscore. The default is case
2111 insensitive matching. Matching is also done on the attributes of objects
2112 and not only on the objects in a module.
2113
2114 [OBJECT TYPE]
2115
2116 Is the name of a python type from the types module. The name is given in
2117 lowercase without the ending type, ex. StringType is written string. By
2118 adding a type here only objects matching the given type are matched.
2119 Using all here makes the pattern match all types (this is the default).
2120
2121 Options:
2122
2123 -a: makes the pattern match even objects whose names start with a single
2124 underscore. These names are normally ommitted from the search.
2125
2126 -i/-c: make the pattern case insensitive/sensitive. If neither of these
2127 options is given, the default is read from your ipythonrc file. The
2128 option name which sets this value is 'wildcards_case_sensitive'. If this
2129 option is not specified in your ipythonrc file, IPython's internal
2130 default is to do a case sensitive search.
2131
2132 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
2133 specifiy can be searched in any of the following namespaces: 'builtin',
2134 'user', 'user_global','internal', 'alias', where 'builtin' and 'user'
2135 are the search defaults. Note that you should not use quotes when
2136 specifying namespaces.
2137
2138 'Builtin' contains the python module builtin, 'user' contains all user
2139 data, 'alias' only contain the shell aliases and no python objects,
2140 'internal' contains objects used by IPython. The 'user_global' namespace
2141 is only used by embedded IPython instances, and it contains module-level
2142 globals. You can add namespaces to the search with -s or exclude them
2143 with -e (these options can be given more than once).
2144
2145 Examples:
2146
2147 %psearch a* -> objects beginning with an a %psearch -e builtin a* ->
2148 objects NOT in the builtin space starting in a %psearch a* function ->
2149 all functions beginning with an a %psearch re.e* -> objects beginning
2150 with an e in module re %psearch r*.e* -> objects that start with e in
2151 modules starting in r %psearch r*.* string -> all strings in modules
2152 beginning with r
2153
2154 Case sensitve search:
2155
2156 %psearch -c a* list all object beginning with lower case a
2157
2158 Show objects beginning with a single _:
2159
2160 %psearch -a _* list objects beginning with a single underscore
2161
2162
2163 %psource: Print (or run through pager) the source code for an object.
2164
2165
2166 %pushd: Place the current dir on stack and change directory.
2167
2168 Usage:
2169 %pushd ['dirname']
2170
2171
2172 %pwd: Return the current working directory path.
2173
2174
2175 %pycat: Show a syntax-highlighted file through a pager.
2176
2177 This magic is similar to the cat utility, but it will assume the file to
2178 be Python source and will show it with syntax highlighting.
2179
2180
2181 %quickref: Show a quick reference sheet
2182
2183
2184 %quit: Exit IPython, confirming if configured to do so (like %exit)
2185
2186
2187 %r: Repeat previous input.
2188
2189 Note: Consider using the more powerfull %rep instead!
2190
2191 If given an argument, repeats the previous command which starts with the
2192 same string, otherwise it just repeats the previous input.
2193
2194 Shell escaped commands (with ! as first character) are not recognized by
2195 this system, only pure python code and magic commands.
2196
2197
2198 %rehashx: Update the alias table with all executable files in $PATH.
2199
2200 This version explicitly checks that every entry in $PATH is a file with
2201 execute access (os.X_OK), so it is much slower than %rehash.
2202
2203 Under Windows, it checks executability as a match agains a '|'-separated
2204 string of extensions, stored in the IPython config variable
2205 win_exec_ext. This defaults to 'exe|com|bat'.
2206
2207 This function also resets the root module cache of module completer,
2208 used on slow filesystems.
2209
2210
2211 %reset: Resets the namespace by removing all names defined by the user.
2212
2213 Input/Output history are left around in case you need them.
2214
2215
2216 %run: Run the named file inside IPython as a program.
2217
2218 Usage:
2219 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
2220
2221 Parameters after the filename are passed as command-line arguments to
2222 the program (put in sys.argv). Then, control returns to IPython's prompt.
2223
2224 This is similar to running at a system prompt:
2225 $ python file args
2226 but with the advantage of giving you IPython's tracebacks, and of
2227 loading all variables into your interactive namespace for further use
2228 (unless -p is used, see below).
2229
2230 The file is executed in a namespace initially consisting only of
2231 __name__=='__main__' and sys.argv constructed as indicated. It thus sees
2232 its environment as if it were being run as a stand-alone program (except
2233 for sharing global objects such as previously imported modules). But
2234 after execution, the IPython interactive namespace gets updated with all
2235 variables defined in the program (except for __name__ and sys.argv).
2236 This allows for very convenient loading of code for interactive work,
2237 while giving each program a 'clean sheet' to run in.
2238
2239 Options:
2240
2241 -n: __name__ is NOT set to '__main__', but to the running file's name
2242 without extension (as python does under import). This allows running
2243 scripts and reloading the definitions in them without calling code
2244 protected by an ' if __name__ == "__main__" ' clause.
2245
2246 -i: run the file in IPython's namespace instead of an empty one. This is
2247 useful if you are experimenting with code written in a text editor which
2248 depends on variables defined interactively.
2249
2250 -e: ignore sys.exit() calls or SystemExit exceptions in the script being
2251 run. This is particularly useful if IPython is being used to run
2252 unittests, which always exit with a sys.exit() call. In such cases you
2253 are interested in the output of the test results, not in seeing a
2254 traceback of the unittest module.
2255
2256 -t: print timing information at the end of the run. IPython will give
2257 you an estimated CPU time consumption for your script, which under Unix
2258 uses the resource module to avoid the wraparound problems of
2259 time.clock(). Under Unix, an estimate of time spent on system tasks is
2260 also given (for Windows platforms this is reported as 0.0).
2261
2262 If -t is given, an additional -N<N> option can be given, where <N> must
2263 be an integer indicating how many times you want the script to run. The
2264 final timing report will include total and per run results.
2265
2266 For example (testing the script uniq_stable.py):
2267
2268 In [1]: run -t uniq_stable
2269
2270 IPython CPU timings (estimated):
2271 User : 0.19597 s.
2272 System: 0.0 s.
2273
2274 In [2]: run -t -N5 uniq_stable
2275
2276 IPython CPU timings (estimated):
2277 Total runs performed: 5
2278 Times : Total Per run
2279 User : 0.910862 s, 0.1821724 s.
2280 System: 0.0 s, 0.0 s.
2281
2282 -d: run your program under the control of pdb, the Python debugger. This
2283 allows you to execute your program step by step, watch variables, etc.
2284 Internally, what IPython does is similar to calling:
2285
2286 pdb.run('execfile("YOURFILENAME")')
2287
2288 with a breakpoint set on line 1 of your file. You can change the line
2289 number for this automatic breakpoint to be <N> by using the -bN option
2290 (where N must be an integer). For example:
2291
2292 %run -d -b40 myscript
2293
2294 will set the first breakpoint at line 40 in myscript.py. Note that the
2295 first breakpoint must be set on a line which actually does something
2296 (not a comment or docstring) for it to stop execution.
2297
2298 When the pdb debugger starts, you will see a (Pdb) prompt. You must
2299 first enter 'c' (without qoutes) to start execution up to the first
2300 breakpoint.
2301
2302 Entering 'help' gives information about the use of the debugger. You can
2303 easily see pdb's full documentation with "import pdb;pdb.help()" at a
2304 prompt.
2305
2306 -p: run program under the control of the Python profiler module (which
2307 prints a detailed report of execution times, function calls, etc).
2308
2309 You can pass other options after -p which affect the behavior of the
2310 profiler itself. See the docs for %prun for details.
2311
2312 In this mode, the program's variables do NOT propagate back to the
2313 IPython interactive namespace (because they remain in the namespace
2314 where the profiler executes them).
2315
2316 Internally this triggers a call to %prun, see its documentation for
2317 details on the options available specifically for profiling.
2318
2319 There is one special usage for which the text above doesn't apply: if
2320 the filename ends with .ipy, the file is run as ipython script, just as
2321 if the commands were written on IPython prompt.
2322
2323
2324 %runlog: Run files as logs.
2325
2326 Usage:
2327 %runlog file1 file2 ...
2328
2329 Run the named files (treating them as log files) in sequence inside the
2330 interpreter, and return to the prompt. This is much slower than %run
2331 because each line is executed in a try/except block, but it allows
2332 running files with syntax errors in them.
2333
2334 Normally IPython will guess when a file is one of its own logfiles, so
2335 you can typically use %run even for logs. This shorthand allows you to
2336 force any file to be treated as a log file.
2337
2338
2339 %save: Save a set of lines to a given filename.
2340
2341 Usage:
2342 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2343
2344 Options:
2345
2346 -r: use 'raw' input. By default, the 'processed' history is used, so
2347 that magics are loaded in their transformed version to valid Python. If
2348 this option is given, the raw input as typed as the command line is used
2349 instead.
2350
2351 This function uses the same syntax as %macro for line extraction, but
2352 instead of creating a macro it saves the resulting string to the
2353 filename you specify.
2354
2355 It adds a '.py' extension to the file if you don't do so yourself, and
2356 it asks for confirmation before overwriting existing files.
2357
2358
2359 %sc: Shell capture - execute a shell command and capture its output.
2360
2361 DEPRECATED. Suboptimal, retained for backwards compatibility.
2362
2363 You should use the form 'var = !command' instead. Example:
2364
2365 "%sc -l myfiles = ls " should now be written as
2366
2367 "myfiles = !ls "
2368
2369 myfiles.s, myfiles.l and myfiles.n still apply as documented below.
2370
2371 - %sc [options] varname=command
2372
2373 IPython will run the given command using commands.getoutput(), and will
2374 then update the user's interactive namespace with a variable called
2375 varname, containing the value of the call. Your command can contain
2376 shell wildcards, pipes, etc.
2377
2378 The '=' sign in the syntax is mandatory, and the variable name you
2379 supply must follow Python's standard conventions for valid names.
2380
2381 (A special format without variable name exists for internal use)
2382
2383 Options:
2384
2385 -l: list output. Split the output on newlines into a list before
2386 assigning it to the given variable. By default the output is stored as a
2387 single string.
2388
2389 -v: verbose. Print the contents of the variable.
2390
2391 In most cases you should not need to split as a list, because the
2392 returned value is a special type of string which can automatically
2393 provide its contents either as a list (split on newlines) or as a
2394 space-separated string. These are convenient, respectively, either for
2395 sequential processing or to be passed to a shell command.
2396
2397 For example:
2398
2399 # Capture into variable a In [9]: sc a=ls *py
2400
2401 # a is a string with embedded newlines In [10]: a Out[10]: 'setup.py
2402 win32_manual_post_install.py'
2403
2404 # which can be seen as a list: In [11]: a.l Out[11]: ['setup.py',
2405 'win32_manual_post_install.py']
2406
2407 # or as a whitespace-separated string: In [12]: a.s Out[12]: 'setup.py
2408 win32_manual_post_install.py'
2409
2410 # a.s is useful to pass as a single command line: In [13]: !wc -l $a.s
2411 146 setup.py 130 win32_manual_post_install.py 276 total
2412
2413 # while the list form is useful to loop over: In [14]: for f in a.l:
2414 ....: !wc -l $f ....: 146 setup.py 130 win32_manual_post_install.py
2415
2416 Similiarly, the lists returned by the -l option are also special, in the
2417 sense that you can equally invoke the .s attribute on them to
2418 automatically get a whitespace-separated string from their contents:
2419
2420 In [1]: sc -l b=ls *py
2421
2422 In [2]: b Out[2]: ['setup.py', 'win32_manual_post_install.py']
2423
2424 In [3]: b.s Out[3]: 'setup.py win32_manual_post_install.py'
2425
2426 In summary, both the lists and strings used for ouptut capture have the
2427 following special attributes:
2428
2429 .l (or .list) : value as list. .n (or .nlstr): value as
2430 newline-separated string. .s (or .spstr): value as space-separated string.
2431
2432
2433 %sx: Shell execute - run a shell command and capture its output.
2434
2435 %sx command
2436
2437 IPython will run the given command using commands.getoutput(), and
2438 return the result formatted as a list (split on '\n'). Since the output
2439 is _returned_, it will be stored in ipython's regular output cache
2440 Out[N] and in the '_N' automatic variables.
2441
2442 Notes:
2443
2444 1) If an input line begins with '!!', then %sx is automatically invoked.
2445 That is, while: !ls causes ipython to simply issue system('ls'), typing
2446 !!ls is a shorthand equivalent to: %sx ls
2447
2448 2) %sx differs from %sc in that %sx automatically splits into a list,
2449 like '%sc -l'. The reason for this is to make it as easy as possible to
2450 process line-oriented shell output via further python commands. %sc is
2451 meant to provide much finer control, but requires more typing.
2452
2453 3) Just like %sc -l, this is a list with special attributes:
2454
2455 .l (or .list) : value as list. .n (or .nlstr): value as
2456 newline-separated string. .s (or .spstr): value as whitespace-separated
2457 string.
2458
2459 This is very useful when trying to use such lists as arguments to system
2460 commands.
2461
2462
2463 %system_verbose: Set verbose printing of system calls.
2464
2465 If called without an argument, act as a toggle
2466
2467
2468 %time: Time execution of a Python statement or expression.
2469
2470 The CPU and wall clock times are printed, and the value of the
2471 expression (if any) is returned. Note that under Win32, system time is
2472 always reported as 0, since it can not be measured.
2473
2474 This function provides very basic timing functionality. In Python 2.3,
2475 the timeit module offers more control and sophistication, so this could
2476 be rewritten to use it (patches welcome).
2477
2478 Some examples:
2479
2480 In [1]: time 2**128 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2481 Wall time: 0.00 Out[1]: 340282366920938463463374607431768211456L
2482
2483 In [2]: n = 1000000
2484
2485 In [3]: time sum(range(n)) CPU times: user 1.20 s, sys: 0.05 s, total:
2486 1.25 s Wall time: 1.37 Out[3]: 499999500000L
2487
2488 In [4]: time print 'hello world' hello world CPU times: user 0.00 s,
2489 sys: 0.00 s, total: 0.00 s Wall time: 0.00
2490
2491 Note that the time needed by Python to compile the given expression will
2492 be reported if it is more than 0.1s. In this example, the actual
2493 exponentiation is done by Python at compilation time, so while the
2494 expression can take a noticeable amount of time to compute, that time is
2495 purely due to the compilation:
2496
2497 In [5]: time 3**9999; CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2498 Wall time: 0.00 s
2499
2500 In [6]: time 3**999999; CPU times: user 0.00 s, sys: 0.00 s, total: 0.00
2501 s Wall time: 0.00 s Compiler : 0.78 s
2502
1256
1257 Interactive use
1258 ===============
2503
1259
2504 %timeit: Time execution of a Python statement or expression
1260 Warning: IPython relies on the existence of a global variable called
1261 __IP which controls the shell itself. If you redefine __IP to anything,
1262 bizarre behavior will quickly occur.
2505
1263
2506 Usage:
1264 Other than the above warning, IPython is meant to work as a drop-in
2507 %timeit [-n<N> -r<R> [-t|-c]] statement
1265 replacement for the standard interactive interpreter. As such, any code
1266 which is valid python should execute normally under IPython (cases where
1267 this is not true should be reported as bugs). It does, however, offer
1268 many features which are not available at a standard python prompt. What
1269 follows is a list of these.
2508
1270
2509 Time execution of a Python statement or expression using the timeit module.
2510
1271
2511 Options: -n<N>: execute the given statement <N> times in a loop. If this
1272 Caution for Windows users
2512 value is not given, a fitting value is chosen.
1273 -------------------------
2513
1274
2514 -r<R>: repeat the loop iteration <R> times and take the best result.
1275 Windows, unfortunately, uses the '\' character as a path separator. This
2515 Default: 3
1276 is a terrible choice, because '\' also represents the escape character
1277 in most modern programming languages, including Python. For this reason,
1278 issuing many of the commands discussed below (especially magics which
1279 affect the filesystem) with '\' in them will cause strange errors.
2516
1280
2517 -t: use time.time to measure the time, which is the default on Unix.
1281 A partial solution is to use instead the '/' character as a path
2518 This function measures wall time.
1282 separator, which Windows recognizes in most situations. However, in
1283 Windows commands '/' flags options, so you can not use it for the root
1284 directory. This means that paths beginning at the root must be typed in
1285 a contrived manner like:
1286 %copy \opt/foo/bar.txt \tmp
2519
1287
2520 -c: use time.clock to measure the time, which is the default on Windows
1288 There is no sensible thing IPython can do to truly work around this flaw
2521 and measures wall time. On Unix, resource.getrusage is used instead and
1289 in Windows^3 <footnode.html#foot878>.
2522 returns the CPU user time.
2523
1290
2524 -p<P>: use a precision of <P> digits to display the timing result.
2525 Default: 3
2526
1291
2527 Examples:
2528 In [1]: %timeit pass 10000000 loops, best of 3: 53.3 ns per loop
2529
1292
2530 In [2]: u = None
1293 Magic command system
1294 --------------------
2531
1295
2532 In [3]: %timeit u is None 10000000 loops, best of 3: 184 ns per loop
1296 IPython will treat any line whose first character is a % as a special
1297 call to a 'magic' function. These allow you to control the behavior of
1298 IPython itself, plus a lot of system-type features. They are all
1299 prefixed with a % character, but parameters are given without
1300 parentheses or quotes.
2533
1301
2534 In [4]: %timeit -r 4 u == None 1000000 loops, best of 4: 242 ns per loop
1302 Example: typing '%cd mydir' (without the quotes) changes you working
1303 directory to 'mydir', if it exists.
2535
1304
2536 In [5]: import time
1305 If you have 'automagic' enabled (in your ipythonrc file, via the command
1306 line option -automagic or with the %automagic function), you don't need
1307 to type in the % explicitly. IPython will scan its internal list of
1308 magic functions and call one if it exists. With automagic on you can
1309 then just type 'cd mydir' to go to directory 'mydir'. The automagic
1310 system has the lowest possible precedence in name searches, so defining
1311 an identifier with the same name as an existing magic function will
1312 shadow it for automagic use. You can still access the shadowed magic
1313 function by explicitly using the % character at the beginning of the line.
2537
1314
2538 In [6]: %timeit -n1 time.sleep(2) 1 loops, best of 3: 2 s per loop
1315 An example (with automagic on) should clarify all this::
2539
1316
2540 The times reported by %timeit will be slightly higher than those
1317 In [1]: cd ipython # %cd is called by automagic
2541 reported by the timeit.py script when variables are accessed. This is
2542 due to the fact that %timeit executes the statement in the namespace of
2543 the shell, compared with timeit.py, which uses a single setup statement
2544 to import function or create variables. Generally, the bias does not
2545 matter as long as results from timeit.py are not mixed with those from
2546 %timeit.
2547
1318
1319 /home/fperez/ipython
2548
1320
2549 %unalias: Remove an alias
1321 In [2]: cd=1 # now cd is just a variable
2550
1322
1323 In [3]: cd .. # and doesn't work as a function anymore
2551
1324
2552 %upgrade: Upgrade your IPython installation
1325 ------------------------------
2553
1326
2554 This will copy the config files that don't yet exist in your ipython dir
1327 File "<console>", line 1
2555 from the system config dir. Use this after upgrading IPython if you
2556 don't wish to delete your .ipython dir.
2557
1328
2558 Call with -nolegacy to get rid of ipythonrc* files (recommended for new
1329 cd ..
2559 users)
2560
1330
1331 ^
2561
1332
2562 %who: Print all interactive variables, with some minimal formatting.
1333 SyntaxError: invalid syntax
2563
1334
2564 If any arguments are given, only variables whose type matches one of
1335 In [4]: %cd .. # but %cd always works
2565 these are printed. For example:
2566
1336
2567 %who function str
1337 /home/fperez
2568
1338
2569 will only list functions and strings, excluding all other types of
1339 In [5]: del cd # if you remove the cd variable
2570 variables. To find the proper type names, simply use type(var) at a
2571 command line to see how python prints type names. For example:
2572
1340
2573 In [1]: type('hello')
1341 In [6]: cd ipython # automagic can work again
2574 Out[1]: <type 'str'>
2575
1342
2576 indicates that the type name for strings is 'str'.
1343 /home/fperez/ipython
2577
1344
2578 %who always excludes executed names loaded through your configuration
1345 You can define your own magic functions to extend the system. The
2579 file and things which are internal to IPython.
1346 following example defines a new magic command, %impall::
2580
1347
2581 This is deliberate, as typically you may load many modules and the
1348 import IPython.ipapi
2582 purpose of %who is to show you only what you've manually defined.
2583
1349
1350 ip = IPython.ipapi.get()
2584
1351
2585 %who_ls: Return a sorted list of all interactive variables.
1352 def doimp(self, arg):
2586
1353
2587 If arguments are given, only variables of types matching these arguments
1354 ip = self.api
2588 are returned.
2589
1355
1356 ip.ex("import %s; reload(%s); from %s import *" % (
2590
1357
2591 %whos: Like %who, but gives some extra information about each variable.
1358 arg,arg,arg)
2592
1359
2593 The same type filtering of %who can be applied here.
1360 )
2594
1361
2595 For all variables, the type is printed. Additionally it prints:
1362 ip.expose_magic('impall', doimp)
2596
1363
2597 - For ,[],(): their length.
1364 You can also define your own aliased names for magic functions. In your
1365 ipythonrc file, placing a line like:
2598
1366
2599 - For numpy and Numeric arrays, a summary with shape, number of
1367 execute __IP.magic_cl = __IP.magic_clear
2600 elements, typecode and size in memory.
2601
1368
2602 - Everything else: a string representation, snipping their middle if too
1369 will define %cl as a new name for %clear.
2603 long.
2604
1370
1371 Type %magic for more information, including a list of all available
1372 magic functions at any time and their docstrings. You can also type
1373 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
1374 information on the '?' system) to get information about any particular
1375 magic function you are interested in.
2605
1376
2606 %xmode: Switch modes for the exception handlers.
2607
1377
2608 Valid modes: Plain, Context and Verbose.
1378 Magic commands
1379 --------------
2609
1380
2610 If called without arguments, acts as a toggle.
1381 The rest of this section is automatically generated for each release
1382 from the docstrings in the IPython code. Therefore the formatting is
1383 somewhat minimal, but this method has the advantage of having
1384 information always in sync with the code.
2611
1385
1386 A list of all the magic commands available in IPython's default
1387 installation follows. This is similar to what you'll see by simply
1388 typing %magic at the prompt, but that will also give you information
1389 about magic commands you may have added as part of your personal
1390 customizations.
2612
1391
2613 Access to the standard Python help
1392 ::
1393
1394 %Exit: Exit IPython without confirmation.
1395
1396
1397 %Pprint: Toggle pretty printing on/off.
1398
1399
1400 %alias: Define an alias for a system command.
1401
1402 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1403
1404 Then, typing 'alias_name params' will execute the system command 'cmd
1405 params' (from your underlying operating system).
1406
1407 Aliases have lower precedence than magic functions and Python normal
1408 variables, so if 'foo' is both a Python variable and an alias, the alias
1409 can not be executed until 'del foo' removes the Python variable.
1410
1411 You can use the %l specifier in an alias definition to represent the
1412 whole line when the alias is called. For example:
1413
1414 In [2]: alias all echo "Input in brackets: <%l>"
1415 In [3]: all hello world
1416 Input in brackets: <hello world>
1417
1418 You can also define aliases with parameters using %s specifiers (one per
1419 parameter):
1420
1421 In [1]: alias parts echo first %s second %s
1422 In [2]: %parts A B
1423 first A second B
1424 In [3]: %parts A
1425 Incorrect number of arguments: 2 expected.
1426 parts is an alias to: 'echo first %s second %s'
1427
1428 Note that %l and %s are mutually exclusive. You can only use one or the
1429 other in your aliases.
1430
1431 Aliases expand Python variables just like system calls using ! or !! do:
1432 all expressions prefixed with '$' get expanded. For details of the
1433 semantic rules, see PEP-215: http://www.python.org/peps/pep-0215.html.
1434 This is the library used by IPython for variable expansion. If you want
1435 to access a true shell variable, an extra $ is necessary to prevent its
1436 expansion by IPython:
1437
1438 In [6]: alias show echo
1439 In [7]: PATH='A Python string'
1440 In [8]: show $PATH
1441 A Python string
1442 In [9]: show $$PATH
1443 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1444
1445 You can use the alias facility to acess all of $PATH. See the %rehash
1446 and %rehashx functions, which automatically create aliases for the
1447 contents of your $PATH.
1448
1449 If called with no parameters, %alias prints the current alias table.
1450
1451
1452 %autocall: Make functions callable without having to type parentheses.
1453
1454 Usage:
1455
1456 %autocall [mode]
1457
1458 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
1459 value is toggled on and off (remembering the previous state).
1460
1461 In more detail, these values mean:
1462
1463 0 -> fully disabled
1464
1465 1 -> active, but do not apply if there are no arguments on the line.
1466
1467 In this mode, you get:
1468
1469 In [1]: callable Out[1]: <built-in function callable>
1470
1471 In [2]: callable 'hello' ---> callable('hello') Out[2]: False
1472
1473 2 -> Active always. Even if no arguments are present, the callable
1474 object is called:
1475
1476 In [4]: callable ---> callable()
1477
1478 Note that even with autocall off, you can still use '/' at the start of
1479 a line to treat the first argument on the command line as a function and
1480 add parentheses to it:
1481
1482 In [8]: /str 43 ---> str(43) Out[8]: '43'
1483
1484
1485 %autoindent: Toggle autoindent on/off (if available).
1486
1487
1488 %automagic: Make magic functions callable without having to type the
1489 initial %.
1490
1491 Without argumentsl toggles on/off (when off, you must call it as
1492 %automagic, of course). With arguments it sets the value, and you can
1493 use any of (case insensitive):
1494
1495 - on,1,True: to activate
1496
1497 - off,0,False: to deactivate.
1498
1499 Note that magic functions have lowest priority, so if there's a variable
1500 whose name collides with that of a magic fn, automagic won't work for
1501 that function (you get the variable instead). However, if you delete the
1502 variable (del var), the previously shadowed magic function becomes
1503 visible to automagic again.
1504
1505
1506 %bg: Run a job in the background, in a separate thread.
1507
1508 For example,
1509
1510 %bg myfunc(x,y,z=1)
1511
1512 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
1513 execution starts, a message will be printed indicating the job number.
1514 If your job number is 5, you can use
1515
1516 myvar = jobs.result(5) or myvar = jobs[5].result
1517
1518 to assign this result to variable 'myvar'.
1519
1520 IPython has a job manager, accessible via the 'jobs' object. You can
1521 type jobs? to get more information about it, and use jobs.<TAB> to see
1522 its attributes. All attributes not starting with an underscore are meant
1523 for public use.
1524
1525 In particular, look at the jobs.new() method, which is used to create
1526 new jobs. This magic %bg function is just a convenience wrapper around
1527 jobs.new(), for expression-based jobs. If you want to create a new job
1528 with an explicit function object and arguments, you must call jobs.new()
1529 directly.
1530
1531 The jobs.new docstring also describes in detail several important
1532 caveats associated with a thread-based model for background job
1533 execution. Type jobs.new? for details.
1534
1535 You can check the status of all jobs with jobs.status().
1536
1537 The jobs variable is set by IPython into the Python builtin namespace.
1538 If you ever declare a variable named 'jobs', you will shadow this name.
1539 You can either delete your global jobs variable to regain access to the
1540 job manager, or make a new name and assign it manually to the manager
1541 (stored in IPython's namespace). For example, to assign the job manager
1542 to the Jobs name, use:
1543
1544 Jobs = __builtins__.jobs
1545
1546
1547 %bookmark: Manage IPython's bookmark system.
1548
1549 %bookmark <name> - set bookmark to current dir %bookmark <name> <dir> -
1550 set bookmark to <dir> %bookmark -l - list all bookmarks %bookmark -d
1551 <name> - remove bookmark %bookmark -r - remove all bookmarks
1552
1553 You can later on access a bookmarked folder with: %cd -b <name> or
1554 simply '%cd <name>' if there is no directory called <name> AND there is
1555 such a bookmark defined.
1556
1557 Your bookmarks persist through IPython sessions, but they are associated
1558 with each profile.
1559
1560
1561 %cd: Change the current working directory.
1562
1563 This command automatically maintains an internal list of directories you
1564 visit during your IPython session, in the variable _dh. The command
1565 %dhist shows this history nicely formatted. You can also do 'cd -<tab>'
1566 to see directory history conveniently.
1567
1568 Usage:
1569
1570 cd 'dir': changes to directory 'dir'.
1571
1572 cd -: changes to the last visited directory.
1573
1574 cd -<n>: changes to the n-th directory in the directory history.
1575
1576 cd -b <bookmark_name>: jump to a bookmark set by %bookmark (note: cd
1577 <bookmark_name> is enough if there is no directory <bookmark_name>, but
1578 a bookmark with the name exists.) 'cd -b <tab>' allows you to
1579 tab-complete bookmark names.
1580
1581 Options:
1582
1583 -q: quiet. Do not print the working directory after the cd command is
1584 executed. By default IPython's cd command does print this directory,
1585 since the default prompts do not display path information.
1586
1587 Note that !cd doesn't work for this purpose because the shell where
1588 !command runs is immediately discarded after executing 'command'.
1589
1590
1591 %color_info: Toggle color_info.
1592
1593 The color_info configuration parameter controls whether colors are used
1594 for displaying object details (by things like %psource, %pfile or the
1595 '?' system). This function toggles this value with each call.
1596
1597 Note that unless you have a fairly recent pager (less works better than
1598 more) in your system, using colored object information displays will not
1599 work properly. Test it and see.
1600
1601
1602 %colors: Switch color scheme for prompts, info system and exception
1603 handlers.
1604
1605 Currently implemented schemes: NoColor, Linux, LightBG.
1606
1607 Color scheme names are not case-sensitive.
1608
1609
1610 %cpaste: Allows you to paste & execute a pre-formatted code block from
1611 clipboard
1612
1613 You must terminate the block with '-' (two minus-signs) alone on the
1614 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
1615 is the new sentinel for this operation)
1616
1617 The block is dedented prior to execution to enable execution of method
1618 definitions. '>' and '+' characters at the beginning of a line are
1619 ignored, to allow pasting directly from e-mails or diff files. The
1620 executed block is also assigned to variable named 'pasted_block' for
1621 later editing with '%edit pasted_block'.
1622
1623 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
1624 This assigns the pasted block to variable 'foo' as string, without
1625 dedenting or executing it.
1626
1627 Do not be alarmed by garbled output on Windows (it's a readline bug).
1628 Just press enter and type - (and press enter again) and the block will
1629 be what was just pasted.
1630
1631 IPython statements (magics, shell escapes) are not supported (yet).
1632
1633
1634 %debug: Activate the interactive debugger in post-mortem mode.
1635
1636 If an exception has just occurred, this lets you inspect its stack
1637 frames interactively. Note that this will always work only on the last
1638 traceback that occurred, so you must call this quickly after an
1639 exception that you wish to inspect has fired, because if another one
1640 occurs, it clobbers the previous one.
1641
1642 If you want IPython to automatically do this on every exception, see the
1643 %pdb magic for more details.
1644
1645
1646 %dhist: Print your history of visited directories.
1647
1648 %dhist -> print full history
1649 %dhist n -> print last n entries only
1650 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)
1651
1652 This history is automatically maintained by the %cd command, and always
1653 available as the global list variable _dh. You can use %cd -<n> to go to
1654 directory number <n>.
1655
1656 Note that most of time, you should view directory history by entering cd
1657 -<TAB>.
1658
1659
1660 %dirs: Return the current directory stack.
1661
1662
1663 %doctest_mode: Toggle doctest mode on and off.
1664
1665 This mode allows you to toggle the prompt behavior between normal
1666 IPython prompts and ones that are as similar to the default IPython
1667 interpreter as possible.
1668
1669 It also supports the pasting of code snippets that have leading 'Β»>' and
1670 '...' prompts in them. This means that you can paste doctests from files
1671 or docstrings (even if they have leading whitespace), and the code will
1672 execute correctly. You can then use '%history -tn' to see the translated
1673 history without line numbers; this will give you the input after removal
1674 of all the leading prompts and whitespace, which can be pasted back into
1675 an editor.
1676
1677 With these features, you can switch into this mode easily whenever you
1678 need to do testing and changes to doctests, without having to leave your
1679 existing IPython session.
1680
1681
1682 %ed: Alias to %edit.
1683
1684
1685 %edit: Bring up an editor and execute the resulting code.
1686
1687 Usage: %edit [options] [args]
1688
1689 %edit runs IPython's editor hook. The default version of this hook is
1690 set to call the __IPYTHON__.rc.editor command. This is read from your
1691 environment variable $EDITOR. If this isn't found, it will default to vi
1692 under Linux/Unix and to notepad under Windows. See the end of this
1693 docstring for how to change the editor hook.
1694
1695 You can also set the value of this editor via the command line option
1696 '-editor' or in your ipythonrc file. This is useful if you wish to use
1697 specifically for IPython an editor different from your typical default
1698 (and for Windows users who typically don't set environment variables).
1699
1700 This command allows you to conveniently edit multi-line code right in
1701 your IPython session.
1702
1703 If called without arguments, %edit opens up an empty editor with a
1704 temporary file and will execute the contents of this file when you close
1705 it (don't forget to save it!).
1706
1707 Options:
1708
1709 -n <number>: open the editor at a specified line number. By default, the
1710 IPython editor hook uses the unix syntax 'editor +N filename', but you
1711 can configure this by providing your own modified hook if your favorite
1712 editor supports line-number specifications with a different syntax.
1713
1714 -p: this will call the editor with the same data as the previous time it
1715 was used, regardless of how long ago (in your current session) it was.
1716
1717 -r: use 'raw' input. This option only applies to input taken from the
1718 user's history. By default, the 'processed' history is used, so that
1719 magics are loaded in their transformed version to valid Python. If this
1720 option is given, the raw input as typed as the command line is used
1721 instead. When you exit the editor, it will be executed by IPython's own
1722 processor.
1723
1724 -x: do not execute the edited code immediately upon exit. This is mainly
1725 useful if you are editing programs which need to be called with command
1726 line arguments, which you can then do using %run.
1727
1728 Arguments:
1729
1730 If arguments are given, the following possibilites exist:
1731
1732 - The arguments are numbers or pairs of dash-separated numbers (like 1
1733 4-8 9). These are interpreted as lines of previous input to be loaded
1734 into the editor. The syntax is the same of the %macro command.
1735
1736 - If the argument doesn't start with a number, it is evaluated as a
1737 variable and its contents loaded into the editor. You can thus edit any
1738 string which contains python code (including the result of previous edits).
1739
1740 - If the argument is the name of an object (other than a string),
1741 IPython will try to locate the file where it was defined and open the
1742 editor at the point where it is defined. You can use '%edit function' to
1743 load an editor exactly at the point where 'function' is defined, edit it
1744 and have the file be executed automatically.
1745
1746 If the object is a macro (see %macro for details), this opens up your
1747 specified editor with a temporary file containing the macro's data. Upon
1748 exit, the macro is reloaded with the contents of the file.
1749
1750 Note: opening at an exact line is only supported under Unix, and some
1751 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1752 '+NUMBER' parameter necessary for this feature. Good editors like
1753 (X)Emacs, vi, jed, pico and joe all do.
1754
1755 If the argument is not found as a variable, IPython will look for a
1756 file with that name (adding .py if necessary) and load it into the
1757 editor. It will execute its contents with execfile() when you exit,
1758 loading any code in the file into your interactive namespace.
1759
1760 After executing your code, %edit will return as output the code you
1761 typed in the editor (except when it was an existing file). This way you
1762 can reload the code in further invocations of %edit as a variable, via
1763 _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of the
1764 output.
1765
1766 Note that %edit is also available through the alias %ed.
1767
1768 This is an example of creating a simple function inside the editor and
1769 then modifying it. First, start up the editor::
1770
1771 In [1]: ed
1772 Editing... done. Executing edited code...
1773 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
1774
1775 We can then call the function foo():
1776
1777 In [2]: foo()
1778 foo() was defined in an editing session
1779
1780 Now we edit foo. IPython automatically loads the editor with the
1781 (temporary) file where foo() was previously defined:
1782
1783 In [3]: ed foo
1784 Editing... done. Executing edited code...
1785
1786 And if we call foo() again we get the modified version:
1787
1788 In [4]: foo()
1789 foo() has now been changed!
1790
1791 Here is an example of how to edit a code snippet successive times. First
1792 we call the editor:
1793
1794 In [8]: ed
1795 Editing... done. Executing edited code...
1796 hello
1797 Out[8]: "print 'hello'\n"
1798
1799 Now we call it again with the previous output (stored in _):
1800
1801 In [9]: ed _
1802 Editing... done. Executing edited code...
1803 hello world
1804 Out[9]: "print 'hello world'\n"
1805
1806 Now we call it with the output #8 (stored in _8, also as Out[8]):
1807
1808 In [10]: ed _8
1809 Editing... done. Executing edited code...
1810 hello again
1811 Out[10]: "print 'hello again'\n"
1812
1813 Changing the default editor hook:
1814
1815 If you wish to write your own editor hook, you can put it in a
1816 configuration file which you load at startup time. The default hook is
1817 defined in the IPython.hooks module, and you can use that as a starting
1818 example for further modifications. That file also has general
1819 instructions on how to set a new hook for use once you've defined it.
1820
1821
1822 %env: List environment variables.
1823
1824
1825 %exit: Exit IPython, confirming if configured to do so.
1826
1827 You can configure whether IPython asks for confirmation upon exit by
1828 setting the confirm_exit flag in the ipythonrc file.
1829
1830
1831 %logoff: Temporarily stop logging.
1832
1833 You must have previously started logging.
1834
1835
1836 %logon: Restart logging.
1837
1838 This function is for restarting logging which you've temporarily stopped
1839 with %logoff. For starting logging for the first time, you must use the
1840 %logstart function, which allows you to specify an optional log filename.
1841
1842
1843 %logstart: Start logging anywhere in a session.
1844
1845 %logstart [-o|-r|-t] [log_name [log_mode]]
1846
1847 If no name is given, it defaults to a file named 'ipython_log.py' in
1848 your current directory, in 'rotate' mode (see below).
1849
1850 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1851 history up to that point and then continues logging.
1852
1853 %logstart takes a second optional parameter: logging mode. This can be
1854 one of (note that the modes are given unquoted):
1855 append: well, that says it.
1856 backup: rename (if exists) to name and start name.
1857 global: single logfile in your home dir, appended to.
1858 over : overwrite existing log.
1859 rotate: create rotating logs name.1 , name.2 , etc.
1860
1861 Options:
1862
1863 -o: log also IPython's output. In this mode, all commands which generate
1864 an Out[NN] prompt are recorded to the logfile, right after their
1865 corresponding input line. The output lines are always prepended with a
1866 '#[Out]# ' marker, so that the log remains valid Python code.
1867
1868 Since this marker is always the same, filtering only the output from a
1869 log is very easy, using for example a simple awk call:
1870
1871 awk -F'#
1872
1873 \begin{displaymath}Out\end{displaymath}
1874
1875 # ' 'if($2) print $2' ipython_log.py
1876
1877 -r: log 'raw' input. Normally, IPython's logs contain the processed
1878 input, so that user lines are logged in their final form, converted into
1879 valid Python. For example, %Exit is logged as '_ip.magic("Exit"). If the
1880 -r flag is given, all input is logged exactly as typed, with no
1881 transformations applied.
1882
1883 -t: put timestamps before each input line logged (these are put in
1884 comments).
1885
1886
1887 %logstate: Print the status of the logging system.
1888
1889
1890 %logstop: Fully stop logging and close log file.
1891
1892 In order to start logging again, a new %logstart call needs to be made,
1893 possibly (though not necessarily) with a new filename, mode and other
1894 options.
1895
1896
1897 %lsmagic: List currently available magic functions.
1898
1899
1900 %macro: Define a set of input lines as a macro for future re-execution.
1901
1902 Usage:
1903 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1904
1905 Options:
1906
1907 -r: use 'raw' input. By default, the 'processed' history is used, so
1908 that magics are loaded in their transformed version to valid Python. If
1909 this option is given, the raw input as typed as the command line is used
1910 instead.
1911
1912 This will define a global variable called 'name' which is a string made
1913 of joining the slices and lines you specify (n1,n2,... numbers above)
1914 from your input history into a single string. This variable acts like an
1915 automatic function which re-executes those lines as if you had typed
1916 them. You just type 'name' at the prompt and the code executes.
1917
1918 The notation for indicating number ranges is: n1-n2 means 'use line
1919 numbers n1,...n2' (the endpoint is included). That is, '5-7' means using
1920 the lines numbered 5,6 and 7.
1921
1922 Note: as a 'hidden' feature, you can also use traditional python slice
1923 notation, where N:M means numbers N through M-1.
1924
1925 For example, if your history contains (%hist prints it):
1926
1927 44: x=1
1928 45: y=3
1929 46: z=x+y
1930 47: print x
1931 48: a=5
1932 49: print 'x',x,'y',y
1933
1934 you can create a macro with lines 44 through 47 (included) and line 49
1935 called my_macro with:
1936
1937 In [51]: %macro my_macro 44-47 49
1938
1939 Now, typing 'my_macro' (without quotes) will re-execute all this code in
1940 one pass.
1941
1942 You don't need to give the line-numbers in order, and any given line
1943 number can appear multiple times. You can assemble macros with any lines
1944 from your input history in any order.
1945
1946 The macro is a simple object which holds its value in an attribute, but
1947 IPython's display system checks for macros and executes them as code
1948 instead of printing them when you type their name.
1949
1950 You can view a macro's contents by explicitly printing it with:
1951
1952 'print macro_name'.
1953
1954 For one-off cases which DON'T contain magic function calls in them you
1955 can obtain similar results by explicitly executing slices from your
1956 input history with:
1957
1958 In [60]: exec In[44:48]+In[49]
1959
1960
1961 %magic: Print information about the magic function system.
1962
1963
1964 %page: Pretty print the object and display it through a pager.
1965
1966 %page [options] OBJECT
1967
1968 If no object is given, use _ (last output).
1969
1970 Options:
1971
1972 -r: page str(object), don't pretty-print it.
1973
1974
1975 %pdb: Control the automatic calling of the pdb interactive debugger.
1976
1977 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1978 argument it works as a toggle.
1979
1980 When an exception is triggered, IPython can optionally call the
1981 interactive pdb debugger after the traceback printout. %pdb toggles this
1982 feature on and off.
1983
1984 The initial state of this feature is set in your ipythonrc configuration
1985 file (the variable is called 'pdb').
1986
1987 If you want to just activate the debugger AFTER an exception has fired,
1988 without having to type '%pdb on' and rerunning your code, you can use
1989 the %debug magic.
1990
1991
1992 %pdef: Print the definition header for any callable object.
1993
1994 If the object is a class, print the constructor information.
1995
1996
1997 %pdoc: Print the docstring for an object.
1998
1999 If the given object is a class, it will print both the class and the
2000 constructor docstrings.
2001
2002
2003 %pfile: Print (or run through pager) the file where an object is defined.
2004
2005 The file opens at the line where the object definition begins. IPython
2006 will honor the environment variable PAGER if set, and otherwise will do
2007 its best to print the file in a convenient form.
2008
2009 If the given argument is not an object currently defined, IPython will
2010 try to interpret it as a filename (automatically adding a .py extension
2011 if needed). You can thus use %pfile as a syntax highlighting code viewer.
2012
2013
2014 %pinfo: Provide detailed information about an object.
2015
2016 '%pinfo object' is just a synonym for object? or ?object.
2017
2018
2019 %popd: Change to directory popped off the top of the stack.
2020
2021
2022 %profile: Print your currently active IPyhton profile.
2023
2024
2025 %prun: Run a statement through the python code profiler.
2026
2027 Usage:
2028 %prun [options] statement
2029
2030 The given statement (which doesn't require quote marks) is run via the
2031 python profiler in a manner similar to the profile.run() function.
2032 Namespaces are internally managed to work correctly; profile.run cannot
2033 be used in IPython because it makes certain assumptions about namespaces
2034 which do not hold under IPython.
2035
2036 Options:
2037
2038 -l <limit>: you can place restrictions on what or how much of the
2039 profile gets printed. The limit value can be:
2040
2041 * A string: only information for function names containing this string
2042 is printed.
2043
2044 * An integer: only these many lines are printed.
2045
2046 * A float (between 0 and 1): this fraction of the report is printed (for
2047 example, use a limit of 0.4 to see the topmost 40% only).
2048
2049 You can combine several limits with repeated use of the option. For
2050 example, '-l __init__ -l 5' will print only the topmost 5 lines of
2051 information about class constructors.
2052
2053 -r: return the pstats.Stats object generated by the profiling. This
2054 object has all the information about the profile in it, and you can
2055 later use it for further analysis or in other functions.
2056
2057 -s <key>: sort profile by given key. You can provide more than one key
2058 by using the option several times: '-s key1 -s key2 -s key3...'. The
2059 default sorting key is 'time'.
2060
2061 The following is copied verbatim from the profile documentation
2062 referenced below:
2063
2064 When more than one key is provided, additional keys are used as
2065 secondary criteria when the there is equality in all keys selected
2066 before them.
2067
2068 Abbreviations can be used for any key names, as long as the abbreviation
2069 is unambiguous. The following are the keys currently defined:
2070
2071 Valid Arg Meaning
2072 "calls" call count
2073 "cumulative" cumulative time
2074 "file" file name
2075 "module" file name
2076 "pcalls" primitive call count
2077 "line" line number
2078 "name" function name
2079 "nfl" name/file/line
2080 "stdname" standard name
2081 "time" internal time
2082
2083 Note that all sorts on statistics are in descending order (placing most
2084 time consuming items first), where as name, file, and line number
2085 searches are in ascending order (i.e., alphabetical). The subtle
2086 distinction between "nfl" and "stdname" is that the standard name is a
2087 sort of the name as printed, which means that the embedded line numbers
2088 get compared in an odd way. For example, lines 3, 20, and 40 would (if
2089 the file names were the same) appear in the string order "20" "3" and
2090 "40". In contrast, "nfl" does a numeric compare of the line numbers. In
2091 fact, sort_stats("nfl") is the same as sort_stats("name", "file", "line").
2092
2093 -T <filename>: save profile results as shown on screen to a text file.
2094 The profile is still shown on screen.
2095
2096 -D <filename>: save (via dump_stats) profile statistics to given
2097 filename. This data is in a format understod by the pstats module, and
2098 is generated by a call to the dump_stats() method of profile objects.
2099 The profile is still shown on screen.
2100
2101 If you want to run complete programs under the profiler's control, use
2102 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
2103 contains profiler specific options as described here.
2104
2105 You can read the complete documentation for the profile module with:
2106 In [1]: import profile; profile.help()
2107
2108
2109 %psearch: Search for object in namespaces by wildcard.
2110
2111 %psearch [options] PATTERN [OBJECT TYPE]
2112
2113 Note: ? can be used as a synonym for %psearch, at the beginning or at
2114 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
2115 rest of the command line must be unchanged (options come first), so for
2116 example the following forms are equivalent
2117
2118 %psearch -i a* function -i a* function? ?-i a* function
2119
2120 Arguments:
2121
2122 PATTERN
2123
2124 where PATTERN is a string containing * as a wildcard similar to its use
2125 in a shell. The pattern is matched in all namespaces on the search path.
2126 By default objects starting with a single _ are not matched, many
2127 IPython generated objects have a single underscore. The default is case
2128 insensitive matching. Matching is also done on the attributes of objects
2129 and not only on the objects in a module.
2130
2131 [OBJECT TYPE]
2132
2133 Is the name of a python type from the types module. The name is given in
2134 lowercase without the ending type, ex. StringType is written string. By
2135 adding a type here only objects matching the given type are matched.
2136 Using all here makes the pattern match all types (this is the default).
2137
2138 Options:
2139
2140 -a: makes the pattern match even objects whose names start with a single
2141 underscore. These names are normally ommitted from the search.
2142
2143 -i/-c: make the pattern case insensitive/sensitive. If neither of these
2144 options is given, the default is read from your ipythonrc file. The
2145 option name which sets this value is 'wildcards_case_sensitive'. If this
2146 option is not specified in your ipythonrc file, IPython's internal
2147 default is to do a case sensitive search.
2148
2149 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
2150 specifiy can be searched in any of the following namespaces: 'builtin',
2151 'user', 'user_global','internal', 'alias', where 'builtin' and 'user'
2152 are the search defaults. Note that you should not use quotes when
2153 specifying namespaces.
2154
2155 'Builtin' contains the python module builtin, 'user' contains all user
2156 data, 'alias' only contain the shell aliases and no python objects,
2157 'internal' contains objects used by IPython. The 'user_global' namespace
2158 is only used by embedded IPython instances, and it contains module-level
2159 globals. You can add namespaces to the search with -s or exclude them
2160 with -e (these options can be given more than once).
2161
2162 Examples:
2163
2164 %psearch a* -> objects beginning with an a %psearch -e builtin a* ->
2165 objects NOT in the builtin space starting in a %psearch a* function ->
2166 all functions beginning with an a %psearch re.e* -> objects beginning
2167 with an e in module re %psearch r*.e* -> objects that start with e in
2168 modules starting in r %psearch r*.* string -> all strings in modules
2169 beginning with r
2170
2171 Case sensitve search:
2172
2173 %psearch -c a* list all object beginning with lower case a
2174
2175 Show objects beginning with a single _:
2176
2177 %psearch -a _* list objects beginning with a single underscore
2178
2179
2180 %psource: Print (or run through pager) the source code for an object.
2181
2182
2183 %pushd: Place the current dir on stack and change directory.
2184
2185 Usage:
2186 %pushd ['dirname']
2187
2188
2189 %pwd: Return the current working directory path.
2190
2191
2192 %pycat: Show a syntax-highlighted file through a pager.
2193
2194 This magic is similar to the cat utility, but it will assume the file to
2195 be Python source and will show it with syntax highlighting.
2196
2197
2198 %quickref: Show a quick reference sheet
2199
2200
2201 %quit: Exit IPython, confirming if configured to do so (like %exit)
2202
2203
2204 %r: Repeat previous input.
2205
2206 Note: Consider using the more powerfull %rep instead!
2207
2208 If given an argument, repeats the previous command which starts with the
2209 same string, otherwise it just repeats the previous input.
2210
2211 Shell escaped commands (with ! as first character) are not recognized by
2212 this system, only pure python code and magic commands.
2213
2214
2215 %rehashx: Update the alias table with all executable files in $PATH.
2216
2217 This version explicitly checks that every entry in $PATH is a file with
2218 execute access (os.X_OK), so it is much slower than %rehash.
2219
2220 Under Windows, it checks executability as a match agains a ``|``-separated
2221 string of extensions, stored in the IPython config variable
2222 win_exec_ext. This defaults to ``exe|com|bat``.
2223
2224 This function also resets the root module cache of module completer,
2225 used on slow filesystems.
2226
2227
2228 %reset: Resets the namespace by removing all names defined by the user.
2229
2230 Input/Output history are left around in case you need them.
2231
2232
2233 %run: Run the named file inside IPython as a program.
2234
2235 Usage:
2236 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
2237
2238 Parameters after the filename are passed as command-line arguments to
2239 the program (put in sys.argv). Then, control returns to IPython's prompt.
2240
2241 This is similar to running at a system prompt:
2242 $ python file args
2243 but with the advantage of giving you IPython's tracebacks, and of
2244 loading all variables into your interactive namespace for further use
2245 (unless -p is used, see below).
2246
2247 The file is executed in a namespace initially consisting only of
2248 __name__=='__main__' and sys.argv constructed as indicated. It thus sees
2249 its environment as if it were being run as a stand-alone program (except
2250 for sharing global objects such as previously imported modules). But
2251 after execution, the IPython interactive namespace gets updated with all
2252 variables defined in the program (except for __name__ and sys.argv).
2253 This allows for very convenient loading of code for interactive work,
2254 while giving each program a 'clean sheet' to run in.
2255
2256 Options:
2257
2258 -n: __name__ is NOT set to '__main__', but to the running file's name
2259 without extension (as python does under import). This allows running
2260 scripts and reloading the definitions in them without calling code
2261 protected by an ' if __name__ == "__main__" ' clause.
2262
2263 -i: run the file in IPython's namespace instead of an empty one. This is
2264 useful if you are experimenting with code written in a text editor which
2265 depends on variables defined interactively.
2266
2267 -e: ignore sys.exit() calls or SystemExit exceptions in the script being
2268 run. This is particularly useful if IPython is being used to run
2269 unittests, which always exit with a sys.exit() call. In such cases you
2270 are interested in the output of the test results, not in seeing a
2271 traceback of the unittest module.
2272
2273 -t: print timing information at the end of the run. IPython will give
2274 you an estimated CPU time consumption for your script, which under Unix
2275 uses the resource module to avoid the wraparound problems of
2276 time.clock(). Under Unix, an estimate of time spent on system tasks is
2277 also given (for Windows platforms this is reported as 0.0).
2278
2279 If -t is given, an additional -N<N> option can be given, where <N> must
2280 be an integer indicating how many times you want the script to run. The
2281 final timing report will include total and per run results.
2282
2283 For example (testing the script uniq_stable.py):
2284
2285 In [1]: run -t uniq_stable
2286
2287 IPython CPU timings (estimated):
2288 User : 0.19597 s.
2289 System: 0.0 s.
2290
2291 In [2]: run -t -N5 uniq_stable
2292
2293 IPython CPU timings (estimated):
2294 Total runs performed: 5
2295 Times : Total Per run
2296 User : 0.910862 s, 0.1821724 s.
2297 System: 0.0 s, 0.0 s.
2298
2299 -d: run your program under the control of pdb, the Python debugger. This
2300 allows you to execute your program step by step, watch variables, etc.
2301 Internally, what IPython does is similar to calling:
2302
2303 pdb.run('execfile("YOURFILENAME")')
2304
2305 with a breakpoint set on line 1 of your file. You can change the line
2306 number for this automatic breakpoint to be <N> by using the -bN option
2307 (where N must be an integer). For example:
2308
2309 %run -d -b40 myscript
2310
2311 will set the first breakpoint at line 40 in myscript.py. Note that the
2312 first breakpoint must be set on a line which actually does something
2313 (not a comment or docstring) for it to stop execution.
2314
2315 When the pdb debugger starts, you will see a (Pdb) prompt. You must
2316 first enter 'c' (without qoutes) to start execution up to the first
2317 breakpoint.
2318
2319 Entering 'help' gives information about the use of the debugger. You can
2320 easily see pdb's full documentation with "import pdb;pdb.help()" at a
2321 prompt.
2322
2323 -p: run program under the control of the Python profiler module (which
2324 prints a detailed report of execution times, function calls, etc).
2325
2326 You can pass other options after -p which affect the behavior of the
2327 profiler itself. See the docs for %prun for details.
2328
2329 In this mode, the program's variables do NOT propagate back to the
2330 IPython interactive namespace (because they remain in the namespace
2331 where the profiler executes them).
2332
2333 Internally this triggers a call to %prun, see its documentation for
2334 details on the options available specifically for profiling.
2335
2336 There is one special usage for which the text above doesn't apply: if
2337 the filename ends with .ipy, the file is run as ipython script, just as
2338 if the commands were written on IPython prompt.
2339
2340
2341 %runlog: Run files as logs.
2342
2343 Usage:
2344 %runlog file1 file2 ...
2345
2346 Run the named files (treating them as log files) in sequence inside the
2347 interpreter, and return to the prompt. This is much slower than %run
2348 because each line is executed in a try/except block, but it allows
2349 running files with syntax errors in them.
2350
2351 Normally IPython will guess when a file is one of its own logfiles, so
2352 you can typically use %run even for logs. This shorthand allows you to
2353 force any file to be treated as a log file.
2354
2355
2356 %save: Save a set of lines to a given filename.
2357
2358 Usage:
2359 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2360
2361 Options:
2362
2363 -r: use 'raw' input. By default, the 'processed' history is used, so
2364 that magics are loaded in their transformed version to valid Python. If
2365 this option is given, the raw input as typed as the command line is used
2366 instead.
2367
2368 This function uses the same syntax as %macro for line extraction, but
2369 instead of creating a macro it saves the resulting string to the
2370 filename you specify.
2371
2372 It adds a '.py' extension to the file if you don't do so yourself, and
2373 it asks for confirmation before overwriting existing files.
2374
2375
2376 %sc: Shell capture - execute a shell command and capture its output.
2377
2378 DEPRECATED. Suboptimal, retained for backwards compatibility.
2379
2380 You should use the form 'var = !command' instead. Example:
2381
2382 "%sc -l myfiles = ls " should now be written as
2383
2384 "myfiles = !ls "
2385
2386 myfiles.s, myfiles.l and myfiles.n still apply as documented below.
2387
2388 - %sc [options] varname=command
2389
2390 IPython will run the given command using commands.getoutput(), and will
2391 then update the user's interactive namespace with a variable called
2392 varname, containing the value of the call. Your command can contain
2393 shell wildcards, pipes, etc.
2394
2395 The '=' sign in the syntax is mandatory, and the variable name you
2396 supply must follow Python's standard conventions for valid names.
2397
2398 (A special format without variable name exists for internal use)
2399
2400 Options:
2401
2402 -l: list output. Split the output on newlines into a list before
2403 assigning it to the given variable. By default the output is stored as a
2404 single string.
2405
2406 -v: verbose. Print the contents of the variable.
2407
2408 In most cases you should not need to split as a list, because the
2409 returned value is a special type of string which can automatically
2410 provide its contents either as a list (split on newlines) or as a
2411 space-separated string. These are convenient, respectively, either for
2412 sequential processing or to be passed to a shell command.
2413
2414 For example:
2415
2416 # Capture into variable a In [9]: sc a=ls *py
2417
2418 # a is a string with embedded newlines In [10]: a Out[10]: 'setup.py
2419 win32_manual_post_install.py'
2420
2421 # which can be seen as a list: In [11]: a.l Out[11]: ['setup.py',
2422 'win32_manual_post_install.py']
2423
2424 # or as a whitespace-separated string: In [12]: a.s Out[12]: 'setup.py
2425 win32_manual_post_install.py'
2426
2427 # a.s is useful to pass as a single command line: In [13]: !wc -l $a.s
2428 146 setup.py 130 win32_manual_post_install.py 276 total
2429
2430 # while the list form is useful to loop over: In [14]: for f in a.l:
2431 ....: !wc -l $f ....: 146 setup.py 130 win32_manual_post_install.py
2432
2433 Similiarly, the lists returned by the -l option are also special, in the
2434 sense that you can equally invoke the .s attribute on them to
2435 automatically get a whitespace-separated string from their contents:
2436
2437 In [1]: sc -l b=ls *py
2438
2439 In [2]: b Out[2]: ['setup.py', 'win32_manual_post_install.py']
2440
2441 In [3]: b.s Out[3]: 'setup.py win32_manual_post_install.py'
2442
2443 In summary, both the lists and strings used for ouptut capture have the
2444 following special attributes:
2445
2446 .l (or .list) : value as list. .n (or .nlstr): value as
2447 newline-separated string. .s (or .spstr): value as space-separated string.
2448
2449
2450 %sx: Shell execute - run a shell command and capture its output.
2451
2452 %sx command
2453
2454 IPython will run the given command using commands.getoutput(), and
2455 return the result formatted as a list (split on '\n'). Since the output
2456 is _returned_, it will be stored in ipython's regular output cache
2457 Out[N] and in the '_N' automatic variables.
2458
2459 Notes:
2460
2461 1) If an input line begins with '!!', then %sx is automatically invoked.
2462 That is, while: !ls causes ipython to simply issue system('ls'), typing
2463 !!ls is a shorthand equivalent to: %sx ls
2464
2465 2) %sx differs from %sc in that %sx automatically splits into a list,
2466 like '%sc -l'. The reason for this is to make it as easy as possible to
2467 process line-oriented shell output via further python commands. %sc is
2468 meant to provide much finer control, but requires more typing.
2469
2470 3) Just like %sc -l, this is a list with special attributes:
2471
2472 .l (or .list) : value as list. .n (or .nlstr): value as
2473 newline-separated string. .s (or .spstr): value as whitespace-separated
2474 string.
2475
2476 This is very useful when trying to use such lists as arguments to system
2477 commands.
2478
2479
2480 %system_verbose: Set verbose printing of system calls.
2481
2482 If called without an argument, act as a toggle
2483
2484
2485 %time: Time execution of a Python statement or expression.
2486
2487 The CPU and wall clock times are printed, and the value of the
2488 expression (if any) is returned. Note that under Win32, system time is
2489 always reported as 0, since it can not be measured.
2490
2491 This function provides very basic timing functionality. In Python 2.3,
2492 the timeit module offers more control and sophistication, so this could
2493 be rewritten to use it (patches welcome).
2494
2495 Some examples:
2496
2497 In [1]: time 2**128 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2498 Wall time: 0.00 Out[1]: 340282366920938463463374607431768211456L
2499
2500 In [2]: n = 1000000
2501
2502 In [3]: time sum(range(n)) CPU times: user 1.20 s, sys: 0.05 s, total:
2503 1.25 s Wall time: 1.37 Out[3]: 499999500000L
2504
2505 In [4]: time print 'hello world' hello world CPU times: user 0.00 s,
2506 sys: 0.00 s, total: 0.00 s Wall time: 0.00
2507
2508 Note that the time needed by Python to compile the given expression will
2509 be reported if it is more than 0.1s. In this example, the actual
2510 exponentiation is done by Python at compilation time, so while the
2511 expression can take a noticeable amount of time to compute, that time is
2512 purely due to the compilation:
2513
2514 In [5]: time 3**9999; CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2515 Wall time: 0.00 s
2516
2517 In [6]: time 3**999999; CPU times: user 0.00 s, sys: 0.00 s, total: 0.00
2518 s Wall time: 0.00 s Compiler : 0.78 s
2519
2520
2521 %timeit: Time execution of a Python statement or expression
2522
2523 Usage:
2524 %timeit [-n<N> -r<R> [-t|-c]] statement
2525
2526 Time execution of a Python statement or expression using the timeit module.
2527
2528 Options: -n<N>: execute the given statement <N> times in a loop. If this
2529 value is not given, a fitting value is chosen.
2530
2531 -r<R>: repeat the loop iteration <R> times and take the best result.
2532 Default: 3
2533
2534 -t: use time.time to measure the time, which is the default on Unix.
2535 This function measures wall time.
2536
2537 -c: use time.clock to measure the time, which is the default on Windows
2538 and measures wall time. On Unix, resource.getrusage is used instead and
2539 returns the CPU user time.
2540
2541 -p<P>: use a precision of <P> digits to display the timing result.
2542 Default: 3
2543
2544 Examples:
2545 In [1]: %timeit pass 10000000 loops, best of 3: 53.3 ns per loop
2546
2547 In [2]: u = None
2548
2549 In [3]: %timeit u is None 10000000 loops, best of 3: 184 ns per loop
2550
2551 In [4]: %timeit -r 4 u == None 1000000 loops, best of 4: 242 ns per loop
2552
2553 In [5]: import time
2554
2555 In [6]: %timeit -n1 time.sleep(2) 1 loops, best of 3: 2 s per loop
2556
2557 The times reported by %timeit will be slightly higher than those
2558 reported by the timeit.py script when variables are accessed. This is
2559 due to the fact that %timeit executes the statement in the namespace of
2560 the shell, compared with timeit.py, which uses a single setup statement
2561 to import function or create variables. Generally, the bias does not
2562 matter as long as results from timeit.py are not mixed with those from
2563 %timeit.
2564
2565
2566 %unalias: Remove an alias
2567
2568
2569 %upgrade: Upgrade your IPython installation
2570
2571 This will copy the config files that don't yet exist in your ipython dir
2572 from the system config dir. Use this after upgrading IPython if you
2573 don't wish to delete your .ipython dir.
2574
2575 Call with -nolegacy to get rid of ipythonrc* files (recommended for new
2576 users)
2577
2578
2579 %who: Print all interactive variables, with some minimal formatting.
2580
2581 If any arguments are given, only variables whose type matches one of
2582 these are printed. For example:
2583
2584 %who function str
2585
2586 will only list functions and strings, excluding all other types of
2587 variables. To find the proper type names, simply use type(var) at a
2588 command line to see how python prints type names. For example:
2589
2590 In [1]: type('hello')
2591 Out[1]: <type 'str'>
2592
2593 indicates that the type name for strings is 'str'.
2594
2595 %who always excludes executed names loaded through your configuration
2596 file and things which are internal to IPython.
2597
2598 This is deliberate, as typically you may load many modules and the
2599 purpose of %who is to show you only what you've manually defined.
2600
2601
2602 %who_ls: Return a sorted list of all interactive variables.
2603
2604 If arguments are given, only variables of types matching these arguments
2605 are returned.
2606
2607
2608 %whos: Like %who, but gives some extra information about each variable.
2609
2610 The same type filtering of %who can be applied here.
2611
2612 For all variables, the type is printed. Additionally it prints:
2613
2614 - For ,[],(): their length.
2615
2616 - For numpy and Numeric arrays, a summary with shape, number of
2617 elements, typecode and size in memory.
2618
2619 - Everything else: a string representation, snipping their middle if too
2620 long.
2621
2622
2623 %xmode: Switch modes for the exception handlers.
2624
2625 Valid modes: Plain, Context and Verbose.
2626
2627 If called without arguments, acts as a toggle.
2628
2629
2630 Access to the standard Python help
2631 ----------------------------------
2614
2632
2615 As of Python 2.1, a help system is available with access to object
2633 As of Python 2.1, a help system is available with access to object
2616 docstrings and the Python manuals. Simply type 'help' (no quotes) to
2634 docstrings and the Python manuals. Simply type 'help' (no quotes) to
@@ -2621,7 +2639,8 b' your environment variable PYTHONDOCS for this feature to work correctly.'
2621
2639
2622
2640
2623
2641
2624 Dynamic object information
2642 Dynamic object information
2643 --------------------------
2625
2644
2626 Typing ?word or word? prints detailed information about an object. If
2645 Typing ?word or word? prints detailed information about an object. If
2627 certain strings in the object are too long (docstrings, code, etc.) they
2646 certain strings in the object are too long (docstrings, code, etc.) they
@@ -2662,7 +2681,8 b' are not really defined as separate identifiers. Try for example typing'
2662
2681
2663
2682
2664
2683
2665 Readline-based features
2684 Readline-based features
2685 -----------------------
2666
2686
2667 These features require the GNU readline library, so they won't work if
2687 These features require the GNU readline library, so they won't work if
2668 your Python installation lacks readline support. We will first describe
2688 your Python installation lacks readline support. We will first describe
@@ -2820,7 +2840,6 b' Any input line beginning with a ! character is passed verbatim (minus'
2820 the !, of course) to the underlying operating system. For example,
2840 the !, of course) to the underlying operating system. For example,
2821 typing !ls will run 'ls' in the current directory.
2841 typing !ls will run 'ls' in the current directory.
2822
2842
2823
2824 Manual capture of command output
2843 Manual capture of command output
2825 --------------------------------
2844 --------------------------------
2826
2845
@@ -2832,10 +2851,9 b' output. The !! syntax is a shorthand for the %sx magic command.'
2832
2851
2833 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
2852 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
2834 but allowing more fine-grained control of the capture details, and
2853 but allowing more fine-grained control of the capture details, and
2835 storing the result directly into a named variable.
2854 storing the result directly into a named variable. The direct use of
2836
2855 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
2837 See Sec. 6.2 <#sec:magic> for details on the magics %sc and %sx, or use
2856 instead.
2838 IPython's own help (sc? and sx?) for further details.
2839
2857
2840 IPython also allows you to expand the value of python variables when
2858 IPython also allows you to expand the value of python variables when
2841 making system calls. Any python variable or expression which you prepend
2859 making system calls. Any python variable or expression which you prepend
@@ -3004,7 +3022,8 b' Directory history'
3004
3022
3005 Your history of visited directories is kept in the global list _dh, and
3023 Your history of visited directories is kept in the global list _dh, and
3006 the magic %cd command can be used to go to any entry in that list. The
3024 the magic %cd command can be used to go to any entry in that list. The
3007 %dhist command allows you to view this history.
3025 %dhist command allows you to view this history. do ``cd -<TAB`` to
3026 conventiently view the directory history.
3008
3027
3009
3028
3010 Automatic parentheses and quotes
3029 Automatic parentheses and quotes
@@ -3078,6 +3097,23 b" won't work::"
3078 Customization
3097 Customization
3079 =============
3098 =============
3080
3099
3100 There are 2 ways to configure IPython - the old way of using ipythonrc
3101 files (an INI-file like format), and the new way that involves editing
3102 your ipy_user_conf.py. Both configuration systems work at the same
3103 time, so you can set your options in both, but if you are hesitating
3104 about which alternative to choose, we recommend the ipy_user_conf.py
3105 approach, as it will give you more power and control in the long
3106 run. However, there are few options such as pylab_import_all that can
3107 only be specified in ipythonrc file or command line - the reason for
3108 this is that they are needed before IPython has been started up, and
3109 the IPApi object used in ipy_user_conf.py is not yet available at that
3110 time. A hybrid approach of specifying a few options in ipythonrc and
3111 doing the more advanced configuration in ipy_user_conf.py is also
3112 possible.
3113
3114 The ipythonrc approach
3115 ----------------------
3116
3081 As we've already mentioned, IPython reads a configuration file which can
3117 As we've already mentioned, IPython reads a configuration file which can
3082 be specified at the command line (-rcfile) or which by default is
3118 be specified at the command line (-rcfile) or which by default is
3083 assumed to be called ipythonrc. Such a file is looked for in the current
3119 assumed to be called ipythonrc. Such a file is looked for in the current
@@ -3118,7 +3154,7 b' Each of these options may appear as many times as you need it in the file.'
3118 * [import_some <mod> <f1> <f2> ...:] import functions with 'from
3154 * [import_some <mod> <f1> <f2> ...:] import functions with 'from
3119 <mod> import <f1>,<f2>,...'
3155 <mod> import <f1>,<f2>,...'
3120 * [import_all <mod1> <mod2> ...:] for each module listed import
3156 * [import_all <mod1> <mod2> ...:] for each module listed import
3121 functions with 'from <mod> import *'
3157 functions with ``from <mod> import *``.
3122 * [execute <python code>:] give any single-line python code to be
3158 * [execute <python code>:] give any single-line python code to be
3123 executed.
3159 executed.
3124 * [execfile <filename>:] execute the python file given with an
3160 * [execfile <filename>:] execute the python file given with an
@@ -3136,7 +3172,6 b' Each of these options may appear as many times as you need it in the file.'
3136 normal system shell.
3172 normal system shell.
3137
3173
3138
3174
3139
3140 Sample ipythonrc file
3175 Sample ipythonrc file
3141 ---------------------
3176 ---------------------
3142
3177
@@ -3777,7 +3812,95 b' reproduce it here for reference::'
3777 # alias
3812 # alias
3778
3813
3779 #************************* end of file <ipythonrc> ************************
3814 #************************* end of file <ipythonrc> ************************
3780
3815
3816
3817 ipy_user_conf.py
3818 ----------------
3819
3820 There should be a simple template ipy_user_conf.py file in your
3821 ~/.ipython directory. It is a plain python module that is imported
3822 during IPython startup, so you can do pretty much what you want there
3823 - import modules, configure extensions, change options, define magic
3824 commands, put variables and functions in the IPython namespace,
3825 etc. You use the IPython extension api object, acquired by
3826 IPython.ipapi.get() and documented in the "IPython extension API"
3827 chapter, to interact with IPython. A sample ipy_user_conf.py is listed
3828 below for reference::
3829
3830 # Most of your config files and extensions will probably start
3831 # with this import
3832
3833 import IPython.ipapi
3834 ip = IPython.ipapi.get()
3835
3836 # You probably want to uncomment this if you did %upgrade -nolegacy
3837 # import ipy_defaults
3838
3839 import os
3840
3841 def main():
3842
3843 #ip.dbg.debugmode = True
3844 ip.dbg.debug_stack()
3845
3846 # uncomment if you want to get ipython -p sh behaviour
3847 # without having to use command line switches
3848 import ipy_profile_sh
3849 import jobctrl
3850
3851 # Configure your favourite editor?
3852 # Good idea e.g. for %edit os.path.isfile
3853
3854 #import ipy_editors
3855
3856 # Choose one of these:
3857
3858 #ipy_editors.scite()
3859 #ipy_editors.scite('c:/opt/scite/scite.exe')
3860 #ipy_editors.komodo()
3861 #ipy_editors.idle()
3862 # ... or many others, try 'ipy_editors??' after import to see them
3863
3864 # Or roll your own:
3865 #ipy_editors.install_editor("c:/opt/jed +$line $file")
3866
3867
3868 o = ip.options
3869 # An example on how to set options
3870 #o.autocall = 1
3871 o.system_verbose = 0
3872
3873 #import_all("os sys")
3874 #execf('~/_ipython/ns.py')
3875
3876
3877 # -- prompt
3878 # A different, more compact set of prompts from the default ones, that
3879 # always show your current location in the filesystem:
3880
3881 #o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
3882 #o.prompt_in2 = r'.\D: '
3883 #o.prompt_out = r'[\#] '
3884
3885 # Try one of these color settings if you can't read the text easily
3886 # autoexec is a list of IPython commands to execute on startup
3887 #o.autoexec.append('%colors LightBG')
3888 #o.autoexec.append('%colors NoColor')
3889 o.autoexec.append('%colors Linux')
3890
3891
3892 # some config helper functions you can use
3893 def import_all(modules):
3894 """ Usage: import_all("os sys") """
3895 for m in modules.split():
3896 ip.ex("from %s import *" % m)
3897
3898 def execf(fname):
3899 """ Execute a file in user namespace """
3900 ip.ex('execfile("%s")' % os.path.expanduser(fname))
3901
3902 main()
3903
3781
3904
3782
3905
3783 Fine-tuning your prompt
3906 Fine-tuning your prompt
@@ -3785,42 +3908,42 b' Fine-tuning your prompt'
3785
3908
3786 IPython's prompts can be customized using a syntax similar to that of
3909 IPython's prompts can be customized using a syntax similar to that of
3787 the bash shell. Many of bash's escapes are supported, as well as a few
3910 the bash shell. Many of bash's escapes are supported, as well as a few
3788 additional ones. We list them below:
3911 additional ones. We list them below::
3789
3912
3790 *\#*
3913 \#
3791 the prompt/history count number. This escape is automatically
3914 the prompt/history count number. This escape is automatically
3792 wrapped in the coloring codes for the currently active color scheme.
3915 wrapped in the coloring codes for the currently active color scheme.
3793 *\N*
3916 \N
3794 the 'naked' prompt/history count number: this is just the number
3917 the 'naked' prompt/history count number: this is just the number
3795 itself, without any coloring applied to it. This lets you produce
3918 itself, without any coloring applied to it. This lets you produce
3796 numbered prompts with your own colors.
3919 numbered prompts with your own colors.
3797 *\D*
3920 \D
3798 the prompt/history count, with the actual digits replaced by dots.
3921 the prompt/history count, with the actual digits replaced by dots.
3799 Used mainly in continuation prompts (prompt_in2)
3922 Used mainly in continuation prompts (prompt_in2)
3800 *\w*
3923 \w
3801 the current working directory
3924 the current working directory
3802 *\W*
3925 \W
3803 the basename of current working directory
3926 the basename of current working directory
3804 *\Xn*
3927 \Xn
3805 where $n=0\ldots5.$ The current working directory, with $HOME
3928 where $n=0\ldots5.$ The current working directory, with $HOME
3806 replaced by ~, and filtered out to contain only $n$ path elements
3929 replaced by ~, and filtered out to contain only $n$ path elements
3807 *\Yn*
3930 \Yn
3808 Similar to \Xn, but with the $n+1$ element included if it is ~ (this
3931 Similar to \Xn, but with the $n+1$ element included if it is ~ (this
3809 is similar to the behavior of the %cn escapes in tcsh)
3932 is similar to the behavior of the %cn escapes in tcsh)
3810 *\u*
3933 \u
3811 the username of the current user
3934 the username of the current user
3812 *\$*
3935 \$
3813 if the effective UID is 0, a #, otherwise a $
3936 if the effective UID is 0, a #, otherwise a $
3814 *\h*
3937 \h
3815 the hostname up to the first '.'
3938 the hostname up to the first '.'
3816 *\H*
3939 \H
3817 the hostname
3940 the hostname
3818 *\n*
3941 \n
3819 a newline
3942 a newline
3820 *\r*
3943 \r
3821 a carriage return
3944 a carriage return
3822 *\v*
3945 \v
3823 IPython version string
3946 IPython version string
3824
3947
3825 In addition to these, ANSI color escapes can be insterted into the
3948 In addition to these, ANSI color escapes can be insterted into the
3826 prompts, as \C_ColorName. The list of valid color names is: Black, Blue,
3949 prompts, as \C_ColorName. The list of valid color names is: Black, Blue,
@@ -3848,7 +3971,7 b' default prompts::'
3848 prompt_in2 ' .\D.:'
3971 prompt_in2 ' .\D.:'
3849 prompt_out 'Out[\#]:'
3972 prompt_out 'Out[\#]:'
3850
3973
3851 which look like this:
3974 which look like this::
3852
3975
3853 In [1]: 1+2
3976 In [1]: 1+2
3854 Out[1]: 3
3977 Out[1]: 3
@@ -4166,7 +4289,6 b' code fragments in your programs which are ready for cut and paste::'
4166 Using the Python debugger (pdb)
4289 Using the Python debugger (pdb)
4167 ===============================
4290 ===============================
4168
4291
4169
4170 Running entire programs via pdb
4292 Running entire programs via pdb
4171 -------------------------------
4293 -------------------------------
4172
4294
@@ -4212,11 +4334,11 b' uncaught exception is triggered by your code.'
4212
4334
4213 For stand-alone use of the feature in your programs which do not use
4335 For stand-alone use of the feature in your programs which do not use
4214 IPython at all, put the following lines toward the top of your 'main'
4336 IPython at all, put the following lines toward the top of your 'main'
4215 routine:
4337 routine::
4216
4338
4217 import sys,IPython.ultraTB
4339 import sys,IPython.ultraTB
4218 sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
4340 sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
4219 color_scheme='Linux', call_pdb=1)
4341 color_scheme='Linux', call_pdb=1)
4220
4342
4221 The mode keyword can be either 'Verbose' or 'Plain', giving either very
4343 The mode keyword can be either 'Verbose' or 'Plain', giving either very
4222 detailed or normal tracebacks respectively. The color_scheme keyword can
4344 detailed or normal tracebacks respectively. The color_scheme keyword can
@@ -4242,7 +4364,7 b" supplied, which we will briefly describe now. These can be used 'as is'"
4242 starting point for writing your own extensions.
4364 starting point for writing your own extensions.
4243
4365
4244
4366
4245 Pasting of code starting with 'Β»> ' or '... '
4367 Pasting of code starting with '>>> ' or '... '
4246 ----------------------------------------------
4368 ----------------------------------------------
4247
4369
4248 In the python tutorial it is common to find code examples which have
4370 In the python tutorial it is common to find code examples which have
@@ -4304,6 +4426,7 b" Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython"
4304 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
4426 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
4305 but these must be declared as instances of a class. For example, to
4427 but these must be declared as instances of a class. For example, to
4306 define v as a velocity of 3 m/s, normally you would write::
4428 define v as a velocity of 3 m/s, normally you would write::
4429
4307 In [1]: v = PhysicalQuantity(3,'m/s')
4430 In [1]: v = PhysicalQuantity(3,'m/s')
4308
4431
4309 Using the PhysicalQ_Input extension this can be input instead as:
4432 Using the PhysicalQ_Input extension this can be input instead as:
@@ -4318,235 +4441,286 b' from math import * # math MUST be imported BEFORE PhysicalQInteractive'
4318 from IPython.Extensions.PhysicalQInteractive import *
4441 from IPython.Extensions.PhysicalQInteractive import *
4319 import IPython.Extensions.PhysicalQInput
4442 import IPython.Extensions.PhysicalQInput
4320
4443
4321 IPython as a system shell
4322 =========================
4323
4444
4324 IPython ships with a special profile called pysh, which you can activate
4445 IPython as a system shell - the 'Sh' profile
4325 at the command line as 'ipython -p pysh'. This loads InterpreterExec,
4446 ============================================
4326 along with some additional facilities and a prompt customized for
4447
4327 filesystem navigation.
4448 The 'sh' profile optimizes IPython for system shell usage. Apart from
4449 certain job control functionality that is present in unix (ctrl+z does
4450 "suspend"), the sh profile should provide you with most of the
4451 functionality you use daily in system shell, and more. Invoke IPython
4452 in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching
4453 the "pysh" shortcut in start menu.
4454
4455 If you want to use the features of sh profile as your defaults (which
4456 might be a good idea if you use other profiles a lot of the time but
4457 still want the convenience of sh profile), add ``import ipy_profile_sh``
4458 to your ~/.ipython/ipy_user_conf.py.
4459
4460 The 'sh' profile is different from the default profile in that:
4328
4461
4329 Note that this does not make IPython a full-fledged system shell. In
4462 * Prompt shows the current directory
4330 particular, it has no job control, so if you type Ctrl-Z (under Unix),
4463 * Spacing between prompts and input is more compact (no padding with
4331 you'll suspend pysh itself, not the process you just started.
4464 empty lines). The startup banner is more compact as well.
4465 * System commands are directly available (in alias table) without
4466 requesting %rehashx - however, if you install new programs along
4467 your PATH, you might want to run %rehashx to update the persistent
4468 alias table
4469 * Macros are stored in raw format by default. That is, instead of
4470 '_ip.system("cat foo"), the macro will contain text 'cat foo')
4471 * Autocall is in full mode
4472 * Calling "up" does "cd .."
4332
4473
4333 What the shell profile allows you to do is to use the convenient and
4474 The 'sh' profile is different from the now-obsolete (and unavailable)
4334 powerful syntax of Python to do quick scripting at the command line.
4475 'pysh' profile in that:
4335 Below we describe some of its features.
4336
4476
4477 * '$$var = command' and '$var = command' syntax is not supported
4478 * anymore. Use 'var = !command' instead (incidentally, this is
4479 * available in all IPython profiles). Note that !!command *will*
4480 * work.
4337
4481
4338 Aliases
4482 Aliases
4339 -------
4483 -------
4340
4484
4341 All of your $PATH has been loaded as IPython aliases, so you should be
4485 All of your $PATH has been loaded as IPython aliases, so you should be
4342 able to type any normal system command and have it executed. See %alias?
4486 able to type any normal system command and have it executed. See
4343 and %unalias? for details on the alias facilities. See also %rehash? and
4487 %alias? and %unalias? for details on the alias facilities. See also
4344 %rehashx? for details on the mechanism used to load $PATH.
4488 %rehashx? for details on the mechanism used to load $PATH.
4345
4489
4346
4490
4347 Special syntax
4491 Directory management
4348 --------------
4492 --------------------
4493
4494 Since each command passed by ipython to the underlying system is executed
4495 in a subshell which exits immediately, you can NOT use !cd to navigate
4496 the filesystem.
4349
4497
4350 Any lines which begin with '~', '/' and '.' will be executed as shell
4498 IPython provides its own builtin '%cd' magic command to move in the
4351 commands instead of as Python code. The special escapes below are also
4499 filesystem (the % is not required with automagic on). It also maintains
4352 recognized. !cmd is valid in single or multi-line input, all others are
4500 a list of visited directories (use %dhist to see it) and allows direct
4353 only valid in single-line input::
4501 switching to any of them. Type 'cd?' for more details.
4354
4502
4355 *!cmd*
4503 %pushd, %popd and %dirs are provided for directory stack handling.
4356 pass 'cmd' directly to the shell
4357 *!!cmd*
4358 execute 'cmd' and return output as a list (split on '\n')
4359 *var=!cmd
4360 capture output of cmd into var, as a string list
4361
4504
4362 The $/$$ syntaxes make Python variables from system output, which you
4363 can later use for further scripting. The converse is also possible: when
4364 executing an alias or calling to the system via !/!!, you can expand any
4365 python variable or expression by prepending it with $. Full details of
4366 the allowed syntax can be found in Python's PEP 215.
4367
4505
4368 A few brief examples will illustrate these (note that the indentation
4506 Enabled extensions
4369 below may be incorrectly displayed)::
4507 ------------------
4370
4508
4371 fperez[~/test]|3> !ls *s.py
4509 Some extensions, listed below, are enabled as default in this profile.
4372 scopes.py strings.py
4373
4510
4374 ls is an internal alias, so there's no need to use !::
4511 envpersist
4512 ++++++++++
4375
4513
4376 fperez[~/test]|4> ls *s.py
4514 %env can be used to "remember" environment variable manipulations. Examples::
4377 scopes.py* strings.py
4378
4515
4379 !!ls will return the output into a Python variable FIXME!!!::
4516 %env - Show all environment variables
4517 %env VISUAL=jed - set VISUAL to jed
4518 %env PATH+=;/foo - append ;foo to PATH
4519 %env PATH+=;/bar - also append ;bar to PATH
4520 %env PATH-=/wbin; - prepend /wbin; to PATH
4521 %env -d VISUAL - forget VISUAL persistent val
4522 %env -p - print all persistent env modifications
4380
4523
4381 fperez[~/test]|5> !!ls *s.py
4524 ipy_which
4382 <5> ['scopes.py', 'strings.py']
4525 +++++++++
4383 fperez[~/test]|6> print _5
4384 ['scopes.py', 'strings.py']
4385
4526
4386 $ and $$ allow direct capture to named variables:
4527 %which magic command. Like 'which' in unix, but knows about ipython aliases.
4387
4528
4388 fperez[~/test]|7> $astr = ls *s.py
4529 Example::
4389 fperez[~/test]|8> astr
4390 <8> 'scopes.py\nstrings.py'
4391
4530
4392 fperez[~/test]|9> $$alist = ls *s.py
4531 [C:/ipython]|14> %which st
4393 fperez[~/test]|10> alist
4532 st -> start .
4394 <10> ['scopes.py', 'strings.py']
4533 [C:/ipython]|15> %which d
4534 d -> dir /w /og /on
4535 [C:/ipython]|16> %which cp
4536 cp -> cp
4537 == c:\bin\cp.exe
4538 c:\bin\cp.exe
4395
4539
4396 alist is now a normal python list you can loop over. Using $ will expand
4540 ipy_app_completers
4397 back the python values when alias calls are made:
4541 ++++++++++++++++++
4398
4542
4399 fperez[~/test]|11> for f in alist:
4543 Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu.
4400 |..> print 'file',f,
4401 |..> wc -l $f
4402 |..>
4403 file scopes.py 13 scopes.py
4404 file strings.py 4 strings.py
4405
4544
4406 Note that you may need to protect your variables with braces if you want
4545 ipy_rehashdir
4407 to append strings to their names. To copy all files in alist to .bak
4546 +++++++++++++
4408 extensions, you must use::
4409
4547
4410 fperez[~/test]|12> for f in alist:
4548 Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir::
4411 |..> cp $f ${f}.bak
4412
4549
4413 If you try using $f.bak, you'll get an AttributeError exception saying
4550 [~]|22> cd c:/opt/PuTTY/
4414 that your string object doesn't have a .bak attribute. This is because
4551 [c:opt/PuTTY]|23> rehashdir .
4415 the $ expansion mechanism allows you to expand full Python expressions::
4552 <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000']
4416
4553
4417 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
4554 Now, you can execute any of those commams directly::
4418 sys.platform is: linux2
4419
4555
4420 IPython's input history handling is still active, which allows you to
4556 [c:opt/PuTTY]|24> cd
4421 rerun a single block of multi-line input by simply using exec::
4557 [~]|25> putty
4422
4558
4423 fperez[~/test]|14> $$alist = ls *.eps
4559 (the putty window opens).
4424 fperez[~/test]|15> exec _i11
4425 file image2.eps 921 image2.eps
4426 file image.eps 921 image.eps
4427
4560
4428 While these are new special-case syntaxes, they are designed to allow
4561 If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop::
4429 very efficient use of the shell with minimal typing. At an interactive
4430 shell prompt, conciseness of expression wins over readability.
4431
4562
4563 [~]|27> for a in _23:
4564 |..> %store $a
4565 |..>
4566 |..>
4567 Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe')
4568 Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe')
4569 Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe')
4570 Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe')
4571 ...
4432
4572
4433 Useful functions and modules
4573 mglob
4434 ----------------------------
4574 +++++
4435
4575
4436 The os, sys and shutil modules from the Python standard library are
4576 Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples::
4437 automatically loaded. Some additional functions, useful for shell usage,
4438 are listed below. You can request more help about them with '?'.
4439
4577
4440 *shell*
4578 [c:/ipython]|9> mglob *.py
4441 - execute a command in the underlying system shell
4579 [c:/ipython]|10> mglob *.py rec:*.txt
4442 *system*
4580 [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:.
4443 - like shell(), but return the exit status of the command
4444 *sout*
4445 - capture the output of a command as a string
4446 *lout*
4447 - capture the output of a command as a list (split on '\n')
4448 *getoutputerror*
4449 - capture (output,error) of a shell commandss
4450
4581
4451 sout/lout are the functional equivalents of $/$$. They are provided to
4582 Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'.
4452 allow you to capture system output in the middle of true python code,
4453 function definitions, etc (where $ and $$ are invalid).
4454
4583
4455
4584
4456 Directory management
4585 Prompt customization
4457 --------------------
4586 --------------------
4458
4587
4459 Since each command passed by pysh to the underlying system is executed
4588 The sh profile uses the following prompt configurations::
4460 in a subshell which exits immediately, you can NOT use !cd to navigate
4461 the filesystem.
4462
4589
4463 Pysh provides its own builtin '%cd' magic command to move in the
4590 o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#>'
4464 filesystem (the % is not required with automagic on). It also maintains
4591 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green>'
4465 a list of visited directories (use %dhist to see it) and allows direct
4466 switching to any of them. Type 'cd?' for more details.
4467
4592
4468 %pushd, %popd and %dirs are provided for directory stack handling.
4593 You can change the prompt configuration to your liking by editing
4594 ipy_user_conf.py.
4595
4596 String lists
4597 ============
4598
4599 String lists (IPython.genutils.SList) are handy way to process output
4600 from system commands. They are produced by ``var = !cmd`` syntax.
4469
4601
4602 First, we acquire the output of 'ls -l'::
4470
4603
4471 Prompt customization
4604 [Q:doc/examples]|2> lines = !ls -l
4605 ==
4606 ['total 23',
4607 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
4608 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
4609 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
4610 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
4611 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
4612 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
4613 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
4472
4614
4473 The supplied ipythonrc-pysh profile comes with an example of a very
4615 Now, let's take a look at the contents of 'lines' (the first number is
4474 colored and detailed prompt, mainly to serve as an illustration. The
4616 the list element number)::
4475 valid escape sequences, besides color names, are:
4476
4617
4477 *\#*
4618 [Q:doc/examples]|3> lines
4478 - Prompt number, wrapped in the color escapes for the input prompt
4619 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
4479 (determined by the current color scheme).
4480 *\N*
4481 - Just the prompt counter number, without any coloring wrappers. You
4482 can thus customize the actual prompt colors manually.
4483 *\D*
4484 - Dots, as many as there are digits in \# (so they align).
4485 *\w*
4486 - Current working directory (cwd).
4487 *\W*
4488 - Basename of current working directory.
4489 *\XN*
4490 - Where N=0..5. N terms of the cwd, with $HOME written as ~.
4491 *\YN*
4492 - Where N=0..5. Like XN, but if ~ is term N+1 it's also shown.
4493 *\u*
4494 - Username.
4495 *\H*
4496 - Full hostname.
4497 *\h*
4498 - Hostname up to first '.'
4499 *\$*
4500 - Root symbol ($ or #).
4501 *\t*
4502 - Current time, in H:M:S format.
4503 *\v*
4504 - IPython release version.
4505 *\n*
4506 - Newline.
4507 *\r*
4508 - Carriage return.
4509 *\\*
4510 - An explicitly escaped '\'.
4511
4620
4512 You can configure your prompt colors using any ANSI color escape. Each
4621 0: total 23
4513 color escape sets the color for any subsequent text, until another
4622 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
4514 escape comes in and changes things. The valid color escapes are:
4623 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
4624 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
4625 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
4626 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
4627 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
4628 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
4515
4629
4516 *\C_Black*
4630 Now, let's filter out the 'embed' lines::
4517
4631
4518 *\C_Blue*
4632 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
4633 [Q:doc/examples]|5> l2
4634 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
4519
4635
4520 *\C_Brown*
4636 0: total 23
4637 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
4638 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
4639 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
4640 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
4641 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
4521
4642
4522 *\C_Cyan*
4643 Now, we want strings having just file names and permissions::
4523
4644
4524 *\C_DarkGray*
4645 [Q:doc/examples]|6> l2.fields(8,0)
4646 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
4525
4647
4526 *\C_Green*
4648 0: total
4649 1: example-demo.py -rw-rw-rw-
4650 2: example-gnuplot.py -rwxrwxrwx
4651 3: extension.py -rwxrwxrwx
4652 4: seteditor.py -rwxrwxrwx
4653 5: seteditor.pyc -rwxrwxrwx
4527
4654
4528 *\C_LightBlue*
4655 Note how the line with 'total' does not raise IndexError.
4529
4656
4530 *\C_LightCyan*
4657 If you want to split these (yielding lists), call fields() without
4658 arguments::
4531
4659
4532 *\C_LightGray*
4660 [Q:doc/examples]|7> _.fields()
4661 <7>
4662 [['total'],
4663 ['example-demo.py', '-rw-rw-rw-'],
4664 ['example-gnuplot.py', '-rwxrwxrwx'],
4665 ['extension.py', '-rwxrwxrwx'],
4666 ['seteditor.py', '-rwxrwxrwx'],
4667 ['seteditor.pyc', '-rwxrwxrwx']]
4533
4668
4534 *\C_LightGreen*
4669 If you want to pass these separated with spaces to a command (typical
4670 for lists if files), use the .s property::
4535
4671
4536 *\C_LightPurple*
4537
4672
4538 *\C_LightRed*
4673 [Q:doc/examples]|13> files = l2.fields(8).s
4674 [Q:doc/examples]|14> files
4675 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
4676 [Q:doc/examples]|15> ls $files
4677 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
4539
4678
4540 *\C_Purple*
4679 SLists are inherited from normal python lists, so every list method is
4680 available::
4541
4681
4542 *\C_Red*
4682 [Q:doc/examples]|21> lines.append('hey')
4543
4683
4544 *\C_White*
4545
4684
4546 *\C_Yellow*
4685 Real world example: remove all files outside version control
4686 ------------------------------------------------------------
4687
4688 First, capture output of "hg status"::
4689
4690 [Q:/ipython]|28> out = !hg status
4691 ==
4692 ['M IPython\\Extensions\\ipy_kitcfg.py',
4693 'M IPython\\Extensions\\ipy_rehashdir.py',
4694 ...
4695 '? build\\lib\\IPython\\Debugger.py',
4696 '? build\\lib\\IPython\\Extensions\\InterpreterExec.py',
4697 '? build\\lib\\IPython\\Extensions\\InterpreterPasteInput.py',
4698 ...
4699
4700 (lines starting with ? are not under version control).
4701
4702 ::
4703
4704 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
4705 [Q:/ipython]|36> junk
4706 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
4707 ...
4708 10: build\bdist.win32\winexe\temp\_ctypes.py
4709 11: build\bdist.win32\winexe\temp\_hashlib.py
4710 12: build\bdist.win32\winexe\temp\_socket.py
4711
4712 Now we can just remove these files by doing 'rm $junk.s'.
4713
4714 The .s, .n, .p properties
4715 -------------------------
4716
4717 The '.s' property returns one string where lines are separated by
4718 single space (for convenient passing to system commands). The '.n'
4719 property return one string where the lines are separated by '\n'
4720 (i.e. the original output of the function). If the items in string
4721 list are file names, '.p' can be used to get a list of "path" objects
4722 for convenient file manipulation.
4547
4723
4548 *\C_Normal*
4549 Stop coloring, defaults to your terminal settings.
4550
4724
4551 Threading support
4725 Threading support
4552 =================
4726 =================
@@ -4595,8 +4769,10 b' value can be read by using the sys.getcheckinterval() function, and it'
4595 can be reset via sys.setcheckinterval(N). This switching of threads can
4769 can be reset via sys.setcheckinterval(N). This switching of threads can
4596 cause subtly confusing effects if one of your threads is doing file I/O.
4770 cause subtly confusing effects if one of your threads is doing file I/O.
4597 In text mode, most systems only flush file buffers when they encounter a
4771 In text mode, most systems only flush file buffers when they encounter a
4598 '\n'. An instruction as simple as
4772 '\n'. An instruction as simple as::
4773
4599 print >> filehandle, ''hello world''
4774 print >> filehandle, ''hello world''
4775
4600 actually consists of several bytecodes, so it is possible that the
4776 actually consists of several bytecodes, so it is possible that the
4601 newline does not reach your file before the next thread switch.
4777 newline does not reach your file before the next thread switch.
4602 Similarly, if you are writing to a file in binary mode, the file won't
4778 Similarly, if you are writing to a file in binary mode, the file won't
@@ -4608,6 +4784,7 b' example) a GUI application which will read data generated by files'
4608 written to from the IPython thread, the safest approach is to open all
4784 written to from the IPython thread, the safest approach is to open all
4609 of your files in unbuffered mode (the third argument to the file/open
4785 of your files in unbuffered mode (the third argument to the file/open
4610 function is the buffering value)::
4786 function is the buffering value)::
4787
4611 filehandle = open(filename,mode,0)
4788 filehandle = open(filename,mode,0)
4612
4789
4613 This is obviously a brute force way of avoiding race conditions with the
4790 This is obviously a brute force way of avoiding race conditions with the
@@ -4738,6 +4915,204 b" mechanism (Sec. 7.3 <node7.html#sec:profiles>): ''ipython -pylab -p"
4738 myprofile'' will load the profile defined in ipythonrc-myprofile after
4915 myprofile'' will load the profile defined in ipythonrc-myprofile after
4739 configuring matplotlib.
4916 configuring matplotlib.
4740
4917
4918 IPython Extension Api
4919 =====================
4920
4921 IPython api (defined in IPython/ipapi.py) is the public api that
4922 should be used for
4923
4924 * Configuration of user preferences (.ipython/ipy_user_conf.py)
4925 * Creating new profiles (.ipython/ipy_profile_PROFILENAME.py)
4926 * Writing extensions
4927
4928 Note that by using the extension api for configuration (editing
4929 ipy_user_conf.py instead of ipythonrc), you get better validity checks
4930 and get richer functionality - for example, you can import an
4931 extension and call functions in it to configure it for your purposes.
4932
4933 For an example extension (the 'sh' profile), see
4934 IPython/Extensions/ipy_profile_sh.py.
4935
4936 For the last word on what's available, see the source code of
4937 IPython/ipapi.py.
4938
4939
4940 Getting started
4941 ---------------
4942
4943 If you want to define an extension, create a normal python module that
4944 can be imported. The module will access IPython functionality through
4945 the 'ip' object defined below.
4946
4947 If you are creating a new profile (e.g. foobar), name the module as
4948 'ipy_profile_foobar.py' and put it in your ~/.ipython directory. Then,
4949 when you start ipython with the '-p foobar' argument, the module is
4950 automatically imported on ipython startup.
4951
4952 If you are just doing some per-user configuration, you can either
4953
4954 * Put the commands directly into ipy_user_conf.py.
4955
4956 * Create a new module with your customization code and import *that*
4957 module in ipy_user_conf.py. This is preferable to the first approach,
4958 because now you can reuse and distribute your customization code.
4959
4960 Getting a handle to the api
4961 ---------------------------
4962
4963 Put this in the start of your module::
4964
4965 #!python
4966 import IPython.ipapi
4967 ip = IPython.ipapi.get()
4968
4969 The 'ip' object will then be used for accessing IPython
4970 functionality. 'ip' will mean this api object in all the following
4971 code snippets. The same 'ip' that we just acquired is always
4972 accessible in interactive IPython sessions by the name _ip - play with
4973 it like this::
4974
4975 [~\_ipython]|81> a = 10
4976 [~\_ipython]|82> _ip.e
4977 _ip.ev _ip.ex _ip.expose_magic
4978 [~\_ipython]|82> _ip.ev('a+13')
4979 <82> 23
4980
4981 The _ip object is also used in some examples in this document - it can
4982 be substituted by 'ip' in non-interactive use.
4983
4984 Changing options
4985 ----------------
4986
4987 The ip object has 'options' attribute that can be used te get/set
4988 configuration options (just as in the ipythonrc file)::
4989
4990 o = ip.options
4991 o.autocall = 2
4992 o.automagic = 1
4993
4994 Executing statements in IPython namespace with 'ex' and 'ev'
4995 ------------------------------------------------------------
4996
4997 Often, you want to e.g. import some module or define something that
4998 should be visible in IPython namespace. Use ``ip.ev`` to
4999 *evaluate* (calculate the value of) expression and ``ip.ex`` to
5000 '''execute''' a statement::
5001
5002 # path module will be visible to the interactive session
5003 ip.ex("from path import path" )
5004
5005 # define a handy function 'up' that changes the working directory
5006
5007 ip.ex('import os')
5008 ip.ex("def up(): os.chdir('..')")
5009
5010
5011 # _i2 has the input history entry #2, print its value in uppercase.
5012 print ip.ev('_i2.upper()')
5013
5014 Accessing the IPython namespace
5015 -------------------------------
5016
5017 ip.user_ns attribute has a dictionary containing the IPython global
5018 namespace (the namespace visible in the interactive session).
5019
5020 ::
5021
5022 [~\_ipython]|84> tauno = 555
5023 [~\_ipython]|85> _ip.user_ns['tauno']
5024 <85> 555
5025
5026 Defining new magic commands
5027 ---------------------------
5028
5029 The following example defines a new magic command, %impall. What the
5030 command does should be obvious::
5031
5032 def doimp(self, arg):
5033 ip = self.api
5034 ip.ex("import %s; reload(%s); from %s import *" % (
5035 arg,arg,arg)
5036 )
5037
5038 ip.expose_magic('impall', doimp)
5039
5040 Things to observe in this example:
5041
5042 * Define a function that implements the magic command using the
5043 ipapi methods defined in this document
5044 * The first argument of the function is 'self', i.e. the
5045 interpreter object. It shouldn't be used directly. however.
5046 The interpreter object is probably *not* going to remain stable
5047 through IPython versions.
5048 * Access the ipapi through 'self.api' instead of the global 'ip' object.
5049 * All the text following the magic command on the command line is
5050 contained in the second argument
5051 * Expose the magic by ip.expose_magic()
5052
5053
5054 Calling magic functions and system commands
5055 -------------------------------------------
5056
5057 Use ip.magic() to execute a magic function, and ip.system() to execute
5058 a system command::
5059
5060 # go to a bookmark
5061 ip.magic('%cd -b relfiles')
5062
5063 # execute 'ls -F' system command. Interchangeable with os.system('ls'), really.
5064 ip.system('ls -F')
5065
5066 Launching IPython instance from normal python code
5067 --------------------------------------------------
5068
5069 Use ipapi.launch_new_instance() with an argument that specifies the
5070 namespace to use. This can be useful for trivially embedding IPython
5071 into your program. Here's an example of normal python program test.py
5072 ('''without''' an existing IPython session) that launches an IPython
5073 interpreter and regains control when the interpreter is exited::
5074
5075 [ipython]|1> cat test.py
5076 my_ns = dict(
5077 kissa = 15,
5078 koira = 16)
5079 import IPython.ipapi
5080 print "launching IPython instance"
5081 IPython.ipapi.launch_new_instance(my_ns)
5082 print "Exited IPython instance!"
5083 print "New vals:",my_ns['kissa'], my_ns['koira']
5084
5085 And here's what it looks like when run (note how we don't start it
5086 from an ipython session)::
5087
5088 Q:\ipython>python test.py
5089 launching IPython instance
5090 Py 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] IPy 0.7.3b3.r1975
5091 [ipython]|1> kissa = 444
5092 [ipython]|2> koira = 555
5093 [ipython]|3> Exit
5094 Exited IPython instance!
5095 New vals: 444 555
5096
5097 Accessing unexposed functionality
5098 ---------------------------------
5099
5100 There are still many features that are not exposed via the ipapi. If
5101 you can't avoid using them, you can use the functionality in
5102 InteractiveShell object (central IPython session class, defined in
5103 iplib.py) through ip.IP.
5104
5105 For example::
5106
5107 [~]|7> _ip.IP.expand_aliases('np','myfile.py')
5108 <7> 'c:/opt/Notepad++/notepad++.exe myfile.py'
5109 [~]|8>
5110
5111 Still, it's preferable that if you encounter such a feature, contact
5112 the IPython team and request that the functionality be exposed in a
5113 future version of IPython. Things not in ipapi are more likely to
5114 change over time.
5115
4741 Reporting bugs
5116 Reporting bugs
4742 ==============
5117 ==============
4743
5118
@@ -4772,7 +5147,8 b' Brief history'
4772 =============
5147 =============
4773
5148
4774
5149
4775 Origins
5150 Origins
5151 -------
4776
5152
4777 The current IPython system grew out of the following three projects:
5153 The current IPython system grew out of the following three projects:
4778
5154
General Comments 0
You need to be logged in to leave comments. Login now