##// END OF EJS Templates
ipython.rst: add magic command docs
Ville M. Vainio -
Show More
This diff has been collapsed as it changes many lines, (2788 lines changed) Show them Hide them
@@ -2,8 +2,8 b''
2 You can adapt this file completely to your liking, but it should at least
2 You can adapt this file completely to your liking, but it should at least
3 contain the root 'toctree' directive.
3 contain the root 'toctree' directive.
4
4
5 Welcome to IPython's documentation!
5 IPython documentation
6 ===================================
6 =====================
7
7
8 Contents:
8 Contents:
9
9
@@ -1389,1243 +1389,1557 b' 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
1389 about magic commands you may have added as part of your personal
1390 customizations.
1390 customizations.
1391
1391
1392 ::
1392 .. magic_start
1393
1393
1394 %Exit: Exit IPython without confirmation.
1394 **%Exit**::
1395
1395
1396
1396 Exit IPython without confirmation.
1397 %Pprint: Toggle pretty printing on/off.
1397
1398
1398 **%Pprint**::
1399
1399
1400 %alias: Define an alias for a system command.
1400 Toggle pretty printing on/off.
1401
1401
1402 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1402 **%alias**::
1403
1403
1404 Then, typing 'alias_name params' will execute the system command 'cmd
1404 Define an alias for a system command.
1405 params' (from your underlying operating system).
1405
1406
1406 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1407 Aliases have lower precedence than magic functions and Python normal
1407
1408 variables, so if 'foo' is both a Python variable and an alias, the alias
1408 Then, typing 'alias_name params' will execute the system command 'cmd
1409 can not be executed until 'del foo' removes the Python variable.
1409 params' (from your underlying operating system).
1410
1410
1411 You can use the %l specifier in an alias definition to represent the
1411 Aliases have lower precedence than magic functions and Python normal
1412 whole line when the alias is called. For example:
1412 variables, so if 'foo' is both a Python variable and an alias, the
1413
1413 alias can not be executed until 'del foo' removes the Python variable.
1414 In [2]: alias all echo "Input in brackets: <%l>"
1414
1415 In [3]: all hello world
1415 You can use the %l specifier in an alias definition to represent the
1416 Input in brackets: <hello world>
1416 whole line when the alias is called. For example:
1417
1417
1418 You can also define aliases with parameters using %s specifiers (one per
1418 In [2]: alias all echo "Input in brackets: <%l>"\
1419 parameter):
1419 In [3]: all hello world\
1420
1420 Input in brackets: <hello world>
1421 In [1]: alias parts echo first %s second %s
1421
1422 In [2]: %parts A B
1422 You can also define aliases with parameters using %s specifiers (one
1423 first A second B
1423 per parameter):
1424 In [3]: %parts A
1424
1425 Incorrect number of arguments: 2 expected.
1425 In [1]: alias parts echo first %s second %s\
1426 parts is an alias to: 'echo first %s second %s'
1426 In [2]: %parts A B\
1427
1427 first A second B\
1428 Note that %l and %s are mutually exclusive. You can only use one or the
1428 In [3]: %parts A\
1429 other in your aliases.
1429 Incorrect number of arguments: 2 expected.\
1430
1430 parts is an alias to: 'echo first %s second %s'
1431 Aliases expand Python variables just like system calls using ! or !! do:
1431
1432 all expressions prefixed with '$' get expanded. For details of the
1432 Note that %l and %s are mutually exclusive. You can only use one or
1433 semantic rules, see PEP-215: http://www.python.org/peps/pep-0215.html.
1433 the other in your aliases.
1434 This is the library used by IPython for variable expansion. If you want
1434
1435 to access a true shell variable, an extra $ is necessary to prevent its
1435 Aliases expand Python variables just like system calls using ! or !!
1436 expansion by IPython:
1436 do: all expressions prefixed with '$' get expanded. For details of
1437
1437 the semantic rules, see PEP-215:
1438 In [6]: alias show echo
1438 http://www.python.org/peps/pep-0215.html. This is the library used by
1439 In [7]: PATH='A Python string'
1439 IPython for variable expansion. If you want to access a true shell
1440 In [8]: show $PATH
1440 variable, an extra $ is necessary to prevent its expansion by IPython:
1441 A Python string
1441
1442 In [9]: show $$PATH
1442 In [6]: alias show echo\
1443 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1443 In [7]: PATH='A Python string'\
1444
1444 In [8]: show $PATH\
1445 You can use the alias facility to acess all of $PATH. See the %rehash
1445 A Python string\
1446 and %rehashx functions, which automatically create aliases for the
1446 In [9]: show $$PATH\
1447 contents of your $PATH.
1447 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1448
1448
1449 If called with no parameters, %alias prints the current alias table.
1449 You can use the alias facility to acess all of $PATH. See the %rehash
1450
1450 and %rehashx functions, which automatically create aliases for the
1451
1451 contents of your $PATH.
1452 %autocall: Make functions callable without having to type parentheses.
1452
1453
1453 If called with no parameters, %alias prints the current alias table.
1454 Usage:
1454
1455
1455 **%autocall**::
1456 %autocall [mode]
1456
1457
1457 Make functions callable without having to type parentheses.
1458 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
1458
1459 value is toggled on and off (remembering the previous state).
1459 Usage:
1460
1460
1461 In more detail, these values mean:
1461 %autocall [mode]
1462
1462
1463 0 -> fully disabled
1463 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
1464
1464 value is toggled on and off (remembering the previous state).
1465 1 -> active, but do not apply if there are no arguments on the line.
1465
1466
1466 In more detail, these values mean:
1467 In this mode, you get:
1467
1468
1468 0 -> fully disabled
1469 In [1]: callable Out[1]: <built-in function callable>
1469
1470
1470 1 -> active, but do not apply if there are no arguments on the line.
1471 In [2]: callable 'hello' ---> callable('hello') Out[2]: False
1471
1472
1472 In this mode, you get:
1473 2 -> Active always. Even if no arguments are present, the callable
1473
1474 object is called:
1474 In [1]: callable
1475
1475 Out[1]: <built-in function callable>
1476 In [4]: callable ---> callable()
1476
1477
1477 In [2]: callable 'hello'
1478 Note that even with autocall off, you can still use '/' at the start of
1478 ------> callable('hello')
1479 a line to treat the first argument on the command line as a function and
1479 Out[2]: False
1480 add parentheses to it:
1480
1481
1481 2 -> Active always. Even if no arguments are present, the callable
1482 In [8]: /str 43 ---> str(43) Out[8]: '43'
1482 object is called:
1483
1483
1484
1484 In [4]: callable
1485 %autoindent: Toggle autoindent on/off (if available).
1485 ------> callable()
1486
1486
1487
1487 Note that even with autocall off, you can still use '/' at the start of
1488 %automagic: Make magic functions callable without having to type the
1488 a line to treat the first argument on the command line as a function
1489 initial %.
1489 and add parentheses to it:
1490
1490
1491 Without argumentsl toggles on/off (when off, you must call it as
1491 In [8]: /str 43
1492 %automagic, of course). With arguments it sets the value, and you can
1492 ------> str(43)
1493 use any of (case insensitive):
1493 Out[8]: '43'
1494
1494
1495 - on,1,True: to activate
1495 **%autoindent**::
1496
1496
1497 - off,0,False: to deactivate.
1497 Toggle autoindent on/off (if available).
1498
1498
1499 Note that magic functions have lowest priority, so if there's a variable
1499 **%automagic**::
1500 whose name collides with that of a magic fn, automagic won't work for
1500
1501 that function (you get the variable instead). However, if you delete the
1501 Make magic functions callable without having to type the initial %.
1502 variable (del var), the previously shadowed magic function becomes
1502
1503 visible to automagic again.
1503 Without argumentsl toggles on/off (when off, you must call it as
1504
1504 %automagic, of course). With arguments it sets the value, and you can
1505
1505 use any of (case insensitive):
1506 %bg: Run a job in the background, in a separate thread.
1506
1507
1507 - on,1,True: to activate
1508 For example,
1508
1509
1509 - off,0,False: to deactivate.
1510 %bg myfunc(x,y,z=1)
1510
1511
1511 Note that magic functions have lowest priority, so if there's a
1512 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
1512 variable whose name collides with that of a magic fn, automagic won't
1513 execution starts, a message will be printed indicating the job number.
1513 work for that function (you get the variable instead). However, if you
1514 If your job number is 5, you can use
1514 delete the variable (del var), the previously shadowed magic function
1515
1515 becomes visible to automagic again.
1516 myvar = jobs.result(5) or myvar = jobs[5].result
1516
1517
1517 **%bg**::
1518 to assign this result to variable 'myvar'.
1518
1519
1519 Run a job in the background, in a separate thread.
1520 IPython has a job manager, accessible via the 'jobs' object. You can
1520
1521 type jobs? to get more information about it, and use jobs.<TAB> to see
1521 For example,
1522 its attributes. All attributes not starting with an underscore are meant
1522
1523 for public use.
1523 %bg myfunc(x,y,z=1)
1524
1524
1525 In particular, look at the jobs.new() method, which is used to create
1525 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
1526 new jobs. This magic %bg function is just a convenience wrapper around
1526 execution starts, a message will be printed indicating the job
1527 jobs.new(), for expression-based jobs. If you want to create a new job
1527 number. If your job number is 5, you can use
1528 with an explicit function object and arguments, you must call jobs.new()
1528
1529 directly.
1529 myvar = jobs.result(5) or myvar = jobs[5].result
1530
1530
1531 The jobs.new docstring also describes in detail several important
1531 to assign this result to variable 'myvar'.
1532 caveats associated with a thread-based model for background job
1532
1533 execution. Type jobs.new? for details.
1533 IPython has a job manager, accessible via the 'jobs' object. You can
1534
1534 type jobs? to get more information about it, and use jobs.<TAB> to see
1535 You can check the status of all jobs with jobs.status().
1535 its attributes. All attributes not starting with an underscore are
1536
1536 meant for public use.
1537 The jobs variable is set by IPython into the Python builtin namespace.
1537
1538 If you ever declare a variable named 'jobs', you will shadow this name.
1538 In particular, look at the jobs.new() method, which is used to create
1539 You can either delete your global jobs variable to regain access to the
1539 new jobs. This magic %bg function is just a convenience wrapper
1540 job manager, or make a new name and assign it manually to the manager
1540 around jobs.new(), for expression-based jobs. If you want to create a
1541 (stored in IPython's namespace). For example, to assign the job manager
1541 new job with an explicit function object and arguments, you must call
1542 to the Jobs name, use:
1542 jobs.new() directly.
1543
1543
1544 Jobs = __builtins__.jobs
1544 The jobs.new docstring also describes in detail several important
1545
1545 caveats associated with a thread-based model for background job
1546
1546 execution. Type jobs.new? for details.
1547 %bookmark: Manage IPython's bookmark system.
1547
1548
1548 You can check the status of all jobs with jobs.status().
1549 %bookmark <name> - set bookmark to current dir %bookmark <name> <dir> -
1549
1550 set bookmark to <dir> %bookmark -l - list all bookmarks %bookmark -d
1550 The jobs variable is set by IPython into the Python builtin namespace.
1551 <name> - remove bookmark %bookmark -r - remove all bookmarks
1551 If you ever declare a variable named 'jobs', you will shadow this
1552
1552 name. You can either delete your global jobs variable to regain
1553 You can later on access a bookmarked folder with: %cd -b <name> or
1553 access to the job manager, or make a new name and assign it manually
1554 simply '%cd <name>' if there is no directory called <name> AND there is
1554 to the manager (stored in IPython's namespace). For example, to
1555 such a bookmark defined.
1555 assign the job manager to the Jobs name, use:
1556
1556
1557 Your bookmarks persist through IPython sessions, but they are associated
1557 Jobs = __builtins__.jobs
1558 with each profile.
1558
1559
1559 **%bookmark**::
1560
1560
1561 %cd: Change the current working directory.
1561 Manage IPython's bookmark system.
1562
1562
1563 This command automatically maintains an internal list of directories you
1563 %bookmark <name> - set bookmark to current dir
1564 visit during your IPython session, in the variable _dh. The command
1564 %bookmark <name> <dir> - set bookmark to <dir>
1565 %dhist shows this history nicely formatted. You can also do 'cd -<tab>'
1565 %bookmark -l - list all bookmarks
1566 to see directory history conveniently.
1566 %bookmark -d <name> - remove bookmark
1567
1567 %bookmark -r - remove all bookmarks
1568 Usage:
1568
1569
1569 You can later on access a bookmarked folder with:
1570 cd 'dir': changes to directory 'dir'.
1570 %cd -b <name>
1571
1571 or simply '%cd <name>' if there is no directory called <name> AND
1572 cd -: changes to the last visited directory.
1572 there is such a bookmark defined.
1573
1573
1574 cd -<n>: changes to the n-th directory in the directory history.
1574 Your bookmarks persist through IPython sessions, but they are
1575
1575 associated with each profile.
1576 cd -b <bookmark_name>: jump to a bookmark set by %bookmark (note: cd
1576
1577 <bookmark_name> is enough if there is no directory <bookmark_name>, but
1577 **%cd**::
1578 a bookmark with the name exists.) 'cd -b <tab>' allows you to
1578
1579 tab-complete bookmark names.
1579 Change the current working directory.
1580
1580
1581 Options:
1581 This command automatically maintains an internal list of directories
1582
1582 you visit during your IPython session, in the variable _dh. The
1583 -q: quiet. Do not print the working directory after the cd command is
1583 command %dhist shows this history nicely formatted. You can also
1584 executed. By default IPython's cd command does print this directory,
1584 do 'cd -<tab>' to see directory history conveniently.
1585 since the default prompts do not display path information.
1585
1586
1586 Usage:
1587 Note that !cd doesn't work for this purpose because the shell where
1587
1588 !command runs is immediately discarded after executing 'command'.
1588 cd 'dir': changes to directory 'dir'.
1589
1589
1590
1590 cd -: changes to the last visited directory.
1591 %color_info: Toggle color_info.
1591
1592
1592 cd -<n>: changes to the n-th directory in the directory history.
1593 The color_info configuration parameter controls whether colors are used
1593
1594 for displaying object details (by things like %psource, %pfile or the
1594 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
1595 '?' system). This function toggles this value with each call.
1595 (note: cd <bookmark_name> is enough if there is no
1596
1596 directory <bookmark_name>, but a bookmark with the name exists.)
1597 Note that unless you have a fairly recent pager (less works better than
1597 'cd -b <tab>' allows you to tab-complete bookmark names.
1598 more) in your system, using colored object information displays will not
1598
1599 work properly. Test it and see.
1599 Options:
1600
1600
1601
1601 -q: quiet. Do not print the working directory after the cd command is
1602 %colors: Switch color scheme for prompts, info system and exception
1602 executed. By default IPython's cd command does print this directory,
1603 handlers.
1603 since the default prompts do not display path information.
1604
1604
1605 Currently implemented schemes: NoColor, Linux, LightBG.
1605 Note that !cd doesn't work for this purpose because the shell where
1606
1606 !command runs is immediately discarded after executing 'command'.
1607 Color scheme names are not case-sensitive.
1607
1608
1608 **%clear**::
1609
1609
1610 %cpaste: Allows you to paste & execute a pre-formatted code block from
1610 Clear various data (e.g. stored history data)
1611 clipboard
1611
1612
1612 %clear out - clear output history
1613 You must terminate the block with '-' (two minus-signs) alone on the
1613 %clear in - clear input history
1614 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
1614 %clear shadow_compress - Compresses shadow history (to speed up ipython)
1615 is the new sentinel for this operation)
1615 %clear shadow_nuke - permanently erase all entries in shadow history
1616
1616 %clear dhist - clear dir history
1617 The block is dedented prior to execution to enable execution of method
1617
1618 definitions. '>' and '+' characters at the beginning of a line are
1618 **%color_info**::
1619 ignored, to allow pasting directly from e-mails or diff files. The
1619
1620 executed block is also assigned to variable named 'pasted_block' for
1620 Toggle color_info.
1621 later editing with '%edit pasted_block'.
1621
1622
1622 The color_info configuration parameter controls whether colors are
1623 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
1623 used for displaying object details (by things like %psource, %pfile or
1624 This assigns the pasted block to variable 'foo' as string, without
1624 the '?' system). This function toggles this value with each call.
1625 dedenting or executing it.
1625
1626
1626 Note that unless you have a fairly recent pager (less works better
1627 Do not be alarmed by garbled output on Windows (it's a readline bug).
1627 than more) in your system, using colored object information displays
1628 Just press enter and type - (and press enter again) and the block will
1628 will not work properly. Test it and see.
1629 be what was just pasted.
1629
1630
1630 **%colors**::
1631 IPython statements (magics, shell escapes) are not supported (yet).
1631
1632
1632 Switch color scheme for prompts, info system and exception handlers.
1633
1633
1634 %debug: Activate the interactive debugger in post-mortem mode.
1634 Currently implemented schemes: NoColor, Linux, LightBG.
1635
1635
1636 If an exception has just occurred, this lets you inspect its stack
1636 Color scheme names are not case-sensitive.
1637 frames interactively. Note that this will always work only on the last
1637
1638 traceback that occurred, so you must call this quickly after an
1638 **%cpaste**::
1639 exception that you wish to inspect has fired, because if another one
1639
1640 occurs, it clobbers the previous one.
1640 Allows you to paste & execute a pre-formatted code block from clipboard
1641
1641
1642 If you want IPython to automatically do this on every exception, see the
1642 You must terminate the block with '--' (two minus-signs) alone on the
1643 %pdb magic for more details.
1643 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
1644
1644 is the new sentinel for this operation)
1645
1645
1646 %dhist: Print your history of visited directories.
1646 The block is dedented prior to execution to enable execution of method
1647
1647 definitions. '>' and '+' characters at the beginning of a line are
1648 %dhist -> print full history
1648 ignored, to allow pasting directly from e-mails or diff files. The
1649 %dhist n -> print last n entries only
1649 executed block is also assigned to variable named 'pasted_block' for
1650 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)
1650 later editing with '%edit pasted_block'.
1651
1651
1652 This history is automatically maintained by the %cd command, and always
1652 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
1653 available as the global list variable _dh. You can use %cd -<n> to go to
1653 This assigns the pasted block to variable 'foo' as string, without
1654 directory number <n>.
1654 dedenting or executing it.
1655
1655
1656 Note that most of time, you should view directory history by entering cd
1656 Do not be alarmed by garbled output on Windows (it's a readline bug).
1657 -<TAB>.
1657 Just press enter and type -- (and press enter again) and the block
1658
1658 will be what was just pasted.
1659
1659
1660 %dirs: Return the current directory stack.
1660 IPython statements (magics, shell escapes) are not supported (yet).
1661
1661
1662
1662 **%debug**::
1663 %doctest_mode: Toggle doctest mode on and off.
1663
1664
1664 Activate the interactive debugger in post-mortem mode.
1665 This mode allows you to toggle the prompt behavior between normal
1665
1666 IPython prompts and ones that are as similar to the default IPython
1666 If an exception has just occurred, this lets you inspect its stack
1667 interpreter as possible.
1667 frames interactively. Note that this will always work only on the last
1668
1668 traceback that occurred, so you must call this quickly after an
1669 It also supports the pasting of code snippets that have leading 'Β»>' and
1669 exception that you wish to inspect has fired, because if another one
1670 '...' prompts in them. This means that you can paste doctests from files
1670 occurs, it clobbers the previous one.
1671 or docstrings (even if they have leading whitespace), and the code will
1671
1672 execute correctly. You can then use '%history -tn' to see the translated
1672 If you want IPython to automatically do this on every exception, see
1673 history without line numbers; this will give you the input after removal
1673 the %pdb magic for more details.
1674 of all the leading prompts and whitespace, which can be pasted back into
1674
1675 an editor.
1675 **%dhist**::
1676
1676
1677 With these features, you can switch into this mode easily whenever you
1677 Print your history of visited directories.
1678 need to do testing and changes to doctests, without having to leave your
1678
1679 existing IPython session.
1679 %dhist -> print full history\
1680
1680 %dhist n -> print last n entries only\
1681
1681 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\
1682 %ed: Alias to %edit.
1682
1683
1683 This history is automatically maintained by the %cd command, and
1684
1684 always available as the global list variable _dh. You can use %cd -<n>
1685 %edit: Bring up an editor and execute the resulting code.
1685 to go to directory number <n>.
1686
1686
1687 Usage: %edit [options] [args]
1687 Note that most of time, you should view directory history by entering
1688
1688 cd -<TAB>.
1689 %edit runs IPython's editor hook. The default version of this hook is
1689
1690 set to call the __IPYTHON__.rc.editor command. This is read from your
1690 **%dirs**::
1691 environment variable $EDITOR. If this isn't found, it will default to vi
1691
1692 under Linux/Unix and to notepad under Windows. See the end of this
1692 Return the current directory stack.
1693 docstring for how to change the editor hook.
1693
1694
1694 **%doctest_mode**::
1695 You can also set the value of this editor via the command line option
1695
1696 '-editor' or in your ipythonrc file. This is useful if you wish to use
1696 Toggle doctest mode on and off.
1697 specifically for IPython an editor different from your typical default
1697
1698 (and for Windows users who typically don't set environment variables).
1698 This mode allows you to toggle the prompt behavior between normal
1699
1699 IPython prompts and ones that are as similar to the default IPython
1700 This command allows you to conveniently edit multi-line code right in
1700 interpreter as possible.
1701 your IPython session.
1701
1702
1702 It also supports the pasting of code snippets that have leading '>>>'
1703 If called without arguments, %edit opens up an empty editor with a
1703 and '...' prompts in them. This means that you can paste doctests from
1704 temporary file and will execute the contents of this file when you close
1704 files or docstrings (even if they have leading whitespace), and the
1705 it (don't forget to save it!).
1705 code will execute correctly. You can then use '%history -tn' to see
1706
1706 the translated history without line numbers; this will give you the
1707 Options:
1707 input after removal of all the leading prompts and whitespace, which
1708
1708 can be pasted back into an editor.
1709 -n <number>: open the editor at a specified line number. By default, the
1709
1710 IPython editor hook uses the unix syntax 'editor +N filename', but you
1710 With these features, you can switch into this mode easily whenever you
1711 can configure this by providing your own modified hook if your favorite
1711 need to do testing and changes to doctests, without having to leave
1712 editor supports line-number specifications with a different syntax.
1712 your existing IPython session.
1713
1713
1714 -p: this will call the editor with the same data as the previous time it
1714 **%ed**::
1715 was used, regardless of how long ago (in your current session) it was.
1715
1716
1716 Alias to %edit.
1717 -r: use 'raw' input. This option only applies to input taken from the
1717
1718 user's history. By default, the 'processed' history is used, so that
1718 **%edit**::
1719 magics are loaded in their transformed version to valid Python. If this
1719
1720 option is given, the raw input as typed as the command line is used
1720 Bring up an editor and execute the resulting code.
1721 instead. When you exit the editor, it will be executed by IPython's own
1721
1722 processor.
1722 Usage:
1723
1723 %edit [options] [args]
1724 -x: do not execute the edited code immediately upon exit. This is mainly
1724
1725 useful if you are editing programs which need to be called with command
1725 %edit runs IPython's editor hook. The default version of this hook is
1726 line arguments, which you can then do using %run.
1726 set to call the __IPYTHON__.rc.editor command. This is read from your
1727
1727 environment variable $EDITOR. If this isn't found, it will default to
1728 Arguments:
1728 vi under Linux/Unix and to notepad under Windows. See the end of this
1729
1729 docstring for how to change the editor hook.
1730 If arguments are given, the following possibilites exist:
1730
1731
1731 You can also set the value of this editor via the command line option
1732 - The arguments are numbers or pairs of dash-separated numbers (like 1
1732 '-editor' or in your ipythonrc file. This is useful if you wish to use
1733 4-8 9). These are interpreted as lines of previous input to be loaded
1733 specifically for IPython an editor different from your typical default
1734 into the editor. The syntax is the same of the %macro command.
1734 (and for Windows users who typically don't set environment variables).
1735
1735
1736 - If the argument doesn't start with a number, it is evaluated as a
1736 This command allows you to conveniently edit multi-line code right in
1737 variable and its contents loaded into the editor. You can thus edit any
1737 your IPython session.
1738 string which contains python code (including the result of previous edits).
1738
1739
1739 If called without arguments, %edit opens up an empty editor with a
1740 - If the argument is the name of an object (other than a string),
1740 temporary file and will execute the contents of this file when you
1741 IPython will try to locate the file where it was defined and open the
1741 close it (don't forget to save it!).
1742 editor at the point where it is defined. You can use '%edit function' to
1742
1743 load an editor exactly at the point where 'function' is defined, edit it
1743
1744 and have the file be executed automatically.
1744 Options:
1745
1745
1746 If the object is a macro (see %macro for details), this opens up your
1746 -n <number>: open the editor at a specified line number. By default,
1747 specified editor with a temporary file containing the macro's data. Upon
1747 the IPython editor hook uses the unix syntax 'editor +N filename', but
1748 exit, the macro is reloaded with the contents of the file.
1748 you can configure this by providing your own modified hook if your
1749
1749 favorite editor supports line-number specifications with a different
1750 Note: opening at an exact line is only supported under Unix, and some
1750 syntax.
1751 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1751
1752 '+NUMBER' parameter necessary for this feature. Good editors like
1752 -p: this will call the editor with the same data as the previous time
1753 (X)Emacs, vi, jed, pico and joe all do.
1753 it was used, regardless of how long ago (in your current session) it
1754
1754 was.
1755 If the argument is not found as a variable, IPython will look for a
1755
1756 file with that name (adding .py if necessary) and load it into the
1756 -r: use 'raw' input. This option only applies to input taken from the
1757 editor. It will execute its contents with execfile() when you exit,
1757 user's history. By default, the 'processed' history is used, so that
1758 loading any code in the file into your interactive namespace.
1758 magics are loaded in their transformed version to valid Python. If
1759
1759 this option is given, the raw input as typed as the command line is
1760 After executing your code, %edit will return as output the code you
1760 used instead. When you exit the editor, it will be executed by
1761 typed in the editor (except when it was an existing file). This way you
1761 IPython's own processor.
1762 can reload the code in further invocations of %edit as a variable, via
1762
1763 _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of the
1763 -x: do not execute the edited code immediately upon exit. This is
1764 output.
1764 mainly useful if you are editing programs which need to be called with
1765
1765 command line arguments, which you can then do using %run.
1766 Note that %edit is also available through the alias %ed.
1766
1767
1767
1768 This is an example of creating a simple function inside the editor and
1768 Arguments:
1769 then modifying it. First, start up the editor::
1769
1770
1770 If arguments are given, the following possibilites exist:
1771 In [1]: ed
1771
1772 Editing... done. Executing edited code...
1772 - The arguments are numbers or pairs of colon-separated numbers (like
1773 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
1773 1 4:8 9). These are interpreted as lines of previous input to be
1774
1774 loaded into the editor. The syntax is the same of the %macro command.
1775 We can then call the function foo():
1775
1776
1776 - If the argument doesn't start with a number, it is evaluated as a
1777 In [2]: foo()
1777 variable and its contents loaded into the editor. You can thus edit
1778 foo() was defined in an editing session
1778 any string which contains python code (including the result of
1779
1779 previous edits).
1780 Now we edit foo. IPython automatically loads the editor with the
1780
1781 (temporary) file where foo() was previously defined:
1781 - If the argument is the name of an object (other than a string),
1782
1782 IPython will try to locate the file where it was defined and open the
1783 In [3]: ed foo
1783 editor at the point where it is defined. You can use `%edit function`
1784 Editing... done. Executing edited code...
1784 to load an editor exactly at the point where 'function' is defined,
1785
1785 edit it and have the file be executed automatically.
1786 And if we call foo() again we get the modified version:
1786
1787
1787 If the object is a macro (see %macro for details), this opens up your
1788 In [4]: foo()
1788 specified editor with a temporary file containing the macro's data.
1789 foo() has now been changed!
1789 Upon exit, the macro is reloaded with the contents of the file.
1790
1790
1791 Here is an example of how to edit a code snippet successive times. First
1791 Note: opening at an exact line is only supported under Unix, and some
1792 we call the editor:
1792 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1793
1793 '+NUMBER' parameter necessary for this feature. Good editors like
1794 In [8]: ed
1794 (X)Emacs, vi, jed, pico and joe all do.
1795 Editing... done. Executing edited code...
1795
1796 hello
1796 - If the argument is not found as a variable, IPython will look for a
1797 Out[8]: "print 'hello'\n"
1797 file with that name (adding .py if necessary) and load it into the
1798
1798 editor. It will execute its contents with execfile() when you exit,
1799 Now we call it again with the previous output (stored in _):
1799 loading any code in the file into your interactive namespace.
1800
1800
1801 In [9]: ed _
1801 After executing your code, %edit will return as output the code you
1802 Editing... done. Executing edited code...
1802 typed in the editor (except when it was an existing file). This way
1803 hello world
1803 you can reload the code in further invocations of %edit as a variable,
1804 Out[9]: "print 'hello world'\n"
1804 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1805
1805 the output.
1806 Now we call it with the output #8 (stored in _8, also as Out[8]):
1806
1807
1807 Note that %edit is also available through the alias %ed.
1808 In [10]: ed _8
1808
1809 Editing... done. Executing edited code...
1809 This is an example of creating a simple function inside the editor and
1810 hello again
1810 then modifying it. First, start up the editor:
1811 Out[10]: "print 'hello again'\n"
1811
1812
1812 In [1]: ed\
1813 Changing the default editor hook:
1813 Editing... done. Executing edited code...\
1814
1814 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
1815 If you wish to write your own editor hook, you can put it in a
1815
1816 configuration file which you load at startup time. The default hook is
1816 We can then call the function foo():
1817 defined in the IPython.hooks module, and you can use that as a starting
1817
1818 example for further modifications. That file also has general
1818 In [2]: foo()\
1819 instructions on how to set a new hook for use once you've defined it.
1819 foo() was defined in an editing session
1820
1820
1821
1821 Now we edit foo. IPython automatically loads the editor with the
1822 %env: List environment variables.
1822 (temporary) file where foo() was previously defined:
1823
1823
1824
1824 In [3]: ed foo\
1825 %exit: Exit IPython, confirming if configured to do so.
1825 Editing... done. Executing edited code...
1826
1826
1827 You can configure whether IPython asks for confirmation upon exit by
1827 And if we call foo() again we get the modified version:
1828 setting the confirm_exit flag in the ipythonrc file.
1828
1829
1829 In [4]: foo()\
1830
1830 foo() has now been changed!
1831 %logoff: Temporarily stop logging.
1831
1832
1832 Here is an example of how to edit a code snippet successive
1833 You must have previously started logging.
1833 times. First we call the editor:
1834
1834
1835
1835 In [8]: ed\
1836 %logon: Restart logging.
1836 Editing... done. Executing edited code...\
1837
1837 hello\
1838 This function is for restarting logging which you've temporarily stopped
1838 Out[8]: "print 'hello'\n"
1839 with %logoff. For starting logging for the first time, you must use the
1839
1840 %logstart function, which allows you to specify an optional log filename.
1840 Now we call it again with the previous output (stored in _):
1841
1841
1842
1842 In [9]: ed _\
1843 %logstart: Start logging anywhere in a session.
1843 Editing... done. Executing edited code...\
1844
1844 hello world\
1845 %logstart [-o|-r|-t] [log_name [log_mode]]
1845 Out[9]: "print 'hello world'\n"
1846
1846
1847 If no name is given, it defaults to a file named 'ipython_log.py' in
1847 Now we call it with the output #8 (stored in _8, also as Out[8]):
1848 your current directory, in 'rotate' mode (see below).
1848
1849
1849 In [10]: ed _8\
1850 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1850 Editing... done. Executing edited code...\
1851 history up to that point and then continues logging.
1851 hello again\
1852
1852 Out[10]: "print 'hello again'\n"
1853 %logstart takes a second optional parameter: logging mode. This can be
1853
1854 one of (note that the modes are given unquoted):
1854
1855 append: well, that says it.
1855 Changing the default editor hook:
1856 backup: rename (if exists) to name and start name.
1856
1857 global: single logfile in your home dir, appended to.
1857 If you wish to write your own editor hook, you can put it in a
1858 over : overwrite existing log.
1858 configuration file which you load at startup time. The default hook
1859 rotate: create rotating logs name.1 , name.2 , etc.
1859 is defined in the IPython.hooks module, and you can use that as a
1860
1860 starting example for further modifications. That file also has
1861 Options:
1861 general instructions on how to set a new hook for use once you've
1862
1862 defined it.
1863 -o: log also IPython's output. In this mode, all commands which generate
1863
1864 an Out[NN] prompt are recorded to the logfile, right after their
1864 **%env**::
1865 corresponding input line. The output lines are always prepended with a
1865
1866 '#[Out]# ' marker, so that the log remains valid Python code.
1866 List environment variables.
1867
1867
1868 Since this marker is always the same, filtering only the output from a
1868 **%exit**::
1869 log is very easy, using for example a simple awk call:
1869
1870
1870 Exit IPython, confirming if configured to do so.
1871 awk -F'#
1871
1872
1872 You can configure whether IPython asks for confirmation upon exit by
1873 \begin{displaymath}Out\end{displaymath}
1873 setting the confirm_exit flag in the ipythonrc file.
1874
1874
1875 # ' 'if($2) print $2' ipython_log.py
1875 **%hist**::
1876
1876
1877 -r: log 'raw' input. Normally, IPython's logs contain the processed
1877 Alternate name for %history.
1878 input, so that user lines are logged in their final form, converted into
1878
1879 valid Python. For example, %Exit is logged as '_ip.magic("Exit"). If the
1879 **%history**::
1880 -r flag is given, all input is logged exactly as typed, with no
1880
1881 transformations applied.
1881 Print input history (_i<n> variables), with most recent last.
1882
1882
1883 -t: put timestamps before each input line logged (these are put in
1883 %history -> print at most 40 inputs (some may be multi-line)\
1884 comments).
1884 %history n -> print at most n inputs\
1885
1885 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\
1886
1886
1887 %logstate: Print the status of the logging system.
1887 Each input's number <n> is shown, and is accessible as the
1888
1888 automatically generated variable _i<n>. Multi-line statements are
1889
1889 printed starting at a new line for easy copy/paste.
1890 %logstop: Fully stop logging and close log file.
1890
1891
1891
1892 In order to start logging again, a new %logstart call needs to be made,
1892 Options:
1893 possibly (though not necessarily) with a new filename, mode and other
1893
1894 options.
1894 -n: do NOT print line numbers. This is useful if you want to get a
1895
1895 printout of many lines which can be directly pasted into a text
1896
1896 editor.
1897 %lsmagic: List currently available magic functions.
1897
1898
1898 This feature is only available if numbered prompts are in use.
1899
1899
1900 %macro: Define a set of input lines as a macro for future re-execution.
1900 -t: (default) print the 'translated' history, as IPython understands it.
1901
1901 IPython filters your input and converts it all into valid Python source
1902 Usage:
1902 before executing it (things like magics or aliases are turned into
1903 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1903 function calls, for example). With this option, you'll see the native
1904
1904 history instead of the user-entered version: '%cd /' will be seen as
1905 Options:
1905 '_ip.magic("%cd /")' instead of '%cd /'.
1906
1906
1907 -r: use 'raw' input. By default, the 'processed' history is used, so
1907 -r: print the 'raw' history, i.e. the actual commands you typed.
1908 that magics are loaded in their transformed version to valid Python. If
1908
1909 this option is given, the raw input as typed as the command line is used
1909 -g: treat the arg as a pattern to grep for in (full) history.
1910 instead.
1910 This includes the "shadow history" (almost all commands ever written).
1911
1911 Use '%hist -g' to show full shadow history (may be very long).
1912 This will define a global variable called 'name' which is a string made
1912 In shadow history, every index nuwber starts with 0.
1913 of joining the slices and lines you specify (n1,n2,... numbers above)
1913
1914 from your input history into a single string. This variable acts like an
1914 -f FILENAME: instead of printing the output to the screen, redirect it to
1915 automatic function which re-executes those lines as if you had typed
1915 the given file. The file is always overwritten, though IPython asks for
1916 them. You just type 'name' at the prompt and the code executes.
1916 confirmation first if it already exists.
1917
1917
1918 The notation for indicating number ranges is: n1-n2 means 'use line
1918 **%logoff**::
1919 numbers n1,...n2' (the endpoint is included). That is, '5-7' means using
1919
1920 the lines numbered 5,6 and 7.
1920 Temporarily stop logging.
1921
1921
1922 Note: as a 'hidden' feature, you can also use traditional python slice
1922 You must have previously started logging.
1923 notation, where N:M means numbers N through M-1.
1923
1924
1924 **%logon**::
1925 For example, if your history contains (%hist prints it):
1925
1926
1926 Restart logging.
1927 44: x=1
1927
1928 45: y=3
1928 This function is for restarting logging which you've temporarily
1929 46: z=x+y
1929 stopped with %logoff. For starting logging for the first time, you
1930 47: print x
1930 must use the %logstart function, which allows you to specify an
1931 48: a=5
1931 optional log filename.
1932 49: print 'x',x,'y',y
1932
1933
1933 **%logstart**::
1934 you can create a macro with lines 44 through 47 (included) and line 49
1934
1935 called my_macro with:
1935 Start logging anywhere in a session.
1936
1936
1937 In [51]: %macro my_macro 44-47 49
1937 %logstart [-o|-r|-t] [log_name [log_mode]]
1938
1938
1939 Now, typing 'my_macro' (without quotes) will re-execute all this code in
1939 If no name is given, it defaults to a file named 'ipython_log.py' in your
1940 one pass.
1940 current directory, in 'rotate' mode (see below).
1941
1941
1942 You don't need to give the line-numbers in order, and any given line
1942 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1943 number can appear multiple times. You can assemble macros with any lines
1943 history up to that point and then continues logging.
1944 from your input history in any order.
1944
1945
1945 %logstart takes a second optional parameter: logging mode. This can be one
1946 The macro is a simple object which holds its value in an attribute, but
1946 of (note that the modes are given unquoted):\
1947 IPython's display system checks for macros and executes them as code
1947 append: well, that says it.\
1948 instead of printing them when you type their name.
1948 backup: rename (if exists) to name~ and start name.\
1949
1949 global: single logfile in your home dir, appended to.\
1950 You can view a macro's contents by explicitly printing it with:
1950 over : overwrite existing log.\
1951
1951 rotate: create rotating logs name.1~, name.2~, etc.
1952 'print macro_name'.
1952
1953
1953 Options:
1954 For one-off cases which DON'T contain magic function calls in them you
1954
1955 can obtain similar results by explicitly executing slices from your
1955 -o: log also IPython's output. In this mode, all commands which
1956 input history with:
1956 generate an Out[NN] prompt are recorded to the logfile, right after
1957
1957 their corresponding input line. The output lines are always
1958 In [60]: exec In[44:48]+In[49]
1958 prepended with a '#[Out]# ' marker, so that the log remains valid
1959
1959 Python code.
1960
1960
1961 %magic: Print information about the magic function system.
1961 Since this marker is always the same, filtering only the output from
1962
1962 a log is very easy, using for example a simple awk call:
1963
1963
1964 %page: Pretty print the object and display it through a pager.
1964 awk -F'#\[Out\]# ' '{if($2) {print $2}}' ipython_log.py
1965
1965
1966 %page [options] OBJECT
1966 -r: log 'raw' input. Normally, IPython's logs contain the processed
1967
1967 input, so that user lines are logged in their final form, converted
1968 If no object is given, use _ (last output).
1968 into valid Python. For example, %Exit is logged as
1969
1969 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1970 Options:
1970 exactly as typed, with no transformations applied.
1971
1971
1972 -r: page str(object), don't pretty-print it.
1972 -t: put timestamps before each input line logged (these are put in
1973
1973 comments).
1974
1974
1975 %pdb: Control the automatic calling of the pdb interactive debugger.
1975 **%logstate**::
1976
1976
1977 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1977 Print the status of the logging system.
1978 argument it works as a toggle.
1978
1979
1979 **%logstop**::
1980 When an exception is triggered, IPython can optionally call the
1980
1981 interactive pdb debugger after the traceback printout. %pdb toggles this
1981 Fully stop logging and close log file.
1982 feature on and off.
1982
1983
1983 In order to start logging again, a new %logstart call needs to be made,
1984 The initial state of this feature is set in your ipythonrc configuration
1984 possibly (though not necessarily) with a new filename, mode and other
1985 file (the variable is called 'pdb').
1985 options.
1986
1986
1987 If you want to just activate the debugger AFTER an exception has fired,
1987 **%lsmagic**::
1988 without having to type '%pdb on' and rerunning your code, you can use
1988
1989 the %debug magic.
1989 List currently available magic functions.
1990
1990
1991
1991 **%macro**::
1992 %pdef: Print the definition header for any callable object.
1992
1993
1993 Define a set of input lines as a macro for future re-execution.
1994 If the object is a class, print the constructor information.
1994
1995
1995 Usage:\
1996
1996 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1997 %pdoc: Print the docstring for an object.
1997
1998
1998 Options:
1999 If the given object is a class, it will print both the class and the
1999
2000 constructor docstrings.
2000 -r: use 'raw' input. By default, the 'processed' history is used,
2001
2001 so that magics are loaded in their transformed version to valid
2002
2002 Python. If this option is given, the raw input as typed as the
2003 %pfile: Print (or run through pager) the file where an object is defined.
2003 command line is used instead.
2004
2004
2005 The file opens at the line where the object definition begins. IPython
2005 This will define a global variable called `name` which is a string
2006 will honor the environment variable PAGER if set, and otherwise will do
2006 made of joining the slices and lines you specify (n1,n2,... numbers
2007 its best to print the file in a convenient form.
2007 above) from your input history into a single string. This variable
2008
2008 acts like an automatic function which re-executes those lines as if
2009 If the given argument is not an object currently defined, IPython will
2009 you had typed them. You just type 'name' at the prompt and the code
2010 try to interpret it as a filename (automatically adding a .py extension
2010 executes.
2011 if needed). You can thus use %pfile as a syntax highlighting code viewer.
2011
2012
2012 The notation for indicating number ranges is: n1-n2 means 'use line
2013
2013 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2014 %pinfo: Provide detailed information about an object.
2014 using the lines numbered 5,6 and 7.
2015
2015
2016 '%pinfo object' is just a synonym for object? or ?object.
2016 Note: as a 'hidden' feature, you can also use traditional python slice
2017
2017 notation, where N:M means numbers N through M-1.
2018
2018
2019 %popd: Change to directory popped off the top of the stack.
2019 For example, if your history contains (%hist prints it):
2020
2020
2021
2021 44: x=1\
2022 %profile: Print your currently active IPyhton profile.
2022 45: y=3\
2023
2023 46: z=x+y\
2024
2024 47: print x\
2025 %prun: Run a statement through the python code profiler.
2025 48: a=5\
2026
2026 49: print 'x',x,'y',y\
2027 Usage:
2027
2028 %prun [options] statement
2028 you can create a macro with lines 44 through 47 (included) and line 49
2029
2029 called my_macro with:
2030 The given statement (which doesn't require quote marks) is run via the
2030
2031 python profiler in a manner similar to the profile.run() function.
2031 In [51]: %macro my_macro 44-47 49
2032 Namespaces are internally managed to work correctly; profile.run cannot
2032
2033 be used in IPython because it makes certain assumptions about namespaces
2033 Now, typing `my_macro` (without quotes) will re-execute all this code
2034 which do not hold under IPython.
2034 in one pass.
2035
2035
2036 Options:
2036 You don't need to give the line-numbers in order, and any given line
2037
2037 number can appear multiple times. You can assemble macros with any
2038 -l <limit>: you can place restrictions on what or how much of the
2038 lines from your input history in any order.
2039 profile gets printed. The limit value can be:
2039
2040
2040 The macro is a simple object which holds its value in an attribute,
2041 * A string: only information for function names containing this string
2041 but IPython's display system checks for macros and executes them as
2042 is printed.
2042 code instead of printing them when you type their name.
2043
2043
2044 * An integer: only these many lines are printed.
2044 You can view a macro's contents by explicitly printing it with:
2045
2045
2046 * A float (between 0 and 1): this fraction of the report is printed (for
2046 'print macro_name'.
2047 example, use a limit of 0.4 to see the topmost 40% only).
2047
2048
2048 For one-off cases which DON'T contain magic function calls in them you
2049 You can combine several limits with repeated use of the option. For
2049 can obtain similar results by explicitly executing slices from your
2050 example, '-l __init__ -l 5' will print only the topmost 5 lines of
2050 input history with:
2051 information about class constructors.
2051
2052
2052 In [60]: exec In[44:48]+In[49]
2053 -r: return the pstats.Stats object generated by the profiling. This
2053
2054 object has all the information about the profile in it, and you can
2054 **%magic**::
2055 later use it for further analysis or in other functions.
2055
2056
2056 Print information about the magic function system.
2057 -s <key>: sort profile by given key. You can provide more than one key
2057
2058 by using the option several times: '-s key1 -s key2 -s key3...'. The
2058 **%mglob**::
2059 default sorting key is 'time'.
2059
2060
2060 This program allows specifying filenames with "mglob" mechanism.
2061 The following is copied verbatim from the profile documentation
2061 Supported syntax in globs (wilcard matching patterns)::
2062 referenced below:
2062
2063
2063 *.cpp ?ellowo*
2064 When more than one key is provided, additional keys are used as
2064 - obvious. Differs from normal glob in that dirs are not included.
2065 secondary criteria when the there is equality in all keys selected
2065 Unix users might want to write this as: "*.cpp" "?ellowo*"
2066 before them.
2066 rec:/usr/share=*.txt,*.doc
2067
2067 - get all *.txt and *.doc under /usr/share,
2068 Abbreviations can be used for any key names, as long as the abbreviation
2068 recursively
2069 is unambiguous. The following are the keys currently defined:
2069 rec:/usr/share
2070
2070 - All files under /usr/share, recursively
2071 Valid Arg Meaning
2071 rec:*.py
2072 "calls" call count
2072 - All .py files under current working dir, recursively
2073 "cumulative" cumulative time
2073 foo
2074 "file" file name
2074 - File or dir foo
2075 "module" file name
2075 !*.bak readme*
2076 "pcalls" primitive call count
2076 - readme*, exclude files ending with .bak
2077 "line" line number
2077 !.svn/ !.hg/ !*_Data/ rec:.
2078 "name" function name
2078 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
2079 "nfl" name/file/line
2079 Trailing / is the key, \ does not work!
2080 "stdname" standard name
2080 dir:foo
2081 "time" internal time
2081 - the directory foo if it exists (not files in foo)
2082
2082 dir:*
2083 Note that all sorts on statistics are in descending order (placing most
2083 - all directories in current folder
2084 time consuming items first), where as name, file, and line number
2084 foo.py bar.* !h* rec:*.py
2085 searches are in ascending order (i.e., alphabetical). The subtle
2085 - Obvious. !h* exclusion only applies for rec:*.py.
2086 distinction between "nfl" and "stdname" is that the standard name is a
2086 foo.py is *not* included twice.
2087 sort of the name as printed, which means that the embedded line numbers
2087 @filelist.txt
2088 get compared in an odd way. For example, lines 3, 20, and 40 would (if
2088 - All files listed in 'filelist.txt' file, on separate lines.
2089 the file names were the same) appear in the string order "20" "3" and
2089
2090 "40". In contrast, "nfl" does a numeric compare of the line numbers. In
2090 **%page**::
2091 fact, sort_stats("nfl") is the same as sort_stats("name", "file", "line").
2091
2092
2092 Pretty print the object and display it through a pager.
2093 -T <filename>: save profile results as shown on screen to a text file.
2093
2094 The profile is still shown on screen.
2094 %page [options] OBJECT
2095
2095
2096 -D <filename>: save (via dump_stats) profile statistics to given
2096 If no object is given, use _ (last output).
2097 filename. This data is in a format understod by the pstats module, and
2097
2098 is generated by a call to the dump_stats() method of profile objects.
2098 Options:
2099 The profile is still shown on screen.
2099
2100
2100 -r: page str(object), don't pretty-print it.
2101 If you want to run complete programs under the profiler's control, use
2101
2102 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
2102 **%pdb**::
2103 contains profiler specific options as described here.
2103
2104
2104 Control the automatic calling of the pdb interactive debugger.
2105 You can read the complete documentation for the profile module with:
2105
2106 In [1]: import profile; profile.help()
2106 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
2107
2107 argument it works as a toggle.
2108
2108
2109 %psearch: Search for object in namespaces by wildcard.
2109 When an exception is triggered, IPython can optionally call the
2110
2110 interactive pdb debugger after the traceback printout. %pdb toggles
2111 %psearch [options] PATTERN [OBJECT TYPE]
2111 this feature on and off.
2112
2112
2113 Note: ? can be used as a synonym for %psearch, at the beginning or at
2113 The initial state of this feature is set in your ipythonrc
2114 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
2114 configuration file (the variable is called 'pdb').
2115 rest of the command line must be unchanged (options come first), so for
2115
2116 example the following forms are equivalent
2116 If you want to just activate the debugger AFTER an exception has fired,
2117
2117 without having to type '%pdb on' and rerunning your code, you can use
2118 %psearch -i a* function -i a* function? ?-i a* function
2118 the %debug magic.
2119
2119
2120 Arguments:
2120 **%pdef**::
2121
2121
2122 PATTERN
2122 Print the definition header for any callable object.
2123
2123
2124 where PATTERN is a string containing * as a wildcard similar to its use
2124 If the object is a class, print the constructor information.
2125 in a shell. The pattern is matched in all namespaces on the search path.
2125
2126 By default objects starting with a single _ are not matched, many
2126 **%pdoc**::
2127 IPython generated objects have a single underscore. The default is case
2127
2128 insensitive matching. Matching is also done on the attributes of objects
2128 Print the docstring for an object.
2129 and not only on the objects in a module.
2129
2130
2130 If the given object is a class, it will print both the class and the
2131 [OBJECT TYPE]
2131 constructor docstrings.
2132
2132
2133 Is the name of a python type from the types module. The name is given in
2133 **%pfile**::
2134 lowercase without the ending type, ex. StringType is written string. By
2134
2135 adding a type here only objects matching the given type are matched.
2135 Print (or run through pager) the file where an object is defined.
2136 Using all here makes the pattern match all types (this is the default).
2136
2137
2137 The file opens at the line where the object definition begins. IPython
2138 Options:
2138 will honor the environment variable PAGER if set, and otherwise will
2139
2139 do its best to print the file in a convenient form.
2140 -a: makes the pattern match even objects whose names start with a single
2140
2141 underscore. These names are normally ommitted from the search.
2141 If the given argument is not an object currently defined, IPython will
2142
2142 try to interpret it as a filename (automatically adding a .py extension
2143 -i/-c: make the pattern case insensitive/sensitive. If neither of these
2143 if needed). You can thus use %pfile as a syntax highlighting code
2144 options is given, the default is read from your ipythonrc file. The
2144 viewer.
2145 option name which sets this value is 'wildcards_case_sensitive'. If this
2145
2146 option is not specified in your ipythonrc file, IPython's internal
2146 **%pinfo**::
2147 default is to do a case sensitive search.
2147
2148
2148 Provide detailed information about an object.
2149 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
2149
2150 specifiy can be searched in any of the following namespaces: 'builtin',
2150 '%pinfo object' is just a synonym for object? or ?object.
2151 'user', 'user_global','internal', 'alias', where 'builtin' and 'user'
2151
2152 are the search defaults. Note that you should not use quotes when
2152 **%popd**::
2153 specifying namespaces.
2153
2154
2154 Change to directory popped off the top of the stack.
2155 'Builtin' contains the python module builtin, 'user' contains all user
2155
2156 data, 'alias' only contain the shell aliases and no python objects,
2156 **%profile**::
2157 'internal' contains objects used by IPython. The 'user_global' namespace
2157
2158 is only used by embedded IPython instances, and it contains module-level
2158 Print your currently active IPyhton profile.
2159 globals. You can add namespaces to the search with -s or exclude them
2159
2160 with -e (these options can be given more than once).
2160 **%prun**::
2161
2161
2162 Examples:
2162 Run a statement through the python code profiler.
2163
2163
2164 %psearch a* -> objects beginning with an a %psearch -e builtin a* ->
2164 Usage:\
2165 objects NOT in the builtin space starting in a %psearch a* function ->
2165 %prun [options] statement
2166 all functions beginning with an a %psearch re.e* -> objects beginning
2166
2167 with an e in module re %psearch r*.e* -> objects that start with e in
2167 The given statement (which doesn't require quote marks) is run via the
2168 modules starting in r %psearch r*.* string -> all strings in modules
2168 python profiler in a manner similar to the profile.run() function.
2169 beginning with r
2169 Namespaces are internally managed to work correctly; profile.run
2170
2170 cannot be used in IPython because it makes certain assumptions about
2171 Case sensitve search:
2171 namespaces which do not hold under IPython.
2172
2172
2173 %psearch -c a* list all object beginning with lower case a
2173 Options:
2174
2174
2175 Show objects beginning with a single _:
2175 -l <limit>: you can place restrictions on what or how much of the
2176
2176 profile gets printed. The limit value can be:
2177 %psearch -a _* list objects beginning with a single underscore
2177
2178
2178 * A string: only information for function names containing this string
2179
2179 is printed.
2180 %psource: Print (or run through pager) the source code for an object.
2180
2181
2181 * An integer: only these many lines are printed.
2182
2182
2183 %pushd: Place the current dir on stack and change directory.
2183 * A float (between 0 and 1): this fraction of the report is printed
2184
2184 (for example, use a limit of 0.4 to see the topmost 40% only).
2185 Usage:
2185
2186 %pushd ['dirname']
2186 You can combine several limits with repeated use of the option. For
2187
2187 example, '-l __init__ -l 5' will print only the topmost 5 lines of
2188
2188 information about class constructors.
2189 %pwd: Return the current working directory path.
2189
2190
2190 -r: return the pstats.Stats object generated by the profiling. This
2191
2191 object has all the information about the profile in it, and you can
2192 %pycat: Show a syntax-highlighted file through a pager.
2192 later use it for further analysis or in other functions.
2193
2193
2194 This magic is similar to the cat utility, but it will assume the file to
2194 -s <key>: sort profile by given key. You can provide more than one key
2195 be Python source and will show it with syntax highlighting.
2195 by using the option several times: '-s key1 -s key2 -s key3...'. The
2196
2196 default sorting key is 'time'.
2197
2197
2198 %quickref: Show a quick reference sheet
2198 The following is copied verbatim from the profile documentation
2199
2199 referenced below:
2200
2200
2201 %quit: Exit IPython, confirming if configured to do so (like %exit)
2201 When more than one key is provided, additional keys are used as
2202
2202 secondary criteria when the there is equality in all keys selected
2203
2203 before them.
2204 %r: Repeat previous input.
2204
2205
2205 Abbreviations can be used for any key names, as long as the
2206 Note: Consider using the more powerfull %rep instead!
2206 abbreviation is unambiguous. The following are the keys currently
2207
2207 defined:
2208 If given an argument, repeats the previous command which starts with the
2208
2209 same string, otherwise it just repeats the previous input.
2209 Valid Arg Meaning\
2210
2210 "calls" call count\
2211 Shell escaped commands (with ! as first character) are not recognized by
2211 "cumulative" cumulative time\
2212 this system, only pure python code and magic commands.
2212 "file" file name\
2213
2213 "module" file name\
2214
2214 "pcalls" primitive call count\
2215 %rehashx: Update the alias table with all executable files in $PATH.
2215 "line" line number\
2216
2216 "name" function name\
2217 This version explicitly checks that every entry in $PATH is a file with
2217 "nfl" name/file/line\
2218 execute access (os.X_OK), so it is much slower than %rehash.
2218 "stdname" standard name\
2219
2219 "time" internal time
2220 Under Windows, it checks executability as a match agains a ``|``-separated
2220
2221 string of extensions, stored in the IPython config variable
2221 Note that all sorts on statistics are in descending order (placing
2222 win_exec_ext. This defaults to ``exe|com|bat``.
2222 most time consuming items first), where as name, file, and line number
2223
2223 searches are in ascending order (i.e., alphabetical). The subtle
2224 This function also resets the root module cache of module completer,
2224 distinction between "nfl" and "stdname" is that the standard name is a
2225 used on slow filesystems.
2225 sort of the name as printed, which means that the embedded line
2226
2226 numbers get compared in an odd way. For example, lines 3, 20, and 40
2227
2227 would (if the file names were the same) appear in the string order
2228 %reset: Resets the namespace by removing all names defined by the user.
2228 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
2229
2229 line numbers. In fact, sort_stats("nfl") is the same as
2230 Input/Output history are left around in case you need them.
2230 sort_stats("name", "file", "line").
2231
2231
2232
2232 -T <filename>: save profile results as shown on screen to a text
2233 %run: Run the named file inside IPython as a program.
2233 file. The profile is still shown on screen.
2234
2234
2235 Usage:
2235 -D <filename>: save (via dump_stats) profile statistics to given
2236 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
2236 filename. This data is in a format understod by the pstats module, and
2237
2237 is generated by a call to the dump_stats() method of profile
2238 Parameters after the filename are passed as command-line arguments to
2238 objects. The profile is still shown on screen.
2239 the program (put in sys.argv). Then, control returns to IPython's prompt.
2239
2240
2240 If you want to run complete programs under the profiler's control, use
2241 This is similar to running at a system prompt:
2241 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
2242 $ python file args
2242 contains profiler specific options as described here.
2243 but with the advantage of giving you IPython's tracebacks, and of
2243
2244 loading all variables into your interactive namespace for further use
2244 You can read the complete documentation for the profile module with:\
2245 (unless -p is used, see below).
2245 In [1]: import profile; profile.help()
2246
2246
2247 The file is executed in a namespace initially consisting only of
2247 **%psearch**::
2248 __name__=='__main__' and sys.argv constructed as indicated. It thus sees
2248
2249 its environment as if it were being run as a stand-alone program (except
2249 Search for object in namespaces by wildcard.
2250 for sharing global objects such as previously imported modules). But
2250
2251 after execution, the IPython interactive namespace gets updated with all
2251 %psearch [options] PATTERN [OBJECT TYPE]
2252 variables defined in the program (except for __name__ and sys.argv).
2252
2253 This allows for very convenient loading of code for interactive work,
2253 Note: ? can be used as a synonym for %psearch, at the beginning or at
2254 while giving each program a 'clean sheet' to run in.
2254 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
2255
2255 rest of the command line must be unchanged (options come first), so
2256 Options:
2256 for example the following forms are equivalent
2257
2257
2258 -n: __name__ is NOT set to '__main__', but to the running file's name
2258 %psearch -i a* function
2259 without extension (as python does under import). This allows running
2259 -i a* function?
2260 scripts and reloading the definitions in them without calling code
2260 ?-i a* function
2261 protected by an ' if __name__ == "__main__" ' clause.
2261
2262
2262 Arguments:
2263 -i: run the file in IPython's namespace instead of an empty one. This is
2263
2264 useful if you are experimenting with code written in a text editor which
2264 PATTERN
2265 depends on variables defined interactively.
2265
2266
2266 where PATTERN is a string containing * as a wildcard similar to its
2267 -e: ignore sys.exit() calls or SystemExit exceptions in the script being
2267 use in a shell. The pattern is matched in all namespaces on the
2268 run. This is particularly useful if IPython is being used to run
2268 search path. By default objects starting with a single _ are not
2269 unittests, which always exit with a sys.exit() call. In such cases you
2269 matched, many IPython generated objects have a single
2270 are interested in the output of the test results, not in seeing a
2270 underscore. The default is case insensitive matching. Matching is
2271 traceback of the unittest module.
2271 also done on the attributes of objects and not only on the objects
2272
2272 in a module.
2273 -t: print timing information at the end of the run. IPython will give
2273
2274 you an estimated CPU time consumption for your script, which under Unix
2274 [OBJECT TYPE]
2275 uses the resource module to avoid the wraparound problems of
2275
2276 time.clock(). Under Unix, an estimate of time spent on system tasks is
2276 Is the name of a python type from the types module. The name is
2277 also given (for Windows platforms this is reported as 0.0).
2277 given in lowercase without the ending type, ex. StringType is
2278
2278 written string. By adding a type here only objects matching the
2279 If -t is given, an additional -N<N> option can be given, where <N> must
2279 given type are matched. Using all here makes the pattern match all
2280 be an integer indicating how many times you want the script to run. The
2280 types (this is the default).
2281 final timing report will include total and per run results.
2281
2282
2282 Options:
2283 For example (testing the script uniq_stable.py):
2283
2284
2284 -a: makes the pattern match even objects whose names start with a
2285 In [1]: run -t uniq_stable
2285 single underscore. These names are normally ommitted from the
2286
2286 search.
2287 IPython CPU timings (estimated):
2287
2288 User : 0.19597 s.
2288 -i/-c: make the pattern case insensitive/sensitive. If neither of
2289 System: 0.0 s.
2289 these options is given, the default is read from your ipythonrc
2290
2290 file. The option name which sets this value is
2291 In [2]: run -t -N5 uniq_stable
2291 'wildcards_case_sensitive'. If this option is not specified in your
2292
2292 ipythonrc file, IPython's internal default is to do a case sensitive
2293 IPython CPU timings (estimated):
2293 search.
2294 Total runs performed: 5
2294
2295 Times : Total Per run
2295 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
2296 User : 0.910862 s, 0.1821724 s.
2296 specifiy can be searched in any of the following namespaces:
2297 System: 0.0 s, 0.0 s.
2297 'builtin', 'user', 'user_global','internal', 'alias', where
2298
2298 'builtin' and 'user' are the search defaults. Note that you should
2299 -d: run your program under the control of pdb, the Python debugger. This
2299 not use quotes when specifying namespaces.
2300 allows you to execute your program step by step, watch variables, etc.
2300
2301 Internally, what IPython does is similar to calling:
2301 'Builtin' contains the python module builtin, 'user' contains all
2302
2302 user data, 'alias' only contain the shell aliases and no python
2303 pdb.run('execfile("YOURFILENAME")')
2303 objects, 'internal' contains objects used by IPython. The
2304
2304 'user_global' namespace is only used by embedded IPython instances,
2305 with a breakpoint set on line 1 of your file. You can change the line
2305 and it contains module-level globals. You can add namespaces to the
2306 number for this automatic breakpoint to be <N> by using the -bN option
2306 search with -s or exclude them with -e (these options can be given
2307 (where N must be an integer). For example:
2307 more than once).
2308
2308
2309 %run -d -b40 myscript
2309 Examples:
2310
2310
2311 will set the first breakpoint at line 40 in myscript.py. Note that the
2311 %psearch a* -> objects beginning with an a
2312 first breakpoint must be set on a line which actually does something
2312 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
2313 (not a comment or docstring) for it to stop execution.
2313 %psearch a* function -> all functions beginning with an a
2314
2314 %psearch re.e* -> objects beginning with an e in module re
2315 When the pdb debugger starts, you will see a (Pdb) prompt. You must
2315 %psearch r*.e* -> objects that start with e in modules starting in r
2316 first enter 'c' (without qoutes) to start execution up to the first
2316 %psearch r*.* string -> all strings in modules beginning with r
2317 breakpoint.
2317
2318
2318 Case sensitve search:
2319 Entering 'help' gives information about the use of the debugger. You can
2319
2320 easily see pdb's full documentation with "import pdb;pdb.help()" at a
2320 %psearch -c a* list all object beginning with lower case a
2321 prompt.
2321
2322
2322 Show objects beginning with a single _:
2323 -p: run program under the control of the Python profiler module (which
2323
2324 prints a detailed report of execution times, function calls, etc).
2324 %psearch -a _* list objects beginning with a single underscore
2325
2325
2326 You can pass other options after -p which affect the behavior of the
2326 **%psource**::
2327 profiler itself. See the docs for %prun for details.
2327
2328
2328 Print (or run through pager) the source code for an object.
2329 In this mode, the program's variables do NOT propagate back to the
2329
2330 IPython interactive namespace (because they remain in the namespace
2330 **%pushd**::
2331 where the profiler executes them).
2331
2332
2332 Place the current dir on stack and change directory.
2333 Internally this triggers a call to %prun, see its documentation for
2333
2334 details on the options available specifically for profiling.
2334 Usage:\
2335
2335 %pushd ['dirname']
2336 There is one special usage for which the text above doesn't apply: if
2336
2337 the filename ends with .ipy, the file is run as ipython script, just as
2337 **%pwd**::
2338 if the commands were written on IPython prompt.
2338
2339
2339 Return the current working directory path.
2340
2340
2341 %runlog: Run files as logs.
2341 **%pycat**::
2342
2342
2343 Usage:
2343 Show a syntax-highlighted file through a pager.
2344 %runlog file1 file2 ...
2344
2345
2345 This magic is similar to the cat utility, but it will assume the file
2346 Run the named files (treating them as log files) in sequence inside the
2346 to be Python source and will show it with syntax highlighting.
2347 interpreter, and return to the prompt. This is much slower than %run
2347
2348 because each line is executed in a try/except block, but it allows
2348 **%quickref**::
2349 running files with syntax errors in them.
2349
2350
2350 Show a quick reference sheet
2351 Normally IPython will guess when a file is one of its own logfiles, so
2351
2352 you can typically use %run even for logs. This shorthand allows you to
2352 **%quit**::
2353 force any file to be treated as a log file.
2353
2354
2354 Exit IPython, confirming if configured to do so (like %exit)
2355
2355
2356 %save: Save a set of lines to a given filename.
2356 **%r**::
2357
2357
2358 Usage:
2358 Repeat previous input.
2359 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2359
2360
2360 Note: Consider using the more powerfull %rep instead!
2361 Options:
2361
2362
2362 If given an argument, repeats the previous command which starts with
2363 -r: use 'raw' input. By default, the 'processed' history is used, so
2363 the same string, otherwise it just repeats the previous input.
2364 that magics are loaded in their transformed version to valid Python. If
2364
2365 this option is given, the raw input as typed as the command line is used
2365 Shell escaped commands (with ! as first character) are not recognized
2366 instead.
2366 by this system, only pure python code and magic commands.
2367
2367
2368 This function uses the same syntax as %macro for line extraction, but
2368 **%rehashdir**::
2369 instead of creating a macro it saves the resulting string to the
2369
2370 filename you specify.
2370 Add executables in all specified dirs to alias table
2371
2371
2372 It adds a '.py' extension to the file if you don't do so yourself, and
2372 Usage:
2373 it asks for confirmation before overwriting existing files.
2373
2374
2374 %rehashdir c:/bin;c:/tools
2375
2375 - Add all executables under c:/bin and c:/tools to alias table, in
2376 %sc: Shell capture - execute a shell command and capture its output.
2376 order to make them directly executable from any directory.
2377
2377
2378 DEPRECATED. Suboptimal, retained for backwards compatibility.
2378 Without arguments, add all executables in current directory.
2379
2379
2380 You should use the form 'var = !command' instead. Example:
2380 **%rehashx**::
2381
2381
2382 "%sc -l myfiles = ls " should now be written as
2382 Update the alias table with all executable files in $PATH.
2383
2383
2384 "myfiles = !ls "
2384 This version explicitly checks that every entry in $PATH is a file
2385
2385 with execute access (os.X_OK), so it is much slower than %rehash.
2386 myfiles.s, myfiles.l and myfiles.n still apply as documented below.
2386
2387
2387 Under Windows, it checks executability as a match agains a
2388 - %sc [options] varname=command
2388 '|'-separated string of extensions, stored in the IPython config
2389
2389 variable win_exec_ext. This defaults to 'exe|com|bat'.
2390 IPython will run the given command using commands.getoutput(), and will
2390
2391 then update the user's interactive namespace with a variable called
2391 This function also resets the root module cache of module completer,
2392 varname, containing the value of the call. Your command can contain
2392 used on slow filesystems.
2393 shell wildcards, pipes, etc.
2393
2394
2394 **%rep**::
2395 The '=' sign in the syntax is mandatory, and the variable name you
2395
2396 supply must follow Python's standard conventions for valid names.
2396 Repeat a command, or get command to input line for editing
2397
2397
2398 (A special format without variable name exists for internal use)
2398 - %rep (no arguments):
2399
2399
2400 Options:
2400 Place a string version of last computation result (stored in the special '_'
2401
2401 variable) to the next input prompt. Allows you to create elaborate command
2402 -l: list output. Split the output on newlines into a list before
2402 lines without using copy-paste::
2403 assigning it to the given variable. By default the output is stored as a
2403
2404 single string.
2404 $ l = ["hei", "vaan"]
2405
2405 $ "".join(l)
2406 -v: verbose. Print the contents of the variable.
2406 ==> heivaan
2407
2407 $ %rep
2408 In most cases you should not need to split as a list, because the
2408 $ heivaan_ <== cursor blinking
2409 returned value is a special type of string which can automatically
2409
2410 provide its contents either as a list (split on newlines) or as a
2410 %rep 45
2411 space-separated string. These are convenient, respectively, either for
2411
2412 sequential processing or to be passed to a shell command.
2412 Place history line 45 to next input prompt. Use %hist to find out the
2413
2413 number.
2414 For example:
2414
2415
2415 %rep 1-4 6-7 3
2416 # Capture into variable a In [9]: sc a=ls *py
2416
2417
2417 Repeat the specified lines immediately. Input slice syntax is the same as
2418 # a is a string with embedded newlines In [10]: a Out[10]: 'setup.py
2418 in %macro and %save.
2419 win32_manual_post_install.py'
2419
2420
2420 %rep foo
2421 # which can be seen as a list: In [11]: a.l Out[11]: ['setup.py',
2421
2422 'win32_manual_post_install.py']
2422 Place the most recent line that has the substring "foo" to next input.
2423
2423 (e.g. 'svn ci -m foobar').
2424 # or as a whitespace-separated string: In [12]: a.s Out[12]: 'setup.py
2424
2425 win32_manual_post_install.py'
2425 **%reset**::
2426
2426
2427 # a.s is useful to pass as a single command line: In [13]: !wc -l $a.s
2427 Resets the namespace by removing all names defined by the user.
2428 146 setup.py 130 win32_manual_post_install.py 276 total
2428
2429
2429 Input/Output history are left around in case you need them.
2430 # while the list form is useful to loop over: In [14]: for f in a.l:
2430
2431 ....: !wc -l $f ....: 146 setup.py 130 win32_manual_post_install.py
2431 **%run**::
2432
2432
2433 Similiarly, the lists returned by the -l option are also special, in the
2433 Run the named file inside IPython as a program.
2434 sense that you can equally invoke the .s attribute on them to
2434
2435 automatically get a whitespace-separated string from their contents:
2435 Usage:\
2436
2436 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
2437 In [1]: sc -l b=ls *py
2437
2438
2438 Parameters after the filename are passed as command-line arguments to
2439 In [2]: b Out[2]: ['setup.py', 'win32_manual_post_install.py']
2439 the program (put in sys.argv). Then, control returns to IPython's
2440
2440 prompt.
2441 In [3]: b.s Out[3]: 'setup.py win32_manual_post_install.py'
2441
2442
2442 This is similar to running at a system prompt:\
2443 In summary, both the lists and strings used for ouptut capture have the
2443 $ python file args\
2444 following special attributes:
2444 but with the advantage of giving you IPython's tracebacks, and of
2445
2445 loading all variables into your interactive namespace for further use
2446 .l (or .list) : value as list. .n (or .nlstr): value as
2446 (unless -p is used, see below).
2447 newline-separated string. .s (or .spstr): value as space-separated string.
2447
2448
2448 The file is executed in a namespace initially consisting only of
2449
2449 __name__=='__main__' and sys.argv constructed as indicated. It thus
2450 %sx: Shell execute - run a shell command and capture its output.
2450 sees its environment as if it were being run as a stand-alone program
2451
2451 (except for sharing global objects such as previously imported
2452 %sx command
2452 modules). But after execution, the IPython interactive namespace gets
2453
2453 updated with all variables defined in the program (except for __name__
2454 IPython will run the given command using commands.getoutput(), and
2454 and sys.argv). This allows for very convenient loading of code for
2455 return the result formatted as a list (split on '\n'). Since the output
2455 interactive work, while giving each program a 'clean sheet' to run in.
2456 is _returned_, it will be stored in ipython's regular output cache
2456
2457 Out[N] and in the '_N' automatic variables.
2457 Options:
2458
2458
2459 Notes:
2459 -n: __name__ is NOT set to '__main__', but to the running file's name
2460
2460 without extension (as python does under import). This allows running
2461 1) If an input line begins with '!!', then %sx is automatically invoked.
2461 scripts and reloading the definitions in them without calling code
2462 That is, while: !ls causes ipython to simply issue system('ls'), typing
2462 protected by an ' if __name__ == "__main__" ' clause.
2463 !!ls is a shorthand equivalent to: %sx ls
2463
2464
2464 -i: run the file in IPython's namespace instead of an empty one. This
2465 2) %sx differs from %sc in that %sx automatically splits into a list,
2465 is useful if you are experimenting with code written in a text editor
2466 like '%sc -l'. The reason for this is to make it as easy as possible to
2466 which depends on variables defined interactively.
2467 process line-oriented shell output via further python commands. %sc is
2467
2468 meant to provide much finer control, but requires more typing.
2468 -e: ignore sys.exit() calls or SystemExit exceptions in the script
2469
2469 being run. This is particularly useful if IPython is being used to
2470 3) Just like %sc -l, this is a list with special attributes:
2470 run unittests, which always exit with a sys.exit() call. In such
2471
2471 cases you are interested in the output of the test results, not in
2472 .l (or .list) : value as list. .n (or .nlstr): value as
2472 seeing a traceback of the unittest module.
2473 newline-separated string. .s (or .spstr): value as whitespace-separated
2473
2474 string.
2474 -t: print timing information at the end of the run. IPython will give
2475
2475 you an estimated CPU time consumption for your script, which under
2476 This is very useful when trying to use such lists as arguments to system
2476 Unix uses the resource module to avoid the wraparound problems of
2477 commands.
2477 time.clock(). Under Unix, an estimate of time spent on system tasks
2478
2478 is also given (for Windows platforms this is reported as 0.0).
2479
2479
2480 %system_verbose: Set verbose printing of system calls.
2480 If -t is given, an additional -N<N> option can be given, where <N>
2481
2481 must be an integer indicating how many times you want the script to
2482 If called without an argument, act as a toggle
2482 run. The final timing report will include total and per run results.
2483
2483
2484
2484 For example (testing the script uniq_stable.py):
2485 %time: Time execution of a Python statement or expression.
2485
2486
2486 In [1]: run -t uniq_stable
2487 The CPU and wall clock times are printed, and the value of the
2487
2488 expression (if any) is returned. Note that under Win32, system time is
2488 IPython CPU timings (estimated):\
2489 always reported as 0, since it can not be measured.
2489 User : 0.19597 s.\
2490
2490 System: 0.0 s.\
2491 This function provides very basic timing functionality. In Python 2.3,
2491
2492 the timeit module offers more control and sophistication, so this could
2492 In [2]: run -t -N5 uniq_stable
2493 be rewritten to use it (patches welcome).
2493
2494
2494 IPython CPU timings (estimated):\
2495 Some examples:
2495 Total runs performed: 5\
2496
2496 Times : Total Per run\
2497 In [1]: time 2**128 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2497 User : 0.910862 s, 0.1821724 s.\
2498 Wall time: 0.00 Out[1]: 340282366920938463463374607431768211456L
2498 System: 0.0 s, 0.0 s.
2499
2499
2500 In [2]: n = 1000000
2500 -d: run your program under the control of pdb, the Python debugger.
2501
2501 This allows you to execute your program step by step, watch variables,
2502 In [3]: time sum(range(n)) CPU times: user 1.20 s, sys: 0.05 s, total:
2502 etc. Internally, what IPython does is similar to calling:
2503 1.25 s Wall time: 1.37 Out[3]: 499999500000L
2503
2504
2504 pdb.run('execfile("YOURFILENAME")')
2505 In [4]: time print 'hello world' hello world CPU times: user 0.00 s,
2505
2506 sys: 0.00 s, total: 0.00 s Wall time: 0.00
2506 with a breakpoint set on line 1 of your file. You can change the line
2507
2507 number for this automatic breakpoint to be <N> by using the -bN option
2508 Note that the time needed by Python to compile the given expression will
2508 (where N must be an integer). For example:
2509 be reported if it is more than 0.1s. In this example, the actual
2509
2510 exponentiation is done by Python at compilation time, so while the
2510 %run -d -b40 myscript
2511 expression can take a noticeable amount of time to compute, that time is
2511
2512 purely due to the compilation:
2512 will set the first breakpoint at line 40 in myscript.py. Note that
2513
2513 the first breakpoint must be set on a line which actually does
2514 In [5]: time 3**9999; CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2514 something (not a comment or docstring) for it to stop execution.
2515 Wall time: 0.00 s
2515
2516
2516 When the pdb debugger starts, you will see a (Pdb) prompt. You must
2517 In [6]: time 3**999999; CPU times: user 0.00 s, sys: 0.00 s, total: 0.00
2517 first enter 'c' (without qoutes) to start execution up to the first
2518 s Wall time: 0.00 s Compiler : 0.78 s
2518 breakpoint.
2519
2519
2520
2520 Entering 'help' gives information about the use of the debugger. You
2521 %timeit: Time execution of a Python statement or expression
2521 can easily see pdb's full documentation with "import pdb;pdb.help()"
2522
2522 at a prompt.
2523 Usage:
2523
2524 %timeit [-n<N> -r<R> [-t|-c]] statement
2524 -p: run program under the control of the Python profiler module (which
2525
2525 prints a detailed report of execution times, function calls, etc).
2526 Time execution of a Python statement or expression using the timeit module.
2526
2527
2527 You can pass other options after -p which affect the behavior of the
2528 Options: -n<N>: execute the given statement <N> times in a loop. If this
2528 profiler itself. See the docs for %prun for details.
2529 value is not given, a fitting value is chosen.
2529
2530
2530 In this mode, the program's variables do NOT propagate back to the
2531 -r<R>: repeat the loop iteration <R> times and take the best result.
2531 IPython interactive namespace (because they remain in the namespace
2532 Default: 3
2532 where the profiler executes them).
2533
2533
2534 -t: use time.time to measure the time, which is the default on Unix.
2534 Internally this triggers a call to %prun, see its documentation for
2535 This function measures wall time.
2535 details on the options available specifically for profiling.
2536
2536
2537 -c: use time.clock to measure the time, which is the default on Windows
2537 There is one special usage for which the text above doesn't apply:
2538 and measures wall time. On Unix, resource.getrusage is used instead and
2538 if the filename ends with .ipy, the file is run as ipython script,
2539 returns the CPU user time.
2539 just as if the commands were written on IPython prompt.
2540
2540
2541 -p<P>: use a precision of <P> digits to display the timing result.
2541 **%runlog**::
2542 Default: 3
2542
2543
2543 Run files as logs.
2544 Examples:
2544
2545 In [1]: %timeit pass 10000000 loops, best of 3: 53.3 ns per loop
2545 Usage:\
2546
2546 %runlog file1 file2 ...
2547 In [2]: u = None
2547
2548
2548 Run the named files (treating them as log files) in sequence inside
2549 In [3]: %timeit u is None 10000000 loops, best of 3: 184 ns per loop
2549 the interpreter, and return to the prompt. This is much slower than
2550
2550 %run because each line is executed in a try/except block, but it
2551 In [4]: %timeit -r 4 u == None 1000000 loops, best of 4: 242 ns per loop
2551 allows running files with syntax errors in them.
2552
2552
2553 In [5]: import time
2553 Normally IPython will guess when a file is one of its own logfiles, so
2554
2554 you can typically use %run even for logs. This shorthand allows you to
2555 In [6]: %timeit -n1 time.sleep(2) 1 loops, best of 3: 2 s per loop
2555 force any file to be treated as a log file.
2556
2556
2557 The times reported by %timeit will be slightly higher than those
2557 **%save**::
2558 reported by the timeit.py script when variables are accessed. This is
2558
2559 due to the fact that %timeit executes the statement in the namespace of
2559 Save a set of lines to a given filename.
2560 the shell, compared with timeit.py, which uses a single setup statement
2560
2561 to import function or create variables. Generally, the bias does not
2561 Usage:\
2562 matter as long as results from timeit.py are not mixed with those from
2562 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2563 %timeit.
2563
2564
2564 Options:
2565
2565
2566 %unalias: Remove an alias
2566 -r: use 'raw' input. By default, the 'processed' history is used,
2567
2567 so that magics are loaded in their transformed version to valid
2568
2568 Python. If this option is given, the raw input as typed as the
2569 %upgrade: Upgrade your IPython installation
2569 command line is used instead.
2570
2570
2571 This will copy the config files that don't yet exist in your ipython dir
2571 This function uses the same syntax as %macro for line extraction, but
2572 from the system config dir. Use this after upgrading IPython if you
2572 instead of creating a macro it saves the resulting string to the
2573 don't wish to delete your .ipython dir.
2573 filename you specify.
2574
2574
2575 Call with -nolegacy to get rid of ipythonrc* files (recommended for new
2575 It adds a '.py' extension to the file if you don't do so yourself, and
2576 users)
2576 it asks for confirmation before overwriting existing files.
2577
2577
2578
2578 **%sc**::
2579 %who: Print all interactive variables, with some minimal formatting.
2579
2580
2580 Shell capture - execute a shell command and capture its output.
2581 If any arguments are given, only variables whose type matches one of
2581
2582 these are printed. For example:
2582 DEPRECATED. Suboptimal, retained for backwards compatibility.
2583
2583
2584 %who function str
2584 You should use the form 'var = !command' instead. Example:
2585
2585
2586 will only list functions and strings, excluding all other types of
2586 "%sc -l myfiles = ls ~" should now be written as
2587 variables. To find the proper type names, simply use type(var) at a
2587
2588 command line to see how python prints type names. For example:
2588 "myfiles = !ls ~"
2589
2589
2590 In [1]: type('hello')
2590 myfiles.s, myfiles.l and myfiles.n still apply as documented
2591 Out[1]: <type 'str'>
2591 below.
2592
2592
2593 indicates that the type name for strings is 'str'.
2593 --
2594
2594 %sc [options] varname=command
2595 %who always excludes executed names loaded through your configuration
2595
2596 file and things which are internal to IPython.
2596 IPython will run the given command using commands.getoutput(), and
2597
2597 will then update the user's interactive namespace with a variable
2598 This is deliberate, as typically you may load many modules and the
2598 called varname, containing the value of the call. Your command can
2599 purpose of %who is to show you only what you've manually defined.
2599 contain shell wildcards, pipes, etc.
2600
2600
2601
2601 The '=' sign in the syntax is mandatory, and the variable name you
2602 %who_ls: Return a sorted list of all interactive variables.
2602 supply must follow Python's standard conventions for valid names.
2603
2603
2604 If arguments are given, only variables of types matching these arguments
2604 (A special format without variable name exists for internal use)
2605 are returned.
2605
2606
2606 Options:
2607
2607
2608 %whos: Like %who, but gives some extra information about each variable.
2608 -l: list output. Split the output on newlines into a list before
2609
2609 assigning it to the given variable. By default the output is stored
2610 The same type filtering of %who can be applied here.
2610 as a single string.
2611
2611
2612 For all variables, the type is printed. Additionally it prints:
2612 -v: verbose. Print the contents of the variable.
2613
2613
2614 - For ,[],(): their length.
2614 In most cases you should not need to split as a list, because the
2615
2615 returned value is a special type of string which can automatically
2616 - For numpy and Numeric arrays, a summary with shape, number of
2616 provide its contents either as a list (split on newlines) or as a
2617 elements, typecode and size in memory.
2617 space-separated string. These are convenient, respectively, either
2618
2618 for sequential processing or to be passed to a shell command.
2619 - Everything else: a string representation, snipping their middle if too
2619
2620 long.
2620 For example:
2621
2621
2622
2622 # Capture into variable a
2623 %xmode: Switch modes for the exception handlers.
2623 In [9]: sc a=ls *py
2624
2624
2625 Valid modes: Plain, Context and Verbose.
2625 # a is a string with embedded newlines
2626
2626 In [10]: a
2627 If called without arguments, acts as a toggle.
2627 Out[10]: 'setup.py win32_manual_post_install.py'
2628
2629 # which can be seen as a list:
2630 In [11]: a.l
2631 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2632
2633 # or as a whitespace-separated string:
2634 In [12]: a.s
2635 Out[12]: 'setup.py win32_manual_post_install.py'
2636
2637 # a.s is useful to pass as a single command line:
2638 In [13]: !wc -l $a.s
2639 146 setup.py
2640 130 win32_manual_post_install.py
2641 276 total
2642
2643 # while the list form is useful to loop over:
2644 In [14]: for f in a.l:
2645 ....: !wc -l $f
2646 ....:
2647 146 setup.py
2648 130 win32_manual_post_install.py
2649
2650 Similiarly, the lists returned by the -l option are also special, in
2651 the sense that you can equally invoke the .s attribute on them to
2652 automatically get a whitespace-separated string from their contents:
2653
2654 In [1]: sc -l b=ls *py
2655
2656 In [2]: b
2657 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2658
2659 In [3]: b.s
2660 Out[3]: 'setup.py win32_manual_post_install.py'
2661
2662 In summary, both the lists and strings used for ouptut capture have
2663 the following special attributes:
2664
2665 .l (or .list) : value as list.
2666 .n (or .nlstr): value as newline-separated string.
2667 .s (or .spstr): value as space-separated string.
2668
2669 **%store**::
2670
2671 Lightweight persistence for python variables.
2672
2673 Example:
2674
2675 ville@badger[~]|1> A = ['hello',10,'world']\
2676 ville@badger[~]|2> %store A\
2677 ville@badger[~]|3> Exit
2678
2679 (IPython session is closed and started again...)
2680
2681 ville@badger:~$ ipython -p pysh\
2682 ville@badger[~]|1> print A
2683
2684 ['hello', 10, 'world']
2685
2686 Usage:
2687
2688 %store - Show list of all variables and their current values\
2689 %store <var> - Store the *current* value of the variable to disk\
2690 %store -d <var> - Remove the variable and its value from storage\
2691 %store -z - Remove all variables from storage\
2692 %store -r - Refresh all variables from store (delete current vals)\
2693 %store foo >a.txt - Store value of foo to new file a.txt\
2694 %store foo >>a.txt - Append value of foo to file a.txt\
2695
2696 It should be noted that if you change the value of a variable, you
2697 need to %store it again if you want to persist the new value.
2698
2699 Note also that the variables will need to be pickleable; most basic
2700 python types can be safely %stored.
2701
2702 Also aliases can be %store'd across sessions.
2703
2704 **%sx**::
2705
2706 Shell execute - run a shell command and capture its output.
2707
2708 %sx command
2709
2710 IPython will run the given command using commands.getoutput(), and
2711 return the result formatted as a list (split on '\n'). Since the
2712 output is _returned_, it will be stored in ipython's regular output
2713 cache Out[N] and in the '_N' automatic variables.
2714
2715 Notes:
2716
2717 1) If an input line begins with '!!', then %sx is automatically
2718 invoked. That is, while:
2719 !ls
2720 causes ipython to simply issue system('ls'), typing
2721 !!ls
2722 is a shorthand equivalent to:
2723 %sx ls
2724
2725 2) %sx differs from %sc in that %sx automatically splits into a list,
2726 like '%sc -l'. The reason for this is to make it as easy as possible
2727 to process line-oriented shell output via further python commands.
2728 %sc is meant to provide much finer control, but requires more
2729 typing.
2730
2731 3) Just like %sc -l, this is a list with special attributes:
2732
2733 .l (or .list) : value as list.
2734 .n (or .nlstr): value as newline-separated string.
2735 .s (or .spstr): value as whitespace-separated string.
2736
2737 This is very useful when trying to use such lists as arguments to
2738 system commands.
2739
2740 **%system_verbose**::
2741
2742 Set verbose printing of system calls.
2743
2744 If called without an argument, act as a toggle
2745
2746 **%time**::
2747
2748 Time execution of a Python statement or expression.
2749
2750 The CPU and wall clock times are printed, and the value of the
2751 expression (if any) is returned. Note that under Win32, system time
2752 is always reported as 0, since it can not be measured.
2753
2754 This function provides very basic timing functionality. In Python
2755 2.3, the timeit module offers more control and sophistication, so this
2756 could be rewritten to use it (patches welcome).
2757
2758 Some examples:
2759
2760 In [1]: time 2**128
2761 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2762 Wall time: 0.00
2763 Out[1]: 340282366920938463463374607431768211456L
2764
2765 In [2]: n = 1000000
2766
2767 In [3]: time sum(range(n))
2768 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2769 Wall time: 1.37
2770 Out[3]: 499999500000L
2771
2772 In [4]: time print 'hello world'
2773 hello world
2774 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2775 Wall time: 0.00
2776
2777 Note that the time needed by Python to compile the given expression
2778 will be reported if it is more than 0.1s. In this example, the
2779 actual exponentiation is done by Python at compilation time, so while
2780 the expression can take a noticeable amount of time to compute, that
2781 time is purely due to the compilation:
2782
2783 In [5]: time 3**9999;
2784 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2785 Wall time: 0.00 s
2786
2787 In [6]: time 3**999999;
2788 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2789 Wall time: 0.00 s
2790 Compiler : 0.78 s
2791
2792 **%timeit**::
2793
2794 Time execution of a Python statement or expression
2795
2796 Usage:\
2797 %timeit [-n<N> -r<R> [-t|-c]] statement
2798
2799 Time execution of a Python statement or expression using the timeit
2800 module.
2801
2802 Options:
2803 -n<N>: execute the given statement <N> times in a loop. If this value
2804 is not given, a fitting value is chosen.
2805
2806 -r<R>: repeat the loop iteration <R> times and take the best result.
2807 Default: 3
2808
2809 -t: use time.time to measure the time, which is the default on Unix.
2810 This function measures wall time.
2811
2812 -c: use time.clock to measure the time, which is the default on
2813 Windows and measures wall time. On Unix, resource.getrusage is used
2814 instead and returns the CPU user time.
2815
2816 -p<P>: use a precision of <P> digits to display the timing result.
2817 Default: 3
2818
2819
2820 Examples:\
2821 In [1]: %timeit pass
2822 10000000 loops, best of 3: 53.3 ns per loop
2823
2824 In [2]: u = None
2825
2826 In [3]: %timeit u is None
2827 10000000 loops, best of 3: 184 ns per loop
2828
2829 In [4]: %timeit -r 4 u == None
2830 1000000 loops, best of 4: 242 ns per loop
2831
2832 In [5]: import time
2833
2834 In [6]: %timeit -n1 time.sleep(2)
2835 1 loops, best of 3: 2 s per loop
2836
2837
2838 The times reported by %timeit will be slightly higher than those
2839 reported by the timeit.py script when variables are accessed. This is
2840 due to the fact that %timeit executes the statement in the namespace
2841 of the shell, compared with timeit.py, which uses a single setup
2842 statement to import function or create variables. Generally, the bias
2843 does not matter as long as results from timeit.py are not mixed with
2844 those from %timeit.
2845
2846 **%unalias**::
2847
2848 Remove an alias
2849
2850 **%upgrade**::
2851
2852 Upgrade your IPython installation
2853
2854 This will copy the config files that don't yet exist in your
2855 ipython dir from the system config dir. Use this after upgrading
2856 IPython if you don't wish to delete your .ipython dir.
2857
2858 Call with -nolegacy to get rid of ipythonrc* files (recommended for
2859 new users)
2860
2861 **%which**::
2862
2863 %which <cmd> => search PATH for files matching cmd. Also scans aliases.
2864
2865 Traverses PATH and prints all files (not just executables!) that match the
2866 pattern on command line. Probably more useful in finding stuff
2867 interactively than 'which', which only prints the first matching item.
2868
2869 Also discovers and expands aliases, so you'll see what will be executed
2870 when you call an alias.
2871
2872 Example:
2873
2874 [~]|62> %which d
2875 d -> ls -F --color=auto
2876 == c:\cygwin\bin\ls.exe
2877 c:\cygwin\bin\d.exe
2878
2879 [~]|64> %which diff*
2880 diff3 -> diff3
2881 == c:\cygwin\bin\diff3.exe
2882 diff -> diff
2883 == c:\cygwin\bin\diff.exe
2884 c:\cygwin\bin\diff.exe
2885 c:\cygwin\bin\diff3.exe
2886
2887 **%who**::
2888
2889 Print all interactive variables, with some minimal formatting.
2890
2891 If any arguments are given, only variables whose type matches one of
2892 these are printed. For example:
2893
2894 %who function str
2895
2896 will only list functions and strings, excluding all other types of
2897 variables. To find the proper type names, simply use type(var) at a
2898 command line to see how python prints type names. For example:
2899
2900 In [1]: type('hello')\
2901 Out[1]: <type 'str'>
2902
2903 indicates that the type name for strings is 'str'.
2904
2905 %who always excludes executed names loaded through your configuration
2906 file and things which are internal to IPython.
2907
2908 This is deliberate, as typically you may load many modules and the
2909 purpose of %who is to show you only what you've manually defined.
2910
2911 **%who_ls**::
2912
2913 Return a sorted list of all interactive variables.
2914
2915 If arguments are given, only variables of types matching these
2916 arguments are returned.
2917
2918 **%whos**::
2919
2920 Like %who, but gives some extra information about each variable.
2921
2922 The same type filtering of %who can be applied here.
2923
2924 For all variables, the type is printed. Additionally it prints:
2925
2926 - For {},[],(): their length.
2927
2928 - For numpy and Numeric arrays, a summary with shape, number of
2929 elements, typecode and size in memory.
2930
2931 - Everything else: a string representation, snipping their middle if
2932 too long.
2933
2934 **%xmode**::
2935
2936 Switch modes for the exception handlers.
2937
2938 Valid modes: Plain, Context and Verbose.
2939
2940 If called without arguments, acts as a toggle.
2628
2941
2942 .. magic_end
2629
2943
2630 Access to the standard Python help
2944 Access to the standard Python help
2631 ----------------------------------
2945 ----------------------------------
General Comments 0
You need to be logged in to leave comments. Login now