##// END OF EJS Templates
update embedding doc to reflect new API
MinRK -
Show More
@@ -1,51 +1,50 b''
1 """Quick code snippets for embedding IPython into other programs.
1 """Quick code snippets for embedding IPython into other programs.
2
2
3 See example-embed.py for full details, this file has the bare minimum code for
3 See example-embed.py for full details, this file has the bare minimum code for
4 cut and paste use once you understand how to use the system."""
4 cut and paste use once you understand how to use the system."""
5
5
6 #---------------------------------------------------------------------------
6 #---------------------------------------------------------------------------
7 # This code loads IPython but modifies a few things if it detects it's running
7 # This code loads IPython but modifies a few things if it detects it's running
8 # embedded in another IPython session (helps avoid confusion)
8 # embedded in another IPython session (helps avoid confusion)
9
9
10 try:
10 try:
11 __IPYTHON__
11 get_ipython
12 except NameError:
12 except NameError:
13 argv = ['']
13 banner=exit_msg=''
14 banner = exit_msg = ''
15 else:
14 else:
16 # Command-line options for IPython (a list like sys.argv)
17 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
18 banner = '*** Nested interpreter ***'
15 banner = '*** Nested interpreter ***'
19 exit_msg = '*** Back in main IPython ***'
16 exit_msg = '*** Back in main IPython ***'
20
17
21 # First import the embeddable shell class
18 # First import the embed function
22 from IPython.Shell import IPShellEmbed
19 from IPython.frontend.terminal.embed import InteractiveShellEmbed
23 # Now create the IPython shell instance. Put ipshell() anywhere in your code
20 # Now create the IPython shell instance. Put ipshell() anywhere in your code
24 # where you want it to open.
21 # where you want it to open.
25 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
22 ipshell = InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg)
26
23
27 #---------------------------------------------------------------------------
24 #---------------------------------------------------------------------------
28 # This code will load an embeddable IPython shell always with no changes for
25 # This code will load an embeddable IPython shell always with no changes for
29 # nested embededings.
26 # nested embededings.
30
27
31 from IPython.Shell import IPShellEmbed
28 # This code will load an embeddable IPython shell always with no changes for
32 ipshell = IPShellEmbed()
29 # nested embededings.
33 # Now ipshell() will open IPython anywhere in the code.
30
31 from IPython import embed
32 # Now embed() will open IPython anywhere in the code.
34
33
35 #---------------------------------------------------------------------------
34 #---------------------------------------------------------------------------
36 # This code loads an embeddable shell only if NOT running inside
35 # This code loads an embeddable shell only if NOT running inside
37 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
36 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
38 # dummy function.
37 # dummy function.
39
38
40 try:
39 try:
41 __IPYTHON__
40 get_ipython
42 except NameError:
41 except NameError:
43 from IPython.Shell import IPShellEmbed
42 from IPython.frontend.terminal.embed import InteractiveShellEmbed
44 ipshell = IPShellEmbed()
43 ipshell = InteractiveShellEmbed()
45 # Now ipshell() will open IPython anywhere in the code
44 # Now ipshell() will open IPython anywhere in the code
46 else:
45 else:
47 # Define a dummy ipshell() so the same code doesn't crash inside an
46 # Define a dummy ipshell() so the same code doesn't crash inside an
48 # interactive IPython
47 # interactive IPython
49 def ipshell(): pass
48 def ipshell(): pass
50
49
51 #******************* End of file <example-embed-short.py> ********************
50 #******************* End of file <example-embed-short.py> ********************
@@ -1,131 +1,137 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
2
3 """An example of how to embed an IPython shell into a running program.
3 """An example of how to embed an IPython shell into a running program.
4
4
5 Please see the documentation in the IPython.Shell module for more details.
5 Please see the documentation in the IPython.Shell module for more details.
6
6
7 The accompanying file example-embed-short.py has quick code fragments for
7 The accompanying file example-embed-short.py has quick code fragments for
8 embedding which you can cut and paste in your code once you understand how
8 embedding which you can cut and paste in your code once you understand how
9 things work.
9 things work.
10
10
11 The code in this file is deliberately extra-verbose, meant for learning."""
11 The code in this file is deliberately extra-verbose, meant for learning."""
12
12
13 # The basics to get you going:
13 # The basics to get you going:
14
14
15 # IPython sets the __IPYTHON__ variable so you can know if you have nested
15 # IPython sets the __IPYTHON__ variable so you can know if you have nested
16 # copies running.
16 # copies running.
17
17
18 # Try running this code both at the command line and from inside IPython (with
18 # Try running this code both at the command line and from inside IPython (with
19 # %run example-embed.py)
19 # %run example-embed.py)
20 from IPython.config.loader import Config
20 try:
21 try:
21 __IPYTHON__
22 get_ipython
22 except NameError:
23 except NameError:
23 nested = 0
24 nested = 0
24 args = ['']
25 cfg = Config()
26 shell_config = cfg.InteractiveShellEmbed
27 shell_config.prompt_in1 = 'In <\\#>: '
28 shell_config.prompt_in2 = ' .\\D.: '
29 shell_config.prompt_out = 'Out<\\#>: '
25 else:
30 else:
26 print "Running nested copies of IPython."
31 print "Running nested copies of IPython."
27 print "The prompts for the nested copy have been modified"
32 print "The prompts for the nested copy have been modified"
33 cfg = Config()
28 nested = 1
34 nested = 1
29 # what the embedded instance will see as sys.argv:
30 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
31 '-po','Out<\\#>: ','-nosep']
32
35
33 # First import the embeddable shell class
36 # First import the embeddable shell class
34 from IPython.core.shell import IPShellEmbed
37 from IPython.frontend.terminal.embed import InteractiveShellEmbed
35
38
36 # Now create an instance of the embeddable shell. The first argument is a
39 # Now create an instance of the embeddable shell. The first argument is a
37 # string with options exactly as you would type them if you were starting
40 # string with options exactly as you would type them if you were starting
38 # IPython at the system command line. Any parameters you want to define for
41 # IPython at the system command line. Any parameters you want to define for
39 # configuration can thus be specified here.
42 # configuration can thus be specified here.
40 ipshell = IPShellEmbed(args,
43 ipshell = InteractiveShellEmbed(config=cfg,
41 banner = 'Dropping into IPython',
44 banner1 = 'Dropping into IPython',
42 exit_msg = 'Leaving Interpreter, back to program.')
45 exit_msg = 'Leaving Interpreter, back to program.')
43
46
44 # Make a second instance, you can have as many as you want.
47 # Make a second instance, you can have as many as you want.
45 if nested:
48 cfg2 = cfg.copy()
46 args[1] = 'In2<\\#>'
49 shell_config = cfg2.InteractiveShellEmbed
47 else:
50 shell_config.prompt_in1 = 'In2<\\#>: '
48 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
51 if not nested:
49 '-po','Out<\\#>: ','-nosep']
52 shell_config.prompt_in1 = 'In2<\\#>: '
50 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
53 shell_config.prompt_in2 = ' .\\D.: '
54 shell_config.prompt_out = 'Out<\\#>: '
55 ipshell2 = InteractiveShellEmbed(config=cfg,
56 banner1 = 'Second IPython instance.')
51
57
52 print '\nHello. This is printed from the main controller program.\n'
58 print '\nHello. This is printed from the main controller program.\n'
53
59
54 # You can then call ipshell() anywhere you need it (with an optional
60 # You can then call ipshell() anywhere you need it (with an optional
55 # message):
61 # message):
56 ipshell('***Called from top level. '
62 ipshell('***Called from top level. '
57 'Hit Ctrl-D to exit interpreter and continue program.\n'
63 'Hit Ctrl-D to exit interpreter and continue program.\n'
58 'Note that if you use %kill_embedded, you can fully deactivate\n'
64 'Note that if you use %kill_embedded, you can fully deactivate\n'
59 'This embedded instance so it will never turn on again')
65 'This embedded instance so it will never turn on again')
60
66
61 print '\nBack in caller program, moving along...\n'
67 print '\nBack in caller program, moving along...\n'
62
68
63 #---------------------------------------------------------------------------
69 #---------------------------------------------------------------------------
64 # More details:
70 # More details:
65
71
66 # IPShellEmbed instances don't print the standard system banner and
72 # InteractiveShellEmbed instances don't print the standard system banner and
67 # messages. The IPython banner (which actually may contain initialization
73 # messages. The IPython banner (which actually may contain initialization
68 # messages) is available as <instance>.IP.BANNER in case you want it.
74 # messages) is available as get_ipython().banner in case you want it.
69
75
70 # IPShellEmbed instances print the following information everytime they
76 # InteractiveShellEmbed instances print the following information everytime they
71 # start:
77 # start:
72
78
73 # - A global startup banner.
79 # - A global startup banner.
74
80
75 # - A call-specific header string, which you can use to indicate where in the
81 # - A call-specific header string, which you can use to indicate where in the
76 # execution flow the shell is starting.
82 # execution flow the shell is starting.
77
83
78 # They also print an exit message every time they exit.
84 # They also print an exit message every time they exit.
79
85
80 # Both the startup banner and the exit message default to None, and can be set
86 # Both the startup banner and the exit message default to None, and can be set
81 # either at the instance constructor or at any other time with the
87 # either at the instance constructor or at any other time with the
82 # set_banner() and set_exit_msg() methods.
88 # by setting the banner and exit_msg attributes.
83
89
84 # The shell instance can be also put in 'dummy' mode globally or on a per-call
90 # The shell instance can be also put in 'dummy' mode globally or on a per-call
85 # basis. This gives you fine control for debugging without having to change
91 # basis. This gives you fine control for debugging without having to change
86 # code all over the place.
92 # code all over the place.
87
93
88 # The code below illustrates all this.
94 # The code below illustrates all this.
89
95
90
96
91 # This is how the global banner and exit_msg can be reset at any point
97 # This is how the global banner and exit_msg can be reset at any point
92 ipshell.set_banner('Entering interpreter - New Banner')
98 ipshell.banner = 'Entering interpreter - New Banner'
93 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
99 ipshell.exit_msg = 'Leaving interpreter - New exit_msg'
94
100
95 def foo(m):
101 def foo(m):
96 s = 'spam'
102 s = 'spam'
97 ipshell('***In foo(). Try @whos, or print s or m:')
103 ipshell('***In foo(). Try %whos, or print s or m:')
98 print 'foo says m = ',m
104 print 'foo says m = ',m
99
105
100 def bar(n):
106 def bar(n):
101 s = 'eggs'
107 s = 'eggs'
102 ipshell('***In bar(). Try @whos, or print s or n:')
108 ipshell('***In bar(). Try %whos, or print s or n:')
103 print 'bar says n = ',n
109 print 'bar says n = ',n
104
110
105 # Some calls to the above functions which will trigger IPython:
111 # Some calls to the above functions which will trigger IPython:
106 print 'Main program calling foo("eggs")\n'
112 print 'Main program calling foo("eggs")\n'
107 foo('eggs')
113 foo('eggs')
108
114
109 # The shell can be put in 'dummy' mode where calls to it silently return. This
115 # The shell can be put in 'dummy' mode where calls to it silently return. This
110 # allows you, for example, to globally turn off debugging for a program with a
116 # allows you, for example, to globally turn off debugging for a program with a
111 # single call.
117 # single call.
112 ipshell.set_dummy_mode(1)
118 ipshell.dummy_mode = True
113 print '\nTrying to call IPython which is now "dummy":'
119 print '\nTrying to call IPython which is now "dummy":'
114 ipshell()
120 ipshell()
115 print 'Nothing happened...'
121 print 'Nothing happened...'
116 # The global 'dummy' mode can still be overridden for a single call
122 # The global 'dummy' mode can still be overridden for a single call
117 print '\nOverriding dummy mode manually:'
123 print '\nOverriding dummy mode manually:'
118 ipshell(dummy=0)
124 ipshell(dummy=False)
119
125
120 # Reactivate the IPython shell
126 # Reactivate the IPython shell
121 ipshell.set_dummy_mode(0)
127 ipshell.dummy_mode = False
122
128
123 print 'You can even have multiple embedded instances:'
129 print 'You can even have multiple embedded instances:'
124 ipshell2()
130 ipshell2()
125
131
126 print '\nMain program calling bar("spam")\n'
132 print '\nMain program calling bar("spam")\n'
127 bar('spam')
133 bar('spam')
128
134
129 print 'Main program finished. Bye!'
135 print 'Main program finished. Bye!'
130
136
131 #********************** End of file <example-embed.py> ***********************
137 #********************** End of file <example-embed.py> ***********************
@@ -1,17 +1,17 b''
1 # This shows how to use the new top-level embed function. It is a simpler
1 # This shows how to use the new top-level embed function. It is a simpler
2 # API that manages the creation of the embedded shell.
2 # API that manages the creation of the embedded shell.
3
3
4 from IPython import embed
4 from IPython import embed
5
5
6 a = 10
6 a = 10
7 b = 20
7 b = 20
8
8
9 embed('First time')
9 embed(header='First time', banner1='')
10
10
11 c = 30
11 c = 30
12 d = 40
12 d = 40
13
13
14 try:
14 try:
15 raise Exception('adsfasdf')
15 raise Exception('adsfasdf')
16 except:
16 except:
17 embed('The second time')
17 embed(header='The second time')
@@ -1,1578 +1,1572 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. warning::
5 .. warning::
6
6
7 As of the 0.11 version of IPython, some of the features and APIs
7 As of the 0.11 version of IPython, some of the features and APIs
8 described in this section have been deprecated or are broken. Our plan
8 described in this section have been deprecated or are broken. Our plan
9 is to continue to support these features, but they need to be updated
9 is to continue to support these features, but they need to be updated
10 to take advantage of recent API changes. Furthermore, this section
10 to take advantage of recent API changes. Furthermore, this section
11 of the documentation need to be updated to reflect all of these changes.
11 of the documentation need to be updated to reflect all of these changes.
12
12
13 .. _command_line_options:
13 .. _command_line_options:
14
14
15 Command-line usage
15 Command-line usage
16 ==================
16 ==================
17
17
18 You start IPython with the command::
18 You start IPython with the command::
19
19
20 $ ipython [options] files
20 $ ipython [options] files
21
21
22 If invoked with no options, it executes all the files listed in sequence
22 If invoked with no options, it executes all the files listed in sequence
23 and drops you into the interpreter while still acknowledging any options
23 and drops you into the interpreter while still acknowledging any options
24 you may have set in your ipython_config.py. This behavior is different from
24 you may have set in your ipython_config.py. This behavior is different from
25 standard Python, which when called as python -i will only execute one
25 standard Python, which when called as python -i will only execute one
26 file and ignore your configuration setup.
26 file and ignore your configuration setup.
27
27
28 Please note that some of the configuration options are not available at
28 Please note that some of the configuration options are not available at
29 the command line, simply because they are not practical here. Look into
29 the command line, simply because they are not practical here. Look into
30 your ipythonrc configuration file for details on those. This file is typically
30 your ipythonrc configuration file for details on those. This file is typically
31 installed in the IPYTHON_DIR directory. For Linux
31 installed in the IPYTHON_DIR directory. For Linux
32 users, this will be $HOME/.config/ipython, and for other users it will be
32 users, this will be $HOME/.config/ipython, and for other users it will be
33 $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
33 $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
34 Settings\\YourUserName in most instances.
34 Settings\\YourUserName in most instances.
35
35
36
36
37
37
38
38
39 Special Threading Options
39 Special Threading Options
40 -------------------------
40 -------------------------
41
41
42 Previously IPython had command line options for controlling GUI event loop
42 Previously IPython had command line options for controlling GUI event loop
43 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
43 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
44 version 0.11, these have been removed. Please see the new ``%gui``
44 version 0.11, these have been removed. Please see the new ``%gui``
45 magic command or :ref:`this section <gui_support>` for details on the new
45 magic command or :ref:`this section <gui_support>` for details on the new
46 interface, or specify the gui at the commandline::
46 interface, or specify the gui at the commandline::
47
47
48 $ ipython gui=qt
48 $ ipython gui=qt
49
49
50
50
51 Regular Options
51 Regular Options
52 ---------------
52 ---------------
53
53
54 After the above threading options have been given, regular options can
54 After the above threading options have been given, regular options can
55 follow in any order. All options can be abbreviated to their shortest
55 follow in any order. All options can be abbreviated to their shortest
56 non-ambiguous form and are case-sensitive. One or two dashes can be
56 non-ambiguous form and are case-sensitive. One or two dashes can be
57 used. Some options have an alternate short form, indicated after a ``|``.
57 used. Some options have an alternate short form, indicated after a ``|``.
58
58
59 Most options can also be set from your ipythonrc configuration file. See
59 Most options can also be set from your ipythonrc configuration file. See
60 the provided example for more details on what the options do. Options
60 the provided example for more details on what the options do. Options
61 given at the command line override the values set in the ipythonrc file.
61 given at the command line override the values set in the ipythonrc file.
62
62
63 All options with a [no] prepended can be specified in negated form
63 All options with a [no] prepended can be specified in negated form
64 (--no-option instead of --option) to turn the feature off.
64 (--no-option instead of --option) to turn the feature off.
65
65
66 -h, --help print a help message and exit.
66 -h, --help print a help message and exit.
67
67
68 --pylab, pylab=<name>
68 --pylab, pylab=<name>
69 See :ref:`Matplotlib support <matplotlib_support>`
69 See :ref:`Matplotlib support <matplotlib_support>`
70 for more details.
70 for more details.
71
71
72 autocall=<val>
72 autocall=<val>
73 Make IPython automatically call any callable object even if you
73 Make IPython automatically call any callable object even if you
74 didn't type explicit parentheses. For example, 'str 43' becomes
74 didn't type explicit parentheses. For example, 'str 43' becomes
75 'str(43)' automatically. The value can be '0' to disable the feature,
75 'str(43)' automatically. The value can be '0' to disable the feature,
76 '1' for smart autocall, where it is not applied if there are no more
76 '1' for smart autocall, where it is not applied if there are no more
77 arguments on the line, and '2' for full autocall, where all callable
77 arguments on the line, and '2' for full autocall, where all callable
78 objects are automatically called (even if no arguments are
78 objects are automatically called (even if no arguments are
79 present). The default is '1'.
79 present). The default is '1'.
80
80
81 --[no-]autoindent
81 --[no-]autoindent
82 Turn automatic indentation on/off.
82 Turn automatic indentation on/off.
83
83
84 --[no-]automagic
84 --[no-]automagic
85 make magic commands automatic (without needing their first character
85 make magic commands automatic (without needing their first character
86 to be %). Type %magic at the IPython prompt for more information.
86 to be %). Type %magic at the IPython prompt for more information.
87
87
88 --[no-]autoedit_syntax
88 --[no-]autoedit_syntax
89 When a syntax error occurs after editing a file, automatically
89 When a syntax error occurs after editing a file, automatically
90 open the file to the trouble causing line for convenient
90 open the file to the trouble causing line for convenient
91 fixing.
91 fixing.
92
92
93 --[no-]banner Print the initial information banner (default on).
93 --[no-]banner Print the initial information banner (default on).
94
94
95 c=<command>
95 c=<command>
96 execute the given command string. This is similar to the -c
96 execute the given command string. This is similar to the -c
97 option in the normal Python interpreter.
97 option in the normal Python interpreter.
98
98
99 cache_size=<n>
99 cache_size=<n>
100 size of the output cache (maximum number of entries to hold in
100 size of the output cache (maximum number of entries to hold in
101 memory). The default is 1000, you can change it permanently in your
101 memory). The default is 1000, you can change it permanently in your
102 config file. Setting it to 0 completely disables the caching system,
102 config file. Setting it to 0 completely disables the caching system,
103 and the minimum value accepted is 20 (if you provide a value less than
103 and the minimum value accepted is 20 (if you provide a value less than
104 20, it is reset to 0 and a warning is issued) This limit is defined
104 20, it is reset to 0 and a warning is issued) This limit is defined
105 because otherwise you'll spend more time re-flushing a too small cache
105 because otherwise you'll spend more time re-flushing a too small cache
106 than working.
106 than working.
107
107
108 --classic
108 --classic
109 Gives IPython a similar feel to the classic Python
109 Gives IPython a similar feel to the classic Python
110 prompt.
110 prompt.
111
111
112 colors=<scheme>
112 colors=<scheme>
113 Color scheme for prompts and exception reporting. Currently
113 Color scheme for prompts and exception reporting. Currently
114 implemented: NoColor, Linux and LightBG.
114 implemented: NoColor, Linux and LightBG.
115
115
116 --[no-]color_info
116 --[no-]color_info
117 IPython can display information about objects via a set of functions,
117 IPython can display information about objects via a set of functions,
118 and optionally can use colors for this, syntax highlighting source
118 and optionally can use colors for this, syntax highlighting source
119 code and various other elements. However, because this information is
119 code and various other elements. However, because this information is
120 passed through a pager (like 'less') and many pagers get confused with
120 passed through a pager (like 'less') and many pagers get confused with
121 color codes, this option is off by default. You can test it and turn
121 color codes, this option is off by default. You can test it and turn
122 it on permanently in your ipythonrc file if it works for you. As a
122 it on permanently in your ipythonrc file if it works for you. As a
123 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
123 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
124 that in RedHat 7.2 doesn't.
124 that in RedHat 7.2 doesn't.
125
125
126 Test it and turn it on permanently if it works with your
126 Test it and turn it on permanently if it works with your
127 system. The magic function %color_info allows you to toggle this
127 system. The magic function %color_info allows you to toggle this
128 interactively for testing.
128 interactively for testing.
129
129
130 --[no-]debug
130 --[no-]debug
131 Show information about the loading process. Very useful to pin down
131 Show information about the loading process. Very useful to pin down
132 problems with your configuration files or to get details about
132 problems with your configuration files or to get details about
133 session restores.
133 session restores.
134
134
135 --[no-]deep_reload:
135 --[no-]deep_reload:
136 IPython can use the deep_reload module which reloads changes in
136 IPython can use the deep_reload module which reloads changes in
137 modules recursively (it replaces the reload() function, so you don't
137 modules recursively (it replaces the reload() function, so you don't
138 need to change anything to use it). deep_reload() forces a full
138 need to change anything to use it). deep_reload() forces a full
139 reload of modules whose code may have changed, which the default
139 reload of modules whose code may have changed, which the default
140 reload() function does not.
140 reload() function does not.
141
141
142 When deep_reload is off, IPython will use the normal reload(),
142 When deep_reload is off, IPython will use the normal reload(),
143 but deep_reload will still be available as dreload(). This
143 but deep_reload will still be available as dreload(). This
144 feature is off by default [which means that you have both
144 feature is off by default [which means that you have both
145 normal reload() and dreload()].
145 normal reload() and dreload()].
146
146
147 editor=<name>
147 editor=<name>
148 Which editor to use with the %edit command. By default,
148 Which editor to use with the %edit command. By default,
149 IPython will honor your EDITOR environment variable (if not
149 IPython will honor your EDITOR environment variable (if not
150 set, vi is the Unix default and notepad the Windows one).
150 set, vi is the Unix default and notepad the Windows one).
151 Since this editor is invoked on the fly by IPython and is
151 Since this editor is invoked on the fly by IPython and is
152 meant for editing small code snippets, you may want to use a
152 meant for editing small code snippets, you may want to use a
153 small, lightweight editor here (in case your default EDITOR is
153 small, lightweight editor here (in case your default EDITOR is
154 something like Emacs).
154 something like Emacs).
155
155
156 ipython_dir=<name>
156 ipython_dir=<name>
157 name of your IPython configuration directory IPYTHON_DIR. This
157 name of your IPython configuration directory IPYTHON_DIR. This
158 can also be specified through the environment variable
158 can also be specified through the environment variable
159 IPYTHON_DIR.
159 IPYTHON_DIR.
160
160
161 -log, l
161 -log, l
162 generate a log file of all input. The file is named
162 generate a log file of all input. The file is named
163 ipython_log.py in your current directory (which prevents logs
163 ipython_log.py in your current directory (which prevents logs
164 from multiple IPython sessions from trampling each other). You
164 from multiple IPython sessions from trampling each other). You
165 can use this to later restore a session by loading your
165 can use this to later restore a session by loading your
166 logfile as a file to be executed with option -logplay (see
166 logfile as a file to be executed with option -logplay (see
167 below).
167 below).
168
168
169 -logfile, lf <name> specify the name of your logfile.
169 logfile=<name> specify the name of your logfile.
170
170
171 -logplay, lp <name>
171 logplay=<name>
172
172
173 you can replay a previous log. For restoring a session as close as
173 you can replay a previous log. For restoring a session as close as
174 possible to the state you left it in, use this option (don't just run
174 possible to the state you left it in, use this option (don't just run
175 the logfile). With -logplay, IPython will try to reconstruct the
175 the logfile). With -logplay, IPython will try to reconstruct the
176 previous working environment in full, not just execute the commands in
176 previous working environment in full, not just execute the commands in
177 the logfile.
177 the logfile.
178
178
179 When a session is restored, logging is automatically turned on
179 When a session is restored, logging is automatically turned on
180 again with the name of the logfile it was invoked with (it is
180 again with the name of the logfile it was invoked with (it is
181 read from the log header). So once you've turned logging on for
181 read from the log header). So once you've turned logging on for
182 a session, you can quit IPython and reload it as many times as
182 a session, you can quit IPython and reload it as many times as
183 you want and it will continue to log its history and restore
183 you want and it will continue to log its history and restore
184 from the beginning every time.
184 from the beginning every time.
185
185
186 Caveats: there are limitations in this option. The history
186 Caveats: there are limitations in this option. The history
187 variables _i*,_* and _dh don't get restored properly. In the
187 variables _i*,_* and _dh don't get restored properly. In the
188 future we will try to implement full session saving by writing
188 future we will try to implement full session saving by writing
189 and retrieving a 'snapshot' of the memory state of IPython. But
189 and retrieving a 'snapshot' of the memory state of IPython. But
190 our first attempts failed because of inherent limitations of
190 our first attempts failed because of inherent limitations of
191 Python's Pickle module, so this may have to wait.
191 Python's Pickle module, so this may have to wait.
192
192
193 --[no-]messages
193 --[no-]messages
194 Print messages which IPython collects about its startup
194 Print messages which IPython collects about its startup
195 process (default on).
195 process (default on).
196
196
197 --[no-]pdb
197 --[no-]pdb
198 Automatically call the pdb debugger after every uncaught
198 Automatically call the pdb debugger after every uncaught
199 exception. If you are used to debugging using pdb, this puts
199 exception. If you are used to debugging using pdb, this puts
200 you automatically inside of it after any call (either in
200 you automatically inside of it after any call (either in
201 IPython or in code called by it) which triggers an exception
201 IPython or in code called by it) which triggers an exception
202 which goes uncaught.
202 which goes uncaught.
203
203
204 --pydb
205 Makes IPython use the third party "pydb" package as debugger,
206 instead of pdb. Requires that pydb is installed.
207
208 --[no-]pprint
204 --[no-]pprint
209 ipython can optionally use the pprint (pretty printer) module
205 ipython can optionally use the pprint (pretty printer) module
210 for displaying results. pprint tends to give a nicer display
206 for displaying results. pprint tends to give a nicer display
211 of nested data structures. If you like it, you can turn it on
207 of nested data structures. If you like it, you can turn it on
212 permanently in your config file (default off).
208 permanently in your config file (default off).
213
209
214 profile=<name>
210 profile=<name>
215
211
216 assume that your config file is ipythonrc-<name> or
212 Select the IPython profile by name.
217 ipy_profile_<name>.py (looks in current dir first, then in
213
218 IPYTHON_DIR). This is a quick way to keep and load multiple
214 This is a quick way to keep and load multiple
219 config files for different tasks, especially if you use the
215 config files for different tasks, especially if you use the
220 include option of config files. You can keep a basic
216 include option of config files. You can keep a basic
221 IPYTHON_DIR/ipythonrc file and then have other 'profiles' which
217 IPYTHON_DIR/ipythonrc file and then have other 'profiles' which
222 include this one and load extra things for particular
218 include this one and load extra things for particular
223 tasks. For example:
219 tasks. For example:
224
220
225 1. $IPYTHON_DIR/ipythonrc : load basic things you always want.
221 1. $IPYTHON_DIR/profile_default : load basic things you always want.
226 2. $IPYTHON_DIR/ipythonrc-math : load (1) and basic math-related modules.
222 2. $IPYTHON_DIR/profile_math : load (1) and basic math-related modules.
227 3. $IPYTHON_DIR/ipythonrc-numeric : load (1) and Numeric and plotting modules.
223 3. $IPYTHON_DIR/profile_numeric : load (1) and Numeric and plotting modules.
228
224
229 Since it is possible to create an endless loop by having
225 Since it is possible to create an endless loop by having
230 circular file inclusions, IPython will stop if it reaches 15
226 circular file inclusions, IPython will stop if it reaches 15
231 recursive inclusions.
227 recursive inclusions.
232
228
233 pi1=<string>
229 InteractiveShell.prompt_in1=<string>
234
230
235 Specify the string used for input prompts. Note that if you are using
231 Specify the string used for input prompts. Note that if you are using
236 numbered prompts, the number is represented with a '\#' in the
232 numbered prompts, the number is represented with a '\#' in the
237 string. Don't forget to quote strings with spaces embedded in
233 string. Don't forget to quote strings with spaces embedded in
238 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
234 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
239 discusses in detail all the available escapes to customize your
235 discusses in detail all the available escapes to customize your
240 prompts.
236 prompts.
241
237
242 pi2=<string>
238 InteractiveShell.prompt_in2=<string>
243 Similar to the previous option, but used for the continuation
239 Similar to the previous option, but used for the continuation
244 prompts. The special sequence '\D' is similar to '\#', but
240 prompts. The special sequence '\D' is similar to '\#', but
245 with all digits replaced dots (so you can have your
241 with all digits replaced dots (so you can have your
246 continuation prompt aligned with your input prompt). Default:
242 continuation prompt aligned with your input prompt). Default:
247 ' .\D.:' (note three spaces at the start for alignment with
243 ' .\D.:' (note three spaces at the start for alignment with
248 'In [\#]').
244 'In [\#]').
249
245
250 po=<string>
246 InteractiveShell.prompt_out=<string>
251 String used for output prompts, also uses numbers like
247 String used for output prompts, also uses numbers like
252 prompt_in1. Default: 'Out[\#]:'
248 prompt_in1. Default: 'Out[\#]:'
253
249
254 --quick
250 --quick
255 start in bare bones mode (no config file loaded).
251 start in bare bones mode (no config file loaded).
256
252
257 config_file=<name>
253 config_file=<name>
258 name of your IPython resource configuration file. Normally
254 name of your IPython resource configuration file. Normally
259 IPython loads ipython_config.py (from current directory) or
255 IPython loads ipython_config.py (from current directory) or
260 IPYTHON_DIR/profile_default.
256 IPYTHON_DIR/profile_default.
261
257
262 If the loading of your config file fails, IPython starts with
258 If the loading of your config file fails, IPython starts with
263 a bare bones configuration (no modules loaded at all).
259 a bare bones configuration (no modules loaded at all).
264
260
265 --[no-]readline
261 --[no-]readline
266 use the readline library, which is needed to support name
262 use the readline library, which is needed to support name
267 completion and command history, among other things. It is
263 completion and command history, among other things. It is
268 enabled by default, but may cause problems for users of
264 enabled by default, but may cause problems for users of
269 X/Emacs in Python comint or shell buffers.
265 X/Emacs in Python comint or shell buffers.
270
266
271 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
267 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
272 IPython's readline and syntax coloring fine, only 'emacs' (M-x
268 IPython's readline and syntax coloring fine, only 'emacs' (M-x
273 shell and C-c !) buffers do not.
269 shell and C-c !) buffers do not.
274
270
275 sl=<n>
271 TerminalInteractiveShell.screen_length=<n>
276 number of lines of your screen. This is used to control
272 number of lines of your screen. This is used to control
277 printing of very long strings. Strings longer than this number
273 printing of very long strings. Strings longer than this number
278 of lines will be sent through a pager instead of directly
274 of lines will be sent through a pager instead of directly
279 printed.
275 printed.
280
276
281 The default value for this is 0, which means IPython will
277 The default value for this is 0, which means IPython will
282 auto-detect your screen size every time it needs to print certain
278 auto-detect your screen size every time it needs to print certain
283 potentially long strings (this doesn't change the behavior of the
279 potentially long strings (this doesn't change the behavior of the
284 'print' keyword, it's only triggered internally). If for some
280 'print' keyword, it's only triggered internally). If for some
285 reason this isn't working well (it needs curses support), specify
281 reason this isn't working well (it needs curses support), specify
286 it yourself. Otherwise don't change the default.
282 it yourself. Otherwise don't change the default.
287
283
288 si=<string>
284 TerminalInteractiveShell.separate_in=<string>
289
285
290 separator before input prompts.
286 separator before input prompts.
291 Default: '\n'
287 Default: '\n'
292
288
293 so=<string>
289 TerminalInteractiveShell.separate_out=<string>
294 separator before output prompts.
290 separator before output prompts.
295 Default: nothing.
291 Default: nothing.
296
292
297 so2=<string>
293 TerminalInteractiveShell.separate_out2=<string>
298 separator after output prompts.
294 separator after output prompts.
299 Default: nothing.
295 Default: nothing.
300 For these three options, use the value 0 to specify no separator.
296 For these three options, use the value 0 to specify no separator.
301
297
302 --nosep
298 --nosep
303 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
299 shorthand for setting the above separators to empty strings.
304 0'. Simply removes all input/output separators.
300
301 Simply removes all input/output separators.
305
302
306 --init
303 --init
307 allows you to initialize your IPYTHON_DIR configuration when you
304 allows you to initialize a profile dir for configuration when you
308 install a new version of IPython. Since new versions may
305 install a new version of IPython or want to use a new profile.
309 include new command line options or example files, this copies
306 Since new versions may include new command line options or example
310 updated config files. However, it backs up (with a
307 files, this copies updated config files. Note that you should probably
311 .old extension) all files which it overwrites so that you can
308 use %upgrade instead,it's a safer alternative.
312 merge back any customizations you might have in your personal
313 files. Note that you should probably use %upgrade instead,
314 it's a safer alternative.
315
316
309
317 --version print version information and exit.
310 --version print version information and exit.
318
311
319 xmode=<modename>
312 xmode=<modename>
320
313
321 Mode for exception reporting.
314 Mode for exception reporting.
322
315
323 Valid modes: Plain, Context and Verbose.
316 Valid modes: Plain, Context and Verbose.
324
317
325 * Plain: similar to python's normal traceback printing.
318 * Plain: similar to python's normal traceback printing.
326 * Context: prints 5 lines of context source code around each
319 * Context: prints 5 lines of context source code around each
327 line in the traceback.
320 line in the traceback.
328 * Verbose: similar to Context, but additionally prints the
321 * Verbose: similar to Context, but additionally prints the
329 variables currently visible where the exception happened
322 variables currently visible where the exception happened
330 (shortening their strings if too long). This can potentially be
323 (shortening their strings if too long). This can potentially be
331 very slow, if you happen to have a huge data structure whose
324 very slow, if you happen to have a huge data structure whose
332 string representation is complex to compute. Your computer may
325 string representation is complex to compute. Your computer may
333 appear to freeze for a while with cpu usage at 100%. If this
326 appear to freeze for a while with cpu usage at 100%. If this
334 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
327 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
335 more than once).
328 more than once).
336
329
337 Interactive use
330 Interactive use
338 ===============
331 ===============
339
332
340 Warning: IPython relies on the existence of a global variable called
333 IPython is meant to work as a drop-in
341 _ip which controls the shell itself. If you redefine _ip to anything,
342 bizarre behavior will quickly occur.
343
344 Other than the above warning, IPython is meant to work as a drop-in
345 replacement for the standard interactive interpreter. As such, any code
334 replacement for the standard interactive interpreter. As such, any code
346 which is valid python should execute normally under IPython (cases where
335 which is valid python should execute normally under IPython (cases where
347 this is not true should be reported as bugs). It does, however, offer
336 this is not true should be reported as bugs). It does, however, offer
348 many features which are not available at a standard python prompt. What
337 many features which are not available at a standard python prompt. What
349 follows is a list of these.
338 follows is a list of these.
350
339
351
340
352 Caution for Windows users
341 Caution for Windows users
353 -------------------------
342 -------------------------
354
343
355 Windows, unfortunately, uses the '\\' character as a path
344 Windows, unfortunately, uses the '\\' character as a path
356 separator. This is a terrible choice, because '\\' also represents the
345 separator. This is a terrible choice, because '\\' also represents the
357 escape character in most modern programming languages, including
346 escape character in most modern programming languages, including
358 Python. For this reason, using '/' character is recommended if you
347 Python. For this reason, using '/' character is recommended if you
359 have problems with ``\``. However, in Windows commands '/' flags
348 have problems with ``\``. However, in Windows commands '/' flags
360 options, so you can not use it for the root directory. This means that
349 options, so you can not use it for the root directory. This means that
361 paths beginning at the root must be typed in a contrived manner like:
350 paths beginning at the root must be typed in a contrived manner like:
362 ``%copy \opt/foo/bar.txt \tmp``
351 ``%copy \opt/foo/bar.txt \tmp``
363
352
364 .. _magic:
353 .. _magic:
365
354
366 Magic command system
355 Magic command system
367 --------------------
356 --------------------
368
357
369 IPython will treat any line whose first character is a % as a special
358 IPython will treat any line whose first character is a % as a special
370 call to a 'magic' function. These allow you to control the behavior of
359 call to a 'magic' function. These allow you to control the behavior of
371 IPython itself, plus a lot of system-type features. They are all
360 IPython itself, plus a lot of system-type features. They are all
372 prefixed with a % character, but parameters are given without
361 prefixed with a % character, but parameters are given without
373 parentheses or quotes.
362 parentheses or quotes.
374
363
375 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
364 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
376 exists.
365 exists.
377
366
378 If you have 'automagic' enabled (as it by default), you don't need
367 If you have 'automagic' enabled (as it by default), you don't need
379 to type in the % explicitly. IPython will scan its internal list of
368 to type in the % explicitly. IPython will scan its internal list of
380 magic functions and call one if it exists. With automagic on you can
369 magic functions and call one if it exists. With automagic on you can
381 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
370 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
382 system has the lowest possible precedence in name searches, so defining
371 system has the lowest possible precedence in name searches, so defining
383 an identifier with the same name as an existing magic function will
372 an identifier with the same name as an existing magic function will
384 shadow it for automagic use. You can still access the shadowed magic
373 shadow it for automagic use. You can still access the shadowed magic
385 function by explicitly using the % character at the beginning of the line.
374 function by explicitly using the % character at the beginning of the line.
386
375
387 An example (with automagic on) should clarify all this::
376 An example (with automagic on) should clarify all this:
377
378 .. sourcecode:: ipython
388
379
389 In [1]: cd ipython # %cd is called by automagic
380 In [1]: cd ipython # %cd is called by automagic
390
381
391 /home/fperez/ipython
382 /home/fperez/ipython
392
383
393 In [2]: cd=1 # now cd is just a variable
384 In [2]: cd=1 # now cd is just a variable
394
385
395 In [3]: cd .. # and doesn't work as a function anymore
386 In [3]: cd .. # and doesn't work as a function anymore
396
387
397 ------------------------------
388 ------------------------------
398
389
399 File "<console>", line 1
390 File "<console>", line 1
400
391
401 cd ..
392 cd ..
402
393
403 ^
394 ^
404
395
405 SyntaxError: invalid syntax
396 SyntaxError: invalid syntax
406
397
407 In [4]: %cd .. # but %cd always works
398 In [4]: %cd .. # but %cd always works
408
399
409 /home/fperez
400 /home/fperez
410
401
411 In [5]: del cd # if you remove the cd variable
402 In [5]: del cd # if you remove the cd variable
412
403
413 In [6]: cd ipython # automagic can work again
404 In [6]: cd ipython # automagic can work again
414
405
415 /home/fperez/ipython
406 /home/fperez/ipython
416
407
417 You can define your own magic functions to extend the system. The
408 You can define your own magic functions to extend the system. The
418 following example defines a new magic command, %impall::
409 following example defines a new magic command, %impall:
419
410
420 import IPython.ipapi
411 .. sourcecode:: python
421
412
422 ip = IPython.ipapi.get()
413 ip = get_ipython()
423
414
424 def doimp(self, arg):
415 def doimp(self, arg):
425
416
426 ip = self.api
417 ip = self.api
427
418
428 ip.ex("import %s; reload(%s); from %s import *" % (
419 ip.ex("import %s; reload(%s); from %s import *" % (
429
420
430 arg,arg,arg)
421 arg,arg,arg)
431
422
432 )
423 )
433
424
434 ip.expose_magic('impall', doimp)
425 ip.expose_magic('impall', doimp)
435
426
436 You can also define your own aliased names for magic functions. In your
437 ipythonrc file, placing a line like::
438
439 execute __IP.magic_cl = __IP.magic_clear
440
441 will define %cl as a new name for %clear.
442
443 Type %magic for more information, including a list of all available
427 Type %magic for more information, including a list of all available
444 magic functions at any time and their docstrings. You can also type
428 magic functions at any time and their docstrings. You can also type
445 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
429 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
446 information on the '?' system) to get information about any particular
430 information on the '?' system) to get information about any particular
447 magic function you are interested in.
431 magic function you are interested in.
448
432
449 The API documentation for the :mod:`IPython.Magic` module contains the full
433 The API documentation for the :mod:`IPython.core.magic` module contains the full
450 docstrings of all currently available magic commands.
434 docstrings of all currently available magic commands.
451
435
452
436
453 Access to the standard Python help
437 Access to the standard Python help
454 ----------------------------------
438 ----------------------------------
455
439
456 As of Python 2.1, a help system is available with access to object docstrings
440 As of Python 2.1, a help system is available with access to object docstrings
457 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
441 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
458 also type help(object) to obtain information about a given object, and
442 also type help(object) to obtain information about a given object, and
459 help('keyword') for information on a keyword. As noted :ref:`here
443 help('keyword') for information on a keyword. As noted :ref:`here
460 <accessing_help>`, you need to properly configure your environment variable
444 <accessing_help>`, you need to properly configure your environment variable
461 PYTHONDOCS for this feature to work correctly.
445 PYTHONDOCS for this feature to work correctly.
462
446
463 .. _dynamic_object_info:
447 .. _dynamic_object_info:
464
448
465 Dynamic object information
449 Dynamic object information
466 --------------------------
450 --------------------------
467
451
468 Typing ?word or word? prints detailed information about an object. If
452 Typing ?word or word? prints detailed information about an object. If
469 certain strings in the object are too long (docstrings, code, etc.) they
453 certain strings in the object are too long (docstrings, code, etc.) they
470 get snipped in the center for brevity. This system gives access variable
454 get snipped in the center for brevity. This system gives access variable
471 types and values, full source code for any object (if available),
455 types and values, full source code for any object (if available),
472 function prototypes and other useful information.
456 function prototypes and other useful information.
473
457
474 Typing ??word or word?? gives access to the full information without
458 Typing ??word or word?? gives access to the full information without
475 snipping long strings. Long strings are sent to the screen through the
459 snipping long strings. Long strings are sent to the screen through the
476 less pager if longer than the screen and printed otherwise. On systems
460 less pager if longer than the screen and printed otherwise. On systems
477 lacking the less command, IPython uses a very basic internal pager.
461 lacking the less command, IPython uses a very basic internal pager.
478
462
479 The following magic functions are particularly useful for gathering
463 The following magic functions are particularly useful for gathering
480 information about your working environment. You can get more details by
464 information about your working environment. You can get more details by
481 typing %magic or querying them individually (use %function_name? with or
465 typing %magic or querying them individually (use %function_name? with or
482 without the %), this is just a summary:
466 without the %), this is just a summary:
483
467
484 * **%pdoc <object>**: Print (or run through a pager if too long) the
468 * **%pdoc <object>**: Print (or run through a pager if too long) the
485 docstring for an object. If the given object is a class, it will
469 docstring for an object. If the given object is a class, it will
486 print both the class and the constructor docstrings.
470 print both the class and the constructor docstrings.
487 * **%pdef <object>**: Print the definition header for any callable
471 * **%pdef <object>**: Print the definition header for any callable
488 object. If the object is a class, print the constructor information.
472 object. If the object is a class, print the constructor information.
489 * **%psource <object>**: Print (or run through a pager if too long)
473 * **%psource <object>**: Print (or run through a pager if too long)
490 the source code for an object.
474 the source code for an object.
491 * **%pfile <object>**: Show the entire source file where an object was
475 * **%pfile <object>**: Show the entire source file where an object was
492 defined via a pager, opening it at the line where the object
476 defined via a pager, opening it at the line where the object
493 definition begins.
477 definition begins.
494 * **%who/%whos**: These functions give information about identifiers
478 * **%who/%whos**: These functions give information about identifiers
495 you have defined interactively (not things you loaded or defined
479 you have defined interactively (not things you loaded or defined
496 in your configuration files). %who just prints a list of
480 in your configuration files). %who just prints a list of
497 identifiers and %whos prints a table with some basic details about
481 identifiers and %whos prints a table with some basic details about
498 each identifier.
482 each identifier.
499
483
500 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
484 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
501 %pdef, %psource) give you access to documentation even on things which
485 %pdef, %psource) give you access to documentation even on things which
502 are not really defined as separate identifiers. Try for example typing
486 are not really defined as separate identifiers. Try for example typing
503 {}.get? or after doing import os, type os.path.abspath??.
487 {}.get? or after doing import os, type os.path.abspath??.
504
488
505
489
506 .. _readline:
490 .. _readline:
507
491
508 Readline-based features
492 Readline-based features
509 -----------------------
493 -----------------------
510
494
511 These features require the GNU readline library, so they won't work if
495 These features require the GNU readline library, so they won't work if
512 your Python installation lacks readline support. We will first describe
496 your Python installation lacks readline support. We will first describe
513 the default behavior IPython uses, and then how to change it to suit
497 the default behavior IPython uses, and then how to change it to suit
514 your preferences.
498 your preferences.
515
499
516
500
517 Command line completion
501 Command line completion
518 +++++++++++++++++++++++
502 +++++++++++++++++++++++
519
503
520 At any time, hitting TAB will complete any available python commands or
504 At any time, hitting TAB will complete any available python commands or
521 variable names, and show you a list of the possible completions if
505 variable names, and show you a list of the possible completions if
522 there's no unambiguous one. It will also complete filenames in the
506 there's no unambiguous one. It will also complete filenames in the
523 current directory if no python names match what you've typed so far.
507 current directory if no python names match what you've typed so far.
524
508
525
509
526 Search command history
510 Search command history
527 ++++++++++++++++++++++
511 ++++++++++++++++++++++
528
512
529 IPython provides two ways for searching through previous input and thus
513 IPython provides two ways for searching through previous input and thus
530 reduce the need for repetitive typing:
514 reduce the need for repetitive typing:
531
515
532 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
516 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
533 (next,down) to search through only the history items that match
517 (next,down) to search through only the history items that match
534 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
518 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
535 prompt, they just behave like normal arrow keys.
519 prompt, they just behave like normal arrow keys.
536 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
520 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
537 searches your history for lines that contain what you've typed so
521 searches your history for lines that contain what you've typed so
538 far, completing as much as it can.
522 far, completing as much as it can.
539
523
540
524
541 Persistent command history across sessions
525 Persistent command history across sessions
542 ++++++++++++++++++++++++++++++++++++++++++
526 ++++++++++++++++++++++++++++++++++++++++++
543
527
544 IPython will save your input history when it leaves and reload it next
528 IPython will save your input history when it leaves and reload it next
545 time you restart it. By default, the history file is named
529 time you restart it. By default, the history file is named
546 $IPYTHON_DIR/history, but if you've loaded a named profile,
530 $IPYTHON_DIR/profile_<name>/history.sqlite. This allows you to keep
547 '-PROFILE_NAME' is appended to the name. This allows you to keep
548 separate histories related to various tasks: commands related to
531 separate histories related to various tasks: commands related to
549 numerical work will not be clobbered by a system shell history, for
532 numerical work will not be clobbered by a system shell history, for
550 example.
533 example.
551
534
552
535
553 Autoindent
536 Autoindent
554 ++++++++++
537 ++++++++++
555
538
556 IPython can recognize lines ending in ':' and indent the next line,
539 IPython can recognize lines ending in ':' and indent the next line,
557 while also un-indenting automatically after 'raise' or 'return'.
540 while also un-indenting automatically after 'raise' or 'return'.
558
541
559 This feature uses the readline library, so it will honor your ~/.inputrc
542 This feature uses the readline library, so it will honor your ~/.inputrc
560 configuration (or whatever file your INPUTRC variable points to). Adding
543 configuration (or whatever file your INPUTRC variable points to). Adding
561 the following lines to your .inputrc file can make indenting/unindenting
544 the following lines to your .inputrc file can make indenting/unindenting
562 more convenient (M-i indents, M-u unindents)::
545 more convenient (M-i indents, M-u unindents)::
563
546
564 $if Python
547 $if Python
565 "\M-i": " "
548 "\M-i": " "
566 "\M-u": "\d\d\d\d"
549 "\M-u": "\d\d\d\d"
567 $endif
550 $endif
568
551
569 Note that there are 4 spaces between the quote marks after "M-i" above.
552 Note that there are 4 spaces between the quote marks after "M-i" above.
570
553
571 Warning: this feature is ON by default, but it can cause problems with
554 .. warning::
572 the pasting of multi-line indented code (the pasted code gets
555
573 re-indented on each line). A magic function %autoindent allows you to
556 Setting the above indents will cause problems with unicode text entry in the terminal.
574 toggle it on/off at runtime. You can also disable it permanently on in
557
575 your ipythonrc file (set autoindent 0).
558 .. warning::
559
560 This feature is ON by default, but it can cause problems with
561 the pasting of multi-line indented code (the pasted code gets
562 re-indented on each line). A magic function %autoindent allows you to
563 toggle it on/off at runtime. You can also disable it permanently on in
564 your :file:`ipython_config.py` file (set TerminalInteractiveShell.autoindent=False).
576
565
577
566
578 Customizing readline behavior
567 Customizing readline behavior
579 +++++++++++++++++++++++++++++
568 +++++++++++++++++++++++++++++
580
569
581 All these features are based on the GNU readline library, which has an
570 All these features are based on the GNU readline library, which has an
582 extremely customizable interface. Normally, readline is configured via a
571 extremely customizable interface. Normally, readline is configured via a
583 file which defines the behavior of the library; the details of the
572 file which defines the behavior of the library; the details of the
584 syntax for this can be found in the readline documentation available
573 syntax for this can be found in the readline documentation available
585 with your system or on the Internet. IPython doesn't read this file (if
574 with your system or on the Internet. IPython doesn't read this file (if
586 it exists) directly, but it does support passing to readline valid
575 it exists) directly, but it does support passing to readline valid
587 options via a simple interface. In brief, you can customize readline by
576 options via a simple interface. In brief, you can customize readline by
588 setting the following options in your ipythonrc configuration file (note
577 setting the following options in your ipythonrc configuration file (note
589 that these options can not be specified at the command line):
578 that these options can not be specified at the command line):
590
579
591 * **readline_parse_and_bind**: this option can appear as many times as
580 * **readline_parse_and_bind**: this option can appear as many times as
592 you want, each time defining a string to be executed via a
581 you want, each time defining a string to be executed via a
593 readline.parse_and_bind() command. The syntax for valid commands
582 readline.parse_and_bind() command. The syntax for valid commands
594 of this kind can be found by reading the documentation for the GNU
583 of this kind can be found by reading the documentation for the GNU
595 readline library, as these commands are of the kind which readline
584 readline library, as these commands are of the kind which readline
596 accepts in its configuration file.
585 accepts in its configuration file.
597 * **readline_remove_delims**: a string of characters to be removed
586 * **readline_remove_delims**: a string of characters to be removed
598 from the default word-delimiters list used by readline, so that
587 from the default word-delimiters list used by readline, so that
599 completions may be performed on strings which contain them. Do not
588 completions may be performed on strings which contain them. Do not
600 change the default value unless you know what you're doing.
589 change the default value unless you know what you're doing.
601 * **readline_omit__names**: when tab-completion is enabled, hitting
590 * **readline_omit__names**: when tab-completion is enabled, hitting
602 <tab> after a '.' in a name will complete all attributes of an
591 <tab> after a '.' in a name will complete all attributes of an
603 object, including all the special methods whose names include
592 object, including all the special methods whose names include
604 double underscores (like __getitem__ or __class__). If you'd
593 double underscores (like __getitem__ or __class__). If you'd
605 rather not see these names by default, you can set this option to
594 rather not see these names by default, you can set this option to
606 1. Note that even when this option is set, you can still see those
595 1. Note that even when this option is set, you can still see those
607 names by explicitly typing a _ after the period and hitting <tab>:
596 names by explicitly typing a _ after the period and hitting <tab>:
608 'name._<tab>' will always complete attribute names starting with '_'.
597 'name._<tab>' will always complete attribute names starting with '_'.
609
598
610 This option is off by default so that new users see all
599 This option is off by default so that new users see all
611 attributes of any objects they are dealing with.
600 attributes of any objects they are dealing with.
612
601
613 You will find the default values along with a corresponding detailed
602 You will find the default values along with a corresponding detailed
614 explanation in your ipythonrc file.
603 explanation in your ipythonrc file.
615
604
616
605
617 Session logging and restoring
606 Session logging and restoring
618 -----------------------------
607 -----------------------------
619
608
620 You can log all input from a session either by starting IPython with the
609 You can log all input from a session either by starting IPython with the
621 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
610 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
622 or by activating the logging at any moment with the magic function %logstart.
611 or by activating the logging at any moment with the magic function %logstart.
623
612
624 Log files can later be reloaded with the -logplay option and IPython
613 Log files can later be reloaded with the -logplay option and IPython
625 will attempt to 'replay' the log by executing all the lines in it, thus
614 will attempt to 'replay' the log by executing all the lines in it, thus
626 restoring the state of a previous session. This feature is not quite
615 restoring the state of a previous session. This feature is not quite
627 perfect, but can still be useful in many cases.
616 perfect, but can still be useful in many cases.
628
617
629 The log files can also be used as a way to have a permanent record of
618 The log files can also be used as a way to have a permanent record of
630 any code you wrote while experimenting. Log files are regular text files
619 any code you wrote while experimenting. Log files are regular text files
631 which you can later open in your favorite text editor to extract code or
620 which you can later open in your favorite text editor to extract code or
632 to 'clean them up' before using them to replay a session.
621 to 'clean them up' before using them to replay a session.
633
622
634 The %logstart function for activating logging in mid-session is used as
623 The %logstart function for activating logging in mid-session is used as
635 follows:
624 follows:
636
625
637 %logstart [log_name [log_mode]]
626 %logstart [log_name [log_mode]]
638
627
639 If no name is given, it defaults to a file named 'log' in your
628 If no name is given, it defaults to a file named 'log' in your
640 IPYTHON_DIR directory, in 'rotate' mode (see below).
629 IPYTHON_DIR directory, in 'rotate' mode (see below).
641
630
642 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
631 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
643 history up to that point and then continues logging.
632 history up to that point and then continues logging.
644
633
645 %logstart takes a second optional parameter: logging mode. This can be
634 %logstart takes a second optional parameter: logging mode. This can be
646 one of (note that the modes are given unquoted):
635 one of (note that the modes are given unquoted):
647
636
648 * [over:] overwrite existing log_name.
637 * [over:] overwrite existing log_name.
649 * [backup:] rename (if exists) to log_name~ and start log_name.
638 * [backup:] rename (if exists) to log_name~ and start log_name.
650 * [append:] well, that says it.
639 * [append:] well, that says it.
651 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
640 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
652
641
653 The %logoff and %logon functions allow you to temporarily stop and
642 The %logoff and %logon functions allow you to temporarily stop and
654 resume logging to a file which had previously been started with
643 resume logging to a file which had previously been started with
655 %logstart. They will fail (with an explanation) if you try to use them
644 %logstart. They will fail (with an explanation) if you try to use them
656 before logging has been started.
645 before logging has been started.
657
646
658 .. _system_shell_access:
647 .. _system_shell_access:
659
648
660 System shell access
649 System shell access
661 -------------------
650 -------------------
662
651
663 Any input line beginning with a ! character is passed verbatim (minus
652 Any input line beginning with a ! character is passed verbatim (minus
664 the !, of course) to the underlying operating system. For example,
653 the !, of course) to the underlying operating system. For example,
665 typing !ls will run 'ls' in the current directory.
654 typing !ls will run 'ls' in the current directory.
666
655
667 Manual capture of command output
656 Manual capture of command output
668 --------------------------------
657 --------------------------------
669
658
670 If the input line begins with two exclamation marks, !!, the command is
659 If the input line begins with two exclamation marks, !!, the command is
671 executed but its output is captured and returned as a python list, split
660 executed but its output is captured and returned as a python list, split
672 on newlines. Any output sent by the subprocess to standard error is
661 on newlines. Any output sent by the subprocess to standard error is
673 printed separately, so that the resulting list only captures standard
662 printed separately, so that the resulting list only captures standard
674 output. The !! syntax is a shorthand for the %sx magic command.
663 output. The !! syntax is a shorthand for the %sx magic command.
675
664
676 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
665 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
677 but allowing more fine-grained control of the capture details, and
666 but allowing more fine-grained control of the capture details, and
678 storing the result directly into a named variable. The direct use of
667 storing the result directly into a named variable. The direct use of
679 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
668 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
680 instead.
669 instead.
681
670
682 IPython also allows you to expand the value of python variables when
671 IPython also allows you to expand the value of python variables when
683 making system calls. Any python variable or expression which you prepend
672 making system calls. Any python variable or expression which you prepend
684 with $ will get expanded before the system call is made::
673 with $ will get expanded before the system call is made::
685
674
686 In [1]: pyvar='Hello world'
675 In [1]: pyvar='Hello world'
687 In [2]: !echo "A python variable: $pyvar"
676 In [2]: !echo "A python variable: $pyvar"
688 A python variable: Hello world
677 A python variable: Hello world
689
678
690 If you want the shell to actually see a literal $, you need to type it
679 If you want the shell to actually see a literal $, you need to type it
691 twice::
680 twice::
692
681
693 In [3]: !echo "A system variable: $$HOME"
682 In [3]: !echo "A system variable: $$HOME"
694 A system variable: /home/fperez
683 A system variable: /home/fperez
695
684
696 You can pass arbitrary expressions, though you'll need to delimit them
685 You can pass arbitrary expressions, though you'll need to delimit them
697 with {} if there is ambiguity as to the extent of the expression::
686 with {} if there is ambiguity as to the extent of the expression::
698
687
699 In [5]: x=10
688 In [5]: x=10
700 In [6]: y=20
689 In [6]: y=20
701 In [13]: !echo $x+y
690 In [13]: !echo $x+y
702 10+y
691 10+y
703 In [7]: !echo ${x+y}
692 In [7]: !echo ${x+y}
704 30
693 30
705
694
706 Even object attributes can be expanded::
695 Even object attributes can be expanded::
707
696
708 In [12]: !echo $sys.argv
697 In [12]: !echo $sys.argv
709 [/home/fperez/usr/bin/ipython]
698 [/home/fperez/usr/bin/ipython]
710
699
711
700
712 System command aliases
701 System command aliases
713 ----------------------
702 ----------------------
714
703
715 The %alias magic function and the alias option in the ipythonrc
704 The %alias magic function and the alias option in the ipythonrc
716 configuration file allow you to define magic functions which are in fact
705 configuration file allow you to define magic functions which are in fact
717 system shell commands. These aliases can have parameters.
706 system shell commands. These aliases can have parameters.
718
707
719 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
708 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
720
709
721 Then, typing '%alias_name params' will execute the system command 'cmd
710 Then, typing '%alias_name params' will execute the system command 'cmd
722 params' (from your underlying operating system).
711 params' (from your underlying operating system).
723
712
724 You can also define aliases with parameters using %s specifiers (one per
713 You can also define aliases with parameters using %s specifiers (one per
725 parameter). The following example defines the %parts function as an
714 parameter). The following example defines the %parts function as an
726 alias to the command 'echo first %s second %s' where each %s will be
715 alias to the command 'echo first %s second %s' where each %s will be
727 replaced by a positional parameter to the call to %parts::
716 replaced by a positional parameter to the call to %parts::
728
717
729 In [1]: alias parts echo first %s second %s
718 In [1]: alias parts echo first %s second %s
730 In [2]: %parts A B
719 In [2]: %parts A B
731 first A second B
720 first A second B
732 In [3]: %parts A
721 In [3]: %parts A
733 Incorrect number of arguments: 2 expected.
722 Incorrect number of arguments: 2 expected.
734 parts is an alias to: 'echo first %s second %s'
723 parts is an alias to: 'echo first %s second %s'
735
724
736 If called with no parameters, %alias prints the table of currently
725 If called with no parameters, %alias prints the table of currently
737 defined aliases.
726 defined aliases.
738
727
739 The %rehash/rehashx magics allow you to load your entire $PATH as
728 The %rehash/rehashx magics allow you to load your entire $PATH as
740 ipython aliases. See their respective docstrings (or sec. 6.2
729 ipython aliases. See their respective docstrings (or sec. 6.2
741 <#sec:magic> for further details).
730 <#sec:magic> for further details).
742
731
743
732
744 .. _dreload:
733 .. _dreload:
745
734
746 Recursive reload
735 Recursive reload
747 ----------------
736 ----------------
748
737
749 The dreload function does a recursive reload of a module: changes made
738 The dreload function does a recursive reload of a module: changes made
750 to the module since you imported will actually be available without
739 to the module since you imported will actually be available without
751 having to exit.
740 having to exit.
752
741
753
742
754 Verbose and colored exception traceback printouts
743 Verbose and colored exception traceback printouts
755 -------------------------------------------------
744 -------------------------------------------------
756
745
757 IPython provides the option to see very detailed exception tracebacks,
746 IPython provides the option to see very detailed exception tracebacks,
758 which can be especially useful when debugging large programs. You can
747 which can be especially useful when debugging large programs. You can
759 run any Python file with the %run function to benefit from these
748 run any Python file with the %run function to benefit from these
760 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
749 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
761 be colored (if your terminal supports it) which makes them much easier
750 be colored (if your terminal supports it) which makes them much easier
762 to parse visually.
751 to parse visually.
763
752
764 See the magic xmode and colors functions for details (just type %magic).
753 See the magic xmode and colors functions for details (just type %magic).
765
754
766 These features are basically a terminal version of Ka-Ping Yee's cgitb
755 These features are basically a terminal version of Ka-Ping Yee's cgitb
767 module, now part of the standard Python library.
756 module, now part of the standard Python library.
768
757
769
758
770 .. _input_caching:
759 .. _input_caching:
771
760
772 Input caching system
761 Input caching system
773 --------------------
762 --------------------
774
763
775 IPython offers numbered prompts (In/Out) with input and output caching
764 IPython offers numbered prompts (In/Out) with input and output caching
776 (also referred to as 'input history'). All input is saved and can be
765 (also referred to as 'input history'). All input is saved and can be
777 retrieved as variables (besides the usual arrow key recall), in
766 retrieved as variables (besides the usual arrow key recall), in
778 addition to the %rep magic command that brings a history entry
767 addition to the %rep magic command that brings a history entry
779 up for editing on the next command line.
768 up for editing on the next command line.
780
769
781 The following GLOBAL variables always exist (so don't overwrite them!):
770 The following GLOBAL variables always exist (so don't overwrite them!):
782 _i: stores previous input. _ii: next previous. _iii: next-next previous.
771 _i: stores previous input. _ii: next previous. _iii: next-next previous.
783 _ih : a list of all input _ih[n] is the input from line n and this list
772 _ih : a list of all input _ih[n] is the input from line n and this list
784 is aliased to the global variable In. If you overwrite In with a
773 is aliased to the global variable In. If you overwrite In with a
785 variable of your own, you can remake the assignment to the internal list
774 variable of your own, you can remake the assignment to the internal list
786 with a simple 'In=_ih'.
775 with a simple 'In=_ih'.
787
776
788 Additionally, global variables named _i<n> are dynamically created (<n>
777 Additionally, global variables named _i<n> are dynamically created (<n>
789 being the prompt counter), such that
778 being the prompt counter), such that
790 _i<n> == _ih[<n>] == In[<n>].
779 _i<n> == _ih[<n>] == In[<n>].
791
780
792 For example, what you typed at prompt 14 is available as _i14, _ih[14]
781 For example, what you typed at prompt 14 is available as _i14, _ih[14]
793 and In[14].
782 and In[14].
794
783
795 This allows you to easily cut and paste multi line interactive prompts
784 This allows you to easily cut and paste multi line interactive prompts
796 by printing them out: they print like a clean string, without prompt
785 by printing them out: they print like a clean string, without prompt
797 characters. You can also manipulate them like regular variables (they
786 characters. You can also manipulate them like regular variables (they
798 are strings), modify or exec them (typing 'exec _i9' will re-execute the
787 are strings), modify or exec them (typing 'exec _i9' will re-execute the
799 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
788 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
800 9 through 13 and line 18).
789 9 through 13 and line 18).
801
790
802 You can also re-execute multiple lines of input easily by using the
791 You can also re-execute multiple lines of input easily by using the
803 magic %macro function (which automates the process and allows
792 magic %macro function (which automates the process and allows
804 re-execution without having to type 'exec' every time). The macro system
793 re-execution without having to type 'exec' every time). The macro system
805 also allows you to re-execute previous lines which include magic
794 also allows you to re-execute previous lines which include magic
806 function calls (which require special processing). Type %macro? or see
795 function calls (which require special processing). Type %macro? or see
807 sec. 6.2 <#sec:magic> for more details on the macro system.
796 sec. 6.2 <#sec:magic> for more details on the macro system.
808
797
809 A history function %hist allows you to see any part of your input
798 A history function %hist allows you to see any part of your input
810 history by printing a range of the _i variables.
799 history by printing a range of the _i variables.
811
800
812 You can also search ('grep') through your history by typing
801 You can also search ('grep') through your history by typing
813 '%hist -g somestring'. This also searches through the so called *shadow history*,
802 '%hist -g somestring'. This also searches through the so called *shadow history*,
814 which remembers all the commands (apart from multiline code blocks)
803 which remembers all the commands (apart from multiline code blocks)
815 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
804 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
816 etc. You can bring shadow history entries listed by '%hist -g' up for editing
805 etc. You can bring shadow history entries listed by '%hist -g' up for editing
817 (or re-execution by just pressing ENTER) with %rep command. Shadow history
806 (or re-execution by just pressing ENTER) with %rep command. Shadow history
818 entries are not available as _iNUMBER variables, and they are identified by
807 entries are not available as _iNUMBER variables, and they are identified by
819 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
808 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
820 history entry, but 0231 is a shadow history entry.
809 history entry, but 0231 is a shadow history entry.
821
810
822 Shadow history was added because the readline history is inherently very
811 Shadow history was added because the readline history is inherently very
823 unsafe - if you have multiple IPython sessions open, the last session
812 unsafe - if you have multiple IPython sessions open, the last session
824 to close will overwrite the history of previountly closed session. Likewise,
813 to close will overwrite the history of previountly closed session. Likewise,
825 if a crash occurs, history is never saved, whereas shadow history entries
814 if a crash occurs, history is never saved, whereas shadow history entries
826 are added after entering every command (so a command executed
815 are added after entering every command (so a command executed
827 in another IPython session is immediately available in other IPython
816 in another IPython session is immediately available in other IPython
828 sessions that are open).
817 sessions that are open).
829
818
830 To conserve space, a command can exist in shadow history only once - it doesn't
819 To conserve space, a command can exist in shadow history only once - it doesn't
831 make sense to store a common line like "cd .." a thousand times. The idea is
820 make sense to store a common line like "cd .." a thousand times. The idea is
832 mainly to provide a reliable place where valuable, hard-to-remember commands can
821 mainly to provide a reliable place where valuable, hard-to-remember commands can
833 always be retrieved, as opposed to providing an exact sequence of commands
822 always be retrieved, as opposed to providing an exact sequence of commands
834 you have entered in actual order.
823 you have entered in actual order.
835
824
836 Because shadow history has all the commands you have ever executed,
825 Because shadow history has all the commands you have ever executed,
837 time taken by %hist -g will increase oven time. If it ever starts to take
826 time taken by %hist -g will increase oven time. If it ever starts to take
838 too long (or it ends up containing sensitive information like passwords),
827 too long (or it ends up containing sensitive information like passwords),
839 clear the shadow history by `%clear shadow_nuke`.
828 clear the shadow history by `%clear shadow_nuke`.
840
829
841 Time taken to add entries to shadow history should be negligible, but
830 Time taken to add entries to shadow history should be negligible, but
842 in any case, if you start noticing performance degradation after using
831 in any case, if you start noticing performance degradation after using
843 IPython for a long time (or running a script that floods the shadow history!),
832 IPython for a long time (or running a script that floods the shadow history!),
844 you can 'compress' the shadow history by executing
833 you can 'compress' the shadow history by executing
845 `%clear shadow_compress`. In practice, this should never be necessary
834 `%clear shadow_compress`. In practice, this should never be necessary
846 in normal use.
835 in normal use.
847
836
848 .. _output_caching:
837 .. _output_caching:
849
838
850 Output caching system
839 Output caching system
851 ---------------------
840 ---------------------
852
841
853 For output that is returned from actions, a system similar to the input
842 For output that is returned from actions, a system similar to the input
854 cache exists but using _ instead of _i. Only actions that produce a
843 cache exists but using _ instead of _i. Only actions that produce a
855 result (NOT assignments, for example) are cached. If you are familiar
844 result (NOT assignments, for example) are cached. If you are familiar
856 with Mathematica, IPython's _ variables behave exactly like
845 with Mathematica, IPython's _ variables behave exactly like
857 Mathematica's % variables.
846 Mathematica's % variables.
858
847
859 The following GLOBAL variables always exist (so don't overwrite them!):
848 The following GLOBAL variables always exist (so don't overwrite them!):
860
849
861 * [_] (a single underscore) : stores previous output, like Python's
850 * [_] (a single underscore) : stores previous output, like Python's
862 default interpreter.
851 default interpreter.
863 * [__] (two underscores): next previous.
852 * [__] (two underscores): next previous.
864 * [___] (three underscores): next-next previous.
853 * [___] (three underscores): next-next previous.
865
854
866 Additionally, global variables named _<n> are dynamically created (<n>
855 Additionally, global variables named _<n> are dynamically created (<n>
867 being the prompt counter), such that the result of output <n> is always
856 being the prompt counter), such that the result of output <n> is always
868 available as _<n> (don't use the angle brackets, just the number, e.g.
857 available as _<n> (don't use the angle brackets, just the number, e.g.
869 _21).
858 _21).
870
859
871 These global variables are all stored in a global dictionary (not a
860 These global variables are all stored in a global dictionary (not a
872 list, since it only has entries for lines which returned a result)
861 list, since it only has entries for lines which returned a result)
873 available under the names _oh and Out (similar to _ih and In). So the
862 available under the names _oh and Out (similar to _ih and In). So the
874 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
863 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
875 accidentally overwrite the Out variable you can recover it by typing
864 accidentally overwrite the Out variable you can recover it by typing
876 'Out=_oh' at the prompt.
865 'Out=_oh' at the prompt.
877
866
878 This system obviously can potentially put heavy memory demands on your
867 This system obviously can potentially put heavy memory demands on your
879 system, since it prevents Python's garbage collector from removing any
868 system, since it prevents Python's garbage collector from removing any
880 previously computed results. You can control how many results are kept
869 previously computed results. You can control how many results are kept
881 in memory with the option (at the command line or in your ipythonrc
870 in memory with the option (at the command line or in your ipythonrc
882 file) cache_size. If you set it to 0, the whole system is completely
871 file) cache_size. If you set it to 0, the whole system is completely
883 disabled and the prompts revert to the classic '>>>' of normal Python.
872 disabled and the prompts revert to the classic '>>>' of normal Python.
884
873
885
874
886 Directory history
875 Directory history
887 -----------------
876 -----------------
888
877
889 Your history of visited directories is kept in the global list _dh, and
878 Your history of visited directories is kept in the global list _dh, and
890 the magic %cd command can be used to go to any entry in that list. The
879 the magic %cd command can be used to go to any entry in that list. The
891 %dhist command allows you to view this history. Do ``cd -<TAB`` to
880 %dhist command allows you to view this history. Do ``cd -<TAB`` to
892 conventiently view the directory history.
881 conventiently view the directory history.
893
882
894
883
895 Automatic parentheses and quotes
884 Automatic parentheses and quotes
896 --------------------------------
885 --------------------------------
897
886
898 These features were adapted from Nathan Gray's LazyPython. They are
887 These features were adapted from Nathan Gray's LazyPython. They are
899 meant to allow less typing for common situations.
888 meant to allow less typing for common situations.
900
889
901
890
902 Automatic parentheses
891 Automatic parentheses
903 ---------------------
892 ---------------------
904
893
905 Callable objects (i.e. functions, methods, etc) can be invoked like this
894 Callable objects (i.e. functions, methods, etc) can be invoked like this
906 (notice the commas between the arguments)::
895 (notice the commas between the arguments)::
907
896
908 >>> callable_ob arg1, arg2, arg3
897 >>> callable_ob arg1, arg2, arg3
909
898
910 and the input will be translated to this::
899 and the input will be translated to this::
911
900
912 -> callable_ob(arg1, arg2, arg3)
901 -> callable_ob(arg1, arg2, arg3)
913
902
914 You can force automatic parentheses by using '/' as the first character
903 You can force automatic parentheses by using '/' as the first character
915 of a line. For example::
904 of a line. For example::
916
905
917 >>> /globals # becomes 'globals()'
906 >>> /globals # becomes 'globals()'
918
907
919 Note that the '/' MUST be the first character on the line! This won't work::
908 Note that the '/' MUST be the first character on the line! This won't work::
920
909
921 >>> print /globals # syntax error
910 >>> print /globals # syntax error
922
911
923 In most cases the automatic algorithm should work, so you should rarely
912 In most cases the automatic algorithm should work, so you should rarely
924 need to explicitly invoke /. One notable exception is if you are trying
913 need to explicitly invoke /. One notable exception is if you are trying
925 to call a function with a list of tuples as arguments (the parenthesis
914 to call a function with a list of tuples as arguments (the parenthesis
926 will confuse IPython)::
915 will confuse IPython)::
927
916
928 In [1]: zip (1,2,3),(4,5,6) # won't work
917 In [1]: zip (1,2,3),(4,5,6) # won't work
929
918
930 but this will work::
919 but this will work::
931
920
932 In [2]: /zip (1,2,3),(4,5,6)
921 In [2]: /zip (1,2,3),(4,5,6)
933 ---> zip ((1,2,3),(4,5,6))
922 ---> zip ((1,2,3),(4,5,6))
934 Out[2]= [(1, 4), (2, 5), (3, 6)]
923 Out[2]= [(1, 4), (2, 5), (3, 6)]
935
924
936 IPython tells you that it has altered your command line by displaying
925 IPython tells you that it has altered your command line by displaying
937 the new command line preceded by ->. e.g.::
926 the new command line preceded by ->. e.g.::
938
927
939 In [18]: callable list
928 In [18]: callable list
940 ----> callable (list)
929 ----> callable (list)
941
930
942
931
943 Automatic quoting
932 Automatic quoting
944 -----------------
933 -----------------
945
934
946 You can force automatic quoting of a function's arguments by using ','
935 You can force automatic quoting of a function's arguments by using ','
947 or ';' as the first character of a line. For example::
936 or ';' as the first character of a line. For example::
948
937
949 >>> ,my_function /home/me # becomes my_function("/home/me")
938 >>> ,my_function /home/me # becomes my_function("/home/me")
950
939
951 If you use ';' instead, the whole argument is quoted as a single string
940 If you use ';' instead, the whole argument is quoted as a single string
952 (while ',' splits on whitespace)::
941 (while ',' splits on whitespace)::
953
942
954 >>> ,my_function a b c # becomes my_function("a","b","c")
943 >>> ,my_function a b c # becomes my_function("a","b","c")
955
944
956 >>> ;my_function a b c # becomes my_function("a b c")
945 >>> ;my_function a b c # becomes my_function("a b c")
957
946
958 Note that the ',' or ';' MUST be the first character on the line! This
947 Note that the ',' or ';' MUST be the first character on the line! This
959 won't work::
948 won't work::
960
949
961 >>> x = ,my_function /home/me # syntax error
950 >>> x = ,my_function /home/me # syntax error
962
951
963 IPython as your default Python environment
952 IPython as your default Python environment
964 ==========================================
953 ==========================================
965
954
966 Python honors the environment variable PYTHONSTARTUP and will execute at
955 Python honors the environment variable PYTHONSTARTUP and will execute at
967 startup the file referenced by this variable. If you put at the end of
956 startup the file referenced by this variable. If you put at the end of
968 this file the following two lines of code::
957 this file the following two lines of code::
969
958
970 import IPython
959 from IPython.frontend.terminal.ipapp import launch_new_instance
971 IPython.Shell.IPShell().mainloop(sys_exit=1)
960 launch_new_instance()
961 raise SystemExit
972
962
973 then IPython will be your working environment anytime you start Python.
963 then IPython will be your working environment anytime you start Python.
974 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
964 The ``raise SystemExit`` is needed to exit Python when
975 it finishes, otherwise you'll be back at the normal Python '>>>'
965 it finishes, otherwise you'll be back at the normal Python '>>>'
976 prompt.
966 prompt.
977
967
978 This is probably useful to developers who manage multiple Python
968 This is probably useful to developers who manage multiple Python
979 versions and don't want to have correspondingly multiple IPython
969 versions and don't want to have correspondingly multiple IPython
980 versions. Note that in this mode, there is no way to pass IPython any
970 versions. Note that in this mode, there is no way to pass IPython any
981 command-line options, as those are trapped first by Python itself.
971 command-line options, as those are trapped first by Python itself.
982
972
983 .. _Embedding:
973 .. _Embedding:
984
974
985 Embedding IPython
975 Embedding IPython
986 =================
976 =================
987
977
988 It is possible to start an IPython instance inside your own Python
978 It is possible to start an IPython instance inside your own Python
989 programs. This allows you to evaluate dynamically the state of your
979 programs. This allows you to evaluate dynamically the state of your
990 code, operate with your variables, analyze them, etc. Note however that
980 code, operate with your variables, analyze them, etc. Note however that
991 any changes you make to values while in the shell do not propagate back
981 any changes you make to values while in the shell do not propagate back
992 to the running code, so it is safe to modify your values because you
982 to the running code, so it is safe to modify your values because you
993 won't break your code in bizarre ways by doing so.
983 won't break your code in bizarre ways by doing so.
994
984
995 This feature allows you to easily have a fully functional python
985 This feature allows you to easily have a fully functional python
996 environment for doing object introspection anywhere in your code with a
986 environment for doing object introspection anywhere in your code with a
997 simple function call. In some cases a simple print statement is enough,
987 simple function call. In some cases a simple print statement is enough,
998 but if you need to do more detailed analysis of a code fragment this
988 but if you need to do more detailed analysis of a code fragment this
999 feature can be very valuable.
989 feature can be very valuable.
1000
990
1001 It can also be useful in scientific computing situations where it is
991 It can also be useful in scientific computing situations where it is
1002 common to need to do some automatic, computationally intensive part and
992 common to need to do some automatic, computationally intensive part and
1003 then stop to look at data, plots, etc.
993 then stop to look at data, plots, etc.
1004 Opening an IPython instance will give you full access to your data and
994 Opening an IPython instance will give you full access to your data and
1005 functions, and you can resume program execution once you are done with
995 functions, and you can resume program execution once you are done with
1006 the interactive part (perhaps to stop again later, as many times as
996 the interactive part (perhaps to stop again later, as many times as
1007 needed).
997 needed).
1008
998
1009 The following code snippet is the bare minimum you need to include in
999 The following code snippet is the bare minimum you need to include in
1010 your Python programs for this to work (detailed examples follow later)::
1000 your Python programs for this to work (detailed examples follow later)::
1011
1001
1012 from IPython.Shell import IPShellEmbed
1002 from IPython import embed
1013
1003
1014 ipshell = IPShellEmbed()
1004 embed() # this call anywhere in your program will start IPython
1015
1016 ipshell() # this call anywhere in your program will start IPython
1017
1005
1018 You can run embedded instances even in code which is itself being run at
1006 You can run embedded instances even in code which is itself being run at
1019 the IPython interactive prompt with '%run <filename>'. Since it's easy
1007 the IPython interactive prompt with '%run <filename>'. Since it's easy
1020 to get lost as to where you are (in your top-level IPython or in your
1008 to get lost as to where you are (in your top-level IPython or in your
1021 embedded one), it's a good idea in such cases to set the in/out prompts
1009 embedded one), it's a good idea in such cases to set the in/out prompts
1022 to something different for the embedded instances. The code examples
1010 to something different for the embedded instances. The code examples
1023 below illustrate this.
1011 below illustrate this.
1024
1012
1025 You can also have multiple IPython instances in your program and open
1013 You can also have multiple IPython instances in your program and open
1026 them separately, for example with different options for data
1014 them separately, for example with different options for data
1027 presentation. If you close and open the same instance multiple times,
1015 presentation. If you close and open the same instance multiple times,
1028 its prompt counters simply continue from each execution to the next.
1016 its prompt counters simply continue from each execution to the next.
1029
1017
1030 Please look at the docstrings in the Shell.py module for more details on
1018 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
1031 the use of this system.
1019 module for more details on the use of this system.
1032
1020
1033 The following sample file illustrating how to use the embedding
1021 The following sample file illustrating how to use the embedding
1034 functionality is provided in the examples directory as example-embed.py.
1022 functionality is provided in the examples directory as example-embed.py.
1035 It should be fairly self-explanatory::
1023 It should be fairly self-explanatory:
1036
1024
1025 .. sourcecode:: python
1037
1026
1038 #!/usr/bin/env python
1027 #!/usr/bin/env python
1039
1028
1040 """An example of how to embed an IPython shell into a running program.
1029 """An example of how to embed an IPython shell into a running program.
1041
1030
1042 Please see the documentation in the IPython.Shell module for more details.
1031 Please see the documentation in the IPython.Shell module for more details.
1043
1032
1044 The accompanying file example-embed-short.py has quick code fragments for
1033 The accompanying file example-embed-short.py has quick code fragments for
1045 embedding which you can cut and paste in your code once you understand how
1034 embedding which you can cut and paste in your code once you understand how
1046 things work.
1035 things work.
1047
1036
1048 The code in this file is deliberately extra-verbose, meant for learning."""
1037 The code in this file is deliberately extra-verbose, meant for learning."""
1049
1038
1050 # The basics to get you going:
1039 # The basics to get you going:
1051
1040
1052 # IPython sets the __IPYTHON__ variable so you can know if you have nested
1041 # IPython sets the __IPYTHON__ variable so you can know if you have nested
1053 # copies running.
1042 # copies running.
1054
1043
1055 # Try running this code both at the command line and from inside IPython (with
1044 # Try running this code both at the command line and from inside IPython (with
1056 # %run example-embed.py)
1045 # %run example-embed.py)
1046 from IPython.config.loader import Config
1057 try:
1047 try:
1058 __IPYTHON__
1048 get_ipython
1059 except NameError:
1049 except NameError:
1060 nested = 0
1050 nested = 0
1061 args = ['']
1051 cfg = Config()
1052 shell_config = cfg.InteractiveShellEmbed
1053 shell_config.prompt_in1 = 'In <\\#>: '
1054 shell_config.prompt_in2 = ' .\\D.: '
1055 shell_config.prompt_out = 'Out<\\#>: '
1062 else:
1056 else:
1063 print "Running nested copies of IPython."
1057 print "Running nested copies of IPython."
1064 print "The prompts for the nested copy have been modified"
1058 print "The prompts for the nested copy have been modified"
1059 cfg = Config()
1065 nested = 1
1060 nested = 1
1066 # what the embedded instance will see as sys.argv:
1067 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
1068 '-po','Out<\\#>: ','-nosep']
1069
1061
1070 # First import the embeddable shell class
1062 # First import the embeddable shell class
1071 from IPython.Shell import IPShellEmbed
1063 from IPython.frontend.terminal.embed import InteractiveShellEmbed
1072
1064
1073 # Now create an instance of the embeddable shell. The first argument is a
1065 # Now create an instance of the embeddable shell. The first argument is a
1074 # string with options exactly as you would type them if you were starting
1066 # string with options exactly as you would type them if you were starting
1075 # IPython at the system command line. Any parameters you want to define for
1067 # IPython at the system command line. Any parameters you want to define for
1076 # configuration can thus be specified here.
1068 # configuration can thus be specified here.
1077 ipshell = IPShellEmbed(args,
1069 ipshell = InteractiveShellEmbed(config=cfg,
1078 banner = 'Dropping into IPython',
1070 banner1 = 'Dropping into IPython',
1079 exit_msg = 'Leaving Interpreter, back to program.')
1071 exit_msg = 'Leaving Interpreter, back to program.')
1080
1072
1081 # Make a second instance, you can have as many as you want.
1073 # Make a second instance, you can have as many as you want.
1082 if nested:
1074 cfg2 = cfg.copy()
1083 args[1] = 'In2<\\#>'
1075 shell_config = cfg2.InteractiveShellEmbed
1084 else:
1076 shell_config.prompt_in1 = 'In2<\\#>: '
1085 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
1077 if not nested:
1086 '-po','Out<\\#>: ','-nosep']
1078 shell_config.prompt_in1 = 'In2<\\#>: '
1087 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
1079 shell_config.prompt_in2 = ' .\\D.: '
1080 shell_config.prompt_out = 'Out<\\#>: '
1081 ipshell2 = InteractiveShellEmbed(config=cfg,
1082 banner1 = 'Second IPython instance.')
1088
1083
1089 print '\nHello. This is printed from the main controller program.\n'
1084 print '\nHello. This is printed from the main controller program.\n'
1090
1085
1091 # You can then call ipshell() anywhere you need it (with an optional
1086 # You can then call ipshell() anywhere you need it (with an optional
1092 # message):
1087 # message):
1093 ipshell('***Called from top level. '
1088 ipshell('***Called from top level. '
1094 'Hit Ctrl-D to exit interpreter and continue program.\n'
1089 'Hit Ctrl-D to exit interpreter and continue program.\n'
1095 'Note that if you use %kill_embedded, you can fully deactivate\n'
1090 'Note that if you use %kill_embedded, you can fully deactivate\n'
1096 'This embedded instance so it will never turn on again')
1091 'This embedded instance so it will never turn on again')
1097
1092
1098 print '\nBack in caller program, moving along...\n'
1093 print '\nBack in caller program, moving along...\n'
1099
1094
1100 #---------------------------------------------------------------------------
1095 #---------------------------------------------------------------------------
1101 # More details:
1096 # More details:
1102
1097
1103 # IPShellEmbed instances don't print the standard system banner and
1098 # InteractiveShellEmbed instances don't print the standard system banner and
1104 # messages. The IPython banner (which actually may contain initialization
1099 # messages. The IPython banner (which actually may contain initialization
1105 # messages) is available as <instance>.IP.BANNER in case you want it.
1100 # messages) is available as get_ipython().banner in case you want it.
1106
1101
1107 # IPShellEmbed instances print the following information everytime they
1102 # InteractiveShellEmbed instances print the following information everytime they
1108 # start:
1103 # start:
1109
1104
1110 # - A global startup banner.
1105 # - A global startup banner.
1111
1106
1112 # - A call-specific header string, which you can use to indicate where in the
1107 # - A call-specific header string, which you can use to indicate where in the
1113 # execution flow the shell is starting.
1108 # execution flow the shell is starting.
1114
1109
1115 # They also print an exit message every time they exit.
1110 # They also print an exit message every time they exit.
1116
1111
1117 # Both the startup banner and the exit message default to None, and can be set
1112 # Both the startup banner and the exit message default to None, and can be set
1118 # either at the instance constructor or at any other time with the
1113 # either at the instance constructor or at any other time with the
1119 # set_banner() and set_exit_msg() methods.
1114 # by setting the banner and exit_msg attributes.
1120
1115
1121 # The shell instance can be also put in 'dummy' mode globally or on a per-call
1116 # The shell instance can be also put in 'dummy' mode globally or on a per-call
1122 # basis. This gives you fine control for debugging without having to change
1117 # basis. This gives you fine control for debugging without having to change
1123 # code all over the place.
1118 # code all over the place.
1124
1119
1125 # The code below illustrates all this.
1120 # The code below illustrates all this.
1126
1121
1127
1122
1128 # This is how the global banner and exit_msg can be reset at any point
1123 # This is how the global banner and exit_msg can be reset at any point
1129 ipshell.set_banner('Entering interpreter - New Banner')
1124 ipshell.banner = 'Entering interpreter - New Banner'
1130 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
1125 ipshell.exit_msg = 'Leaving interpreter - New exit_msg'
1131
1126
1132 def foo(m):
1127 def foo(m):
1133 s = 'spam'
1128 s = 'spam'
1134 ipshell('***In foo(). Try @whos, or print s or m:')
1129 ipshell('***In foo(). Try %whos, or print s or m:')
1135 print 'foo says m = ',m
1130 print 'foo says m = ',m
1136
1131
1137 def bar(n):
1132 def bar(n):
1138 s = 'eggs'
1133 s = 'eggs'
1139 ipshell('***In bar(). Try @whos, or print s or n:')
1134 ipshell('***In bar(). Try %whos, or print s or n:')
1140 print 'bar says n = ',n
1135 print 'bar says n = ',n
1141
1136
1142 # Some calls to the above functions which will trigger IPython:
1137 # Some calls to the above functions which will trigger IPython:
1143 print 'Main program calling foo("eggs")\n'
1138 print 'Main program calling foo("eggs")\n'
1144 foo('eggs')
1139 foo('eggs')
1145
1140
1146 # The shell can be put in 'dummy' mode where calls to it silently return. This
1141 # The shell can be put in 'dummy' mode where calls to it silently return. This
1147 # allows you, for example, to globally turn off debugging for a program with a
1142 # allows you, for example, to globally turn off debugging for a program with a
1148 # single call.
1143 # single call.
1149 ipshell.set_dummy_mode(1)
1144 ipshell.dummy_mode = True
1150 print '\nTrying to call IPython which is now "dummy":'
1145 print '\nTrying to call IPython which is now "dummy":'
1151 ipshell()
1146 ipshell()
1152 print 'Nothing happened...'
1147 print 'Nothing happened...'
1153 # The global 'dummy' mode can still be overridden for a single call
1148 # The global 'dummy' mode can still be overridden for a single call
1154 print '\nOverriding dummy mode manually:'
1149 print '\nOverriding dummy mode manually:'
1155 ipshell(dummy=0)
1150 ipshell(dummy=False)
1156
1151
1157 # Reactivate the IPython shell
1152 # Reactivate the IPython shell
1158 ipshell.set_dummy_mode(0)
1153 ipshell.dummy_mode = False
1159
1154
1160 print 'You can even have multiple embedded instances:'
1155 print 'You can even have multiple embedded instances:'
1161 ipshell2()
1156 ipshell2()
1162
1157
1163 print '\nMain program calling bar("spam")\n'
1158 print '\nMain program calling bar("spam")\n'
1164 bar('spam')
1159 bar('spam')
1165
1160
1166 print 'Main program finished. Bye!'
1161 print 'Main program finished. Bye!'
1167
1162
1168 #********************** End of file <example-embed.py> ***********************
1163 #********************** End of file <example-embed.py> ***********************
1169
1164
1170 Once you understand how the system functions, you can use the following
1165 Once you understand how the system functions, you can use the following
1171 code fragments in your programs which are ready for cut and paste::
1166 code fragments in your programs which are ready for cut and paste:
1172
1167
1168 .. sourcecode:: python
1173
1169
1174 """Quick code snippets for embedding IPython into other programs.
1170 """Quick code snippets for embedding IPython into other programs.
1175
1171
1176 See example-embed.py for full details, this file has the bare minimum code for
1172 See example-embed.py for full details, this file has the bare minimum code for
1177 cut and paste use once you understand how to use the system."""
1173 cut and paste use once you understand how to use the system."""
1178
1174
1179 #---------------------------------------------------------------------------
1175 #---------------------------------------------------------------------------
1180 # This code loads IPython but modifies a few things if it detects it's running
1176 # This code loads IPython but modifies a few things if it detects it's running
1181 # embedded in another IPython session (helps avoid confusion)
1177 # embedded in another IPython session (helps avoid confusion)
1182
1178
1183 try:
1179 try:
1184 __IPYTHON__
1180 get_ipython
1185 except NameError:
1181 except NameError:
1186 argv = ['']
1182 argv = ['']
1187 banner = exit_msg = ''
1183 banner = exit_msg = ''
1188 else:
1184 else:
1189 # Command-line options for IPython (a list like sys.argv)
1185 # Command-line options for IPython (a list like sys.argv)
1190 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
1186 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
1191 banner = '*** Nested interpreter ***'
1187 banner = '*** Nested interpreter ***'
1192 exit_msg = '*** Back in main IPython ***'
1188 exit_msg = '*** Back in main IPython ***'
1193
1189
1194 # First import the embeddable shell class
1190 # First import the embeddable shell class
1195 from IPython.Shell import IPShellEmbed
1191 from IPython.Shell import IPShellEmbed
1196 # Now create the IPython shell instance. Put ipshell() anywhere in your code
1192 # Now create the IPython shell instance. Put ipshell() anywhere in your code
1197 # where you want it to open.
1193 # where you want it to open.
1198 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
1194 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
1199
1195
1200 #---------------------------------------------------------------------------
1196 #---------------------------------------------------------------------------
1201 # This code will load an embeddable IPython shell always with no changes for
1197 # This code will load an embeddable IPython shell always with no changes for
1202 # nested embededings.
1198 # nested embededings.
1203
1199
1204 from IPython.Shell import IPShellEmbed
1200 from IPython import embed
1205 ipshell = IPShellEmbed()
1201 # Now embed() will open IPython anywhere in the code.
1206 # Now ipshell() will open IPython anywhere in the code.
1207
1202
1208 #---------------------------------------------------------------------------
1203 #---------------------------------------------------------------------------
1209 # This code loads an embeddable shell only if NOT running inside
1204 # This code loads an embeddable shell only if NOT running inside
1210 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
1205 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
1211 # dummy function.
1206 # dummy function.
1212
1207
1213 try:
1208 try:
1214 __IPYTHON__
1209 get_ipython
1215 except NameError:
1210 except NameError:
1216 from IPython.Shell import IPShellEmbed
1211 from IPython.frontend.terminal.embed import embed
1217 ipshell = IPShellEmbed()
1212 # Now embed() will open IPython anywhere in the code
1218 # Now ipshell() will open IPython anywhere in the code
1219 else:
1213 else:
1220 # Define a dummy ipshell() so the same code doesn't crash inside an
1214 # Define a dummy embed() so the same code doesn't crash inside an
1221 # interactive IPython
1215 # interactive IPython
1222 def ipshell(): pass
1216 def embed(): pass
1223
1217
1224 #******************* End of file <example-embed-short.py> ********************
1218 #******************* End of file <example-embed-short.py> ********************
1225
1219
1226 Using the Python debugger (pdb)
1220 Using the Python debugger (pdb)
1227 ===============================
1221 ===============================
1228
1222
1229 Running entire programs via pdb
1223 Running entire programs via pdb
1230 -------------------------------
1224 -------------------------------
1231
1225
1232 pdb, the Python debugger, is a powerful interactive debugger which
1226 pdb, the Python debugger, is a powerful interactive debugger which
1233 allows you to step through code, set breakpoints, watch variables,
1227 allows you to step through code, set breakpoints, watch variables,
1234 etc. IPython makes it very easy to start any script under the control
1228 etc. IPython makes it very easy to start any script under the control
1235 of pdb, regardless of whether you have wrapped it into a 'main()'
1229 of pdb, regardless of whether you have wrapped it into a 'main()'
1236 function or not. For this, simply type '%run -d myscript' at an
1230 function or not. For this, simply type '%run -d myscript' at an
1237 IPython prompt. See the %run command's documentation (via '%run?' or
1231 IPython prompt. See the %run command's documentation (via '%run?' or
1238 in Sec. magic_ for more details, including how to control where pdb
1232 in Sec. magic_ for more details, including how to control where pdb
1239 will stop execution first.
1233 will stop execution first.
1240
1234
1241 For more information on the use of the pdb debugger, read the included
1235 For more information on the use of the pdb debugger, read the included
1242 pdb.doc file (part of the standard Python distribution). On a stock
1236 pdb.doc file (part of the standard Python distribution). On a stock
1243 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1237 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1244 easiest way to read it is by using the help() function of the pdb module
1238 easiest way to read it is by using the help() function of the pdb module
1245 as follows (in an IPython prompt)::
1239 as follows (in an IPython prompt)::
1246
1240
1247 In [1]: import pdb
1241 In [1]: import pdb
1248 In [2]: pdb.help()
1242 In [2]: pdb.help()
1249
1243
1250 This will load the pdb.doc document in a file viewer for you automatically.
1244 This will load the pdb.doc document in a file viewer for you automatically.
1251
1245
1252
1246
1253 Automatic invocation of pdb on exceptions
1247 Automatic invocation of pdb on exceptions
1254 -----------------------------------------
1248 -----------------------------------------
1255
1249
1256 IPython, if started with the -pdb option (or if the option is set in
1250 IPython, if started with the -pdb option (or if the option is set in
1257 your rc file) can call the Python pdb debugger every time your code
1251 your rc file) can call the Python pdb debugger every time your code
1258 triggers an uncaught exception. This feature
1252 triggers an uncaught exception. This feature
1259 can also be toggled at any time with the %pdb magic command. This can be
1253 can also be toggled at any time with the %pdb magic command. This can be
1260 extremely useful in order to find the origin of subtle bugs, because pdb
1254 extremely useful in order to find the origin of subtle bugs, because pdb
1261 opens up at the point in your code which triggered the exception, and
1255 opens up at the point in your code which triggered the exception, and
1262 while your program is at this point 'dead', all the data is still
1256 while your program is at this point 'dead', all the data is still
1263 available and you can walk up and down the stack frame and understand
1257 available and you can walk up and down the stack frame and understand
1264 the origin of the problem.
1258 the origin of the problem.
1265
1259
1266 Furthermore, you can use these debugging facilities both with the
1260 Furthermore, you can use these debugging facilities both with the
1267 embedded IPython mode and without IPython at all. For an embedded shell
1261 embedded IPython mode and without IPython at all. For an embedded shell
1268 (see sec. Embedding_), simply call the constructor with
1262 (see sec. Embedding_), simply call the constructor with
1269 '-pdb' in the argument string and automatically pdb will be called if an
1263 '--pdb' in the argument string and automatically pdb will be called if an
1270 uncaught exception is triggered by your code.
1264 uncaught exception is triggered by your code.
1271
1265
1272 For stand-alone use of the feature in your programs which do not use
1266 For stand-alone use of the feature in your programs which do not use
1273 IPython at all, put the following lines toward the top of your 'main'
1267 IPython at all, put the following lines toward the top of your 'main'
1274 routine::
1268 routine::
1275
1269
1276 import sys
1270 import sys
1277 from IPython.core import ultratb
1271 from IPython.core import ultratb
1278 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1272 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1279 color_scheme='Linux', call_pdb=1)
1273 color_scheme='Linux', call_pdb=1)
1280
1274
1281 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1275 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1282 detailed or normal tracebacks respectively. The color_scheme keyword can
1276 detailed or normal tracebacks respectively. The color_scheme keyword can
1283 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1277 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1284 options which can be set in IPython with -colors and -xmode.
1278 options which can be set in IPython with -colors and -xmode.
1285
1279
1286 This will give any of your programs detailed, colored tracebacks with
1280 This will give any of your programs detailed, colored tracebacks with
1287 automatic invocation of pdb.
1281 automatic invocation of pdb.
1288
1282
1289
1283
1290 Extensions for syntax processing
1284 Extensions for syntax processing
1291 ================================
1285 ================================
1292
1286
1293 This isn't for the faint of heart, because the potential for breaking
1287 This isn't for the faint of heart, because the potential for breaking
1294 things is quite high. But it can be a very powerful and useful feature.
1288 things is quite high. But it can be a very powerful and useful feature.
1295 In a nutshell, you can redefine the way IPython processes the user input
1289 In a nutshell, you can redefine the way IPython processes the user input
1296 line to accept new, special extensions to the syntax without needing to
1290 line to accept new, special extensions to the syntax without needing to
1297 change any of IPython's own code.
1291 change any of IPython's own code.
1298
1292
1299 In the IPython/extensions directory you will find some examples
1293 In the IPython/extensions directory you will find some examples
1300 supplied, which we will briefly describe now. These can be used 'as is'
1294 supplied, which we will briefly describe now. These can be used 'as is'
1301 (and both provide very useful functionality), or you can use them as a
1295 (and both provide very useful functionality), or you can use them as a
1302 starting point for writing your own extensions.
1296 starting point for writing your own extensions.
1303
1297
1304
1298
1305 Pasting of code starting with '>>> ' or '... '
1299 Pasting of code starting with '>>> ' or '... '
1306 ----------------------------------------------
1300 ----------------------------------------------
1307
1301
1308 In the python tutorial it is common to find code examples which have
1302 In the python tutorial it is common to find code examples which have
1309 been taken from real python sessions. The problem with those is that all
1303 been taken from real python sessions. The problem with those is that all
1310 the lines begin with either '>>> ' or '... ', which makes it impossible
1304 the lines begin with either '>>> ' or '... ', which makes it impossible
1311 to paste them all at once. One must instead do a line by line manual
1305 to paste them all at once. One must instead do a line by line manual
1312 copying, carefully removing the leading extraneous characters.
1306 copying, carefully removing the leading extraneous characters.
1313
1307
1314 This extension identifies those starting characters and removes them
1308 This extension identifies those starting characters and removes them
1315 from the input automatically, so that one can paste multi-line examples
1309 from the input automatically, so that one can paste multi-line examples
1316 directly into IPython, saving a lot of time. Please look at the file
1310 directly into IPython, saving a lot of time. Please look at the file
1317 InterpreterPasteInput.py in the IPython/extensions directory for details
1311 InterpreterPasteInput.py in the IPython/extensions directory for details
1318 on how this is done.
1312 on how this is done.
1319
1313
1320 IPython comes with a special profile enabling this feature, called
1314 IPython comes with a special profile enabling this feature, called
1321 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1315 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1322 will be available. In a normal IPython session you can activate the
1316 will be available. In a normal IPython session you can activate the
1323 feature by importing the corresponding module with:
1317 feature by importing the corresponding module with:
1324 In [1]: import IPython.extensions.InterpreterPasteInput
1318 In [1]: import IPython.extensions.InterpreterPasteInput
1325
1319
1326 The following is a 'screenshot' of how things work when this extension
1320 The following is a 'screenshot' of how things work when this extension
1327 is on, copying an example from the standard tutorial::
1321 is on, copying an example from the standard tutorial::
1328
1322
1329 IPython profile: tutorial
1323 IPython profile: tutorial
1330
1324
1331 *** Pasting of code with ">>>" or "..." has been enabled.
1325 *** Pasting of code with ">>>" or "..." has been enabled.
1332
1326
1333 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1327 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1334 ...: ... """Return a list containing the Fibonacci series up to
1328 ...: ... """Return a list containing the Fibonacci series up to
1335 n."""
1329 n."""
1336 ...: ... result = []
1330 ...: ... result = []
1337 ...: ... a, b = 0, 1
1331 ...: ... a, b = 0, 1
1338 ...: ... while b < n:
1332 ...: ... while b < n:
1339 ...: ... result.append(b) # see below
1333 ...: ... result.append(b) # see below
1340 ...: ... a, b = b, a+b
1334 ...: ... a, b = b, a+b
1341 ...: ... return result
1335 ...: ... return result
1342 ...:
1336 ...:
1343
1337
1344 In [2]: fib2(10)
1338 In [2]: fib2(10)
1345 Out[2]: [1, 1, 2, 3, 5, 8]
1339 Out[2]: [1, 1, 2, 3, 5, 8]
1346
1340
1347 Note that as currently written, this extension does not recognize
1341 Note that as currently written, this extension does not recognize
1348 IPython's prompts for pasting. Those are more complicated, since the
1342 IPython's prompts for pasting. Those are more complicated, since the
1349 user can change them very easily, they involve numbers and can vary in
1343 user can change them very easily, they involve numbers and can vary in
1350 length. One could however extract all the relevant information from the
1344 length. One could however extract all the relevant information from the
1351 IPython instance and build an appropriate regular expression. This is
1345 IPython instance and build an appropriate regular expression. This is
1352 left as an exercise for the reader.
1346 left as an exercise for the reader.
1353
1347
1354
1348
1355 Input of physical quantities with units
1349 Input of physical quantities with units
1356 ---------------------------------------
1350 ---------------------------------------
1357
1351
1358 The module PhysicalQInput allows a simplified form of input for physical
1352 The module PhysicalQInput allows a simplified form of input for physical
1359 quantities with units. This file is meant to be used in conjunction with
1353 quantities with units. This file is meant to be used in conjunction with
1360 the PhysicalQInteractive module (in the same directory) and
1354 the PhysicalQInteractive module (in the same directory) and
1361 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1355 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1362 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1356 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1363
1357
1364 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1358 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1365 but these must be declared as instances of a class. For example, to
1359 but these must be declared as instances of a class. For example, to
1366 define v as a velocity of 3 m/s, normally you would write::
1360 define v as a velocity of 3 m/s, normally you would write::
1367
1361
1368 In [1]: v = PhysicalQuantity(3,'m/s')
1362 In [1]: v = PhysicalQuantity(3,'m/s')
1369
1363
1370 Using the PhysicalQ_Input extension this can be input instead as:
1364 Using the PhysicalQ_Input extension this can be input instead as:
1371 In [1]: v = 3 m/s
1365 In [1]: v = 3 m/s
1372 which is much more convenient for interactive use (even though it is
1366 which is much more convenient for interactive use (even though it is
1373 blatantly invalid Python syntax).
1367 blatantly invalid Python syntax).
1374
1368
1375 The physics profile supplied with IPython (enabled via 'ipython -p
1369 The physics profile supplied with IPython (enabled via 'ipython -p
1376 physics') uses these extensions, which you can also activate with:
1370 physics') uses these extensions, which you can also activate with:
1377
1371
1378 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1372 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1379 from IPython.extensions.PhysicalQInteractive import *
1373 from IPython.extensions.PhysicalQInteractive import *
1380 import IPython.extensions.PhysicalQInput
1374 import IPython.extensions.PhysicalQInput
1381
1375
1382 .. _gui_support:
1376 .. _gui_support:
1383
1377
1384 GUI event loop support support
1378 GUI event loop support support
1385 ==============================
1379 ==============================
1386
1380
1387 .. versionadded:: 0.11
1381 .. versionadded:: 0.11
1388 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1382 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1389
1383
1390 IPython has excellent support for working interactively with Graphical User
1384 IPython has excellent support for working interactively with Graphical User
1391 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1385 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1392 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1386 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1393 is extremely robust compared to our previous threaded based version. The
1387 is extremely robust compared to our previous threaded based version. The
1394 advantages of this are:
1388 advantages of this are:
1395
1389
1396 * GUIs can be enabled and disabled dynamically at runtime.
1390 * GUIs can be enabled and disabled dynamically at runtime.
1397 * The active GUI can be switched dynamically at runtime.
1391 * The active GUI can be switched dynamically at runtime.
1398 * In some cases, multiple GUIs can run simultaneously with no problems.
1392 * In some cases, multiple GUIs can run simultaneously with no problems.
1399 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1393 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1400 all of these things.
1394 all of these things.
1401
1395
1402 For users, enabling GUI event loop integration is simple. You simple use the
1396 For users, enabling GUI event loop integration is simple. You simple use the
1403 ``%gui`` magic as follows::
1397 ``%gui`` magic as follows::
1404
1398
1405 %gui [-a] [GUINAME]
1399 %gui [-a] [GUINAME]
1406
1400
1407 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1401 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1408 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1402 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1409 create and return a running application object for the selected GUI toolkit.
1403 create and return a running application object for the selected GUI toolkit.
1410
1404
1411 Thus, to use wxPython interactively and create a running :class:`wx.App`
1405 Thus, to use wxPython interactively and create a running :class:`wx.App`
1412 object, do::
1406 object, do::
1413
1407
1414 %gui -a wx
1408 %gui -a wx
1415
1409
1416 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1410 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1417 see :ref:`this section <matplotlib_support>`.
1411 see :ref:`this section <matplotlib_support>`.
1418
1412
1419 For developers that want to use IPython's GUI event loop integration in
1413 For developers that want to use IPython's GUI event loop integration in
1420 the form of a library, these capabilities are exposed in library form
1414 the form of a library, these capabilities are exposed in library form
1421 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1415 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1422 module docstrings for more information, but there are a few points that
1416 module docstrings for more information, but there are a few points that
1423 should be mentioned here.
1417 should be mentioned here.
1424
1418
1425 First, the ``PyOSInputHook`` approach only works in command line settings
1419 First, the ``PyOSInputHook`` approach only works in command line settings
1426 where readline is activated.
1420 where readline is activated.
1427
1421
1428 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1422 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1429 *not* start its event loop. Instead all of this is handled by the
1423 *not* start its event loop. Instead all of this is handled by the
1430 ``PyOSInputHook``. This means that applications that are meant to be used both
1424 ``PyOSInputHook``. This means that applications that are meant to be used both
1431 in IPython and as standalone apps need to have special code to detects how the
1425 in IPython and as standalone apps need to have special code to detects how the
1432 application is being run. We highly recommend using IPython's
1426 application is being run. We highly recommend using IPython's
1433 :func:`appstart_` functions for this. Here is a simple example that shows the
1427 :func:`appstart_` functions for this. Here is a simple example that shows the
1434 recommended code that should be at the bottom of a wxPython using GUI
1428 recommended code that should be at the bottom of a wxPython using GUI
1435 application::
1429 application::
1436
1430
1437 try:
1431 try:
1438 from IPython import appstart_wx
1432 from IPython import appstart_wx
1439 appstart_wx(app)
1433 appstart_wx(app)
1440 except ImportError:
1434 except ImportError:
1441 app.MainLoop()
1435 app.MainLoop()
1442
1436
1443 This pattern should be used instead of the simple ``app.MainLoop()`` code
1437 This pattern should be used instead of the simple ``app.MainLoop()`` code
1444 that a standalone wxPython application would have.
1438 that a standalone wxPython application would have.
1445
1439
1446 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1440 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1447 them with no-ops) the event loops. This is done to allow applications that
1441 them with no-ops) the event loops. This is done to allow applications that
1448 actually need to run the real event loops to do so. This is often needed to
1442 actually need to run the real event loops to do so. This is often needed to
1449 process pending events at critical points.
1443 process pending events at critical points.
1450
1444
1451 Finally, we also have a number of examples in our source directory
1445 Finally, we also have a number of examples in our source directory
1452 :file:`docs/examples/lib` that demonstrate these capabilities.
1446 :file:`docs/examples/lib` that demonstrate these capabilities.
1453
1447
1454 .. _matplotlib_support:
1448 .. _matplotlib_support:
1455
1449
1456 Plotting with matplotlib
1450 Plotting with matplotlib
1457 ========================
1451 ========================
1458
1452
1459
1453
1460 `Matplotlib`_ provides high quality 2D and
1454 `Matplotlib`_ provides high quality 2D and
1461 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1455 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1462 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1456 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1463 number of commands useful for scientific computing, all with a syntax
1457 number of commands useful for scientific computing, all with a syntax
1464 compatible with that of the popular Matlab program.
1458 compatible with that of the popular Matlab program.
1465
1459
1466 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1460 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1467 automates the integration of Matplotlib with IPython. We are still in the
1461 automates the integration of Matplotlib with IPython. We are still in the
1468 process of working with the Matplotlib developers to finalize the new pylab
1462 process of working with the Matplotlib developers to finalize the new pylab
1469 API, but for now you can use Matplotlib interactively using the following
1463 API, but for now you can use Matplotlib interactively using the following
1470 commands::
1464 commands::
1471
1465
1472 %gui -a wx
1466 %gui -a wx
1473 import matplotlib
1467 import matplotlib
1474 matplotlib.use('wxagg')
1468 matplotlib.use('wxagg')
1475 from matplotlib import pylab
1469 from matplotlib import pylab
1476 pylab.interactive(True)
1470 pylab.interactive(True)
1477
1471
1478 All of this will soon be automated as Matplotlib begins to include
1472 All of this will soon be automated as Matplotlib begins to include
1479 new logic that uses our new GUI support.
1473 new logic that uses our new GUI support.
1480
1474
1481 .. _Matplotlib: http://matplotlib.sourceforge.net
1475 .. _Matplotlib: http://matplotlib.sourceforge.net
1482
1476
1483 .. _interactive_demos:
1477 .. _interactive_demos:
1484
1478
1485 Interactive demos with IPython
1479 Interactive demos with IPython
1486 ==============================
1480 ==============================
1487
1481
1488 IPython ships with a basic system for running scripts interactively in
1482 IPython ships with a basic system for running scripts interactively in
1489 sections, useful when presenting code to audiences. A few tags embedded
1483 sections, useful when presenting code to audiences. A few tags embedded
1490 in comments (so that the script remains valid Python code) divide a file
1484 in comments (so that the script remains valid Python code) divide a file
1491 into separate blocks, and the demo can be run one block at a time, with
1485 into separate blocks, and the demo can be run one block at a time, with
1492 IPython printing (with syntax highlighting) the block before executing
1486 IPython printing (with syntax highlighting) the block before executing
1493 it, and returning to the interactive prompt after each block. The
1487 it, and returning to the interactive prompt after each block. The
1494 interactive namespace is updated after each block is run with the
1488 interactive namespace is updated after each block is run with the
1495 contents of the demo's namespace.
1489 contents of the demo's namespace.
1496
1490
1497 This allows you to show a piece of code, run it and then execute
1491 This allows you to show a piece of code, run it and then execute
1498 interactively commands based on the variables just created. Once you
1492 interactively commands based on the variables just created. Once you
1499 want to continue, you simply execute the next block of the demo. The
1493 want to continue, you simply execute the next block of the demo. The
1500 following listing shows the markup necessary for dividing a script into
1494 following listing shows the markup necessary for dividing a script into
1501 sections for execution as a demo::
1495 sections for execution as a demo::
1502
1496
1503
1497
1504 """A simple interactive demo to illustrate the use of IPython's Demo class.
1498 """A simple interactive demo to illustrate the use of IPython's Demo class.
1505
1499
1506 Any python script can be run as a demo, but that does little more than showing
1500 Any python script can be run as a demo, but that does little more than showing
1507 it on-screen, syntax-highlighted in one shot. If you add a little simple
1501 it on-screen, syntax-highlighted in one shot. If you add a little simple
1508 markup, you can stop at specified intervals and return to the ipython prompt,
1502 markup, you can stop at specified intervals and return to the ipython prompt,
1509 resuming execution later.
1503 resuming execution later.
1510 """
1504 """
1511
1505
1512 print 'Hello, welcome to an interactive IPython demo.'
1506 print 'Hello, welcome to an interactive IPython demo.'
1513 print 'Executing this block should require confirmation before proceeding,'
1507 print 'Executing this block should require confirmation before proceeding,'
1514 print 'unless auto_all has been set to true in the demo object'
1508 print 'unless auto_all has been set to true in the demo object'
1515
1509
1516 # The mark below defines a block boundary, which is a point where IPython will
1510 # The mark below defines a block boundary, which is a point where IPython will
1517 # stop execution and return to the interactive prompt.
1511 # stop execution and return to the interactive prompt.
1518 # Note that in actual interactive execution,
1512 # Note that in actual interactive execution,
1519 # <demo> --- stop ---
1513 # <demo> --- stop ---
1520
1514
1521 x = 1
1515 x = 1
1522 y = 2
1516 y = 2
1523
1517
1524 # <demo> --- stop ---
1518 # <demo> --- stop ---
1525
1519
1526 # the mark below makes this block as silent
1520 # the mark below makes this block as silent
1527 # <demo> silent
1521 # <demo> silent
1528
1522
1529 print 'This is a silent block, which gets executed but not printed.'
1523 print 'This is a silent block, which gets executed but not printed.'
1530
1524
1531 # <demo> --- stop ---
1525 # <demo> --- stop ---
1532 # <demo> auto
1526 # <demo> auto
1533 print 'This is an automatic block.'
1527 print 'This is an automatic block.'
1534 print 'It is executed without asking for confirmation, but printed.'
1528 print 'It is executed without asking for confirmation, but printed.'
1535 z = x+y
1529 z = x+y
1536
1530
1537 print 'z=',x
1531 print 'z=',x
1538
1532
1539 # <demo> --- stop ---
1533 # <demo> --- stop ---
1540 # This is just another normal block.
1534 # This is just another normal block.
1541 print 'z is now:', z
1535 print 'z is now:', z
1542
1536
1543 print 'bye!'
1537 print 'bye!'
1544
1538
1545 In order to run a file as a demo, you must first make a Demo object out
1539 In order to run a file as a demo, you must first make a Demo object out
1546 of it. If the file is named myscript.py, the following code will make a
1540 of it. If the file is named myscript.py, the following code will make a
1547 demo::
1541 demo::
1548
1542
1549 from IPython.lib.demo import Demo
1543 from IPython.lib.demo import Demo
1550
1544
1551 mydemo = Demo('myscript.py')
1545 mydemo = Demo('myscript.py')
1552
1546
1553 This creates the mydemo object, whose blocks you run one at a time by
1547 This creates the mydemo object, whose blocks you run one at a time by
1554 simply calling the object with no arguments. If you have autocall active
1548 simply calling the object with no arguments. If you have autocall active
1555 in IPython (the default), all you need to do is type::
1549 in IPython (the default), all you need to do is type::
1556
1550
1557 mydemo
1551 mydemo
1558
1552
1559 and IPython will call it, executing each block. Demo objects can be
1553 and IPython will call it, executing each block. Demo objects can be
1560 restarted, you can move forward or back skipping blocks, re-execute the
1554 restarted, you can move forward or back skipping blocks, re-execute the
1561 last block, etc. Simply use the Tab key on a demo object to see its
1555 last block, etc. Simply use the Tab key on a demo object to see its
1562 methods, and call '?' on them to see their docstrings for more usage
1556 methods, and call '?' on them to see their docstrings for more usage
1563 details. In addition, the demo module itself contains a comprehensive
1557 details. In addition, the demo module itself contains a comprehensive
1564 docstring, which you can access via::
1558 docstring, which you can access via::
1565
1559
1566 from IPython.lib import demo
1560 from IPython.lib import demo
1567
1561
1568 demo?
1562 demo?
1569
1563
1570 Limitations: It is important to note that these demos are limited to
1564 Limitations: It is important to note that these demos are limited to
1571 fairly simple uses. In particular, you can not put division marks in
1565 fairly simple uses. In particular, you can not put division marks in
1572 indented code (loops, if statements, function definitions, etc.)
1566 indented code (loops, if statements, function definitions, etc.)
1573 Supporting something like this would basically require tracking the
1567 Supporting something like this would basically require tracking the
1574 internal execution state of the Python interpreter, so only top-level
1568 internal execution state of the Python interpreter, so only top-level
1575 divisions are allowed. If you want to be able to open an IPython
1569 divisions are allowed. If you want to be able to open an IPython
1576 instance at an arbitrary point in a program, you can use IPython's
1570 instance at an arbitrary point in a program, you can use IPython's
1577 embedding facilities, described in detail in Sec. 9
1571 embedding facilities, described in detail in Sec. 9
1578
1572
General Comments 0
You need to be logged in to leave comments. Login now