##// END OF EJS Templates
- Make autoedit_syntax true by default...
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,558 +1,565 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 923 2005-11-15 08:51:15Z fperez $
2 # $Id: ipythonrc 963 2005-12-28 19:21:29Z fperez $
3
3
4 #***************************************************************************
4 #***************************************************************************
5 #
5 #
6 # Configuration file for IPython -- ipythonrc format
6 # Configuration file for IPython -- ipythonrc format
7 #
7 #
8 # The format of this file is simply one of 'key value' lines.
8 # The format of this file is simply one of 'key value' lines.
9 # Lines containing only whitespace at the beginning and then a # are ignored
9 # Lines containing only whitespace at the beginning and then a # are ignored
10 # as comments. But comments can NOT be put on lines with data.
10 # as comments. But comments can NOT be put on lines with data.
11
11
12 # The meaning and use of each key are explained below.
12 # The meaning and use of each key are explained below.
13
13
14 #---------------------------------------------------------------------------
14 #---------------------------------------------------------------------------
15 # Section: included files
15 # Section: included files
16
16
17 # Put one or more *config* files (with the syntax of this file) you want to
17 # Put one or more *config* files (with the syntax of this file) you want to
18 # include. For keys with a unique value the outermost file has precedence. For
18 # include. For keys with a unique value the outermost file has precedence. For
19 # keys with multiple values, they all get assembled into a list which then
19 # keys with multiple values, they all get assembled into a list which then
20 # gets loaded by IPython.
20 # gets loaded by IPython.
21
21
22 # In this file, all lists of things should simply be space-separated.
22 # In this file, all lists of things should simply be space-separated.
23
23
24 # This allows you to build hierarchies of files which recursively load
24 # This allows you to build hierarchies of files which recursively load
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 # should only keep here basic things you always want available. Then you can
26 # should only keep here basic things you always want available. Then you can
27 # include it in every other special-purpose config file you create.
27 # include it in every other special-purpose config file you create.
28 include
28 include
29
29
30 #---------------------------------------------------------------------------
30 #---------------------------------------------------------------------------
31 # Section: startup setup
31 # Section: startup setup
32
32
33 # These are mostly things which parallel a command line option of the same
33 # These are mostly things which parallel a command line option of the same
34 # name.
34 # name.
35
35
36 # Keys in this section should only appear once. If any key from this section
36 # Keys in this section should only appear once. If any key from this section
37 # is encountered more than once, the last value remains, all earlier ones get
37 # is encountered more than once, the last value remains, all earlier ones get
38 # discarded.
38 # discarded.
39
39
40 # Automatic calling of callable objects. If set to true, callable objects are
40 # Automatic calling of callable objects. If set to true, callable objects are
41 # automatically called when invoked at the command line, even if you don't
41 # automatically called when invoked at the command line, even if you don't
42 # type parentheses. IPython adds the parentheses for you. For example:
42 # type parentheses. IPython adds the parentheses for you. For example:
43
43
44 #In [1]: str 45
44 #In [1]: str 45
45 #------> str(45)
45 #------> str(45)
46 #Out[1]: '45'
46 #Out[1]: '45'
47
47
48 # IPython reprints your line with '---->' indicating that it added
48 # IPython reprints your line with '---->' indicating that it added
49 # parentheses. While this option is very convenient for interactive use, it
49 # parentheses. While this option is very convenient for interactive use, it
50 # may occasionally cause problems with objects which have side-effects if
50 # may occasionally cause problems with objects which have side-effects if
51 # called unexpectedly. Set it to 0 if you want to disable it.
51 # called unexpectedly. Set it to 0 if you want to disable it.
52
52
53 # Note that even with autocall off, you can still use '/' at the start of a
53 # Note that even with autocall off, you can still use '/' at the start of a
54 # line to treat the first argument on the command line as a function and add
54 # line to treat the first argument on the command line as a function and add
55 # parentheses to it:
55 # parentheses to it:
56
56
57 #In [8]: /str 43
57 #In [8]: /str 43
58 #------> str(43)
58 #------> str(43)
59 #Out[8]: '43'
59 #Out[8]: '43'
60
60
61 autocall 1
61 autocall 1
62
62
63 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
64 # source code (see the 'editor' variable below), it is possible that you save
65 # a file with syntax errors in it. If this variable is true, IPython will ask
66 # you whether to re-open the editor immediately to correct such an error.
67
68 autoedit_syntax 1
69
63 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
70 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
64 # line, while also un-indenting automatically after 'raise' or 'return'.
71 # line, while also un-indenting automatically after 'raise' or 'return'.
65
72
66 # This feature uses the readline library, so it will honor your ~/.inputrc
73 # This feature uses the readline library, so it will honor your ~/.inputrc
67 # configuration (or whatever file your INPUTRC variable points to). Adding
74 # configuration (or whatever file your INPUTRC variable points to). Adding
68 # the following lines to your .inputrc file can make indent/unindenting more
75 # the following lines to your .inputrc file can make indent/unindenting more
69 # convenient (M-i indents, M-u unindents):
76 # convenient (M-i indents, M-u unindents):
70
77
71 # $if Python
78 # $if Python
72 # "\M-i": " "
79 # "\M-i": " "
73 # "\M-u": "\d\d\d\d"
80 # "\M-u": "\d\d\d\d"
74 # $endif
81 # $endif
75
82
76 # The feature is potentially a bit dangerous, because it can cause problems
83 # The feature is potentially a bit dangerous, because it can cause problems
77 # with pasting of indented code (the pasted code gets re-indented on each
84 # with pasting of indented code (the pasted code gets re-indented on each
78 # line). But it's a huge time-saver when working interactively. The magic
85 # line). But it's a huge time-saver when working interactively. The magic
79 # function @autoindent allows you to toggle it on/off at runtime.
86 # function @autoindent allows you to toggle it on/off at runtime.
80
87
81 autoindent 1
88 autoindent 1
82
89
83 # Auto-magic. This gives you access to all the magic functions without having
90 # Auto-magic. This gives you access to all the magic functions without having
84 # to prepend them with an @ sign. If you define a variable with the same name
91 # to prepend them with an @ sign. If you define a variable with the same name
85 # as a magic function (say who=1), you will need to access the magic function
92 # as a magic function (say who=1), you will need to access the magic function
86 # with @ (@who in this example). However, if later you delete your variable
93 # with @ (@who in this example). However, if later you delete your variable
87 # (del who), you'll recover the automagic calling form.
94 # (del who), you'll recover the automagic calling form.
88
95
89 # Considering that many magic functions provide a lot of shell-like
96 # Considering that many magic functions provide a lot of shell-like
90 # functionality, automagic gives you something close to a full Python+system
97 # functionality, automagic gives you something close to a full Python+system
91 # shell environment (and you can extend it further if you want).
98 # shell environment (and you can extend it further if you want).
92
99
93 automagic 1
100 automagic 1
94
101
95 # Size of the output cache. After this many entries are stored, the cache will
102 # Size of the output cache. After this many entries are stored, the cache will
96 # get flushed. Depending on the size of your intermediate calculations, you
103 # get flushed. Depending on the size of your intermediate calculations, you
97 # may have memory problems if you make it too big, since keeping things in the
104 # may have memory problems if you make it too big, since keeping things in the
98 # cache prevents Python from reclaiming the memory for old results. Experiment
105 # cache prevents Python from reclaiming the memory for old results. Experiment
99 # with a value that works well for you.
106 # with a value that works well for you.
100
107
101 # If you choose cache_size 0 IPython will revert to python's regular >>>
108 # If you choose cache_size 0 IPython will revert to python's regular >>>
102 # unnumbered prompt. You will still have _, __ and ___ for your last three
109 # unnumbered prompt. You will still have _, __ and ___ for your last three
103 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
110 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
104 # you are running on a slow machine or with very limited memory, this may
111 # you are running on a slow machine or with very limited memory, this may
105 # help.
112 # help.
106
113
107 cache_size 1000
114 cache_size 1000
108
115
109 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
116 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
110 # but that's your choice! Classic 1 -> same as IPython -classic.
117 # but that's your choice! Classic 1 -> same as IPython -classic.
111 # Note that this is _not_ the normal python interpreter, it's simply
118 # Note that this is _not_ the normal python interpreter, it's simply
112 # IPython emulating most of the classic interpreter's behavior.
119 # IPython emulating most of the classic interpreter's behavior.
113 classic 0
120 classic 0
114
121
115 # colors - Coloring option for prompts and traceback printouts.
122 # colors - Coloring option for prompts and traceback printouts.
116
123
117 # Currently available schemes: NoColor, Linux, LightBG.
124 # Currently available schemes: NoColor, Linux, LightBG.
118
125
119 # This option allows coloring the prompts and traceback printouts. This
126 # This option allows coloring the prompts and traceback printouts. This
120 # requires a terminal which can properly handle color escape sequences. If you
127 # requires a terminal which can properly handle color escape sequences. If you
121 # are having problems with this, use the NoColor scheme (uses no color escapes
128 # are having problems with this, use the NoColor scheme (uses no color escapes
122 # at all).
129 # at all).
123
130
124 # The Linux option works well in linux console type environments: dark
131 # The Linux option works well in linux console type environments: dark
125 # background with light fonts.
132 # background with light fonts.
126
133
127 # LightBG is similar to Linux but swaps dark/light colors to be more readable
134 # LightBG is similar to Linux but swaps dark/light colors to be more readable
128 # in light background terminals.
135 # in light background terminals.
129
136
130 # keep uncommented only the one you want:
137 # keep uncommented only the one you want:
131 colors Linux
138 colors Linux
132 #colors LightBG
139 #colors LightBG
133 #colors NoColor
140 #colors NoColor
134
141
135 ########################
142 ########################
136 # Note to Windows users
143 # Note to Windows users
137 #
144 #
138 # Color and readline support is avaialble to Windows users via Gary Bishop's
145 # Color and readline support is avaialble to Windows users via Gary Bishop's
139 # readline library. You can find Gary's tools at
146 # readline library. You can find Gary's tools at
140 # http://sourceforge.net/projects/uncpythontools.
147 # http://sourceforge.net/projects/uncpythontools.
141 # Note that his readline module requires in turn the ctypes library, available
148 # Note that his readline module requires in turn the ctypes library, available
142 # at http://starship.python.net/crew/theller/ctypes.
149 # at http://starship.python.net/crew/theller/ctypes.
143 ########################
150 ########################
144
151
145 # color_info: IPython can display information about objects via a set of
152 # color_info: IPython can display information about objects via a set of
146 # functions, and optionally can use colors for this, syntax highlighting
153 # functions, and optionally can use colors for this, syntax highlighting
147 # source code and various other elements. This information is passed through a
154 # source code and various other elements. This information is passed through a
148 # pager (it defaults to 'less' if $PAGER is not set).
155 # pager (it defaults to 'less' if $PAGER is not set).
149
156
150 # If your pager has problems, try to setting it to properly handle escapes
157 # If your pager has problems, try to setting it to properly handle escapes
151 # (see the less manpage for detail), or disable this option. The magic
158 # (see the less manpage for detail), or disable this option. The magic
152 # function @color_info allows you to toggle this interactively for testing.
159 # function @color_info allows you to toggle this interactively for testing.
153
160
154 color_info 1
161 color_info 1
155
162
156 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
163 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
157 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
164 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
158 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
165 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
159 # any confirmation.
166 # any confirmation.
160
167
161 confirm_exit 1
168 confirm_exit 1
162
169
163 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
170 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
164 # still available as dreload() and appears as a builtin.
171 # still available as dreload() and appears as a builtin.
165
172
166 deep_reload 0
173 deep_reload 0
167
174
168 # Which editor to use with the @edit command. If you leave this at 0, IPython
175 # Which editor to use with the @edit command. If you leave this at 0, IPython
169 # will honor your EDITOR environment variable. Since this editor is invoked on
176 # will honor your EDITOR environment variable. Since this editor is invoked on
170 # the fly by ipython and is meant for editing small code snippets, you may
177 # the fly by ipython and is meant for editing small code snippets, you may
171 # want to use a small, lightweight editor here.
178 # want to use a small, lightweight editor here.
172
179
173 # For Emacs users, setting up your Emacs server properly as described in the
180 # For Emacs users, setting up your Emacs server properly as described in the
174 # manual is a good idea. An alternative is to use jed, a very light editor
181 # manual is a good idea. An alternative is to use jed, a very light editor
175 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
182 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
176
183
177 editor 0
184 editor 0
178
185
179 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
186 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
180 log 0
187 log 0
181
188
182 # Same as ipython -Logfile YourLogfileName.
189 # Same as ipython -Logfile YourLogfileName.
183 # Don't use with log 1 (use one or the other)
190 # Don't use with log 1 (use one or the other)
184 logfile ''
191 logfile ''
185
192
186 # banner 0 -> same as ipython -nobanner
193 # banner 0 -> same as ipython -nobanner
187 banner 1
194 banner 1
188
195
189 # messages 0 -> same as ipython -nomessages
196 # messages 0 -> same as ipython -nomessages
190 messages 1
197 messages 1
191
198
192 # Automatically call the pdb debugger after every uncaught exception. If you
199 # Automatically call the pdb debugger after every uncaught exception. If you
193 # are used to debugging using pdb, this puts you automatically inside of it
200 # are used to debugging using pdb, this puts you automatically inside of it
194 # after any call (either in IPython or in code called by it) which triggers an
201 # after any call (either in IPython or in code called by it) which triggers an
195 # exception which goes uncaught.
202 # exception which goes uncaught.
196 pdb 0
203 pdb 0
197
204
198 # Enable the pprint module for printing. pprint tends to give a more readable
205 # Enable the pprint module for printing. pprint tends to give a more readable
199 # display (than print) for complex nested data structures.
206 # display (than print) for complex nested data structures.
200 pprint 1
207 pprint 1
201
208
202 # Prompt strings
209 # Prompt strings
203
210
204 # Most bash-like escapes can be used to customize IPython's prompts, as well as
211 # Most bash-like escapes can be used to customize IPython's prompts, as well as
205 # a few additional ones which are IPython-specific. All valid prompt escapes
212 # a few additional ones which are IPython-specific. All valid prompt escapes
206 # are described in detail in the Customization section of the IPython HTML/PDF
213 # are described in detail in the Customization section of the IPython HTML/PDF
207 # manual.
214 # manual.
208
215
209 # Use \# to represent the current prompt number, and quote them to protect
216 # Use \# to represent the current prompt number, and quote them to protect
210 # spaces.
217 # spaces.
211 prompt_in1 'In [\#]: '
218 prompt_in1 'In [\#]: '
212
219
213 # \D is replaced by as many dots as there are digits in the
220 # \D is replaced by as many dots as there are digits in the
214 # current value of \#.
221 # current value of \#.
215 prompt_in2 ' .\D.: '
222 prompt_in2 ' .\D.: '
216
223
217 prompt_out 'Out[\#]: '
224 prompt_out 'Out[\#]: '
218
225
219 # Select whether to left-pad the output prompts to match the length of the
226 # Select whether to left-pad the output prompts to match the length of the
220 # input ones. This allows you for example to use a simple '>' as an output
227 # input ones. This allows you for example to use a simple '>' as an output
221 # prompt, and yet have the output line up with the input. If set to false,
228 # prompt, and yet have the output line up with the input. If set to false,
222 # the output prompts will be unpadded (flush left).
229 # the output prompts will be unpadded (flush left).
223 prompts_pad_left 1
230 prompts_pad_left 1
224
231
225 # quick 1 -> same as ipython -quick
232 # quick 1 -> same as ipython -quick
226 quick 0
233 quick 0
227
234
228 # Use the readline library (1) or not (0). Most users will want this on, but
235 # Use the readline library (1) or not (0). Most users will want this on, but
229 # if you experience strange problems with line management (mainly when using
236 # if you experience strange problems with line management (mainly when using
230 # IPython inside Emacs buffers) you may try disabling it. Not having it on
237 # IPython inside Emacs buffers) you may try disabling it. Not having it on
231 # prevents you from getting command history with the arrow keys, searching and
238 # prevents you from getting command history with the arrow keys, searching and
232 # name completion using TAB.
239 # name completion using TAB.
233
240
234 readline 1
241 readline 1
235
242
236 # Screen Length: number of lines of your screen. This is used to control
243 # Screen Length: number of lines of your screen. This is used to control
237 # printing of very long strings. Strings longer than this number of lines will
244 # printing of very long strings. Strings longer than this number of lines will
238 # be paged with the less command instead of directly printed.
245 # be paged with the less command instead of directly printed.
239
246
240 # The default value for this is 0, which means IPython will auto-detect your
247 # The default value for this is 0, which means IPython will auto-detect your
241 # screen size every time it needs to print. If for some reason this isn't
248 # screen size every time it needs to print. If for some reason this isn't
242 # working well (it needs curses support), specify it yourself. Otherwise don't
249 # working well (it needs curses support), specify it yourself. Otherwise don't
243 # change the default.
250 # change the default.
244
251
245 screen_length 0
252 screen_length 0
246
253
247 # Prompt separators for input and output.
254 # Prompt separators for input and output.
248 # Use \n for newline explicitly, without quotes.
255 # Use \n for newline explicitly, without quotes.
249 # Use 0 (like at the cmd line) to turn off a given separator.
256 # Use 0 (like at the cmd line) to turn off a given separator.
250
257
251 # The structure of prompt printing is:
258 # The structure of prompt printing is:
252 # (SeparateIn)Input....
259 # (SeparateIn)Input....
253 # (SeparateOut)Output...
260 # (SeparateOut)Output...
254 # (SeparateOut2), # that is, no newline is printed after Out2
261 # (SeparateOut2), # that is, no newline is printed after Out2
255 # By choosing these you can organize your output any way you want.
262 # By choosing these you can organize your output any way you want.
256
263
257 separate_in \n
264 separate_in \n
258 separate_out 0
265 separate_out 0
259 separate_out2 0
266 separate_out2 0
260
267
261 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
268 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
262 # Simply removes all input/output separators, overriding the choices above.
269 # Simply removes all input/output separators, overriding the choices above.
263 nosep 0
270 nosep 0
264
271
265 # Wildcard searches - IPython has a system for searching names using
272 # Wildcard searches - IPython has a system for searching names using
266 # shell-like wildcards; type %psearch? for details. This variables sets
273 # shell-like wildcards; type %psearch? for details. This variables sets
267 # whether by default such searches should be case sensitive or not. You can
274 # whether by default such searches should be case sensitive or not. You can
268 # always override the default at the system command line or the IPython
275 # always override the default at the system command line or the IPython
269 # prompt.
276 # prompt.
270
277
271 wildcards_case_sensitive 1
278 wildcards_case_sensitive 1
272
279
273 # xmode - Exception reporting mode.
280 # xmode - Exception reporting mode.
274
281
275 # Valid modes: Plain, Context and Verbose.
282 # Valid modes: Plain, Context and Verbose.
276
283
277 # Plain: similar to python's normal traceback printing.
284 # Plain: similar to python's normal traceback printing.
278
285
279 # Context: prints 5 lines of context source code around each line in the
286 # Context: prints 5 lines of context source code around each line in the
280 # traceback.
287 # traceback.
281
288
282 # Verbose: similar to Context, but additionally prints the variables currently
289 # Verbose: similar to Context, but additionally prints the variables currently
283 # visible where the exception happened (shortening their strings if too
290 # visible where the exception happened (shortening their strings if too
284 # long). This can potentially be very slow, if you happen to have a huge data
291 # long). This can potentially be very slow, if you happen to have a huge data
285 # structure whose string representation is complex to compute. Your computer
292 # structure whose string representation is complex to compute. Your computer
286 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
293 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
287 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
294 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
288
295
289 #xmode Plain
296 #xmode Plain
290 xmode Context
297 xmode Context
291 #xmode Verbose
298 #xmode Verbose
292
299
293 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
300 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
294 # !cmd) to be used in multi-line input (like for loops). For example, if you
301 # !cmd) to be used in multi-line input (like for loops). For example, if you
295 # have this active, the following is valid in IPython:
302 # have this active, the following is valid in IPython:
296 #
303 #
297 #In [17]: for i in range(3):
304 #In [17]: for i in range(3):
298 # ....: mkdir $i
305 # ....: mkdir $i
299 # ....: !touch $i/hello
306 # ....: !touch $i/hello
300 # ....: ls -l $i
307 # ....: ls -l $i
301
308
302 multi_line_specials 1
309 multi_line_specials 1
303
310
304 #---------------------------------------------------------------------------
311 #---------------------------------------------------------------------------
305 # Section: Readline configuration (readline is not available for MS-Windows)
312 # Section: Readline configuration (readline is not available for MS-Windows)
306
313
307 # This is done via the following options:
314 # This is done via the following options:
308
315
309 # (i) readline_parse_and_bind: this option can appear as many times as you
316 # (i) readline_parse_and_bind: this option can appear as many times as you
310 # want, each time defining a string to be executed via a
317 # want, each time defining a string to be executed via a
311 # readline.parse_and_bind() command. The syntax for valid commands of this
318 # readline.parse_and_bind() command. The syntax for valid commands of this
312 # kind can be found by reading the documentation for the GNU readline library,
319 # kind can be found by reading the documentation for the GNU readline library,
313 # as these commands are of the kind which readline accepts in its
320 # as these commands are of the kind which readline accepts in its
314 # configuration file.
321 # configuration file.
315
322
316 # The TAB key can be used to complete names at the command line in one of two
323 # The TAB key can be used to complete names at the command line in one of two
317 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
324 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
318 # completes as much as possible while 'menu-complete' cycles through all
325 # completes as much as possible while 'menu-complete' cycles through all
319 # possible completions. Leave the one you prefer uncommented.
326 # possible completions. Leave the one you prefer uncommented.
320
327
321 readline_parse_and_bind tab: complete
328 readline_parse_and_bind tab: complete
322 #readline_parse_and_bind tab: menu-complete
329 #readline_parse_and_bind tab: menu-complete
323
330
324 # This binds Control-l to printing the list of all possible completions when
331 # This binds Control-l to printing the list of all possible completions when
325 # there is more than one (what 'complete' does when hitting TAB twice, or at
332 # there is more than one (what 'complete' does when hitting TAB twice, or at
326 # the first TAB if show-all-if-ambiguous is on)
333 # the first TAB if show-all-if-ambiguous is on)
327 readline_parse_and_bind "\C-l": possible-completions
334 readline_parse_and_bind "\C-l": possible-completions
328
335
329 # This forces readline to automatically print the above list when tab
336 # This forces readline to automatically print the above list when tab
330 # completion is set to 'complete'. You can still get this list manually by
337 # completion is set to 'complete'. You can still get this list manually by
331 # using the key bound to 'possible-completions' (Control-l by default) or by
338 # using the key bound to 'possible-completions' (Control-l by default) or by
332 # hitting TAB twice. Turning this on makes the printing happen at the first
339 # hitting TAB twice. Turning this on makes the printing happen at the first
333 # TAB.
340 # TAB.
334 readline_parse_and_bind set show-all-if-ambiguous on
341 readline_parse_and_bind set show-all-if-ambiguous on
335
342
336 # If you have TAB set to complete names, you can rebind any key (Control-o by
343 # If you have TAB set to complete names, you can rebind any key (Control-o by
337 # default) to insert a true TAB character.
344 # default) to insert a true TAB character.
338 readline_parse_and_bind "\C-o": tab-insert
345 readline_parse_and_bind "\C-o": tab-insert
339
346
340 # These commands allow you to indent/unindent easily, with the 4-space
347 # These commands allow you to indent/unindent easily, with the 4-space
341 # convention of the Python coding standards. Since IPython's internal
348 # convention of the Python coding standards. Since IPython's internal
342 # auto-indent system also uses 4 spaces, you should not change the number of
349 # auto-indent system also uses 4 spaces, you should not change the number of
343 # spaces in the code below.
350 # spaces in the code below.
344 readline_parse_and_bind "\M-i": " "
351 readline_parse_and_bind "\M-i": " "
345 readline_parse_and_bind "\M-o": "\d\d\d\d"
352 readline_parse_and_bind "\M-o": "\d\d\d\d"
346 readline_parse_and_bind "\M-I": "\d\d\d\d"
353 readline_parse_and_bind "\M-I": "\d\d\d\d"
347
354
348 # Bindings for incremental searches in the history. These searches use the
355 # Bindings for incremental searches in the history. These searches use the
349 # string typed so far on the command line and search anything in the previous
356 # string typed so far on the command line and search anything in the previous
350 # input history containing them.
357 # input history containing them.
351 readline_parse_and_bind "\C-r": reverse-search-history
358 readline_parse_and_bind "\C-r": reverse-search-history
352 readline_parse_and_bind "\C-s": forward-search-history
359 readline_parse_and_bind "\C-s": forward-search-history
353
360
354 # Bindings for completing the current line in the history of previous
361 # Bindings for completing the current line in the history of previous
355 # commands. This allows you to recall any previous command by typing its first
362 # commands. This allows you to recall any previous command by typing its first
356 # few letters and hitting Control-p, bypassing all intermediate commands which
363 # few letters and hitting Control-p, bypassing all intermediate commands which
357 # may be in the history (much faster than hitting up-arrow 50 times!)
364 # may be in the history (much faster than hitting up-arrow 50 times!)
358 readline_parse_and_bind "\C-p": history-search-backward
365 readline_parse_and_bind "\C-p": history-search-backward
359 readline_parse_and_bind "\C-n": history-search-forward
366 readline_parse_and_bind "\C-n": history-search-forward
360
367
361 # I also like to have the same functionality on the plain arrow keys. If you'd
368 # I also like to have the same functionality on the plain arrow keys. If you'd
362 # rather have the arrows use all the history (and not just match what you've
369 # rather have the arrows use all the history (and not just match what you've
363 # typed so far), comment out or delete the next two lines.
370 # typed so far), comment out or delete the next two lines.
364 readline_parse_and_bind "\e[A": history-search-backward
371 readline_parse_and_bind "\e[A": history-search-backward
365 readline_parse_and_bind "\e[B": history-search-forward
372 readline_parse_and_bind "\e[B": history-search-forward
366
373
367 # These are typically on by default under *nix, but not win32.
374 # These are typically on by default under *nix, but not win32.
368 readline_parse_and_bind "\C-k": kill-line
375 readline_parse_and_bind "\C-k": kill-line
369 readline_parse_and_bind "\C-u": unix-line-discard
376 readline_parse_and_bind "\C-u": unix-line-discard
370
377
371 # (ii) readline_remove_delims: a string of characters to be removed from the
378 # (ii) readline_remove_delims: a string of characters to be removed from the
372 # default word-delimiters list used by readline, so that completions may be
379 # default word-delimiters list used by readline, so that completions may be
373 # performed on strings which contain them.
380 # performed on strings which contain them.
374
381
375 readline_remove_delims -/~
382 readline_remove_delims -/~
376
383
377 # (iii) readline_merge_completions: whether to merge the result of all
384 # (iii) readline_merge_completions: whether to merge the result of all
378 # possible completions or not. If true, IPython will complete filenames,
385 # possible completions or not. If true, IPython will complete filenames,
379 # python names and aliases and return all possible completions. If you set it
386 # python names and aliases and return all possible completions. If you set it
380 # to false, each completer is used at a time, and only if it doesn't return
387 # to false, each completer is used at a time, and only if it doesn't return
381 # any completions is the next one used.
388 # any completions is the next one used.
382
389
383 # The default order is: [python_matches, file_matches, alias_matches]
390 # The default order is: [python_matches, file_matches, alias_matches]
384
391
385 readline_merge_completions 1
392 readline_merge_completions 1
386
393
387 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
394 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
388 # will complete all attributes of an object, including all the special methods
395 # will complete all attributes of an object, including all the special methods
389 # whose names start with single or double underscores (like __getitem__ or
396 # whose names start with single or double underscores (like __getitem__ or
390 # __class__).
397 # __class__).
391
398
392 # This variable allows you to control this completion behavior:
399 # This variable allows you to control this completion behavior:
393
400
394 # readline_omit__names 1 -> completion will omit showing any names starting
401 # readline_omit__names 1 -> completion will omit showing any names starting
395 # with two __, but it will still show names starting with one _.
402 # with two __, but it will still show names starting with one _.
396
403
397 # readline_omit__names 2 -> completion will omit all names beginning with one
404 # readline_omit__names 2 -> completion will omit all names beginning with one
398 # _ (which obviously means filtering out the double __ ones).
405 # _ (which obviously means filtering out the double __ ones).
399
406
400 # Even when this option is set, you can still see those names by explicitly
407 # Even when this option is set, you can still see those names by explicitly
401 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
408 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
402 # complete attribute names starting with '_'.
409 # complete attribute names starting with '_'.
403
410
404 # This option is off by default so that new users see all attributes of any
411 # This option is off by default so that new users see all attributes of any
405 # objects they are dealing with.
412 # objects they are dealing with.
406
413
407 readline_omit__names 0
414 readline_omit__names 0
408
415
409 #---------------------------------------------------------------------------
416 #---------------------------------------------------------------------------
410 # Section: modules to be loaded with 'import ...'
417 # Section: modules to be loaded with 'import ...'
411
418
412 # List, separated by spaces, the names of the modules you want to import
419 # List, separated by spaces, the names of the modules you want to import
413
420
414 # Example:
421 # Example:
415 # import_mod sys os
422 # import_mod sys os
416 # will produce internally the statements
423 # will produce internally the statements
417 # import sys
424 # import sys
418 # import os
425 # import os
419
426
420 # Each import is executed in its own try/except block, so if one module
427 # Each import is executed in its own try/except block, so if one module
421 # fails to load the others will still be ok.
428 # fails to load the others will still be ok.
422
429
423 import_mod
430 import_mod
424
431
425 #---------------------------------------------------------------------------
432 #---------------------------------------------------------------------------
426 # Section: modules to import some functions from: 'from ... import ...'
433 # Section: modules to import some functions from: 'from ... import ...'
427
434
428 # List, one per line, the modules for which you want only to import some
435 # List, one per line, the modules for which you want only to import some
429 # functions. Give the module name first and then the name of functions to be
436 # functions. Give the module name first and then the name of functions to be
430 # imported from that module.
437 # imported from that module.
431
438
432 # Example:
439 # Example:
433
440
434 # import_some IPython.genutils timing timings
441 # import_some IPython.genutils timing timings
435 # will produce internally the statement
442 # will produce internally the statement
436 # from IPython.genutils import timing, timings
443 # from IPython.genutils import timing, timings
437
444
438 # timing() and timings() are two IPython utilities for timing the execution of
445 # timing() and timings() are two IPython utilities for timing the execution of
439 # your own functions, which you may find useful. Just commment out the above
446 # your own functions, which you may find useful. Just commment out the above
440 # line if you want to test them.
447 # line if you want to test them.
441
448
442 # If you have more than one modules_some line, each gets its own try/except
449 # If you have more than one modules_some line, each gets its own try/except
443 # block (like modules, see above).
450 # block (like modules, see above).
444
451
445 import_some
452 import_some
446
453
447 #---------------------------------------------------------------------------
454 #---------------------------------------------------------------------------
448 # Section: modules to import all from : 'from ... import *'
455 # Section: modules to import all from : 'from ... import *'
449
456
450 # List (same syntax as import_mod above) those modules for which you want to
457 # List (same syntax as import_mod above) those modules for which you want to
451 # import all functions. Remember, this is a potentially dangerous thing to do,
458 # import all functions. Remember, this is a potentially dangerous thing to do,
452 # since it is very easy to overwrite names of things you need. Use with
459 # since it is very easy to overwrite names of things you need. Use with
453 # caution.
460 # caution.
454
461
455 # Example:
462 # Example:
456 # import_all sys os
463 # import_all sys os
457 # will produce internally the statements
464 # will produce internally the statements
458 # from sys import *
465 # from sys import *
459 # from os import *
466 # from os import *
460
467
461 # As before, each will be called in a separate try/except block.
468 # As before, each will be called in a separate try/except block.
462
469
463 import_all
470 import_all
464
471
465 #---------------------------------------------------------------------------
472 #---------------------------------------------------------------------------
466 # Section: Python code to execute.
473 # Section: Python code to execute.
467
474
468 # Put here code to be explicitly executed (keep it simple!)
475 # Put here code to be explicitly executed (keep it simple!)
469 # Put one line of python code per line. All whitespace is removed (this is a
476 # Put one line of python code per line. All whitespace is removed (this is a
470 # feature, not a bug), so don't get fancy building loops here.
477 # feature, not a bug), so don't get fancy building loops here.
471 # This is just for quick convenient creation of things you want available.
478 # This is just for quick convenient creation of things you want available.
472
479
473 # Example:
480 # Example:
474 # execute x = 1
481 # execute x = 1
475 # execute print 'hello world'; y = z = 'a'
482 # execute print 'hello world'; y = z = 'a'
476 # will produce internally
483 # will produce internally
477 # x = 1
484 # x = 1
478 # print 'hello world'; y = z = 'a'
485 # print 'hello world'; y = z = 'a'
479 # and each *line* (not each statement, we don't do python syntax parsing) is
486 # and each *line* (not each statement, we don't do python syntax parsing) is
480 # executed in its own try/except block.
487 # executed in its own try/except block.
481
488
482 execute
489 execute
483
490
484 # Note for the adventurous: you can use this to define your own names for the
491 # Note for the adventurous: you can use this to define your own names for the
485 # magic functions, by playing some namespace tricks:
492 # magic functions, by playing some namespace tricks:
486
493
487 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
494 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
488
495
489 # defines @pf as a new name for @profile.
496 # defines @pf as a new name for @profile.
490
497
491 #---------------------------------------------------------------------------
498 #---------------------------------------------------------------------------
492 # Section: Pyhton files to load and execute.
499 # Section: Pyhton files to load and execute.
493
500
494 # Put here the full names of files you want executed with execfile(file). If
501 # Put here the full names of files you want executed with execfile(file). If
495 # you want complicated initialization, just write whatever you want in a
502 # you want complicated initialization, just write whatever you want in a
496 # regular python file and load it from here.
503 # regular python file and load it from here.
497
504
498 # Filenames defined here (which *must* include the extension) are searched for
505 # Filenames defined here (which *must* include the extension) are searched for
499 # through all of sys.path. Since IPython adds your .ipython directory to
506 # through all of sys.path. Since IPython adds your .ipython directory to
500 # sys.path, they can also be placed in your .ipython dir and will be
507 # sys.path, they can also be placed in your .ipython dir and will be
501 # found. Otherwise (if you want to execute things not in .ipyton nor in
508 # found. Otherwise (if you want to execute things not in .ipyton nor in
502 # sys.path) give a full path (you can use ~, it gets expanded)
509 # sys.path) give a full path (you can use ~, it gets expanded)
503
510
504 # Example:
511 # Example:
505 # execfile file1.py ~/file2.py
512 # execfile file1.py ~/file2.py
506 # will generate
513 # will generate
507 # execfile('file1.py')
514 # execfile('file1.py')
508 # execfile('_path_to_your_home/file2.py')
515 # execfile('_path_to_your_home/file2.py')
509
516
510 # As before, each file gets its own try/except block.
517 # As before, each file gets its own try/except block.
511
518
512 execfile
519 execfile
513
520
514 # If you are feeling adventurous, you can even add functionality to IPython
521 # If you are feeling adventurous, you can even add functionality to IPython
515 # through here. IPython works through a global variable called __ip which
522 # through here. IPython works through a global variable called __ip which
516 # exists at the time when these files are read. If you know what you are doing
523 # exists at the time when these files are read. If you know what you are doing
517 # (read the source) you can add functions to __ip in files loaded here.
524 # (read the source) you can add functions to __ip in files loaded here.
518
525
519 # The file example-magic.py contains a simple but correct example. Try it:
526 # The file example-magic.py contains a simple but correct example. Try it:
520
527
521 # execfile example-magic.py
528 # execfile example-magic.py
522
529
523 # Look at the examples in IPython/iplib.py for more details on how these magic
530 # Look at the examples in IPython/iplib.py for more details on how these magic
524 # functions need to process their arguments.
531 # functions need to process their arguments.
525
532
526 #---------------------------------------------------------------------------
533 #---------------------------------------------------------------------------
527 # Section: aliases for system shell commands
534 # Section: aliases for system shell commands
528
535
529 # Here you can define your own names for system commands. The syntax is
536 # Here you can define your own names for system commands. The syntax is
530 # similar to that of the builtin @alias function:
537 # similar to that of the builtin @alias function:
531
538
532 # alias alias_name command_string
539 # alias alias_name command_string
533
540
534 # The resulting aliases are auto-generated magic functions (hence usable as
541 # The resulting aliases are auto-generated magic functions (hence usable as
535 # @alias_name)
542 # @alias_name)
536
543
537 # For example:
544 # For example:
538
545
539 # alias myls ls -la
546 # alias myls ls -la
540
547
541 # will define 'myls' as an alias for executing the system command 'ls -la'.
548 # will define 'myls' as an alias for executing the system command 'ls -la'.
542 # This allows you to customize IPython's environment to have the same aliases
549 # This allows you to customize IPython's environment to have the same aliases
543 # you are accustomed to from your own shell.
550 # you are accustomed to from your own shell.
544
551
545 # You can also define aliases with parameters using %s specifiers (one per
552 # You can also define aliases with parameters using %s specifiers (one per
546 # parameter):
553 # parameter):
547
554
548 # alias parts echo first %s second %s
555 # alias parts echo first %s second %s
549
556
550 # will give you in IPython:
557 # will give you in IPython:
551 # >>> @parts A B
558 # >>> @parts A B
552 # first A second B
559 # first A second B
553
560
554 # Use one 'alias' statement per alias you wish to define.
561 # Use one 'alias' statement per alias you wish to define.
555
562
556 # alias
563 # alias
557
564
558 #************************* end of file <ipythonrc> ************************
565 #************************* end of file <ipythonrc> ************************
@@ -1,1958 +1,1961 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or newer.
5 Requires Python 2.1 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 962 2005-12-28 18:04:59Z fperez $
9 $Id: iplib.py 963 2005-12-28 19:21:29Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import traceback
58 import traceback
59 import types
59 import types
60
60
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic,magic2python
70 from IPython.Magic import Magic,magic2python
71 from IPython.Struct import Struct
71 from IPython.Struct import Struct
72 from IPython.background_jobs import BackgroundJobManager
72 from IPython.background_jobs import BackgroundJobManager
73 from IPython.usage import cmd_line_usage,interactive_usage
73 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.genutils import *
74 from IPython.genutils import *
75
75
76 # store the builtin raw_input globally, and use this always, in case user code
76 # store the builtin raw_input globally, and use this always, in case user code
77 # overwrites it (like wx.py.PyShell does)
77 # overwrites it (like wx.py.PyShell does)
78 raw_input_original = raw_input
78 raw_input_original = raw_input
79
79
80 #****************************************************************************
80 #****************************************************************************
81 # Some utility function definitions
81 # Some utility function definitions
82
82
83 # This can be replaced with an isspace() call once we drop 2.2 compatibility
83 # This can be replaced with an isspace() call once we drop 2.2 compatibility
84 _isspace_match = re.compile(r'^\s+$').match
84 _isspace_match = re.compile(r'^\s+$').match
85 def isspace(s):
85 def isspace(s):
86 return bool(_isspace_match(s))
86 return bool(_isspace_match(s))
87
87
88 def esc_quotes(strng):
88 def esc_quotes(strng):
89 """Return the input string with single and double quotes escaped out"""
89 """Return the input string with single and double quotes escaped out"""
90
90
91 return strng.replace('"','\\"').replace("'","\\'")
91 return strng.replace('"','\\"').replace("'","\\'")
92
92
93 def import_fail_info(mod_name,fns=None):
93 def import_fail_info(mod_name,fns=None):
94 """Inform load failure for a module."""
94 """Inform load failure for a module."""
95
95
96 if fns == None:
96 if fns == None:
97 warn("Loading of %s failed.\n" % (mod_name,))
97 warn("Loading of %s failed.\n" % (mod_name,))
98 else:
98 else:
99 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
99 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
100
100
101 def qw_lol(indata):
101 def qw_lol(indata):
102 """qw_lol('a b') -> [['a','b']],
102 """qw_lol('a b') -> [['a','b']],
103 otherwise it's just a call to qw().
103 otherwise it's just a call to qw().
104
104
105 We need this to make sure the modules_some keys *always* end up as a
105 We need this to make sure the modules_some keys *always* end up as a
106 list of lists."""
106 list of lists."""
107
107
108 if type(indata) in StringTypes:
108 if type(indata) in StringTypes:
109 return [qw(indata)]
109 return [qw(indata)]
110 else:
110 else:
111 return qw(indata)
111 return qw(indata)
112
112
113 def ipmagic(arg_s):
113 def ipmagic(arg_s):
114 """Call a magic function by name.
114 """Call a magic function by name.
115
115
116 Input: a string containing the name of the magic function to call and any
116 Input: a string containing the name of the magic function to call and any
117 additional arguments to be passed to the magic.
117 additional arguments to be passed to the magic.
118
118
119 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
119 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
120 prompt:
120 prompt:
121
121
122 In[1]: %name -opt foo bar
122 In[1]: %name -opt foo bar
123
123
124 To call a magic without arguments, simply use ipmagic('name').
124 To call a magic without arguments, simply use ipmagic('name').
125
125
126 This provides a proper Python function to call IPython's magics in any
126 This provides a proper Python function to call IPython's magics in any
127 valid Python code you can type at the interpreter, including loops and
127 valid Python code you can type at the interpreter, including loops and
128 compound statements. It is added by IPython to the Python builtin
128 compound statements. It is added by IPython to the Python builtin
129 namespace upon initialization."""
129 namespace upon initialization."""
130
130
131 args = arg_s.split(' ',1)
131 args = arg_s.split(' ',1)
132 magic_name = args[0]
132 magic_name = args[0]
133 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
133 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
134 magic_name = magic_name[1:]
134 magic_name = magic_name[1:]
135 try:
135 try:
136 magic_args = args[1]
136 magic_args = args[1]
137 except IndexError:
137 except IndexError:
138 magic_args = ''
138 magic_args = ''
139 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
139 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
140 if fn is None:
140 if fn is None:
141 error("Magic function `%s` not found." % magic_name)
141 error("Magic function `%s` not found." % magic_name)
142 else:
142 else:
143 magic_args = __IPYTHON__.var_expand(magic_args)
143 magic_args = __IPYTHON__.var_expand(magic_args)
144 return fn(magic_args)
144 return fn(magic_args)
145
145
146 def ipalias(arg_s):
146 def ipalias(arg_s):
147 """Call an alias by name.
147 """Call an alias by name.
148
148
149 Input: a string containing the name of the alias to call and any
149 Input: a string containing the name of the alias to call and any
150 additional arguments to be passed to the magic.
150 additional arguments to be passed to the magic.
151
151
152 ipalias('name -opt foo bar') is equivalent to typing at the ipython
152 ipalias('name -opt foo bar') is equivalent to typing at the ipython
153 prompt:
153 prompt:
154
154
155 In[1]: name -opt foo bar
155 In[1]: name -opt foo bar
156
156
157 To call an alias without arguments, simply use ipalias('name').
157 To call an alias without arguments, simply use ipalias('name').
158
158
159 This provides a proper Python function to call IPython's aliases in any
159 This provides a proper Python function to call IPython's aliases in any
160 valid Python code you can type at the interpreter, including loops and
160 valid Python code you can type at the interpreter, including loops and
161 compound statements. It is added by IPython to the Python builtin
161 compound statements. It is added by IPython to the Python builtin
162 namespace upon initialization."""
162 namespace upon initialization."""
163
163
164 args = arg_s.split(' ',1)
164 args = arg_s.split(' ',1)
165 alias_name = args[0]
165 alias_name = args[0]
166 try:
166 try:
167 alias_args = args[1]
167 alias_args = args[1]
168 except IndexError:
168 except IndexError:
169 alias_args = ''
169 alias_args = ''
170 if alias_name in __IPYTHON__.alias_table:
170 if alias_name in __IPYTHON__.alias_table:
171 __IPYTHON__.call_alias(alias_name,alias_args)
171 __IPYTHON__.call_alias(alias_name,alias_args)
172 else:
172 else:
173 error("Alias `%s` not found." % alias_name)
173 error("Alias `%s` not found." % alias_name)
174
174
175 def softspace(file, newvalue):
175 def softspace(file, newvalue):
176 """Copied from code.py, to remove the dependency"""
176 """Copied from code.py, to remove the dependency"""
177 oldvalue = 0
177 oldvalue = 0
178 try:
178 try:
179 oldvalue = file.softspace
179 oldvalue = file.softspace
180 except AttributeError:
180 except AttributeError:
181 pass
181 pass
182 try:
182 try:
183 file.softspace = newvalue
183 file.softspace = newvalue
184 except (AttributeError, TypeError):
184 except (AttributeError, TypeError):
185 # "attribute-less object" or "read-only attributes"
185 # "attribute-less object" or "read-only attributes"
186 pass
186 pass
187 return oldvalue
187 return oldvalue
188
188
189
189
190 #****************************************************************************
190 #****************************************************************************
191 # Local use exceptions
191 # Local use exceptions
192 class SpaceInInput(exceptions.Exception): pass
192 class SpaceInInput(exceptions.Exception): pass
193
193
194 #****************************************************************************
194 #****************************************************************************
195 # Local use classes
195 # Local use classes
196 class Bunch: pass
196 class Bunch: pass
197
197
198 class InputList(list):
198 class InputList(list):
199 """Class to store user input.
199 """Class to store user input.
200
200
201 It's basically a list, but slices return a string instead of a list, thus
201 It's basically a list, but slices return a string instead of a list, thus
202 allowing things like (assuming 'In' is an instance):
202 allowing things like (assuming 'In' is an instance):
203
203
204 exec In[4:7]
204 exec In[4:7]
205
205
206 or
206 or
207
207
208 exec In[5:9] + In[14] + In[21:25]"""
208 exec In[5:9] + In[14] + In[21:25]"""
209
209
210 def __getslice__(self,i,j):
210 def __getslice__(self,i,j):
211 return ''.join(list.__getslice__(self,i,j))
211 return ''.join(list.__getslice__(self,i,j))
212
212
213 class SyntaxTB(ultraTB.ListTB):
213 class SyntaxTB(ultraTB.ListTB):
214 """Extension which holds some state: the last exception value"""
214 """Extension which holds some state: the last exception value"""
215
215
216 def __init__(self,color_scheme = 'NoColor'):
216 def __init__(self,color_scheme = 'NoColor'):
217 ultraTB.ListTB.__init__(self,color_scheme)
217 ultraTB.ListTB.__init__(self,color_scheme)
218 self.last_syntax_error = None
218 self.last_syntax_error = None
219
219
220 def __call__(self, etype, value, elist):
220 def __call__(self, etype, value, elist):
221 self.last_syntax_error = value
221 self.last_syntax_error = value
222 ultraTB.ListTB.__call__(self,etype,value,elist)
222 ultraTB.ListTB.__call__(self,etype,value,elist)
223
223
224 def clear_err_state(self):
224 def clear_err_state(self):
225 """Return the current error state and clear it"""
225 """Return the current error state and clear it"""
226 e = self.last_syntax_error
226 e = self.last_syntax_error
227 self.last_syntax_error = None
227 self.last_syntax_error = None
228 return e
228 return e
229
229
230 #****************************************************************************
230 #****************************************************************************
231 # Main IPython class
231 # Main IPython class
232 class InteractiveShell(Logger, Magic):
232 class InteractiveShell(Logger, Magic):
233 """An enhanced console for Python."""
233 """An enhanced console for Python."""
234
234
235 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
235 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
236 user_ns = None,user_global_ns=None,banner2='',
236 user_ns = None,user_global_ns=None,banner2='',
237 custom_exceptions=((),None),embedded=False):
237 custom_exceptions=((),None),embedded=False):
238
238
239 # Put a reference to self in builtins so that any form of embedded or
239 # Put a reference to self in builtins so that any form of embedded or
240 # imported code can test for being inside IPython.
240 # imported code can test for being inside IPython.
241 __builtin__.__IPYTHON__ = self
241 __builtin__.__IPYTHON__ = self
242
242
243 # And load into builtins ipmagic/ipalias as well
243 # And load into builtins ipmagic/ipalias as well
244 __builtin__.ipmagic = ipmagic
244 __builtin__.ipmagic = ipmagic
245 __builtin__.ipalias = ipalias
245 __builtin__.ipalias = ipalias
246
246
247 # Add to __builtin__ other parts of IPython's public API
247 # Add to __builtin__ other parts of IPython's public API
248 __builtin__.ip_set_hook = self.set_hook
248 __builtin__.ip_set_hook = self.set_hook
249
249
250 # Keep in the builtins a flag for when IPython is active. We set it
250 # Keep in the builtins a flag for when IPython is active. We set it
251 # with setdefault so that multiple nested IPythons don't clobber one
251 # with setdefault so that multiple nested IPythons don't clobber one
252 # another. Each will increase its value by one upon being activated,
252 # another. Each will increase its value by one upon being activated,
253 # which also gives us a way to determine the nesting level.
253 # which also gives us a way to determine the nesting level.
254 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
254 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
255
255
256 # Do the intuitively correct thing for quit/exit: we remove the
256 # Do the intuitively correct thing for quit/exit: we remove the
257 # builtins if they exist, and our own prefilter routine will handle
257 # builtins if they exist, and our own prefilter routine will handle
258 # these special cases
258 # these special cases
259 try:
259 try:
260 del __builtin__.exit, __builtin__.quit
260 del __builtin__.exit, __builtin__.quit
261 except AttributeError:
261 except AttributeError:
262 pass
262 pass
263
263
264 # We need to know whether the instance is meant for embedding, since
264 # We need to know whether the instance is meant for embedding, since
265 # global/local namespaces need to be handled differently in that case
265 # global/local namespaces need to be handled differently in that case
266 self.embedded = embedded
266 self.embedded = embedded
267
267
268 # command compiler
268 # command compiler
269 self.compile = codeop.CommandCompiler()
269 self.compile = codeop.CommandCompiler()
270
270
271 # User input buffer
271 # User input buffer
272 self.buffer = []
272 self.buffer = []
273
273
274 # Default name given in compilation of code
274 # Default name given in compilation of code
275 self.filename = '<ipython console>'
275 self.filename = '<ipython console>'
276
276
277 # Create the namespace where the user will operate. user_ns is
277 # Create the namespace where the user will operate. user_ns is
278 # normally the only one used, and it is passed to the exec calls as
278 # normally the only one used, and it is passed to the exec calls as
279 # the locals argument. But we do carry a user_global_ns namespace
279 # the locals argument. But we do carry a user_global_ns namespace
280 # given as the exec 'globals' argument, This is useful in embedding
280 # given as the exec 'globals' argument, This is useful in embedding
281 # situations where the ipython shell opens in a context where the
281 # situations where the ipython shell opens in a context where the
282 # distinction between locals and globals is meaningful.
282 # distinction between locals and globals is meaningful.
283
283
284 # FIXME. For some strange reason, __builtins__ is showing up at user
284 # FIXME. For some strange reason, __builtins__ is showing up at user
285 # level as a dict instead of a module. This is a manual fix, but I
285 # level as a dict instead of a module. This is a manual fix, but I
286 # should really track down where the problem is coming from. Alex
286 # should really track down where the problem is coming from. Alex
287 # Schmolck reported this problem first.
287 # Schmolck reported this problem first.
288
288
289 # A useful post by Alex Martelli on this topic:
289 # A useful post by Alex Martelli on this topic:
290 # Re: inconsistent value from __builtins__
290 # Re: inconsistent value from __builtins__
291 # Von: Alex Martelli <aleaxit@yahoo.com>
291 # Von: Alex Martelli <aleaxit@yahoo.com>
292 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
292 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
293 # Gruppen: comp.lang.python
293 # Gruppen: comp.lang.python
294 # Referenzen: 1
294 # Referenzen: 1
295
295
296 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
296 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
297 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
297 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
298 # > <type 'dict'>
298 # > <type 'dict'>
299 # > >>> print type(__builtins__)
299 # > >>> print type(__builtins__)
300 # > <type 'module'>
300 # > <type 'module'>
301 # > Is this difference in return value intentional?
301 # > Is this difference in return value intentional?
302
302
303 # Well, it's documented that '__builtins__' can be either a dictionary
303 # Well, it's documented that '__builtins__' can be either a dictionary
304 # or a module, and it's been that way for a long time. Whether it's
304 # or a module, and it's been that way for a long time. Whether it's
305 # intentional (or sensible), I don't know. In any case, the idea is
305 # intentional (or sensible), I don't know. In any case, the idea is
306 # that if you need to access the built-in namespace directly, you
306 # that if you need to access the built-in namespace directly, you
307 # should start with "import __builtin__" (note, no 's') which will
307 # should start with "import __builtin__" (note, no 's') which will
308 # definitely give you a module. Yeah, it's somewhat confusing:-(.
308 # definitely give you a module. Yeah, it's somewhat confusing:-(.
309
309
310 if user_ns is None:
310 if user_ns is None:
311 # Set __name__ to __main__ to better match the behavior of the
311 # Set __name__ to __main__ to better match the behavior of the
312 # normal interpreter.
312 # normal interpreter.
313 user_ns = {'__name__' :'__main__',
313 user_ns = {'__name__' :'__main__',
314 '__builtins__' : __builtin__,
314 '__builtins__' : __builtin__,
315 }
315 }
316
316
317 if user_global_ns is None:
317 if user_global_ns is None:
318 user_global_ns = {}
318 user_global_ns = {}
319
319
320 # Assign namespaces
320 # Assign namespaces
321 # This is the namespace where all normal user variables live
321 # This is the namespace where all normal user variables live
322 self.user_ns = user_ns
322 self.user_ns = user_ns
323 # Embedded instances require a separate namespace for globals.
323 # Embedded instances require a separate namespace for globals.
324 # Normally this one is unused by non-embedded instances.
324 # Normally this one is unused by non-embedded instances.
325 self.user_global_ns = user_global_ns
325 self.user_global_ns = user_global_ns
326 # A namespace to keep track of internal data structures to prevent
326 # A namespace to keep track of internal data structures to prevent
327 # them from cluttering user-visible stuff. Will be updated later
327 # them from cluttering user-visible stuff. Will be updated later
328 self.internal_ns = {}
328 self.internal_ns = {}
329
329
330 # Namespace of system aliases. Each entry in the alias
330 # Namespace of system aliases. Each entry in the alias
331 # table must be a 2-tuple of the form (N,name), where N is the number
331 # table must be a 2-tuple of the form (N,name), where N is the number
332 # of positional arguments of the alias.
332 # of positional arguments of the alias.
333 self.alias_table = {}
333 self.alias_table = {}
334
334
335 # A table holding all the namespaces IPython deals with, so that
335 # A table holding all the namespaces IPython deals with, so that
336 # introspection facilities can search easily.
336 # introspection facilities can search easily.
337 self.ns_table = {'user':user_ns,
337 self.ns_table = {'user':user_ns,
338 'user_global':user_global_ns,
338 'user_global':user_global_ns,
339 'alias':self.alias_table,
339 'alias':self.alias_table,
340 'internal':self.internal_ns,
340 'internal':self.internal_ns,
341 'builtin':__builtin__.__dict__
341 'builtin':__builtin__.__dict__
342 }
342 }
343
343
344 # The user namespace MUST have a pointer to the shell itself.
344 # The user namespace MUST have a pointer to the shell itself.
345 self.user_ns[name] = self
345 self.user_ns[name] = self
346
346
347 # We need to insert into sys.modules something that looks like a
347 # We need to insert into sys.modules something that looks like a
348 # module but which accesses the IPython namespace, for shelve and
348 # module but which accesses the IPython namespace, for shelve and
349 # pickle to work interactively. Normally they rely on getting
349 # pickle to work interactively. Normally they rely on getting
350 # everything out of __main__, but for embedding purposes each IPython
350 # everything out of __main__, but for embedding purposes each IPython
351 # instance has its own private namespace, so we can't go shoving
351 # instance has its own private namespace, so we can't go shoving
352 # everything into __main__.
352 # everything into __main__.
353
353
354 # note, however, that we should only do this for non-embedded
354 # note, however, that we should only do this for non-embedded
355 # ipythons, which really mimic the __main__.__dict__ with their own
355 # ipythons, which really mimic the __main__.__dict__ with their own
356 # namespace. Embedded instances, on the other hand, should not do
356 # namespace. Embedded instances, on the other hand, should not do
357 # this because they need to manage the user local/global namespaces
357 # this because they need to manage the user local/global namespaces
358 # only, but they live within a 'normal' __main__ (meaning, they
358 # only, but they live within a 'normal' __main__ (meaning, they
359 # shouldn't overtake the execution environment of the script they're
359 # shouldn't overtake the execution environment of the script they're
360 # embedded in).
360 # embedded in).
361
361
362 if not embedded:
362 if not embedded:
363 try:
363 try:
364 main_name = self.user_ns['__name__']
364 main_name = self.user_ns['__name__']
365 except KeyError:
365 except KeyError:
366 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
366 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
367 else:
367 else:
368 #print "pickle hack in place" # dbg
368 #print "pickle hack in place" # dbg
369 sys.modules[main_name] = FakeModule(self.user_ns)
369 sys.modules[main_name] = FakeModule(self.user_ns)
370
370
371 # List of input with multi-line handling.
371 # List of input with multi-line handling.
372 # Fill its zero entry, user counter starts at 1
372 # Fill its zero entry, user counter starts at 1
373 self.input_hist = InputList(['\n'])
373 self.input_hist = InputList(['\n'])
374
374
375 # list of visited directories
375 # list of visited directories
376 try:
376 try:
377 self.dir_hist = [os.getcwd()]
377 self.dir_hist = [os.getcwd()]
378 except IOError, e:
378 except IOError, e:
379 self.dir_hist = []
379 self.dir_hist = []
380
380
381 # dict of output history
381 # dict of output history
382 self.output_hist = {}
382 self.output_hist = {}
383
383
384 # dict of things NOT to alias (keywords, builtins and some magics)
384 # dict of things NOT to alias (keywords, builtins and some magics)
385 no_alias = {}
385 no_alias = {}
386 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
386 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
387 for key in keyword.kwlist + no_alias_magics:
387 for key in keyword.kwlist + no_alias_magics:
388 no_alias[key] = 1
388 no_alias[key] = 1
389 no_alias.update(__builtin__.__dict__)
389 no_alias.update(__builtin__.__dict__)
390 self.no_alias = no_alias
390 self.no_alias = no_alias
391
391
392 # make global variables for user access to these
392 # make global variables for user access to these
393 self.user_ns['_ih'] = self.input_hist
393 self.user_ns['_ih'] = self.input_hist
394 self.user_ns['_oh'] = self.output_hist
394 self.user_ns['_oh'] = self.output_hist
395 self.user_ns['_dh'] = self.dir_hist
395 self.user_ns['_dh'] = self.dir_hist
396
396
397 # user aliases to input and output histories
397 # user aliases to input and output histories
398 self.user_ns['In'] = self.input_hist
398 self.user_ns['In'] = self.input_hist
399 self.user_ns['Out'] = self.output_hist
399 self.user_ns['Out'] = self.output_hist
400
400
401 # Store the actual shell's name
401 # Store the actual shell's name
402 self.name = name
402 self.name = name
403
403
404 # Object variable to store code object waiting execution. This is
404 # Object variable to store code object waiting execution. This is
405 # used mainly by the multithreaded shells, but it can come in handy in
405 # used mainly by the multithreaded shells, but it can come in handy in
406 # other situations. No need to use a Queue here, since it's a single
406 # other situations. No need to use a Queue here, since it's a single
407 # item which gets cleared once run.
407 # item which gets cleared once run.
408 self.code_to_run = None
408 self.code_to_run = None
409
409
410 # Job manager (for jobs run as background threads)
410 # Job manager (for jobs run as background threads)
411 self.jobs = BackgroundJobManager()
411 self.jobs = BackgroundJobManager()
412 # Put the job manager into builtins so it's always there.
412 # Put the job manager into builtins so it's always there.
413 __builtin__.jobs = self.jobs
413 __builtin__.jobs = self.jobs
414
414
415 # escapes for automatic behavior on the command line
415 # escapes for automatic behavior on the command line
416 self.ESC_SHELL = '!'
416 self.ESC_SHELL = '!'
417 self.ESC_HELP = '?'
417 self.ESC_HELP = '?'
418 self.ESC_MAGIC = '%'
418 self.ESC_MAGIC = '%'
419 self.ESC_QUOTE = ','
419 self.ESC_QUOTE = ','
420 self.ESC_QUOTE2 = ';'
420 self.ESC_QUOTE2 = ';'
421 self.ESC_PAREN = '/'
421 self.ESC_PAREN = '/'
422
422
423 # And their associated handlers
423 # And their associated handlers
424 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
424 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
425 self.ESC_QUOTE:self.handle_auto,
425 self.ESC_QUOTE:self.handle_auto,
426 self.ESC_QUOTE2:self.handle_auto,
426 self.ESC_QUOTE2:self.handle_auto,
427 self.ESC_MAGIC:self.handle_magic,
427 self.ESC_MAGIC:self.handle_magic,
428 self.ESC_HELP:self.handle_help,
428 self.ESC_HELP:self.handle_help,
429 self.ESC_SHELL:self.handle_shell_escape,
429 self.ESC_SHELL:self.handle_shell_escape,
430 }
430 }
431
431
432 # class initializations
432 # class initializations
433 Logger.__init__(self,log_ns = self.user_ns)
433 Logger.__init__(self,log_ns = self.user_ns)
434 Magic.__init__(self,self)
434 Magic.__init__(self,self)
435
435
436 # an ugly hack to get a pointer to the shell, so I can start writing
436 # an ugly hack to get a pointer to the shell, so I can start writing
437 # magic code via this pointer instead of the current mixin salad.
437 # magic code via this pointer instead of the current mixin salad.
438 Magic.set_shell(self,self)
438 Magic.set_shell(self,self)
439
439
440 # Python source parser/formatter for syntax highlighting
440 # Python source parser/formatter for syntax highlighting
441 pyformat = PyColorize.Parser().format
441 pyformat = PyColorize.Parser().format
442 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
442 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
443
443
444 # hooks holds pointers used for user-side customizations
444 # hooks holds pointers used for user-side customizations
445 self.hooks = Struct()
445 self.hooks = Struct()
446
446
447 # Set all default hooks, defined in the IPython.hooks module.
447 # Set all default hooks, defined in the IPython.hooks module.
448 hooks = IPython.hooks
448 hooks = IPython.hooks
449 for hook_name in hooks.__all__:
449 for hook_name in hooks.__all__:
450 self.set_hook(hook_name,getattr(hooks,hook_name))
450 self.set_hook(hook_name,getattr(hooks,hook_name))
451
451
452 # Flag to mark unconditional exit
452 # Flag to mark unconditional exit
453 self.exit_now = False
453 self.exit_now = False
454
454
455 self.usage_min = """\
455 self.usage_min = """\
456 An enhanced console for Python.
456 An enhanced console for Python.
457 Some of its features are:
457 Some of its features are:
458 - Readline support if the readline library is present.
458 - Readline support if the readline library is present.
459 - Tab completion in the local namespace.
459 - Tab completion in the local namespace.
460 - Logging of input, see command-line options.
460 - Logging of input, see command-line options.
461 - System shell escape via ! , eg !ls.
461 - System shell escape via ! , eg !ls.
462 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
462 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
463 - Keeps track of locally defined variables via %who, %whos.
463 - Keeps track of locally defined variables via %who, %whos.
464 - Show object information with a ? eg ?x or x? (use ?? for more info).
464 - Show object information with a ? eg ?x or x? (use ?? for more info).
465 """
465 """
466 if usage: self.usage = usage
466 if usage: self.usage = usage
467 else: self.usage = self.usage_min
467 else: self.usage = self.usage_min
468
468
469 # Storage
469 # Storage
470 self.rc = rc # This will hold all configuration information
470 self.rc = rc # This will hold all configuration information
471 self.inputcache = []
471 self.inputcache = []
472 self._boundcache = []
472 self._boundcache = []
473 self.pager = 'less'
473 self.pager = 'less'
474 # temporary files used for various purposes. Deleted at exit.
474 # temporary files used for various purposes. Deleted at exit.
475 self.tempfiles = []
475 self.tempfiles = []
476
476
477 # Keep track of readline usage (later set by init_readline)
477 # Keep track of readline usage (later set by init_readline)
478 self.has_readline = False
478 self.has_readline = False
479
479
480 # for pushd/popd management
480 # for pushd/popd management
481 try:
481 try:
482 self.home_dir = get_home_dir()
482 self.home_dir = get_home_dir()
483 except HomeDirError,msg:
483 except HomeDirError,msg:
484 fatal(msg)
484 fatal(msg)
485
485
486 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
486 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
487
487
488 # Functions to call the underlying shell.
488 # Functions to call the underlying shell.
489
489
490 # utility to expand user variables via Itpl
490 # utility to expand user variables via Itpl
491 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
491 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
492 self.user_ns))
492 self.user_ns))
493 # The first is similar to os.system, but it doesn't return a value,
493 # The first is similar to os.system, but it doesn't return a value,
494 # and it allows interpolation of variables in the user's namespace.
494 # and it allows interpolation of variables in the user's namespace.
495 self.system = lambda cmd: shell(self.var_expand(cmd),
495 self.system = lambda cmd: shell(self.var_expand(cmd),
496 header='IPython system call: ',
496 header='IPython system call: ',
497 verbose=self.rc.system_verbose)
497 verbose=self.rc.system_verbose)
498 # These are for getoutput and getoutputerror:
498 # These are for getoutput and getoutputerror:
499 self.getoutput = lambda cmd: \
499 self.getoutput = lambda cmd: \
500 getoutput(self.var_expand(cmd),
500 getoutput(self.var_expand(cmd),
501 header='IPython system call: ',
501 header='IPython system call: ',
502 verbose=self.rc.system_verbose)
502 verbose=self.rc.system_verbose)
503 self.getoutputerror = lambda cmd: \
503 self.getoutputerror = lambda cmd: \
504 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
504 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
505 self.user_ns)),
505 self.user_ns)),
506 header='IPython system call: ',
506 header='IPython system call: ',
507 verbose=self.rc.system_verbose)
507 verbose=self.rc.system_verbose)
508
508
509 # RegExp for splitting line contents into pre-char//first
509 # RegExp for splitting line contents into pre-char//first
510 # word-method//rest. For clarity, each group in on one line.
510 # word-method//rest. For clarity, each group in on one line.
511
511
512 # WARNING: update the regexp if the above escapes are changed, as they
512 # WARNING: update the regexp if the above escapes are changed, as they
513 # are hardwired in.
513 # are hardwired in.
514
514
515 # Don't get carried away with trying to make the autocalling catch too
515 # Don't get carried away with trying to make the autocalling catch too
516 # much: it's better to be conservative rather than to trigger hidden
516 # much: it's better to be conservative rather than to trigger hidden
517 # evals() somewhere and end up causing side effects.
517 # evals() somewhere and end up causing side effects.
518
518
519 self.line_split = re.compile(r'^([\s*,;/])'
519 self.line_split = re.compile(r'^([\s*,;/])'
520 r'([\?\w\.]+\w*\s*)'
520 r'([\?\w\.]+\w*\s*)'
521 r'(\(?.*$)')
521 r'(\(?.*$)')
522
522
523 # Original re, keep around for a while in case changes break something
523 # Original re, keep around for a while in case changes break something
524 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
524 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
525 # r'(\s*[\?\w\.]+\w*\s*)'
525 # r'(\s*[\?\w\.]+\w*\s*)'
526 # r'(\(?.*$)')
526 # r'(\(?.*$)')
527
527
528 # RegExp to identify potential function names
528 # RegExp to identify potential function names
529 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
529 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
530 # RegExp to exclude strings with this start from autocalling
530 # RegExp to exclude strings with this start from autocalling
531 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
531 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
532
532
533 # try to catch also methods for stuff in lists/tuples/dicts: off
533 # try to catch also methods for stuff in lists/tuples/dicts: off
534 # (experimental). For this to work, the line_split regexp would need
534 # (experimental). For this to work, the line_split regexp would need
535 # to be modified so it wouldn't break things at '['. That line is
535 # to be modified so it wouldn't break things at '['. That line is
536 # nasty enough that I shouldn't change it until I can test it _well_.
536 # nasty enough that I shouldn't change it until I can test it _well_.
537 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
537 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
538
538
539 # keep track of where we started running (mainly for crash post-mortem)
539 # keep track of where we started running (mainly for crash post-mortem)
540 self.starting_dir = os.getcwd()
540 self.starting_dir = os.getcwd()
541
541
542 # Attributes for Logger mixin class, make defaults here
542 # Attributes for Logger mixin class, make defaults here
543 self._dolog = False
543 self._dolog = False
544 self.LOG = ''
544 self.LOG = ''
545 self.LOGDEF = '.InteractiveShell.log'
545 self.LOGDEF = '.InteractiveShell.log'
546 self.LOGMODE = 'over'
546 self.LOGMODE = 'over'
547 self.LOGHEAD = Itpl(
547 self.LOGHEAD = Itpl(
548 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
548 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
549 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
549 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
550 #log# opts = $self.rc.opts
550 #log# opts = $self.rc.opts
551 #log# args = $self.rc.args
551 #log# args = $self.rc.args
552 #log# It is safe to make manual edits below here.
552 #log# It is safe to make manual edits below here.
553 #log#-----------------------------------------------------------------------
553 #log#-----------------------------------------------------------------------
554 """)
554 """)
555 # Various switches which can be set
555 # Various switches which can be set
556 self.CACHELENGTH = 5000 # this is cheap, it's just text
556 self.CACHELENGTH = 5000 # this is cheap, it's just text
557 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
557 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
558 self.banner2 = banner2
558 self.banner2 = banner2
559
559
560 # TraceBack handlers:
560 # TraceBack handlers:
561 # Need two, one for syntax errors and one for other exceptions.
561 # Need two, one for syntax errors and one for other exceptions.
562 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
562 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
563 # The interactive one is initialized with an offset, meaning we always
563 # The interactive one is initialized with an offset, meaning we always
564 # want to remove the topmost item in the traceback, which is our own
564 # want to remove the topmost item in the traceback, which is our own
565 # internal code. Valid modes: ['Plain','Context','Verbose']
565 # internal code. Valid modes: ['Plain','Context','Verbose']
566 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
566 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
567 color_scheme='NoColor',
567 color_scheme='NoColor',
568 tb_offset = 1)
568 tb_offset = 1)
569 # and add any custom exception handlers the user may have specified
569 # and add any custom exception handlers the user may have specified
570 self.set_custom_exc(*custom_exceptions)
570 self.set_custom_exc(*custom_exceptions)
571
571
572 # Object inspector
572 # Object inspector
573 self.inspector = OInspect.Inspector(OInspect.InspectColors,
573 self.inspector = OInspect.Inspector(OInspect.InspectColors,
574 PyColorize.ANSICodeColors,
574 PyColorize.ANSICodeColors,
575 'NoColor')
575 'NoColor')
576 # indentation management
576 # indentation management
577 self.autoindent = False
577 self.autoindent = False
578 self.indent_current_nsp = 0
578 self.indent_current_nsp = 0
579 self.indent_current = '' # actual indent string
579 self.indent_current = '' # actual indent string
580
580
581 # Make some aliases automatically
581 # Make some aliases automatically
582 # Prepare list of shell aliases to auto-define
582 # Prepare list of shell aliases to auto-define
583 if os.name == 'posix':
583 if os.name == 'posix':
584 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
584 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
585 'mv mv -i','rm rm -i','cp cp -i',
585 'mv mv -i','rm rm -i','cp cp -i',
586 'cat cat','less less','clear clear',
586 'cat cat','less less','clear clear',
587 # a better ls
587 # a better ls
588 'ls ls -F',
588 'ls ls -F',
589 # long ls
589 # long ls
590 'll ls -lF',
590 'll ls -lF',
591 # color ls
591 # color ls
592 'lc ls -F -o --color',
592 'lc ls -F -o --color',
593 # ls normal files only
593 # ls normal files only
594 'lf ls -F -o --color %l | grep ^-',
594 'lf ls -F -o --color %l | grep ^-',
595 # ls symbolic links
595 # ls symbolic links
596 'lk ls -F -o --color %l | grep ^l',
596 'lk ls -F -o --color %l | grep ^l',
597 # directories or links to directories,
597 # directories or links to directories,
598 'ldir ls -F -o --color %l | grep /$',
598 'ldir ls -F -o --color %l | grep /$',
599 # things which are executable
599 # things which are executable
600 'lx ls -F -o --color %l | grep ^-..x',
600 'lx ls -F -o --color %l | grep ^-..x',
601 )
601 )
602 elif os.name in ['nt','dos']:
602 elif os.name in ['nt','dos']:
603 auto_alias = ('dir dir /on', 'ls dir /on',
603 auto_alias = ('dir dir /on', 'ls dir /on',
604 'ddir dir /ad /on', 'ldir dir /ad /on',
604 'ddir dir /ad /on', 'ldir dir /ad /on',
605 'mkdir mkdir','rmdir rmdir','echo echo',
605 'mkdir mkdir','rmdir rmdir','echo echo',
606 'ren ren','cls cls','copy copy')
606 'ren ren','cls cls','copy copy')
607 else:
607 else:
608 auto_alias = ()
608 auto_alias = ()
609 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
609 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
610 # Call the actual (public) initializer
610 # Call the actual (public) initializer
611 self.init_auto_alias()
611 self.init_auto_alias()
612 # end __init__
612 # end __init__
613
613
614 def set_hook(self,name,hook):
614 def set_hook(self,name,hook):
615 """set_hook(name,hook) -> sets an internal IPython hook.
615 """set_hook(name,hook) -> sets an internal IPython hook.
616
616
617 IPython exposes some of its internal API as user-modifiable hooks. By
617 IPython exposes some of its internal API as user-modifiable hooks. By
618 resetting one of these hooks, you can modify IPython's behavior to
618 resetting one of these hooks, you can modify IPython's behavior to
619 call at runtime your own routines."""
619 call at runtime your own routines."""
620
620
621 # At some point in the future, this should validate the hook before it
621 # At some point in the future, this should validate the hook before it
622 # accepts it. Probably at least check that the hook takes the number
622 # accepts it. Probably at least check that the hook takes the number
623 # of args it's supposed to.
623 # of args it's supposed to.
624 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
624 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
625
625
626 def set_custom_exc(self,exc_tuple,handler):
626 def set_custom_exc(self,exc_tuple,handler):
627 """set_custom_exc(exc_tuple,handler)
627 """set_custom_exc(exc_tuple,handler)
628
628
629 Set a custom exception handler, which will be called if any of the
629 Set a custom exception handler, which will be called if any of the
630 exceptions in exc_tuple occur in the mainloop (specifically, in the
630 exceptions in exc_tuple occur in the mainloop (specifically, in the
631 runcode() method.
631 runcode() method.
632
632
633 Inputs:
633 Inputs:
634
634
635 - exc_tuple: a *tuple* of valid exceptions to call the defined
635 - exc_tuple: a *tuple* of valid exceptions to call the defined
636 handler for. It is very important that you use a tuple, and NOT A
636 handler for. It is very important that you use a tuple, and NOT A
637 LIST here, because of the way Python's except statement works. If
637 LIST here, because of the way Python's except statement works. If
638 you only want to trap a single exception, use a singleton tuple:
638 you only want to trap a single exception, use a singleton tuple:
639
639
640 exc_tuple == (MyCustomException,)
640 exc_tuple == (MyCustomException,)
641
641
642 - handler: this must be defined as a function with the following
642 - handler: this must be defined as a function with the following
643 basic interface: def my_handler(self,etype,value,tb).
643 basic interface: def my_handler(self,etype,value,tb).
644
644
645 This will be made into an instance method (via new.instancemethod)
645 This will be made into an instance method (via new.instancemethod)
646 of IPython itself, and it will be called if any of the exceptions
646 of IPython itself, and it will be called if any of the exceptions
647 listed in the exc_tuple are caught. If the handler is None, an
647 listed in the exc_tuple are caught. If the handler is None, an
648 internal basic one is used, which just prints basic info.
648 internal basic one is used, which just prints basic info.
649
649
650 WARNING: by putting in your own exception handler into IPython's main
650 WARNING: by putting in your own exception handler into IPython's main
651 execution loop, you run a very good chance of nasty crashes. This
651 execution loop, you run a very good chance of nasty crashes. This
652 facility should only be used if you really know what you are doing."""
652 facility should only be used if you really know what you are doing."""
653
653
654 assert type(exc_tuple)==type(()) , \
654 assert type(exc_tuple)==type(()) , \
655 "The custom exceptions must be given AS A TUPLE."
655 "The custom exceptions must be given AS A TUPLE."
656
656
657 def dummy_handler(self,etype,value,tb):
657 def dummy_handler(self,etype,value,tb):
658 print '*** Simple custom exception handler ***'
658 print '*** Simple custom exception handler ***'
659 print 'Exception type :',etype
659 print 'Exception type :',etype
660 print 'Exception value:',value
660 print 'Exception value:',value
661 print 'Traceback :',tb
661 print 'Traceback :',tb
662 print 'Source code :','\n'.join(self.buffer)
662 print 'Source code :','\n'.join(self.buffer)
663
663
664 if handler is None: handler = dummy_handler
664 if handler is None: handler = dummy_handler
665
665
666 self.CustomTB = new.instancemethod(handler,self,self.__class__)
666 self.CustomTB = new.instancemethod(handler,self,self.__class__)
667 self.custom_exceptions = exc_tuple
667 self.custom_exceptions = exc_tuple
668
668
669 def set_custom_completer(self,completer,pos=0):
669 def set_custom_completer(self,completer,pos=0):
670 """set_custom_completer(completer,pos=0)
670 """set_custom_completer(completer,pos=0)
671
671
672 Adds a new custom completer function.
672 Adds a new custom completer function.
673
673
674 The position argument (defaults to 0) is the index in the completers
674 The position argument (defaults to 0) is the index in the completers
675 list where you want the completer to be inserted."""
675 list where you want the completer to be inserted."""
676
676
677 newcomp = new.instancemethod(completer,self.Completer,
677 newcomp = new.instancemethod(completer,self.Completer,
678 self.Completer.__class__)
678 self.Completer.__class__)
679 self.Completer.matchers.insert(pos,newcomp)
679 self.Completer.matchers.insert(pos,newcomp)
680
680
681 def complete(self,text):
681 def complete(self,text):
682 """Return a sorted list of all possible completions on text.
682 """Return a sorted list of all possible completions on text.
683
683
684 Inputs:
684 Inputs:
685
685
686 - text: a string of text to be completed on.
686 - text: a string of text to be completed on.
687
687
688 This is a wrapper around the completion mechanism, similar to what
688 This is a wrapper around the completion mechanism, similar to what
689 readline does at the command line when the TAB key is hit. By
689 readline does at the command line when the TAB key is hit. By
690 exposing it as a method, it can be used by other non-readline
690 exposing it as a method, it can be used by other non-readline
691 environments (such as GUIs) for text completion.
691 environments (such as GUIs) for text completion.
692
692
693 Simple usage example:
693 Simple usage example:
694
694
695 In [1]: x = 'hello'
695 In [1]: x = 'hello'
696
696
697 In [2]: __IP.complete('x.l')
697 In [2]: __IP.complete('x.l')
698 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
698 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
699
699
700 complete = self.Completer.complete
700 complete = self.Completer.complete
701 state = 0
701 state = 0
702 # use a dict so we get unique keys, since ipyhton's multiple
702 # use a dict so we get unique keys, since ipyhton's multiple
703 # completers can return duplicates.
703 # completers can return duplicates.
704 comps = {}
704 comps = {}
705 while True:
705 while True:
706 newcomp = complete(text,state)
706 newcomp = complete(text,state)
707 if newcomp is None:
707 if newcomp is None:
708 break
708 break
709 comps[newcomp] = 1
709 comps[newcomp] = 1
710 state += 1
710 state += 1
711 outcomps = comps.keys()
711 outcomps = comps.keys()
712 outcomps.sort()
712 outcomps.sort()
713 return outcomps
713 return outcomps
714
714
715 def set_completer_frame(self, frame):
715 def set_completer_frame(self, frame):
716 if frame:
716 if frame:
717 self.Completer.namespace = frame.f_locals
717 self.Completer.namespace = frame.f_locals
718 self.Completer.global_namespace = frame.f_globals
718 self.Completer.global_namespace = frame.f_globals
719 else:
719 else:
720 self.Completer.namespace = self.user_ns
720 self.Completer.namespace = self.user_ns
721 self.Completer.global_namespace = self.user_global_ns
721 self.Completer.global_namespace = self.user_global_ns
722
722
723 def post_config_initialization(self):
723 def post_config_initialization(self):
724 """Post configuration init method
724 """Post configuration init method
725
725
726 This is called after the configuration files have been processed to
726 This is called after the configuration files have been processed to
727 'finalize' the initialization."""
727 'finalize' the initialization."""
728
728
729 rc = self.rc
729 rc = self.rc
730
730
731 # Load readline proper
731 # Load readline proper
732 if rc.readline:
732 if rc.readline:
733 self.init_readline()
733 self.init_readline()
734
734
735 # Set user colors (don't do it in the constructor above so that it
735 # Set user colors (don't do it in the constructor above so that it
736 # doesn't crash if colors option is invalid)
736 # doesn't crash if colors option is invalid)
737 self.magic_colors(rc.colors)
737 self.magic_colors(rc.colors)
738
738
739 # Load user aliases
739 # Load user aliases
740 for alias in rc.alias:
740 for alias in rc.alias:
741 self.magic_alias(alias)
741 self.magic_alias(alias)
742
742
743 # dynamic data that survives through sessions
743 # dynamic data that survives through sessions
744 # XXX make the filename a config option?
744 # XXX make the filename a config option?
745 persist_base = 'persist'
745 persist_base = 'persist'
746 if rc.profile:
746 if rc.profile:
747 persist_base += '_%s' % rc.profile
747 persist_base += '_%s' % rc.profile
748 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
748 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
749
749
750 try:
750 try:
751 self.persist = pickle.load(file(self.persist_fname))
751 self.persist = pickle.load(file(self.persist_fname))
752 except:
752 except:
753 self.persist = {}
753 self.persist = {}
754
754
755 def init_auto_alias(self):
755 def init_auto_alias(self):
756 """Define some aliases automatically.
756 """Define some aliases automatically.
757
757
758 These are ALL parameter-less aliases"""
758 These are ALL parameter-less aliases"""
759 for alias,cmd in self.auto_alias:
759 for alias,cmd in self.auto_alias:
760 self.alias_table[alias] = (0,cmd)
760 self.alias_table[alias] = (0,cmd)
761
761
762 def alias_table_validate(self,verbose=0):
762 def alias_table_validate(self,verbose=0):
763 """Update information about the alias table.
763 """Update information about the alias table.
764
764
765 In particular, make sure no Python keywords/builtins are in it."""
765 In particular, make sure no Python keywords/builtins are in it."""
766
766
767 no_alias = self.no_alias
767 no_alias = self.no_alias
768 for k in self.alias_table.keys():
768 for k in self.alias_table.keys():
769 if k in no_alias:
769 if k in no_alias:
770 del self.alias_table[k]
770 del self.alias_table[k]
771 if verbose:
771 if verbose:
772 print ("Deleting alias <%s>, it's a Python "
772 print ("Deleting alias <%s>, it's a Python "
773 "keyword or builtin." % k)
773 "keyword or builtin." % k)
774
774
775 def set_autoindent(self,value=None):
775 def set_autoindent(self,value=None):
776 """Set the autoindent flag, checking for readline support.
776 """Set the autoindent flag, checking for readline support.
777
777
778 If called with no arguments, it acts as a toggle."""
778 If called with no arguments, it acts as a toggle."""
779
779
780 if not self.has_readline:
780 if not self.has_readline:
781 if os.name == 'posix':
781 if os.name == 'posix':
782 warn("The auto-indent feature requires the readline library")
782 warn("The auto-indent feature requires the readline library")
783 self.autoindent = 0
783 self.autoindent = 0
784 return
784 return
785 if value is None:
785 if value is None:
786 self.autoindent = not self.autoindent
786 self.autoindent = not self.autoindent
787 else:
787 else:
788 self.autoindent = value
788 self.autoindent = value
789
789
790 def rc_set_toggle(self,rc_field,value=None):
790 def rc_set_toggle(self,rc_field,value=None):
791 """Set or toggle a field in IPython's rc config. structure.
791 """Set or toggle a field in IPython's rc config. structure.
792
792
793 If called with no arguments, it acts as a toggle.
793 If called with no arguments, it acts as a toggle.
794
794
795 If called with a non-existent field, the resulting AttributeError
795 If called with a non-existent field, the resulting AttributeError
796 exception will propagate out."""
796 exception will propagate out."""
797
797
798 rc_val = getattr(self.rc,rc_field)
798 rc_val = getattr(self.rc,rc_field)
799 if value is None:
799 if value is None:
800 value = not rc_val
800 value = not rc_val
801 setattr(self.rc,rc_field,value)
801 setattr(self.rc,rc_field,value)
802
802
803 def user_setup(self,ipythondir,rc_suffix,mode='install'):
803 def user_setup(self,ipythondir,rc_suffix,mode='install'):
804 """Install the user configuration directory.
804 """Install the user configuration directory.
805
805
806 Can be called when running for the first time or to upgrade the user's
806 Can be called when running for the first time or to upgrade the user's
807 .ipython/ directory with the mode parameter. Valid modes are 'install'
807 .ipython/ directory with the mode parameter. Valid modes are 'install'
808 and 'upgrade'."""
808 and 'upgrade'."""
809
809
810 def wait():
810 def wait():
811 try:
811 try:
812 raw_input("Please press <RETURN> to start IPython.")
812 raw_input("Please press <RETURN> to start IPython.")
813 except EOFError:
813 except EOFError:
814 print >> Term.cout
814 print >> Term.cout
815 print '*'*70
815 print '*'*70
816
816
817 cwd = os.getcwd() # remember where we started
817 cwd = os.getcwd() # remember where we started
818 glb = glob.glob
818 glb = glob.glob
819 print '*'*70
819 print '*'*70
820 if mode == 'install':
820 if mode == 'install':
821 print \
821 print \
822 """Welcome to IPython. I will try to create a personal configuration directory
822 """Welcome to IPython. I will try to create a personal configuration directory
823 where you can customize many aspects of IPython's functionality in:\n"""
823 where you can customize many aspects of IPython's functionality in:\n"""
824 else:
824 else:
825 print 'I am going to upgrade your configuration in:'
825 print 'I am going to upgrade your configuration in:'
826
826
827 print ipythondir
827 print ipythondir
828
828
829 rcdirend = os.path.join('IPython','UserConfig')
829 rcdirend = os.path.join('IPython','UserConfig')
830 cfg = lambda d: os.path.join(d,rcdirend)
830 cfg = lambda d: os.path.join(d,rcdirend)
831 try:
831 try:
832 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
832 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
833 except IOError:
833 except IOError:
834 warning = """
834 warning = """
835 Installation error. IPython's directory was not found.
835 Installation error. IPython's directory was not found.
836
836
837 Check the following:
837 Check the following:
838
838
839 The ipython/IPython directory should be in a directory belonging to your
839 The ipython/IPython directory should be in a directory belonging to your
840 PYTHONPATH environment variable (that is, it should be in a directory
840 PYTHONPATH environment variable (that is, it should be in a directory
841 belonging to sys.path). You can copy it explicitly there or just link to it.
841 belonging to sys.path). You can copy it explicitly there or just link to it.
842
842
843 IPython will proceed with builtin defaults.
843 IPython will proceed with builtin defaults.
844 """
844 """
845 warn(warning)
845 warn(warning)
846 wait()
846 wait()
847 return
847 return
848
848
849 if mode == 'install':
849 if mode == 'install':
850 try:
850 try:
851 shutil.copytree(rcdir,ipythondir)
851 shutil.copytree(rcdir,ipythondir)
852 os.chdir(ipythondir)
852 os.chdir(ipythondir)
853 rc_files = glb("ipythonrc*")
853 rc_files = glb("ipythonrc*")
854 for rc_file in rc_files:
854 for rc_file in rc_files:
855 os.rename(rc_file,rc_file+rc_suffix)
855 os.rename(rc_file,rc_file+rc_suffix)
856 except:
856 except:
857 warning = """
857 warning = """
858
858
859 There was a problem with the installation:
859 There was a problem with the installation:
860 %s
860 %s
861 Try to correct it or contact the developers if you think it's a bug.
861 Try to correct it or contact the developers if you think it's a bug.
862 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
862 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
863 warn(warning)
863 warn(warning)
864 wait()
864 wait()
865 return
865 return
866
866
867 elif mode == 'upgrade':
867 elif mode == 'upgrade':
868 try:
868 try:
869 os.chdir(ipythondir)
869 os.chdir(ipythondir)
870 except:
870 except:
871 print """
871 print """
872 Can not upgrade: changing to directory %s failed. Details:
872 Can not upgrade: changing to directory %s failed. Details:
873 %s
873 %s
874 """ % (ipythondir,sys.exc_info()[1])
874 """ % (ipythondir,sys.exc_info()[1])
875 wait()
875 wait()
876 return
876 return
877 else:
877 else:
878 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
878 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
879 for new_full_path in sources:
879 for new_full_path in sources:
880 new_filename = os.path.basename(new_full_path)
880 new_filename = os.path.basename(new_full_path)
881 if new_filename.startswith('ipythonrc'):
881 if new_filename.startswith('ipythonrc'):
882 new_filename = new_filename + rc_suffix
882 new_filename = new_filename + rc_suffix
883 # The config directory should only contain files, skip any
883 # The config directory should only contain files, skip any
884 # directories which may be there (like CVS)
884 # directories which may be there (like CVS)
885 if os.path.isdir(new_full_path):
885 if os.path.isdir(new_full_path):
886 continue
886 continue
887 if os.path.exists(new_filename):
887 if os.path.exists(new_filename):
888 old_file = new_filename+'.old'
888 old_file = new_filename+'.old'
889 if os.path.exists(old_file):
889 if os.path.exists(old_file):
890 os.remove(old_file)
890 os.remove(old_file)
891 os.rename(new_filename,old_file)
891 os.rename(new_filename,old_file)
892 shutil.copy(new_full_path,new_filename)
892 shutil.copy(new_full_path,new_filename)
893 else:
893 else:
894 raise ValueError,'unrecognized mode for install:',`mode`
894 raise ValueError,'unrecognized mode for install:',`mode`
895
895
896 # Fix line-endings to those native to each platform in the config
896 # Fix line-endings to those native to each platform in the config
897 # directory.
897 # directory.
898 try:
898 try:
899 os.chdir(ipythondir)
899 os.chdir(ipythondir)
900 except:
900 except:
901 print """
901 print """
902 Problem: changing to directory %s failed.
902 Problem: changing to directory %s failed.
903 Details:
903 Details:
904 %s
904 %s
905
905
906 Some configuration files may have incorrect line endings. This should not
906 Some configuration files may have incorrect line endings. This should not
907 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
907 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
908 wait()
908 wait()
909 else:
909 else:
910 for fname in glb('ipythonrc*'):
910 for fname in glb('ipythonrc*'):
911 try:
911 try:
912 native_line_ends(fname,backup=0)
912 native_line_ends(fname,backup=0)
913 except IOError:
913 except IOError:
914 pass
914 pass
915
915
916 if mode == 'install':
916 if mode == 'install':
917 print """
917 print """
918 Successful installation!
918 Successful installation!
919
919
920 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
920 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
921 IPython manual (there are both HTML and PDF versions supplied with the
921 IPython manual (there are both HTML and PDF versions supplied with the
922 distribution) to make sure that your system environment is properly configured
922 distribution) to make sure that your system environment is properly configured
923 to take advantage of IPython's features."""
923 to take advantage of IPython's features."""
924 else:
924 else:
925 print """
925 print """
926 Successful upgrade!
926 Successful upgrade!
927
927
928 All files in your directory:
928 All files in your directory:
929 %(ipythondir)s
929 %(ipythondir)s
930 which would have been overwritten by the upgrade were backed up with a .old
930 which would have been overwritten by the upgrade were backed up with a .old
931 extension. If you had made particular customizations in those files you may
931 extension. If you had made particular customizations in those files you may
932 want to merge them back into the new files.""" % locals()
932 want to merge them back into the new files.""" % locals()
933 wait()
933 wait()
934 os.chdir(cwd)
934 os.chdir(cwd)
935 # end user_setup()
935 # end user_setup()
936
936
937 def atexit_operations(self):
937 def atexit_operations(self):
938 """This will be executed at the time of exit.
938 """This will be executed at the time of exit.
939
939
940 Saving of persistent data should be performed here. """
940 Saving of persistent data should be performed here. """
941
941
942 # input history
942 # input history
943 self.savehist()
943 self.savehist()
944
944
945 # Cleanup all tempfiles left around
945 # Cleanup all tempfiles left around
946 for tfile in self.tempfiles:
946 for tfile in self.tempfiles:
947 try:
947 try:
948 os.unlink(tfile)
948 os.unlink(tfile)
949 except OSError:
949 except OSError:
950 pass
950 pass
951
951
952 # save the "persistent data" catch-all dictionary
952 # save the "persistent data" catch-all dictionary
953 try:
953 try:
954 pickle.dump(self.persist, open(self.persist_fname,"w"))
954 pickle.dump(self.persist, open(self.persist_fname,"w"))
955 except:
955 except:
956 print "*** ERROR *** persistent data saving failed."
956 print "*** ERROR *** persistent data saving failed."
957
957
958 def savehist(self):
958 def savehist(self):
959 """Save input history to a file (via readline library)."""
959 """Save input history to a file (via readline library)."""
960 try:
960 try:
961 self.readline.write_history_file(self.histfile)
961 self.readline.write_history_file(self.histfile)
962 except:
962 except:
963 print 'Unable to save IPython command history to file: ' + \
963 print 'Unable to save IPython command history to file: ' + \
964 `self.histfile`
964 `self.histfile`
965
965
966 def pre_readline(self):
966 def pre_readline(self):
967 """readline hook to be used at the start of each line.
967 """readline hook to be used at the start of each line.
968
968
969 Currently it handles auto-indent only."""
969 Currently it handles auto-indent only."""
970
970
971 self.readline.insert_text(self.indent_current)
971 self.readline.insert_text(self.indent_current)
972
972
973 def init_readline(self):
973 def init_readline(self):
974 """Command history completion/saving/reloading."""
974 """Command history completion/saving/reloading."""
975 try:
975 try:
976 import readline
976 import readline
977 except ImportError:
977 except ImportError:
978 self.has_readline = 0
978 self.has_readline = 0
979 self.readline = None
979 self.readline = None
980 # no point in bugging windows users with this every time:
980 # no point in bugging windows users with this every time:
981 if os.name == 'posix':
981 if os.name == 'posix':
982 warn('Readline services not available on this platform.')
982 warn('Readline services not available on this platform.')
983 else:
983 else:
984 import atexit
984 import atexit
985 from IPython.completer import IPCompleter
985 from IPython.completer import IPCompleter
986 self.Completer = IPCompleter(self,
986 self.Completer = IPCompleter(self,
987 self.user_ns,
987 self.user_ns,
988 self.user_global_ns,
988 self.user_global_ns,
989 self.rc.readline_omit__names,
989 self.rc.readline_omit__names,
990 self.alias_table)
990 self.alias_table)
991
991
992 # Platform-specific configuration
992 # Platform-specific configuration
993 if os.name == 'nt':
993 if os.name == 'nt':
994 self.readline_startup_hook = readline.set_pre_input_hook
994 self.readline_startup_hook = readline.set_pre_input_hook
995 else:
995 else:
996 self.readline_startup_hook = readline.set_startup_hook
996 self.readline_startup_hook = readline.set_startup_hook
997
997
998 # Load user's initrc file (readline config)
998 # Load user's initrc file (readline config)
999 inputrc_name = os.environ.get('INPUTRC')
999 inputrc_name = os.environ.get('INPUTRC')
1000 if inputrc_name is None:
1000 if inputrc_name is None:
1001 home_dir = get_home_dir()
1001 home_dir = get_home_dir()
1002 if home_dir is not None:
1002 if home_dir is not None:
1003 inputrc_name = os.path.join(home_dir,'.inputrc')
1003 inputrc_name = os.path.join(home_dir,'.inputrc')
1004 if os.path.isfile(inputrc_name):
1004 if os.path.isfile(inputrc_name):
1005 try:
1005 try:
1006 readline.read_init_file(inputrc_name)
1006 readline.read_init_file(inputrc_name)
1007 except:
1007 except:
1008 warn('Problems reading readline initialization file <%s>'
1008 warn('Problems reading readline initialization file <%s>'
1009 % inputrc_name)
1009 % inputrc_name)
1010
1010
1011 self.has_readline = 1
1011 self.has_readline = 1
1012 self.readline = readline
1012 self.readline = readline
1013 # save this in sys so embedded copies can restore it properly
1013 # save this in sys so embedded copies can restore it properly
1014 sys.ipcompleter = self.Completer.complete
1014 sys.ipcompleter = self.Completer.complete
1015 readline.set_completer(self.Completer.complete)
1015 readline.set_completer(self.Completer.complete)
1016
1016
1017 # Configure readline according to user's prefs
1017 # Configure readline according to user's prefs
1018 for rlcommand in self.rc.readline_parse_and_bind:
1018 for rlcommand in self.rc.readline_parse_and_bind:
1019 readline.parse_and_bind(rlcommand)
1019 readline.parse_and_bind(rlcommand)
1020
1020
1021 # remove some chars from the delimiters list
1021 # remove some chars from the delimiters list
1022 delims = readline.get_completer_delims()
1022 delims = readline.get_completer_delims()
1023 delims = delims.translate(string._idmap,
1023 delims = delims.translate(string._idmap,
1024 self.rc.readline_remove_delims)
1024 self.rc.readline_remove_delims)
1025 readline.set_completer_delims(delims)
1025 readline.set_completer_delims(delims)
1026 # otherwise we end up with a monster history after a while:
1026 # otherwise we end up with a monster history after a while:
1027 readline.set_history_length(1000)
1027 readline.set_history_length(1000)
1028 try:
1028 try:
1029 #print '*** Reading readline history' # dbg
1029 #print '*** Reading readline history' # dbg
1030 readline.read_history_file(self.histfile)
1030 readline.read_history_file(self.histfile)
1031 except IOError:
1031 except IOError:
1032 pass # It doesn't exist yet.
1032 pass # It doesn't exist yet.
1033
1033
1034 atexit.register(self.atexit_operations)
1034 atexit.register(self.atexit_operations)
1035 del atexit
1035 del atexit
1036
1036
1037 # Configure auto-indent for all platforms
1037 # Configure auto-indent for all platforms
1038 self.set_autoindent(self.rc.autoindent)
1038 self.set_autoindent(self.rc.autoindent)
1039
1039
1040 def _should_recompile(self,e):
1040 def _should_recompile(self,e):
1041 """Utility routine for edit_syntax_error"""
1041 """Utility routine for edit_syntax_error"""
1042
1042
1043 if e.filename in ('<ipython console>','<input>','<string>',
1043 if e.filename in ('<ipython console>','<input>','<string>',
1044 '<console>'):
1044 '<console>'):
1045 return False
1045 return False
1046 try:
1046 try:
1047 if not ask_yes_no('Return to editor to correct syntax error? '
1047 if not ask_yes_no('Return to editor to correct syntax error? '
1048 '[Y/n] ','y'):
1048 '[Y/n] ','y'):
1049 return False
1049 return False
1050 except EOFError:
1050 except EOFError:
1051 return False
1051 return False
1052 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1052 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1053 return True
1053 return True
1054
1054
1055 def edit_syntax_error(self):
1055 def edit_syntax_error(self):
1056 """The bottom half of the syntax error handler called in the main loop.
1056 """The bottom half of the syntax error handler called in the main loop.
1057
1057
1058 Loop until syntax error is fixed or user cancels.
1058 Loop until syntax error is fixed or user cancels.
1059 """
1059 """
1060
1060
1061 while self.SyntaxTB.last_syntax_error:
1061 while self.SyntaxTB.last_syntax_error:
1062 # copy and clear last_syntax_error
1062 # copy and clear last_syntax_error
1063 err = self.SyntaxTB.clear_err_state()
1063 err = self.SyntaxTB.clear_err_state()
1064 if not self._should_recompile(err):
1064 if not self._should_recompile(err):
1065 return
1065 return
1066 try:
1066 try:
1067 # may set last_syntax_error again if a SyntaxError is raised
1067 # may set last_syntax_error again if a SyntaxError is raised
1068 self.safe_execfile(err.filename,self.shell.user_ns)
1068 self.safe_execfile(err.filename,self.shell.user_ns)
1069 except:
1069 except:
1070 self.showtraceback()
1070 self.showtraceback()
1071 else:
1071 else:
1072 f = file(err.filename)
1072 f = file(err.filename)
1073 try:
1073 try:
1074 sys.displayhook(f.read())
1074 sys.displayhook(f.read())
1075 finally:
1075 finally:
1076 f.close()
1076 f.close()
1077
1077
1078 def showsyntaxerror(self, filename=None):
1078 def showsyntaxerror(self, filename=None):
1079 """Display the syntax error that just occurred.
1079 """Display the syntax error that just occurred.
1080
1080
1081 This doesn't display a stack trace because there isn't one.
1081 This doesn't display a stack trace because there isn't one.
1082
1082
1083 If a filename is given, it is stuffed in the exception instead
1083 If a filename is given, it is stuffed in the exception instead
1084 of what was there before (because Python's parser always uses
1084 of what was there before (because Python's parser always uses
1085 "<string>" when reading from a string).
1085 "<string>" when reading from a string).
1086 """
1086 """
1087 type, value, sys.last_traceback = sys.exc_info()
1087 type, value, sys.last_traceback = sys.exc_info()
1088 sys.last_type = type
1088 sys.last_type = type
1089 sys.last_value = value
1089 sys.last_value = value
1090 if filename and type is SyntaxError:
1090 if filename and type is SyntaxError:
1091 # Work hard to stuff the correct filename in the exception
1091 # Work hard to stuff the correct filename in the exception
1092 try:
1092 try:
1093 msg, (dummy_filename, lineno, offset, line) = value
1093 msg, (dummy_filename, lineno, offset, line) = value
1094 except:
1094 except:
1095 # Not the format we expect; leave it alone
1095 # Not the format we expect; leave it alone
1096 pass
1096 pass
1097 else:
1097 else:
1098 # Stuff in the right filename
1098 # Stuff in the right filename
1099 try:
1099 try:
1100 # Assume SyntaxError is a class exception
1100 # Assume SyntaxError is a class exception
1101 value = SyntaxError(msg, (filename, lineno, offset, line))
1101 value = SyntaxError(msg, (filename, lineno, offset, line))
1102 except:
1102 except:
1103 # If that failed, assume SyntaxError is a string
1103 # If that failed, assume SyntaxError is a string
1104 value = msg, (filename, lineno, offset, line)
1104 value = msg, (filename, lineno, offset, line)
1105 self.SyntaxTB(type,value,[])
1105 self.SyntaxTB(type,value,[])
1106
1106
1107 def debugger(self):
1107 def debugger(self):
1108 """Call the pdb debugger."""
1108 """Call the pdb debugger."""
1109
1109
1110 if not self.rc.pdb:
1110 if not self.rc.pdb:
1111 return
1111 return
1112 pdb.pm()
1112 pdb.pm()
1113
1113
1114 def showtraceback(self,exc_tuple = None,filename=None):
1114 def showtraceback(self,exc_tuple = None,filename=None):
1115 """Display the exception that just occurred."""
1115 """Display the exception that just occurred."""
1116
1116
1117 # Though this won't be called by syntax errors in the input line,
1117 # Though this won't be called by syntax errors in the input line,
1118 # there may be SyntaxError cases whith imported code.
1118 # there may be SyntaxError cases whith imported code.
1119 if exc_tuple is None:
1119 if exc_tuple is None:
1120 type, value, tb = sys.exc_info()
1120 type, value, tb = sys.exc_info()
1121 else:
1121 else:
1122 type, value, tb = exc_tuple
1122 type, value, tb = exc_tuple
1123 if type is SyntaxError:
1123 if type is SyntaxError:
1124 self.showsyntaxerror(filename)
1124 self.showsyntaxerror(filename)
1125 else:
1125 else:
1126 sys.last_type = type
1126 sys.last_type = type
1127 sys.last_value = value
1127 sys.last_value = value
1128 sys.last_traceback = tb
1128 sys.last_traceback = tb
1129 self.InteractiveTB()
1129 self.InteractiveTB()
1130 if self.InteractiveTB.call_pdb and self.has_readline:
1130 if self.InteractiveTB.call_pdb and self.has_readline:
1131 # pdb mucks up readline, fix it back
1131 # pdb mucks up readline, fix it back
1132 self.readline.set_completer(self.Completer.complete)
1132 self.readline.set_completer(self.Completer.complete)
1133
1133
1134 def update_cache(self, line):
1134 def update_cache(self, line):
1135 """puts line into cache"""
1135 """puts line into cache"""
1136 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1136 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1137 if len(self.inputcache) >= self.CACHELENGTH:
1137 if len(self.inputcache) >= self.CACHELENGTH:
1138 self.inputcache.pop() # This doesn't :-)
1138 self.inputcache.pop() # This doesn't :-)
1139
1139
1140 def mainloop(self,banner=None):
1140 def mainloop(self,banner=None):
1141 """Creates the local namespace and starts the mainloop.
1141 """Creates the local namespace and starts the mainloop.
1142
1142
1143 If an optional banner argument is given, it will override the
1143 If an optional banner argument is given, it will override the
1144 internally created default banner."""
1144 internally created default banner."""
1145
1145
1146 if self.rc.c: # Emulate Python's -c option
1146 if self.rc.c: # Emulate Python's -c option
1147 self.exec_init_cmd()
1147 self.exec_init_cmd()
1148 if banner is None:
1148 if banner is None:
1149 if self.rc.banner:
1149 if self.rc.banner:
1150 banner = self.BANNER+self.banner2
1150 banner = self.BANNER+self.banner2
1151 else:
1151 else:
1152 banner = ''
1152 banner = ''
1153 self.interact(banner)
1153 self.interact(banner)
1154
1154
1155 def exec_init_cmd(self):
1155 def exec_init_cmd(self):
1156 """Execute a command given at the command line.
1156 """Execute a command given at the command line.
1157
1157
1158 This emulates Python's -c option."""
1158 This emulates Python's -c option."""
1159
1159
1160 sys.argv = ['-c']
1160 sys.argv = ['-c']
1161 self.push(self.rc.c)
1161 self.push(self.rc.c)
1162
1162
1163 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1163 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1164 """Embeds IPython into a running python program.
1164 """Embeds IPython into a running python program.
1165
1165
1166 Input:
1166 Input:
1167
1167
1168 - header: An optional header message can be specified.
1168 - header: An optional header message can be specified.
1169
1169
1170 - local_ns, global_ns: working namespaces. If given as None, the
1170 - local_ns, global_ns: working namespaces. If given as None, the
1171 IPython-initialized one is updated with __main__.__dict__, so that
1171 IPython-initialized one is updated with __main__.__dict__, so that
1172 program variables become visible but user-specific configuration
1172 program variables become visible but user-specific configuration
1173 remains possible.
1173 remains possible.
1174
1174
1175 - stack_depth: specifies how many levels in the stack to go to
1175 - stack_depth: specifies how many levels in the stack to go to
1176 looking for namespaces (when local_ns and global_ns are None). This
1176 looking for namespaces (when local_ns and global_ns are None). This
1177 allows an intermediate caller to make sure that this function gets
1177 allows an intermediate caller to make sure that this function gets
1178 the namespace from the intended level in the stack. By default (0)
1178 the namespace from the intended level in the stack. By default (0)
1179 it will get its locals and globals from the immediate caller.
1179 it will get its locals and globals from the immediate caller.
1180
1180
1181 Warning: it's possible to use this in a program which is being run by
1181 Warning: it's possible to use this in a program which is being run by
1182 IPython itself (via %run), but some funny things will happen (a few
1182 IPython itself (via %run), but some funny things will happen (a few
1183 globals get overwritten). In the future this will be cleaned up, as
1183 globals get overwritten). In the future this will be cleaned up, as
1184 there is no fundamental reason why it can't work perfectly."""
1184 there is no fundamental reason why it can't work perfectly."""
1185
1185
1186 # Get locals and globals from caller
1186 # Get locals and globals from caller
1187 if local_ns is None or global_ns is None:
1187 if local_ns is None or global_ns is None:
1188 call_frame = sys._getframe(stack_depth).f_back
1188 call_frame = sys._getframe(stack_depth).f_back
1189
1189
1190 if local_ns is None:
1190 if local_ns is None:
1191 local_ns = call_frame.f_locals
1191 local_ns = call_frame.f_locals
1192 if global_ns is None:
1192 if global_ns is None:
1193 global_ns = call_frame.f_globals
1193 global_ns = call_frame.f_globals
1194
1194
1195 # Update namespaces and fire up interpreter
1195 # Update namespaces and fire up interpreter
1196 self.user_ns = local_ns
1196 self.user_ns = local_ns
1197 self.user_global_ns = global_ns
1197 self.user_global_ns = global_ns
1198
1198
1199 # Patch for global embedding to make sure that things don't overwrite
1199 # Patch for global embedding to make sure that things don't overwrite
1200 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1200 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1201 # FIXME. Test this a bit more carefully (the if.. is new)
1201 # FIXME. Test this a bit more carefully (the if.. is new)
1202 if local_ns is None and global_ns is None:
1202 if local_ns is None and global_ns is None:
1203 self.user_global_ns.update(__main__.__dict__)
1203 self.user_global_ns.update(__main__.__dict__)
1204
1204
1205 # make sure the tab-completer has the correct frame information, so it
1205 # make sure the tab-completer has the correct frame information, so it
1206 # actually completes using the frame's locals/globals
1206 # actually completes using the frame's locals/globals
1207 self.set_completer_frame(call_frame)
1207 self.set_completer_frame(call_frame)
1208
1208
1209 self.interact(header)
1209 self.interact(header)
1210
1210
1211 def interact(self, banner=None):
1211 def interact(self, banner=None):
1212 """Closely emulate the interactive Python console.
1212 """Closely emulate the interactive Python console.
1213
1213
1214 The optional banner argument specify the banner to print
1214 The optional banner argument specify the banner to print
1215 before the first interaction; by default it prints a banner
1215 before the first interaction; by default it prints a banner
1216 similar to the one printed by the real Python interpreter,
1216 similar to the one printed by the real Python interpreter,
1217 followed by the current class name in parentheses (so as not
1217 followed by the current class name in parentheses (so as not
1218 to confuse this with the real interpreter -- since it's so
1218 to confuse this with the real interpreter -- since it's so
1219 close!).
1219 close!).
1220
1220
1221 """
1221 """
1222 cprt = 'Type "copyright", "credits" or "license" for more information.'
1222 cprt = 'Type "copyright", "credits" or "license" for more information.'
1223 if banner is None:
1223 if banner is None:
1224 self.write("Python %s on %s\n%s\n(%s)\n" %
1224 self.write("Python %s on %s\n%s\n(%s)\n" %
1225 (sys.version, sys.platform, cprt,
1225 (sys.version, sys.platform, cprt,
1226 self.__class__.__name__))
1226 self.__class__.__name__))
1227 else:
1227 else:
1228 self.write(banner)
1228 self.write(banner)
1229
1229
1230 more = 0
1230 more = 0
1231
1231
1232 # Mark activity in the builtins
1232 # Mark activity in the builtins
1233 __builtin__.__dict__['__IPYTHON__active'] += 1
1233 __builtin__.__dict__['__IPYTHON__active'] += 1
1234
1234
1235 # compiled regexps for autoindent management
1235 # compiled regexps for autoindent management
1236 ini_spaces_re = re.compile(r'^(\s+)')
1236 ini_spaces_re = re.compile(r'^(\s+)')
1237 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1237 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1238
1238
1239 # exit_now is set by a call to %Exit or %Quit
1239 # exit_now is set by a call to %Exit or %Quit
1240 while not self.exit_now:
1240 while not self.exit_now:
1241 try:
1241 try:
1242 if more:
1242 if more:
1243 prompt = self.outputcache.prompt2
1243 prompt = self.outputcache.prompt2
1244 if self.autoindent:
1244 if self.autoindent:
1245 self.readline_startup_hook(self.pre_readline)
1245 self.readline_startup_hook(self.pre_readline)
1246 else:
1246 else:
1247 prompt = self.outputcache.prompt1
1247 prompt = self.outputcache.prompt1
1248 try:
1248 try:
1249 line = self.raw_input(prompt,more)
1249 line = self.raw_input(prompt,more)
1250 if self.autoindent:
1250 if self.autoindent:
1251 self.readline_startup_hook(None)
1251 self.readline_startup_hook(None)
1252 except EOFError:
1252 except EOFError:
1253 if self.autoindent:
1253 if self.autoindent:
1254 self.readline_startup_hook(None)
1254 self.readline_startup_hook(None)
1255 self.write("\n")
1255 self.write("\n")
1256 self.exit()
1256 self.exit()
1257 else:
1257 else:
1258 more = self.push(line)
1258 more = self.push(line)
1259 # Auto-indent management
1259 # Auto-indent management
1260 if self.autoindent:
1260 if self.autoindent:
1261 if line:
1261 if line:
1262 ini_spaces = ini_spaces_re.match(line)
1262 ini_spaces = ini_spaces_re.match(line)
1263 if ini_spaces:
1263 if ini_spaces:
1264 nspaces = ini_spaces.end()
1264 nspaces = ini_spaces.end()
1265 else:
1265 else:
1266 nspaces = 0
1266 nspaces = 0
1267 self.indent_current_nsp = nspaces
1267 self.indent_current_nsp = nspaces
1268
1268
1269 if line[-1] == ':':
1269 if line[-1] == ':':
1270 self.indent_current_nsp += 4
1270 self.indent_current_nsp += 4
1271 elif dedent_re.match(line):
1271 elif dedent_re.match(line):
1272 self.indent_current_nsp -= 4
1272 self.indent_current_nsp -= 4
1273 else:
1273 else:
1274 self.indent_current_nsp = 0
1274 self.indent_current_nsp = 0
1275
1275
1276 # indent_current is the actual string to be inserted
1276 # indent_current is the actual string to be inserted
1277 # by the readline hooks for indentation
1277 # by the readline hooks for indentation
1278 self.indent_current = ' '* self.indent_current_nsp
1278 self.indent_current = ' '* self.indent_current_nsp
1279
1279
1280 if (self.SyntaxTB.last_syntax_error and
1280 if (self.SyntaxTB.last_syntax_error and
1281 self.rc.autoedit_syntax):
1281 self.rc.autoedit_syntax):
1282 self.edit_syntax_error()
1282 self.edit_syntax_error()
1283
1283
1284 except KeyboardInterrupt:
1284 except KeyboardInterrupt:
1285 self.write("\nKeyboardInterrupt\n")
1285 self.write("\nKeyboardInterrupt\n")
1286 self.resetbuffer()
1286 self.resetbuffer()
1287 more = 0
1287 more = 0
1288 # keep cache in sync with the prompt counter:
1288 # keep cache in sync with the prompt counter:
1289 self.outputcache.prompt_count -= 1
1289 self.outputcache.prompt_count -= 1
1290
1290
1291 if self.autoindent:
1291 if self.autoindent:
1292 self.indent_current_nsp = 0
1292 self.indent_current_nsp = 0
1293 self.indent_current = ' '* self.indent_current_nsp
1293 self.indent_current = ' '* self.indent_current_nsp
1294
1294
1295 except bdb.BdbQuit:
1295 except bdb.BdbQuit:
1296 warn("The Python debugger has exited with a BdbQuit exception.\n"
1296 warn("The Python debugger has exited with a BdbQuit exception.\n"
1297 "Because of how pdb handles the stack, it is impossible\n"
1297 "Because of how pdb handles the stack, it is impossible\n"
1298 "for IPython to properly format this particular exception.\n"
1298 "for IPython to properly format this particular exception.\n"
1299 "IPython will resume normal operation.")
1299 "IPython will resume normal operation.")
1300
1300
1301 # We are off again...
1301 # We are off again...
1302 __builtin__.__dict__['__IPYTHON__active'] -= 1
1302 __builtin__.__dict__['__IPYTHON__active'] -= 1
1303
1303
1304 def excepthook(self, type, value, tb):
1304 def excepthook(self, type, value, tb):
1305 """One more defense for GUI apps that call sys.excepthook.
1305 """One more defense for GUI apps that call sys.excepthook.
1306
1306
1307 GUI frameworks like wxPython trap exceptions and call
1307 GUI frameworks like wxPython trap exceptions and call
1308 sys.excepthook themselves. I guess this is a feature that
1308 sys.excepthook themselves. I guess this is a feature that
1309 enables them to keep running after exceptions that would
1309 enables them to keep running after exceptions that would
1310 otherwise kill their mainloop. This is a bother for IPython
1310 otherwise kill their mainloop. This is a bother for IPython
1311 which excepts to catch all of the program exceptions with a try:
1311 which excepts to catch all of the program exceptions with a try:
1312 except: statement.
1312 except: statement.
1313
1313
1314 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1314 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1315 any app directly invokes sys.excepthook, it will look to the user like
1315 any app directly invokes sys.excepthook, it will look to the user like
1316 IPython crashed. In order to work around this, we can disable the
1316 IPython crashed. In order to work around this, we can disable the
1317 CrashHandler and replace it with this excepthook instead, which prints a
1317 CrashHandler and replace it with this excepthook instead, which prints a
1318 regular traceback using our InteractiveTB. In this fashion, apps which
1318 regular traceback using our InteractiveTB. In this fashion, apps which
1319 call sys.excepthook will generate a regular-looking exception from
1319 call sys.excepthook will generate a regular-looking exception from
1320 IPython, and the CrashHandler will only be triggered by real IPython
1320 IPython, and the CrashHandler will only be triggered by real IPython
1321 crashes.
1321 crashes.
1322
1322
1323 This hook should be used sparingly, only in places which are not likely
1323 This hook should be used sparingly, only in places which are not likely
1324 to be true IPython errors.
1324 to be true IPython errors.
1325 """
1325 """
1326
1326
1327 self.InteractiveTB(type, value, tb, tb_offset=0)
1327 self.InteractiveTB(type, value, tb, tb_offset=0)
1328 if self.InteractiveTB.call_pdb and self.has_readline:
1328 if self.InteractiveTB.call_pdb and self.has_readline:
1329 self.readline.set_completer(self.Completer.complete)
1329 self.readline.set_completer(self.Completer.complete)
1330
1330
1331 def call_alias(self,alias,rest=''):
1331 def call_alias(self,alias,rest=''):
1332 """Call an alias given its name and the rest of the line.
1332 """Call an alias given its name and the rest of the line.
1333
1333
1334 This function MUST be given a proper alias, because it doesn't make
1334 This function MUST be given a proper alias, because it doesn't make
1335 any checks when looking up into the alias table. The caller is
1335 any checks when looking up into the alias table. The caller is
1336 responsible for invoking it only with a valid alias."""
1336 responsible for invoking it only with a valid alias."""
1337
1337
1338 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1338 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1339 nargs,cmd = self.alias_table[alias]
1339 nargs,cmd = self.alias_table[alias]
1340 # Expand the %l special to be the user's input line
1340 # Expand the %l special to be the user's input line
1341 if cmd.find('%l') >= 0:
1341 if cmd.find('%l') >= 0:
1342 cmd = cmd.replace('%l',rest)
1342 cmd = cmd.replace('%l',rest)
1343 rest = ''
1343 rest = ''
1344 if nargs==0:
1344 if nargs==0:
1345 # Simple, argument-less aliases
1345 # Simple, argument-less aliases
1346 cmd = '%s %s' % (cmd,rest)
1346 cmd = '%s %s' % (cmd,rest)
1347 else:
1347 else:
1348 # Handle aliases with positional arguments
1348 # Handle aliases with positional arguments
1349 args = rest.split(None,nargs)
1349 args = rest.split(None,nargs)
1350 if len(args)< nargs:
1350 if len(args)< nargs:
1351 error('Alias <%s> requires %s arguments, %s given.' %
1351 error('Alias <%s> requires %s arguments, %s given.' %
1352 (alias,nargs,len(args)))
1352 (alias,nargs,len(args)))
1353 return
1353 return
1354 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1354 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1355 # Now call the macro, evaluating in the user's namespace
1355 # Now call the macro, evaluating in the user's namespace
1356 try:
1356 try:
1357 self.system(cmd)
1357 self.system(cmd)
1358 except:
1358 except:
1359 self.showtraceback()
1359 self.showtraceback()
1360
1360
1361 def runlines(self,lines):
1361 def runlines(self,lines):
1362 """Run a string of one or more lines of source.
1362 """Run a string of one or more lines of source.
1363
1363
1364 This method is capable of running a string containing multiple source
1364 This method is capable of running a string containing multiple source
1365 lines, as if they had been entered at the IPython prompt. Since it
1365 lines, as if they had been entered at the IPython prompt. Since it
1366 exposes IPython's processing machinery, the given strings can contain
1366 exposes IPython's processing machinery, the given strings can contain
1367 magic calls (%magic), special shell access (!cmd), etc."""
1367 magic calls (%magic), special shell access (!cmd), etc."""
1368
1368
1369 # We must start with a clean buffer, in case this is run from an
1369 # We must start with a clean buffer, in case this is run from an
1370 # interactive IPython session (via a magic, for example).
1370 # interactive IPython session (via a magic, for example).
1371 self.resetbuffer()
1371 self.resetbuffer()
1372 lines = lines.split('\n')
1372 lines = lines.split('\n')
1373 more = 0
1373 more = 0
1374 for line in lines:
1374 for line in lines:
1375 # skip blank lines so we don't mess up the prompt counter, but do
1375 # skip blank lines so we don't mess up the prompt counter, but do
1376 # NOT skip even a blank line if we are in a code block (more is
1376 # NOT skip even a blank line if we are in a code block (more is
1377 # true)
1377 # true)
1378 if line or more:
1378 if line or more:
1379 more = self.push((self.prefilter(line,more)))
1379 more = self.push((self.prefilter(line,more)))
1380 # IPython's runsource returns None if there was an error
1380 # IPython's runsource returns None if there was an error
1381 # compiling the code. This allows us to stop processing right
1381 # compiling the code. This allows us to stop processing right
1382 # away, so the user gets the error message at the right place.
1382 # away, so the user gets the error message at the right place.
1383 if more is None:
1383 if more is None:
1384 break
1384 break
1385 # final newline in case the input didn't have it, so that the code
1385 # final newline in case the input didn't have it, so that the code
1386 # actually does get executed
1386 # actually does get executed
1387 if more:
1387 if more:
1388 self.push('\n')
1388 self.push('\n')
1389
1389
1390 def runsource(self, source, filename='<input>', symbol='single'):
1390 def runsource(self, source, filename='<input>', symbol='single'):
1391 """Compile and run some source in the interpreter.
1391 """Compile and run some source in the interpreter.
1392
1392
1393 Arguments are as for compile_command().
1393 Arguments are as for compile_command().
1394
1394
1395 One several things can happen:
1395 One several things can happen:
1396
1396
1397 1) The input is incorrect; compile_command() raised an
1397 1) The input is incorrect; compile_command() raised an
1398 exception (SyntaxError or OverflowError). A syntax traceback
1398 exception (SyntaxError or OverflowError). A syntax traceback
1399 will be printed by calling the showsyntaxerror() method.
1399 will be printed by calling the showsyntaxerror() method.
1400
1400
1401 2) The input is incomplete, and more input is required;
1401 2) The input is incomplete, and more input is required;
1402 compile_command() returned None. Nothing happens.
1402 compile_command() returned None. Nothing happens.
1403
1403
1404 3) The input is complete; compile_command() returned a code
1404 3) The input is complete; compile_command() returned a code
1405 object. The code is executed by calling self.runcode() (which
1405 object. The code is executed by calling self.runcode() (which
1406 also handles run-time exceptions, except for SystemExit).
1406 also handles run-time exceptions, except for SystemExit).
1407
1407
1408 The return value is:
1408 The return value is:
1409
1409
1410 - True in case 2
1410 - True in case 2
1411
1411
1412 - False in the other cases, unless an exception is raised, where
1412 - False in the other cases, unless an exception is raised, where
1413 None is returned instead. This can be used by external callers to
1413 None is returned instead. This can be used by external callers to
1414 know whether to continue feeding input or not.
1414 know whether to continue feeding input or not.
1415
1415
1416 The return value can be used to decide whether to use sys.ps1 or
1416 The return value can be used to decide whether to use sys.ps1 or
1417 sys.ps2 to prompt the next line."""
1417 sys.ps2 to prompt the next line."""
1418
1418
1419 try:
1419 try:
1420 code = self.compile(source,filename,symbol)
1420 code = self.compile(source,filename,symbol)
1421 except (OverflowError, SyntaxError, ValueError):
1421 except (OverflowError, SyntaxError, ValueError):
1422 # Case 1
1422 # Case 1
1423 self.showsyntaxerror(filename)
1423 self.showsyntaxerror(filename)
1424 return None
1424 return None
1425
1425
1426 if code is None:
1426 if code is None:
1427 # Case 2
1427 # Case 2
1428 return True
1428 return True
1429
1429
1430 # Case 3
1430 # Case 3
1431 # We store the code object so that threaded shells and
1431 # We store the code object so that threaded shells and
1432 # custom exception handlers can access all this info if needed.
1432 # custom exception handlers can access all this info if needed.
1433 # The source corresponding to this can be obtained from the
1433 # The source corresponding to this can be obtained from the
1434 # buffer attribute as '\n'.join(self.buffer).
1434 # buffer attribute as '\n'.join(self.buffer).
1435 self.code_to_run = code
1435 self.code_to_run = code
1436 # now actually execute the code object
1436 # now actually execute the code object
1437 if self.runcode(code) == 0:
1437 if self.runcode(code) == 0:
1438 return False
1438 return False
1439 else:
1439 else:
1440 return None
1440 return None
1441
1441
1442 def runcode(self,code_obj):
1442 def runcode(self,code_obj):
1443 """Execute a code object.
1443 """Execute a code object.
1444
1444
1445 When an exception occurs, self.showtraceback() is called to display a
1445 When an exception occurs, self.showtraceback() is called to display a
1446 traceback.
1446 traceback.
1447
1447
1448 Return value: a flag indicating whether the code to be run completed
1448 Return value: a flag indicating whether the code to be run completed
1449 successfully:
1449 successfully:
1450
1450
1451 - 0: successful execution.
1451 - 0: successful execution.
1452 - 1: an error occurred.
1452 - 1: an error occurred.
1453 """
1453 """
1454
1454
1455 # Set our own excepthook in case the user code tries to call it
1455 # Set our own excepthook in case the user code tries to call it
1456 # directly, so that the IPython crash handler doesn't get triggered
1456 # directly, so that the IPython crash handler doesn't get triggered
1457 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1457 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1458 outflag = 1 # happens in more places, so it's easier as default
1458 outflag = 1 # happens in more places, so it's easier as default
1459 try:
1459 try:
1460 try:
1460 try:
1461 # Embedded instances require separate global/local namespaces
1461 # Embedded instances require separate global/local namespaces
1462 # so they can see both the surrounding (local) namespace and
1462 # so they can see both the surrounding (local) namespace and
1463 # the module-level globals when called inside another function.
1463 # the module-level globals when called inside another function.
1464 if self.embedded:
1464 if self.embedded:
1465 exec code_obj in self.user_global_ns, self.user_ns
1465 exec code_obj in self.user_global_ns, self.user_ns
1466 # Normal (non-embedded) instances should only have a single
1466 # Normal (non-embedded) instances should only have a single
1467 # namespace for user code execution, otherwise functions won't
1467 # namespace for user code execution, otherwise functions won't
1468 # see interactive top-level globals.
1468 # see interactive top-level globals.
1469 else:
1469 else:
1470 exec code_obj in self.user_ns
1470 exec code_obj in self.user_ns
1471 finally:
1471 finally:
1472 # Reset our crash handler in place
1472 # Reset our crash handler in place
1473 sys.excepthook = old_excepthook
1473 sys.excepthook = old_excepthook
1474 except SystemExit:
1474 except SystemExit:
1475 self.resetbuffer()
1475 self.resetbuffer()
1476 self.showtraceback()
1476 self.showtraceback()
1477 warn("Type exit or quit to exit IPython "
1477 warn("Type exit or quit to exit IPython "
1478 "(%Exit or %Quit do so unconditionally).",level=1)
1478 "(%Exit or %Quit do so unconditionally).",level=1)
1479 except self.custom_exceptions:
1479 except self.custom_exceptions:
1480 etype,value,tb = sys.exc_info()
1480 etype,value,tb = sys.exc_info()
1481 self.CustomTB(etype,value,tb)
1481 self.CustomTB(etype,value,tb)
1482 except:
1482 except:
1483 self.showtraceback()
1483 self.showtraceback()
1484 else:
1484 else:
1485 outflag = 0
1485 outflag = 0
1486 if softspace(sys.stdout, 0):
1486 if softspace(sys.stdout, 0):
1487 print
1487 print
1488 # Flush out code object which has been run (and source)
1488 # Flush out code object which has been run (and source)
1489 self.code_to_run = None
1489 self.code_to_run = None
1490 return outflag
1490 return outflag
1491
1491
1492 def push(self, line):
1492 def push(self, line):
1493 """Push a line to the interpreter.
1493 """Push a line to the interpreter.
1494
1494
1495 The line should not have a trailing newline; it may have
1495 The line should not have a trailing newline; it may have
1496 internal newlines. The line is appended to a buffer and the
1496 internal newlines. The line is appended to a buffer and the
1497 interpreter's runsource() method is called with the
1497 interpreter's runsource() method is called with the
1498 concatenated contents of the buffer as source. If this
1498 concatenated contents of the buffer as source. If this
1499 indicates that the command was executed or invalid, the buffer
1499 indicates that the command was executed or invalid, the buffer
1500 is reset; otherwise, the command is incomplete, and the buffer
1500 is reset; otherwise, the command is incomplete, and the buffer
1501 is left as it was after the line was appended. The return
1501 is left as it was after the line was appended. The return
1502 value is 1 if more input is required, 0 if the line was dealt
1502 value is 1 if more input is required, 0 if the line was dealt
1503 with in some way (this is the same as runsource()).
1503 with in some way (this is the same as runsource()).
1504
1504
1505 """
1505 """
1506 self.buffer.append(line)
1506 self.buffer.append(line)
1507 more = self.runsource('\n'.join(self.buffer), self.filename)
1507 more = self.runsource('\n'.join(self.buffer), self.filename)
1508 if not more:
1508 if not more:
1509 self.resetbuffer()
1509 self.resetbuffer()
1510 return more
1510 return more
1511
1511
1512 def resetbuffer(self):
1512 def resetbuffer(self):
1513 """Reset the input buffer."""
1513 """Reset the input buffer."""
1514 self.buffer[:] = []
1514 self.buffer[:] = []
1515
1515
1516 def raw_input(self,prompt='',continue_prompt=False):
1516 def raw_input(self,prompt='',continue_prompt=False):
1517 """Write a prompt and read a line.
1517 """Write a prompt and read a line.
1518
1518
1519 The returned line does not include the trailing newline.
1519 The returned line does not include the trailing newline.
1520 When the user enters the EOF key sequence, EOFError is raised.
1520 When the user enters the EOF key sequence, EOFError is raised.
1521
1521
1522 Optional inputs:
1522 Optional inputs:
1523
1523
1524 - prompt(''): a string to be printed to prompt the user.
1524 - prompt(''): a string to be printed to prompt the user.
1525
1525
1526 - continue_prompt(False): whether this line is the first one or a
1526 - continue_prompt(False): whether this line is the first one or a
1527 continuation in a sequence of inputs.
1527 continuation in a sequence of inputs.
1528 """
1528 """
1529
1529
1530 line = raw_input_original(prompt)
1530 line = raw_input_original(prompt)
1531 # Try to be reasonably smart about not re-indenting pasted input more
1531 # Try to be reasonably smart about not re-indenting pasted input more
1532 # than necessary. We do this by trimming out the auto-indent initial
1532 # than necessary. We do this by trimming out the auto-indent initial
1533 # spaces, if the user's actual input started itself with whitespace.
1533 # spaces, if the user's actual input started itself with whitespace.
1534 if self.autoindent:
1534 if self.autoindent:
1535 line2 = line[self.indent_current_nsp:]
1535 line2 = line[self.indent_current_nsp:]
1536 if line2[0:1] in (' ','\t'):
1536 if line2[0:1] in (' ','\t'):
1537 line = line2
1537 line = line2
1538 return self.prefilter(line,continue_prompt)
1538 return self.prefilter(line,continue_prompt)
1539
1539
1540 def split_user_input(self,line):
1540 def split_user_input(self,line):
1541 """Split user input into pre-char, function part and rest."""
1541 """Split user input into pre-char, function part and rest."""
1542
1542
1543 lsplit = self.line_split.match(line)
1543 lsplit = self.line_split.match(line)
1544 if lsplit is None: # no regexp match returns None
1544 if lsplit is None: # no regexp match returns None
1545 try:
1545 try:
1546 iFun,theRest = line.split(None,1)
1546 iFun,theRest = line.split(None,1)
1547 except ValueError:
1547 except ValueError:
1548 iFun,theRest = line,''
1548 iFun,theRest = line,''
1549 pre = re.match('^(\s*)(.*)',line).groups()[0]
1549 pre = re.match('^(\s*)(.*)',line).groups()[0]
1550 else:
1550 else:
1551 pre,iFun,theRest = lsplit.groups()
1551 pre,iFun,theRest = lsplit.groups()
1552
1552
1553 #print 'line:<%s>' % line # dbg
1553 #print 'line:<%s>' % line # dbg
1554 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1554 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1555 return pre,iFun.strip(),theRest
1555 return pre,iFun.strip(),theRest
1556
1556
1557 def _prefilter(self, line, continue_prompt):
1557 def _prefilter(self, line, continue_prompt):
1558 """Calls different preprocessors, depending on the form of line."""
1558 """Calls different preprocessors, depending on the form of line."""
1559
1559
1560 # All handlers *must* return a value, even if it's blank ('').
1560 # All handlers *must* return a value, even if it's blank ('').
1561
1561
1562 # Lines are NOT logged here. Handlers should process the line as
1562 # Lines are NOT logged here. Handlers should process the line as
1563 # needed, update the cache AND log it (so that the input cache array
1563 # needed, update the cache AND log it (so that the input cache array
1564 # stays synced).
1564 # stays synced).
1565
1565
1566 # This function is _very_ delicate, and since it's also the one which
1566 # This function is _very_ delicate, and since it's also the one which
1567 # determines IPython's response to user input, it must be as efficient
1567 # determines IPython's response to user input, it must be as efficient
1568 # as possible. For this reason it has _many_ returns in it, trying
1568 # as possible. For this reason it has _many_ returns in it, trying
1569 # always to exit as quickly as it can figure out what it needs to do.
1569 # always to exit as quickly as it can figure out what it needs to do.
1570
1570
1571 # This function is the main responsible for maintaining IPython's
1571 # This function is the main responsible for maintaining IPython's
1572 # behavior respectful of Python's semantics. So be _very_ careful if
1572 # behavior respectful of Python's semantics. So be _very_ careful if
1573 # making changes to anything here.
1573 # making changes to anything here.
1574
1574
1575 #.....................................................................
1575 #.....................................................................
1576 # Code begins
1576 # Code begins
1577
1577
1578 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1578 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1579
1579
1580 # save the line away in case we crash, so the post-mortem handler can
1580 # save the line away in case we crash, so the post-mortem handler can
1581 # record it
1581 # record it
1582 self._last_input_line = line
1582 self._last_input_line = line
1583
1583
1584 #print '***line: <%s>' % line # dbg
1584 #print '***line: <%s>' % line # dbg
1585
1585
1586 # the input history needs to track even empty lines
1586 # the input history needs to track even empty lines
1587 if not line.strip():
1587 if not line.strip():
1588 if not continue_prompt:
1588 if not continue_prompt:
1589 self.outputcache.prompt_count -= 1
1589 self.outputcache.prompt_count -= 1
1590 return self.handle_normal(line,continue_prompt)
1590 return self.handle_normal(line,continue_prompt)
1591 #return self.handle_normal('',continue_prompt)
1591 #return self.handle_normal('',continue_prompt)
1592
1592
1593 # print '***cont',continue_prompt # dbg
1593 # print '***cont',continue_prompt # dbg
1594 # special handlers are only allowed for single line statements
1594 # special handlers are only allowed for single line statements
1595 if continue_prompt and not self.rc.multi_line_specials:
1595 if continue_prompt and not self.rc.multi_line_specials:
1596 return self.handle_normal(line,continue_prompt)
1596 return self.handle_normal(line,continue_prompt)
1597
1597
1598 # For the rest, we need the structure of the input
1598 # For the rest, we need the structure of the input
1599 pre,iFun,theRest = self.split_user_input(line)
1599 pre,iFun,theRest = self.split_user_input(line)
1600 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1600 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1601
1601
1602 # First check for explicit escapes in the last/first character
1602 # First check for explicit escapes in the last/first character
1603 handler = None
1603 handler = None
1604 if line[-1] == self.ESC_HELP:
1604 if line[-1] == self.ESC_HELP:
1605 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1605 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1606 if handler is None:
1606 if handler is None:
1607 # look at the first character of iFun, NOT of line, so we skip
1607 # look at the first character of iFun, NOT of line, so we skip
1608 # leading whitespace in multiline input
1608 # leading whitespace in multiline input
1609 handler = self.esc_handlers.get(iFun[0:1])
1609 handler = self.esc_handlers.get(iFun[0:1])
1610 if handler is not None:
1610 if handler is not None:
1611 return handler(line,continue_prompt,pre,iFun,theRest)
1611 return handler(line,continue_prompt,pre,iFun,theRest)
1612 # Emacs ipython-mode tags certain input lines
1612 # Emacs ipython-mode tags certain input lines
1613 if line.endswith('# PYTHON-MODE'):
1613 if line.endswith('# PYTHON-MODE'):
1614 return self.handle_emacs(line,continue_prompt)
1614 return self.handle_emacs(line,continue_prompt)
1615
1615
1616 # Next, check if we can automatically execute this thing
1616 # Next, check if we can automatically execute this thing
1617
1617
1618 # Allow ! in multi-line statements if multi_line_specials is on:
1618 # Allow ! in multi-line statements if multi_line_specials is on:
1619 if continue_prompt and self.rc.multi_line_specials and \
1619 if continue_prompt and self.rc.multi_line_specials and \
1620 iFun.startswith(self.ESC_SHELL):
1620 iFun.startswith(self.ESC_SHELL):
1621 return self.handle_shell_escape(line,continue_prompt,
1621 return self.handle_shell_escape(line,continue_prompt,
1622 pre=pre,iFun=iFun,
1622 pre=pre,iFun=iFun,
1623 theRest=theRest)
1623 theRest=theRest)
1624
1624
1625 # Let's try to find if the input line is a magic fn
1625 # Let's try to find if the input line is a magic fn
1626 oinfo = None
1626 oinfo = None
1627 if hasattr(self,'magic_'+iFun):
1627 if hasattr(self,'magic_'+iFun):
1628 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1628 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1629 if oinfo['ismagic']:
1629 if oinfo['ismagic']:
1630 # Be careful not to call magics when a variable assignment is
1630 # Be careful not to call magics when a variable assignment is
1631 # being made (ls='hi', for example)
1631 # being made (ls='hi', for example)
1632 if self.rc.automagic and \
1632 if self.rc.automagic and \
1633 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1633 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1634 (self.rc.multi_line_specials or not continue_prompt):
1634 (self.rc.multi_line_specials or not continue_prompt):
1635 return self.handle_magic(line,continue_prompt,
1635 return self.handle_magic(line,continue_prompt,
1636 pre,iFun,theRest)
1636 pre,iFun,theRest)
1637 else:
1637 else:
1638 return self.handle_normal(line,continue_prompt)
1638 return self.handle_normal(line,continue_prompt)
1639
1639
1640 # If the rest of the line begins with an (in)equality, assginment or
1640 # If the rest of the line begins with an (in)equality, assginment or
1641 # function call, we should not call _ofind but simply execute it.
1641 # function call, we should not call _ofind but simply execute it.
1642 # This avoids spurious geattr() accesses on objects upon assignment.
1642 # This avoids spurious geattr() accesses on objects upon assignment.
1643 #
1643 #
1644 # It also allows users to assign to either alias or magic names true
1644 # It also allows users to assign to either alias or magic names true
1645 # python variables (the magic/alias systems always take second seat to
1645 # python variables (the magic/alias systems always take second seat to
1646 # true python code).
1646 # true python code).
1647 if theRest and theRest[0] in '!=()':
1647 if theRest and theRest[0] in '!=()':
1648 return self.handle_normal(line,continue_prompt)
1648 return self.handle_normal(line,continue_prompt)
1649
1649
1650 if oinfo is None:
1650 if oinfo is None:
1651 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1651 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1652
1652
1653 if not oinfo['found']:
1653 if not oinfo['found']:
1654 return self.handle_normal(line,continue_prompt)
1654 return self.handle_normal(line,continue_prompt)
1655 else:
1655 else:
1656 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1656 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1657 if oinfo['isalias']:
1657 if oinfo['isalias']:
1658 return self.handle_alias(line,continue_prompt,
1658 return self.handle_alias(line,continue_prompt,
1659 pre,iFun,theRest)
1659 pre,iFun,theRest)
1660
1660
1661 if self.rc.autocall and \
1661 if self.rc.autocall and \
1662 not self.re_exclude_auto.match(theRest) and \
1662 not self.re_exclude_auto.match(theRest) and \
1663 self.re_fun_name.match(iFun) and \
1663 self.re_fun_name.match(iFun) and \
1664 callable(oinfo['obj']) :
1664 callable(oinfo['obj']) :
1665 #print 'going auto' # dbg
1665 #print 'going auto' # dbg
1666 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1666 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1667 else:
1667 else:
1668 #print 'was callable?', callable(oinfo['obj']) # dbg
1668 #print 'was callable?', callable(oinfo['obj']) # dbg
1669 return self.handle_normal(line,continue_prompt)
1669 return self.handle_normal(line,continue_prompt)
1670
1670
1671 # If we get here, we have a normal Python line. Log and return.
1671 # If we get here, we have a normal Python line. Log and return.
1672 return self.handle_normal(line,continue_prompt)
1672 return self.handle_normal(line,continue_prompt)
1673
1673
1674 def _prefilter_dumb(self, line, continue_prompt):
1674 def _prefilter_dumb(self, line, continue_prompt):
1675 """simple prefilter function, for debugging"""
1675 """simple prefilter function, for debugging"""
1676 return self.handle_normal(line,continue_prompt)
1676 return self.handle_normal(line,continue_prompt)
1677
1677
1678 # Set the default prefilter() function (this can be user-overridden)
1678 # Set the default prefilter() function (this can be user-overridden)
1679 prefilter = _prefilter
1679 prefilter = _prefilter
1680
1680
1681 def handle_normal(self,line,continue_prompt=None,
1681 def handle_normal(self,line,continue_prompt=None,
1682 pre=None,iFun=None,theRest=None):
1682 pre=None,iFun=None,theRest=None):
1683 """Handle normal input lines. Use as a template for handlers."""
1683 """Handle normal input lines. Use as a template for handlers."""
1684
1684
1685 # With autoindent on, we need some way to exit the input loop, and I
1685 # With autoindent on, we need some way to exit the input loop, and I
1686 # don't want to force the user to have to backspace all the way to
1686 # don't want to force the user to have to backspace all the way to
1687 # clear the line. The rule will be in this case, that either two
1687 # clear the line. The rule will be in this case, that either two
1688 # lines of pure whitespace in a row, or a line of pure whitespace but
1688 # lines of pure whitespace in a row, or a line of pure whitespace but
1689 # of a size different to the indent level, will exit the input loop.
1689 # of a size different to the indent level, will exit the input loop.
1690 if (continue_prompt and self.autoindent and isspace(line) and
1690 if (continue_prompt and self.autoindent and isspace(line) and
1691 (line != self.indent_current or isspace(self.buffer[-1]))):
1691 (line != self.indent_current or isspace(self.buffer[-1]))):
1692 line = ''
1692 line = ''
1693
1693
1694 self.log(line,continue_prompt)
1694 self.log(line,continue_prompt)
1695 self.update_cache(line)
1695 self.update_cache(line)
1696 return line
1696 return line
1697
1697
1698 def handle_alias(self,line,continue_prompt=None,
1698 def handle_alias(self,line,continue_prompt=None,
1699 pre=None,iFun=None,theRest=None):
1699 pre=None,iFun=None,theRest=None):
1700 """Handle alias input lines. """
1700 """Handle alias input lines. """
1701
1701
1702 theRest = esc_quotes(theRest)
1702 theRest = esc_quotes(theRest)
1703 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1703 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1704 self.log(line_out,continue_prompt)
1704 self.log(line_out,continue_prompt)
1705 self.update_cache(line_out)
1705 self.update_cache(line_out)
1706 return line_out
1706 return line_out
1707
1707
1708 def handle_shell_escape(self, line, continue_prompt=None,
1708 def handle_shell_escape(self, line, continue_prompt=None,
1709 pre=None,iFun=None,theRest=None):
1709 pre=None,iFun=None,theRest=None):
1710 """Execute the line in a shell, empty return value"""
1710 """Execute the line in a shell, empty return value"""
1711
1711
1712 #print 'line in :', `line` # dbg
1712 #print 'line in :', `line` # dbg
1713 # Example of a special handler. Others follow a similar pattern.
1713 # Example of a special handler. Others follow a similar pattern.
1714 if continue_prompt: # multi-line statements
1714 if continue_prompt: # multi-line statements
1715 if iFun.startswith('!!'):
1715 if iFun.startswith('!!'):
1716 print 'SyntaxError: !! is not allowed in multiline statements'
1716 print 'SyntaxError: !! is not allowed in multiline statements'
1717 return pre
1717 return pre
1718 else:
1718 else:
1719 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1719 cmd = ("%s %s" % (iFun[1:],theRest)) #.replace('"','\\"')
1720 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1720 #line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1721 line_out = '%s%s.system(r"""%s"""[:-1])' % (pre,self.name,cmd + "_")
1721 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1722 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1722 else: # single-line input
1723 else: # single-line input
1723 if line.startswith('!!'):
1724 if line.startswith('!!'):
1724 # rewrite iFun/theRest to properly hold the call to %sx and
1725 # rewrite iFun/theRest to properly hold the call to %sx and
1725 # the actual command to be executed, so handle_magic can work
1726 # the actual command to be executed, so handle_magic can work
1726 # correctly
1727 # correctly
1727 theRest = '%s %s' % (iFun[2:],theRest)
1728 theRest = '%s %s' % (iFun[2:],theRest)
1728 iFun = 'sx'
1729 iFun = 'sx'
1729 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1730 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1730 continue_prompt,pre,iFun,theRest)
1731 continue_prompt,pre,iFun,theRest)
1731 else:
1732 else:
1732 cmd = esc_quotes(line[1:])
1733 #cmd = esc_quotes(line[1:])
1733 line_out = '%s.system("%s")' % (self.name,cmd)
1734 cmd=line[1:]
1735 #line_out = '%s.system("%s")' % (self.name,cmd)
1736 line_out = '%s.system(r"""%s"""[:-1])' % (self.name,cmd +"_")
1734 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1737 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1735 # update cache/log and return
1738 # update cache/log and return
1736 self.log(line_out,continue_prompt)
1739 self.log(line_out,continue_prompt)
1737 self.update_cache(line_out) # readline cache gets normal line
1740 self.update_cache(line_out) # readline cache gets normal line
1738 #print 'line out r:', `line_out` # dbg
1741 #print 'line out r:', `line_out` # dbg
1739 #print 'line out s:', line_out # dbg
1742 #print 'line out s:', line_out # dbg
1740 return line_out
1743 return line_out
1741
1744
1742 def handle_magic(self, line, continue_prompt=None,
1745 def handle_magic(self, line, continue_prompt=None,
1743 pre=None,iFun=None,theRest=None):
1746 pre=None,iFun=None,theRest=None):
1744 """Execute magic functions.
1747 """Execute magic functions.
1745
1748
1746 Also log them with a prepended # so the log is clean Python."""
1749 Also log them with a prepended # so the log is clean Python."""
1747
1750
1748 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1751 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1749 self.log(cmd,continue_prompt)
1752 self.log(cmd,continue_prompt)
1750 self.update_cache(line)
1753 self.update_cache(line)
1751 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1754 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1752 return cmd
1755 return cmd
1753
1756
1754 def handle_auto(self, line, continue_prompt=None,
1757 def handle_auto(self, line, continue_prompt=None,
1755 pre=None,iFun=None,theRest=None):
1758 pre=None,iFun=None,theRest=None):
1756 """Hande lines which can be auto-executed, quoting if requested."""
1759 """Hande lines which can be auto-executed, quoting if requested."""
1757
1760
1758 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1761 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1759
1762
1760 # This should only be active for single-line input!
1763 # This should only be active for single-line input!
1761 if continue_prompt:
1764 if continue_prompt:
1762 return line
1765 return line
1763
1766
1764 if pre == self.ESC_QUOTE:
1767 if pre == self.ESC_QUOTE:
1765 # Auto-quote splitting on whitespace
1768 # Auto-quote splitting on whitespace
1766 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1769 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1767 elif pre == self.ESC_QUOTE2:
1770 elif pre == self.ESC_QUOTE2:
1768 # Auto-quote whole string
1771 # Auto-quote whole string
1769 newcmd = '%s("%s")' % (iFun,theRest)
1772 newcmd = '%s("%s")' % (iFun,theRest)
1770 else:
1773 else:
1771 # Auto-paren
1774 # Auto-paren
1772 if theRest[0:1] in ('=','['):
1775 if theRest[0:1] in ('=','['):
1773 # Don't autocall in these cases. They can be either
1776 # Don't autocall in these cases. They can be either
1774 # rebindings of an existing callable's name, or item access
1777 # rebindings of an existing callable's name, or item access
1775 # for an object which is BOTH callable and implements
1778 # for an object which is BOTH callable and implements
1776 # __getitem__.
1779 # __getitem__.
1777 return '%s %s' % (iFun,theRest)
1780 return '%s %s' % (iFun,theRest)
1778 if theRest.endswith(';'):
1781 if theRest.endswith(';'):
1779 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1782 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1780 else:
1783 else:
1781 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1784 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1782
1785
1783 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1786 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1784 # log what is now valid Python, not the actual user input (without the
1787 # log what is now valid Python, not the actual user input (without the
1785 # final newline)
1788 # final newline)
1786 self.log(newcmd,continue_prompt)
1789 self.log(newcmd,continue_prompt)
1787 return newcmd
1790 return newcmd
1788
1791
1789 def handle_help(self, line, continue_prompt=None,
1792 def handle_help(self, line, continue_prompt=None,
1790 pre=None,iFun=None,theRest=None):
1793 pre=None,iFun=None,theRest=None):
1791 """Try to get some help for the object.
1794 """Try to get some help for the object.
1792
1795
1793 obj? or ?obj -> basic information.
1796 obj? or ?obj -> basic information.
1794 obj?? or ??obj -> more details.
1797 obj?? or ??obj -> more details.
1795 """
1798 """
1796
1799
1797 # We need to make sure that we don't process lines which would be
1800 # We need to make sure that we don't process lines which would be
1798 # otherwise valid python, such as "x=1 # what?"
1801 # otherwise valid python, such as "x=1 # what?"
1799 try:
1802 try:
1800 codeop.compile_command(line)
1803 codeop.compile_command(line)
1801 except SyntaxError:
1804 except SyntaxError:
1802 # We should only handle as help stuff which is NOT valid syntax
1805 # We should only handle as help stuff which is NOT valid syntax
1803 if line[0]==self.ESC_HELP:
1806 if line[0]==self.ESC_HELP:
1804 line = line[1:]
1807 line = line[1:]
1805 elif line[-1]==self.ESC_HELP:
1808 elif line[-1]==self.ESC_HELP:
1806 line = line[:-1]
1809 line = line[:-1]
1807 self.log('#?'+line)
1810 self.log('#?'+line)
1808 self.update_cache(line)
1811 self.update_cache(line)
1809 if line:
1812 if line:
1810 self.magic_pinfo(line)
1813 self.magic_pinfo(line)
1811 else:
1814 else:
1812 page(self.usage,screen_lines=self.rc.screen_length)
1815 page(self.usage,screen_lines=self.rc.screen_length)
1813 return '' # Empty string is needed here!
1816 return '' # Empty string is needed here!
1814 except:
1817 except:
1815 # Pass any other exceptions through to the normal handler
1818 # Pass any other exceptions through to the normal handler
1816 return self.handle_normal(line,continue_prompt)
1819 return self.handle_normal(line,continue_prompt)
1817 else:
1820 else:
1818 # If the code compiles ok, we should handle it normally
1821 # If the code compiles ok, we should handle it normally
1819 return self.handle_normal(line,continue_prompt)
1822 return self.handle_normal(line,continue_prompt)
1820
1823
1821 def handle_emacs(self,line,continue_prompt=None,
1824 def handle_emacs(self,line,continue_prompt=None,
1822 pre=None,iFun=None,theRest=None):
1825 pre=None,iFun=None,theRest=None):
1823 """Handle input lines marked by python-mode."""
1826 """Handle input lines marked by python-mode."""
1824
1827
1825 # Currently, nothing is done. Later more functionality can be added
1828 # Currently, nothing is done. Later more functionality can be added
1826 # here if needed.
1829 # here if needed.
1827
1830
1828 # The input cache shouldn't be updated
1831 # The input cache shouldn't be updated
1829
1832
1830 return line
1833 return line
1831
1834
1832 def write(self,data):
1835 def write(self,data):
1833 """Write a string to the default output"""
1836 """Write a string to the default output"""
1834 Term.cout.write(data)
1837 Term.cout.write(data)
1835
1838
1836 def write_err(self,data):
1839 def write_err(self,data):
1837 """Write a string to the default error output"""
1840 """Write a string to the default error output"""
1838 Term.cerr.write(data)
1841 Term.cerr.write(data)
1839
1842
1840 def exit(self):
1843 def exit(self):
1841 """Handle interactive exit.
1844 """Handle interactive exit.
1842
1845
1843 This method sets the exit_now attribute."""
1846 This method sets the exit_now attribute."""
1844
1847
1845 if self.rc.confirm_exit:
1848 if self.rc.confirm_exit:
1846 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1849 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1847 self.exit_now = True
1850 self.exit_now = True
1848 else:
1851 else:
1849 self.exit_now = True
1852 self.exit_now = True
1850 return self.exit_now
1853 return self.exit_now
1851
1854
1852 def safe_execfile(self,fname,*where,**kw):
1855 def safe_execfile(self,fname,*where,**kw):
1853 fname = os.path.expanduser(fname)
1856 fname = os.path.expanduser(fname)
1854
1857
1855 # find things also in current directory
1858 # find things also in current directory
1856 dname = os.path.dirname(fname)
1859 dname = os.path.dirname(fname)
1857 if not sys.path.count(dname):
1860 if not sys.path.count(dname):
1858 sys.path.append(dname)
1861 sys.path.append(dname)
1859
1862
1860 try:
1863 try:
1861 xfile = open(fname)
1864 xfile = open(fname)
1862 except:
1865 except:
1863 print >> Term.cerr, \
1866 print >> Term.cerr, \
1864 'Could not open file <%s> for safe execution.' % fname
1867 'Could not open file <%s> for safe execution.' % fname
1865 return None
1868 return None
1866
1869
1867 kw.setdefault('islog',0)
1870 kw.setdefault('islog',0)
1868 kw.setdefault('quiet',1)
1871 kw.setdefault('quiet',1)
1869 kw.setdefault('exit_ignore',0)
1872 kw.setdefault('exit_ignore',0)
1870 first = xfile.readline()
1873 first = xfile.readline()
1871 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1874 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1872 xfile.close()
1875 xfile.close()
1873 # line by line execution
1876 # line by line execution
1874 if first.startswith(_LOGHEAD) or kw['islog']:
1877 if first.startswith(_LOGHEAD) or kw['islog']:
1875 print 'Loading log file <%s> one line at a time...' % fname
1878 print 'Loading log file <%s> one line at a time...' % fname
1876 if kw['quiet']:
1879 if kw['quiet']:
1877 stdout_save = sys.stdout
1880 stdout_save = sys.stdout
1878 sys.stdout = StringIO.StringIO()
1881 sys.stdout = StringIO.StringIO()
1879 try:
1882 try:
1880 globs,locs = where[0:2]
1883 globs,locs = where[0:2]
1881 except:
1884 except:
1882 try:
1885 try:
1883 globs = locs = where[0]
1886 globs = locs = where[0]
1884 except:
1887 except:
1885 globs = locs = globals()
1888 globs = locs = globals()
1886 badblocks = []
1889 badblocks = []
1887
1890
1888 # we also need to identify indented blocks of code when replaying
1891 # we also need to identify indented blocks of code when replaying
1889 # logs and put them together before passing them to an exec
1892 # logs and put them together before passing them to an exec
1890 # statement. This takes a bit of regexp and look-ahead work in the
1893 # statement. This takes a bit of regexp and look-ahead work in the
1891 # file. It's easiest if we swallow the whole thing in memory
1894 # file. It's easiest if we swallow the whole thing in memory
1892 # first, and manually walk through the lines list moving the
1895 # first, and manually walk through the lines list moving the
1893 # counter ourselves.
1896 # counter ourselves.
1894 indent_re = re.compile('\s+\S')
1897 indent_re = re.compile('\s+\S')
1895 xfile = open(fname)
1898 xfile = open(fname)
1896 filelines = xfile.readlines()
1899 filelines = xfile.readlines()
1897 xfile.close()
1900 xfile.close()
1898 nlines = len(filelines)
1901 nlines = len(filelines)
1899 lnum = 0
1902 lnum = 0
1900 while lnum < nlines:
1903 while lnum < nlines:
1901 line = filelines[lnum]
1904 line = filelines[lnum]
1902 lnum += 1
1905 lnum += 1
1903 # don't re-insert logger status info into cache
1906 # don't re-insert logger status info into cache
1904 if line.startswith('#log#'):
1907 if line.startswith('#log#'):
1905 continue
1908 continue
1906 elif line.startswith('#%s'% self.ESC_MAGIC):
1909 elif line.startswith('#%s'% self.ESC_MAGIC):
1907 self.update_cache(line[1:])
1910 self.update_cache(line[1:])
1908 line = magic2python(line)
1911 line = magic2python(line)
1909 elif line.startswith('#!'):
1912 elif line.startswith('#!'):
1910 self.update_cache(line[1:])
1913 self.update_cache(line[1:])
1911 else:
1914 else:
1912 # build a block of code (maybe a single line) for execution
1915 # build a block of code (maybe a single line) for execution
1913 block = line
1916 block = line
1914 try:
1917 try:
1915 next = filelines[lnum] # lnum has already incremented
1918 next = filelines[lnum] # lnum has already incremented
1916 except:
1919 except:
1917 next = None
1920 next = None
1918 while next and indent_re.match(next):
1921 while next and indent_re.match(next):
1919 block += next
1922 block += next
1920 lnum += 1
1923 lnum += 1
1921 try:
1924 try:
1922 next = filelines[lnum]
1925 next = filelines[lnum]
1923 except:
1926 except:
1924 next = None
1927 next = None
1925 # now execute the block of one or more lines
1928 # now execute the block of one or more lines
1926 try:
1929 try:
1927 exec block in globs,locs
1930 exec block in globs,locs
1928 self.update_cache(block.rstrip())
1931 self.update_cache(block.rstrip())
1929 except SystemExit:
1932 except SystemExit:
1930 pass
1933 pass
1931 except:
1934 except:
1932 badblocks.append(block.rstrip())
1935 badblocks.append(block.rstrip())
1933 if kw['quiet']: # restore stdout
1936 if kw['quiet']: # restore stdout
1934 sys.stdout.close()
1937 sys.stdout.close()
1935 sys.stdout = stdout_save
1938 sys.stdout = stdout_save
1936 print 'Finished replaying log file <%s>' % fname
1939 print 'Finished replaying log file <%s>' % fname
1937 if badblocks:
1940 if badblocks:
1938 print >> sys.stderr, ('\nThe following lines/blocks in file '
1941 print >> sys.stderr, ('\nThe following lines/blocks in file '
1939 '<%s> reported errors:' % fname)
1942 '<%s> reported errors:' % fname)
1940
1943
1941 for badline in badblocks:
1944 for badline in badblocks:
1942 print >> sys.stderr, badline
1945 print >> sys.stderr, badline
1943 else: # regular file execution
1946 else: # regular file execution
1944 try:
1947 try:
1945 execfile(fname,*where)
1948 execfile(fname,*where)
1946 except SyntaxError:
1949 except SyntaxError:
1947 etype, evalue = sys.exc_info()[0:2]
1950 etype, evalue = sys.exc_info()[0:2]
1948 self.SyntaxTB(etype,evalue,[])
1951 self.SyntaxTB(etype,evalue,[])
1949 warn('Failure executing file: <%s>' % fname)
1952 warn('Failure executing file: <%s>' % fname)
1950 except SystemExit,status:
1953 except SystemExit,status:
1951 if not kw['exit_ignore']:
1954 if not kw['exit_ignore']:
1952 self.InteractiveTB()
1955 self.InteractiveTB()
1953 warn('Failure executing file: <%s>' % fname)
1956 warn('Failure executing file: <%s>' % fname)
1954 except:
1957 except:
1955 self.InteractiveTB()
1958 self.InteractiveTB()
1956 warn('Failure executing file: <%s>' % fname)
1959 warn('Failure executing file: <%s>' % fname)
1957
1960
1958 #************************* end of file <iplib.py> *****************************
1961 #************************* end of file <iplib.py> *****************************
@@ -1,737 +1,737 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or better.
5 Requires Python 2.1 or better.
6
6
7 This file contains the main make_IPython() starter function.
7 This file contains the main make_IPython() starter function.
8
8
9 $Id: ipmaker.py 960 2005-12-28 06:51:01Z fperez $"""
9 $Id: ipmaker.py 963 2005-12-28 19:21:29Z fperez $"""
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 from IPython import Release
18 from IPython import Release
19 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __license__ = Release.license
20 __license__ = Release.license
21 __version__ = Release.version
21 __version__ = Release.version
22
22
23 credits._Printer__data = """
23 credits._Printer__data = """
24 Python: %s
24 Python: %s
25
25
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 See http://ipython.scipy.org for more information.""" \
27 See http://ipython.scipy.org for more information.""" \
28 % credits._Printer__data
28 % credits._Printer__data
29
29
30 copyright._Printer__data += """
30 copyright._Printer__data += """
31
31
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 All Rights Reserved."""
33 All Rights Reserved."""
34
34
35 #****************************************************************************
35 #****************************************************************************
36 # Required modules
36 # Required modules
37
37
38 # From the standard library
38 # From the standard library
39 import __main__
39 import __main__
40 import __builtin__
40 import __builtin__
41 import os
41 import os
42 import re
42 import re
43 import sys
43 import sys
44 import types
44 import types
45 from pprint import pprint,pformat
45 from pprint import pprint,pformat
46
46
47 # Our own
47 # Our own
48 from IPython import DPyGetOpt
48 from IPython import DPyGetOpt
49 from IPython.Struct import Struct
49 from IPython.Struct import Struct
50 from IPython.OutputTrap import OutputTrap
50 from IPython.OutputTrap import OutputTrap
51 from IPython.ConfigLoader import ConfigLoader
51 from IPython.ConfigLoader import ConfigLoader
52 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
52 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
53 from IPython.usage import cmd_line_usage,interactive_usage
53 from IPython.usage import cmd_line_usage,interactive_usage
54 from IPython.Prompts import CachedOutput
54 from IPython.Prompts import CachedOutput
55 from IPython.genutils import *
55 from IPython.genutils import *
56
56
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
58 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
59 shell_class=InteractiveShell,embedded=False,**kw):
59 shell_class=InteractiveShell,embedded=False,**kw):
60 """This is a dump of IPython into a single function.
60 """This is a dump of IPython into a single function.
61
61
62 Later it will have to be broken up in a sensible manner.
62 Later it will have to be broken up in a sensible manner.
63
63
64 Arguments:
64 Arguments:
65
65
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 script name, b/c DPyGetOpt strips the first argument only for the real
67 script name, b/c DPyGetOpt strips the first argument only for the real
68 sys.argv.
68 sys.argv.
69
69
70 - user_ns: a dict to be used as the user's namespace."""
70 - user_ns: a dict to be used as the user's namespace."""
71
71
72 #----------------------------------------------------------------------
72 #----------------------------------------------------------------------
73 # Defaults and initialization
73 # Defaults and initialization
74
74
75 # For developer debugging, deactivates crash handler and uses pdb.
75 # For developer debugging, deactivates crash handler and uses pdb.
76 DEVDEBUG = False
76 DEVDEBUG = False
77
77
78 if argv is None:
78 if argv is None:
79 argv = sys.argv
79 argv = sys.argv
80
80
81 # __IP is the main global that lives throughout and represents the whole
81 # __IP is the main global that lives throughout and represents the whole
82 # application. If the user redefines it, all bets are off as to what
82 # application. If the user redefines it, all bets are off as to what
83 # happens.
83 # happens.
84
84
85 # __IP is the name of he global which the caller will have accessible as
85 # __IP is the name of he global which the caller will have accessible as
86 # __IP.name. We set its name via the first parameter passed to
86 # __IP.name. We set its name via the first parameter passed to
87 # InteractiveShell:
87 # InteractiveShell:
88
88
89 IP = shell_class('__IP',user_ns=user_ns,embedded=embedded,**kw)
89 IP = shell_class('__IP',user_ns=user_ns,embedded=embedded,**kw)
90
90
91 # Put 'help' in the user namespace
91 # Put 'help' in the user namespace
92 from site import _Helper
92 from site import _Helper
93 IP.user_ns['help'] = _Helper()
93 IP.user_ns['help'] = _Helper()
94
94
95 if DEVDEBUG:
95 if DEVDEBUG:
96 # For developer debugging only (global flag)
96 # For developer debugging only (global flag)
97 from IPython import ultraTB
97 from IPython import ultraTB
98 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
98 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
99 else:
99 else:
100 # IPython itself shouldn't crash. This will produce a detailed
100 # IPython itself shouldn't crash. This will produce a detailed
101 # post-mortem if it does
101 # post-mortem if it does
102 from IPython import CrashHandler
102 from IPython import CrashHandler
103 sys.excepthook = CrashHandler.CrashHandler(IP)
103 sys.excepthook = CrashHandler.CrashHandler(IP)
104
104
105 IP.BANNER_PARTS = ['Python %s\n'
105 IP.BANNER_PARTS = ['Python %s\n'
106 'Type "copyright", "credits" or "license" '
106 'Type "copyright", "credits" or "license" '
107 'for more information.\n'
107 'for more information.\n'
108 % (sys.version.split('\n')[0],),
108 % (sys.version.split('\n')[0],),
109 "IPython %s -- An enhanced Interactive Python."
109 "IPython %s -- An enhanced Interactive Python."
110 % (__version__,),
110 % (__version__,),
111 """? -> Introduction to IPython's features.
111 """? -> Introduction to IPython's features.
112 %magic -> Information about IPython's 'magic' % functions.
112 %magic -> Information about IPython's 'magic' % functions.
113 help -> Python's own help system.
113 help -> Python's own help system.
114 object? -> Details about 'object'. ?object also works, ?? prints more.
114 object? -> Details about 'object'. ?object also works, ?? prints more.
115 """ ]
115 """ ]
116
116
117 IP.usage = interactive_usage
117 IP.usage = interactive_usage
118
118
119 # Platform-dependent suffix and directory names. We use _ipython instead
119 # Platform-dependent suffix and directory names. We use _ipython instead
120 # of .ipython under win32 b/c there's software that breaks with .named
120 # of .ipython under win32 b/c there's software that breaks with .named
121 # directories on that platform.
121 # directories on that platform.
122 if os.name == 'posix':
122 if os.name == 'posix':
123 rc_suffix = ''
123 rc_suffix = ''
124 ipdir_def = '.ipython'
124 ipdir_def = '.ipython'
125 else:
125 else:
126 rc_suffix = '.ini'
126 rc_suffix = '.ini'
127 ipdir_def = '_ipython'
127 ipdir_def = '_ipython'
128
128
129 # default directory for configuration
129 # default directory for configuration
130 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
130 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
131 os.path.join(IP.home_dir,ipdir_def)))
131 os.path.join(IP.home_dir,ipdir_def)))
132
132
133 # we need the directory where IPython itself is installed
133 # we need the directory where IPython itself is installed
134 import IPython
134 import IPython
135 IPython_dir = os.path.dirname(IPython.__file__)
135 IPython_dir = os.path.dirname(IPython.__file__)
136 del IPython
136 del IPython
137
137
138 #-------------------------------------------------------------------------
138 #-------------------------------------------------------------------------
139 # Command line handling
139 # Command line handling
140
140
141 # Valid command line options (uses DPyGetOpt syntax, like Perl's
141 # Valid command line options (uses DPyGetOpt syntax, like Perl's
142 # GetOpt::Long)
142 # GetOpt::Long)
143
143
144 # Any key not listed here gets deleted even if in the file (like session
144 # Any key not listed here gets deleted even if in the file (like session
145 # or profile). That's deliberate, to maintain the rc namespace clean.
145 # or profile). That's deliberate, to maintain the rc namespace clean.
146
146
147 # Each set of options appears twice: under _conv only the names are
147 # Each set of options appears twice: under _conv only the names are
148 # listed, indicating which type they must be converted to when reading the
148 # listed, indicating which type they must be converted to when reading the
149 # ipythonrc file. And under DPyGetOpt they are listed with the regular
149 # ipythonrc file. And under DPyGetOpt they are listed with the regular
150 # DPyGetOpt syntax (=s,=i,:f,etc).
150 # DPyGetOpt syntax (=s,=i,:f,etc).
151
151
152 # Make sure there's a space before each end of line (they get auto-joined!)
152 # Make sure there's a space before each end of line (they get auto-joined!)
153 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
153 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
154 'c=s classic|cl color_info! colors=s confirm_exit! '
154 'c=s classic|cl color_info! colors=s confirm_exit! '
155 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
155 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
156 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
156 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
157 'quick screen_length|sl=i prompts_pad_left=i '
157 'quick screen_length|sl=i prompts_pad_left=i '
158 'logfile|lf=s logplay|lp=s profile|p=s '
158 'logfile|lf=s logplay|lp=s profile|p=s '
159 'readline! readline_merge_completions! '
159 'readline! readline_merge_completions! '
160 'readline_omit__names! '
160 'readline_omit__names! '
161 'rcfile=s separate_in|si=s separate_out|so=s '
161 'rcfile=s separate_in|si=s separate_out|so=s '
162 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
162 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
163 'magic_docstrings system_verbose! '
163 'magic_docstrings system_verbose! '
164 'multi_line_specials! '
164 'multi_line_specials! '
165 'autoedit_syntax!')
165 'autoedit_syntax!')
166
166
167 # Options that can *only* appear at the cmd line (not in rcfiles).
167 # Options that can *only* appear at the cmd line (not in rcfiles).
168
168
169 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
169 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
170 # the 'C-c !' command in emacs automatically appends a -i option at the end.
170 # the 'C-c !' command in emacs automatically appends a -i option at the end.
171 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
171 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
172 'gthread! qthread! wthread! pylab! tk!')
172 'gthread! qthread! wthread! pylab! tk!')
173
173
174 # Build the actual name list to be used by DPyGetOpt
174 # Build the actual name list to be used by DPyGetOpt
175 opts_names = qw(cmdline_opts) + qw(cmdline_only)
175 opts_names = qw(cmdline_opts) + qw(cmdline_only)
176
176
177 # Set sensible command line defaults.
177 # Set sensible command line defaults.
178 # This should have everything from cmdline_opts and cmdline_only
178 # This should have everything from cmdline_opts and cmdline_only
179 opts_def = Struct(autocall = 1,
179 opts_def = Struct(autocall = 1,
180 autoedit_syntax = 1,
180 autoindent=0,
181 autoindent=0,
181 automagic = 1,
182 automagic = 1,
182 banner = 1,
183 banner = 1,
183 cache_size = 1000,
184 cache_size = 1000,
184 c = '',
185 c = '',
185 classic = 0,
186 classic = 0,
186 colors = 'NoColor',
187 colors = 'NoColor',
187 color_info = 0,
188 color_info = 0,
188 confirm_exit = 1,
189 confirm_exit = 1,
189 debug = 0,
190 debug = 0,
190 deep_reload = 0,
191 deep_reload = 0,
191 editor = '0',
192 editor = '0',
192 help = 0,
193 help = 0,
193 ignore = 0,
194 ignore = 0,
194 ipythondir = ipythondir,
195 ipythondir = ipythondir,
195 log = 0,
196 log = 0,
196 logfile = '',
197 logfile = '',
197 logplay = '',
198 logplay = '',
198 multi_line_specials = 1,
199 multi_line_specials = 1,
199 messages = 1,
200 messages = 1,
200 nosep = 0,
201 nosep = 0,
201 pdb = 0,
202 pdb = 0,
202 pprint = 0,
203 pprint = 0,
203 profile = '',
204 profile = '',
204 prompt_in1 = 'In [\\#]: ',
205 prompt_in1 = 'In [\\#]: ',
205 prompt_in2 = ' .\\D.: ',
206 prompt_in2 = ' .\\D.: ',
206 prompt_out = 'Out[\\#]: ',
207 prompt_out = 'Out[\\#]: ',
207 prompts_pad_left = 1,
208 prompts_pad_left = 1,
208 quick = 0,
209 quick = 0,
209 readline = 1,
210 readline = 1,
210 readline_merge_completions = 1,
211 readline_merge_completions = 1,
211 readline_omit__names = 0,
212 readline_omit__names = 0,
212 rcfile = 'ipythonrc' + rc_suffix,
213 rcfile = 'ipythonrc' + rc_suffix,
213 screen_length = 0,
214 screen_length = 0,
214 separate_in = '\n',
215 separate_in = '\n',
215 separate_out = '\n',
216 separate_out = '\n',
216 separate_out2 = '',
217 separate_out2 = '',
217 system_verbose = 0,
218 system_verbose = 0,
218 gthread = 0,
219 gthread = 0,
219 qthread = 0,
220 qthread = 0,
220 wthread = 0,
221 wthread = 0,
221 pylab = 0,
222 pylab = 0,
222 tk = 0,
223 tk = 0,
223 upgrade = 0,
224 upgrade = 0,
224 Version = 0,
225 Version = 0,
225 xmode = 'Verbose',
226 xmode = 'Verbose',
226 wildcards_case_sensitive = 1,
227 wildcards_case_sensitive = 1,
227 magic_docstrings = 0, # undocumented, for doc generation
228 magic_docstrings = 0, # undocumented, for doc generation
228 autoedit_syntax = 0,
229 )
229 )
230
230
231 # Things that will *only* appear in rcfiles (not at the command line).
231 # Things that will *only* appear in rcfiles (not at the command line).
232 # Make sure there's a space before each end of line (they get auto-joined!)
232 # Make sure there's a space before each end of line (they get auto-joined!)
233 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
233 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
234 qw_lol: 'import_some ',
234 qw_lol: 'import_some ',
235 # for things with embedded whitespace:
235 # for things with embedded whitespace:
236 list_strings:'execute alias readline_parse_and_bind ',
236 list_strings:'execute alias readline_parse_and_bind ',
237 # Regular strings need no conversion:
237 # Regular strings need no conversion:
238 None:'readline_remove_delims ',
238 None:'readline_remove_delims ',
239 }
239 }
240 # Default values for these
240 # Default values for these
241 rc_def = Struct(include = [],
241 rc_def = Struct(include = [],
242 import_mod = [],
242 import_mod = [],
243 import_all = [],
243 import_all = [],
244 import_some = [[]],
244 import_some = [[]],
245 execute = [],
245 execute = [],
246 execfile = [],
246 execfile = [],
247 alias = [],
247 alias = [],
248 readline_parse_and_bind = [],
248 readline_parse_and_bind = [],
249 readline_remove_delims = '',
249 readline_remove_delims = '',
250 )
250 )
251
251
252 # Build the type conversion dictionary from the above tables:
252 # Build the type conversion dictionary from the above tables:
253 typeconv = rcfile_opts.copy()
253 typeconv = rcfile_opts.copy()
254 typeconv.update(optstr2types(cmdline_opts))
254 typeconv.update(optstr2types(cmdline_opts))
255
255
256 # FIXME: the None key appears in both, put that back together by hand. Ugly!
256 # FIXME: the None key appears in both, put that back together by hand. Ugly!
257 typeconv[None] += ' ' + rcfile_opts[None]
257 typeconv[None] += ' ' + rcfile_opts[None]
258
258
259 # Remove quotes at ends of all strings (used to protect spaces)
259 # Remove quotes at ends of all strings (used to protect spaces)
260 typeconv[unquote_ends] = typeconv[None]
260 typeconv[unquote_ends] = typeconv[None]
261 del typeconv[None]
261 del typeconv[None]
262
262
263 # Build the list we'll use to make all config decisions with defaults:
263 # Build the list we'll use to make all config decisions with defaults:
264 opts_all = opts_def.copy()
264 opts_all = opts_def.copy()
265 opts_all.update(rc_def)
265 opts_all.update(rc_def)
266
266
267 # Build conflict resolver for recursive loading of config files:
267 # Build conflict resolver for recursive loading of config files:
268 # - preserve means the outermost file maintains the value, it is not
268 # - preserve means the outermost file maintains the value, it is not
269 # overwritten if an included file has the same key.
269 # overwritten if an included file has the same key.
270 # - add_flip applies + to the two values, so it better make sense to add
270 # - add_flip applies + to the two values, so it better make sense to add
271 # those types of keys. But it flips them first so that things loaded
271 # those types of keys. But it flips them first so that things loaded
272 # deeper in the inclusion chain have lower precedence.
272 # deeper in the inclusion chain have lower precedence.
273 conflict = {'preserve': ' '.join([ typeconv[int],
273 conflict = {'preserve': ' '.join([ typeconv[int],
274 typeconv[unquote_ends] ]),
274 typeconv[unquote_ends] ]),
275 'add_flip': ' '.join([ typeconv[qwflat],
275 'add_flip': ' '.join([ typeconv[qwflat],
276 typeconv[qw_lol],
276 typeconv[qw_lol],
277 typeconv[list_strings] ])
277 typeconv[list_strings] ])
278 }
278 }
279
279
280 # Now actually process the command line
280 # Now actually process the command line
281 getopt = DPyGetOpt.DPyGetOpt()
281 getopt = DPyGetOpt.DPyGetOpt()
282 getopt.setIgnoreCase(0)
282 getopt.setIgnoreCase(0)
283
283
284 getopt.parseConfiguration(opts_names)
284 getopt.parseConfiguration(opts_names)
285
285
286 try:
286 try:
287 getopt.processArguments(argv)
287 getopt.processArguments(argv)
288 except:
288 except:
289 print cmd_line_usage
289 print cmd_line_usage
290 warn('\nError in Arguments: ' + `sys.exc_value`)
290 warn('\nError in Arguments: ' + `sys.exc_value`)
291 sys.exit(1)
291 sys.exit(1)
292
292
293 # convert the options dict to a struct for much lighter syntax later
293 # convert the options dict to a struct for much lighter syntax later
294 opts = Struct(getopt.optionValues)
294 opts = Struct(getopt.optionValues)
295 args = getopt.freeValues
295 args = getopt.freeValues
296
296
297 # this is the struct (which has default values at this point) with which
297 # this is the struct (which has default values at this point) with which
298 # we make all decisions:
298 # we make all decisions:
299 opts_all.update(opts)
299 opts_all.update(opts)
300
300
301 # Options that force an immediate exit
301 # Options that force an immediate exit
302 if opts_all.help:
302 if opts_all.help:
303 page(cmd_line_usage)
303 page(cmd_line_usage)
304 sys.exit()
304 sys.exit()
305
305
306 if opts_all.Version:
306 if opts_all.Version:
307 print __version__
307 print __version__
308 sys.exit()
308 sys.exit()
309
309
310 if opts_all.magic_docstrings:
310 if opts_all.magic_docstrings:
311 IP.magic_magic('-latex')
311 IP.magic_magic('-latex')
312 sys.exit()
312 sys.exit()
313
313
314 # Create user config directory if it doesn't exist. This must be done
314 # Create user config directory if it doesn't exist. This must be done
315 # *after* getting the cmd line options.
315 # *after* getting the cmd line options.
316 if not os.path.isdir(opts_all.ipythondir):
316 if not os.path.isdir(opts_all.ipythondir):
317 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
317 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
318
318
319 # upgrade user config files while preserving a copy of the originals
319 # upgrade user config files while preserving a copy of the originals
320 if opts_all.upgrade:
320 if opts_all.upgrade:
321 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
321 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
322
322
323 # check mutually exclusive options in the *original* command line
323 # check mutually exclusive options in the *original* command line
324 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
324 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
325 qw('classic profile'),qw('classic rcfile')])
325 qw('classic profile'),qw('classic rcfile')])
326
326
327 # default logfilename used when -log is called.
327 # default logfilename used when -log is called.
328 IP.LOGDEF = 'ipython.log'
328 IP.LOGDEF = 'ipython.log'
329
329
330 #---------------------------------------------------------------------------
330 #---------------------------------------------------------------------------
331 # Log replay
331 # Log replay
332
332
333 # if -logplay, we need to 'become' the other session. That basically means
333 # if -logplay, we need to 'become' the other session. That basically means
334 # replacing the current command line environment with that of the old
334 # replacing the current command line environment with that of the old
335 # session and moving on.
335 # session and moving on.
336
336
337 # this is needed so that later we know we're in session reload mode, as
337 # this is needed so that later we know we're in session reload mode, as
338 # opts_all will get overwritten:
338 # opts_all will get overwritten:
339 load_logplay = 0
339 load_logplay = 0
340
340
341 if opts_all.logplay:
341 if opts_all.logplay:
342 load_logplay = opts_all.logplay
342 load_logplay = opts_all.logplay
343 opts_debug_save = opts_all.debug
343 opts_debug_save = opts_all.debug
344 try:
344 try:
345 logplay = open(opts_all.logplay)
345 logplay = open(opts_all.logplay)
346 except IOError:
346 except IOError:
347 if opts_all.debug: IP.InteractiveTB()
347 if opts_all.debug: IP.InteractiveTB()
348 warn('Could not open logplay file '+`opts_all.logplay`)
348 warn('Could not open logplay file '+`opts_all.logplay`)
349 # restore state as if nothing had happened and move on, but make
349 # restore state as if nothing had happened and move on, but make
350 # sure that later we don't try to actually load the session file
350 # sure that later we don't try to actually load the session file
351 logplay = None
351 logplay = None
352 load_logplay = 0
352 load_logplay = 0
353 del opts_all.logplay
353 del opts_all.logplay
354 else:
354 else:
355 try:
355 try:
356 logplay.readline()
356 logplay.readline()
357 logplay.readline();
357 logplay.readline();
358 # this reloads that session's command line
358 # this reloads that session's command line
359 cmd = logplay.readline()[6:]
359 cmd = logplay.readline()[6:]
360 exec cmd
360 exec cmd
361 # restore the true debug flag given so that the process of
361 # restore the true debug flag given so that the process of
362 # session loading itself can be monitored.
362 # session loading itself can be monitored.
363 opts.debug = opts_debug_save
363 opts.debug = opts_debug_save
364 # save the logplay flag so later we don't overwrite the log
364 # save the logplay flag so later we don't overwrite the log
365 opts.logplay = load_logplay
365 opts.logplay = load_logplay
366 # now we must update our own structure with defaults
366 # now we must update our own structure with defaults
367 opts_all.update(opts)
367 opts_all.update(opts)
368 # now load args
368 # now load args
369 cmd = logplay.readline()[6:]
369 cmd = logplay.readline()[6:]
370 exec cmd
370 exec cmd
371 logplay.close()
371 logplay.close()
372 except:
372 except:
373 logplay.close()
373 logplay.close()
374 if opts_all.debug: IP.InteractiveTB()
374 if opts_all.debug: IP.InteractiveTB()
375 warn("Logplay file lacking full configuration information.\n"
375 warn("Logplay file lacking full configuration information.\n"
376 "I'll try to read it, but some things may not work.")
376 "I'll try to read it, but some things may not work.")
377
377
378 #-------------------------------------------------------------------------
378 #-------------------------------------------------------------------------
379 # set up output traps: catch all output from files, being run, modules
379 # set up output traps: catch all output from files, being run, modules
380 # loaded, etc. Then give it to the user in a clean form at the end.
380 # loaded, etc. Then give it to the user in a clean form at the end.
381
381
382 msg_out = 'Output messages. '
382 msg_out = 'Output messages. '
383 msg_err = 'Error messages. '
383 msg_err = 'Error messages. '
384 msg_sep = '\n'
384 msg_sep = '\n'
385 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
385 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
386 msg_err,msg_sep,debug,
386 msg_err,msg_sep,debug,
387 quiet_out=1),
387 quiet_out=1),
388 user_exec = OutputTrap('User File Execution',msg_out,
388 user_exec = OutputTrap('User File Execution',msg_out,
389 msg_err,msg_sep,debug),
389 msg_err,msg_sep,debug),
390 logplay = OutputTrap('Log Loader',msg_out,
390 logplay = OutputTrap('Log Loader',msg_out,
391 msg_err,msg_sep,debug),
391 msg_err,msg_sep,debug),
392 summary = ''
392 summary = ''
393 )
393 )
394
394
395 #-------------------------------------------------------------------------
395 #-------------------------------------------------------------------------
396 # Process user ipythonrc-type configuration files
396 # Process user ipythonrc-type configuration files
397
397
398 # turn on output trapping and log to msg.config
398 # turn on output trapping and log to msg.config
399 # remember that with debug on, trapping is actually disabled
399 # remember that with debug on, trapping is actually disabled
400 msg.config.trap_all()
400 msg.config.trap_all()
401
401
402 # look for rcfile in current or default directory
402 # look for rcfile in current or default directory
403 try:
403 try:
404 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
404 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
405 except IOError:
405 except IOError:
406 if opts_all.debug: IP.InteractiveTB()
406 if opts_all.debug: IP.InteractiveTB()
407 warn('Configuration file %s not found. Ignoring request.'
407 warn('Configuration file %s not found. Ignoring request.'
408 % (opts_all.rcfile) )
408 % (opts_all.rcfile) )
409
409
410 # 'profiles' are a shorthand notation for config filenames
410 # 'profiles' are a shorthand notation for config filenames
411 if opts_all.profile:
411 if opts_all.profile:
412 try:
412 try:
413 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
413 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
414 + rc_suffix,
414 + rc_suffix,
415 opts_all.ipythondir)
415 opts_all.ipythondir)
416 except IOError:
416 except IOError:
417 if opts_all.debug: IP.InteractiveTB()
417 if opts_all.debug: IP.InteractiveTB()
418 opts.profile = '' # remove profile from options if invalid
418 opts.profile = '' # remove profile from options if invalid
419 warn('Profile configuration file %s not found. Ignoring request.'
419 warn('Profile configuration file %s not found. Ignoring request.'
420 % (opts_all.profile) )
420 % (opts_all.profile) )
421
421
422 # load the config file
422 # load the config file
423 rcfiledata = None
423 rcfiledata = None
424 if opts_all.quick:
424 if opts_all.quick:
425 print 'Launching IPython in quick mode. No config file read.'
425 print 'Launching IPython in quick mode. No config file read.'
426 elif opts_all.classic:
426 elif opts_all.classic:
427 print 'Launching IPython in classic mode. No config file read.'
427 print 'Launching IPython in classic mode. No config file read.'
428 elif opts_all.rcfile:
428 elif opts_all.rcfile:
429 try:
429 try:
430 cfg_loader = ConfigLoader(conflict)
430 cfg_loader = ConfigLoader(conflict)
431 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
431 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
432 'include',opts_all.ipythondir,
432 'include',opts_all.ipythondir,
433 purge = 1,
433 purge = 1,
434 unique = conflict['preserve'])
434 unique = conflict['preserve'])
435 except:
435 except:
436 IP.InteractiveTB()
436 IP.InteractiveTB()
437 warn('Problems loading configuration file '+
437 warn('Problems loading configuration file '+
438 `opts_all.rcfile`+
438 `opts_all.rcfile`+
439 '\nStarting with default -bare bones- configuration.')
439 '\nStarting with default -bare bones- configuration.')
440 else:
440 else:
441 warn('No valid configuration file found in either currrent directory\n'+
441 warn('No valid configuration file found in either currrent directory\n'+
442 'or in the IPython config. directory: '+`opts_all.ipythondir`+
442 'or in the IPython config. directory: '+`opts_all.ipythondir`+
443 '\nProceeding with internal defaults.')
443 '\nProceeding with internal defaults.')
444
444
445 #------------------------------------------------------------------------
445 #------------------------------------------------------------------------
446 # Set exception handlers in mode requested by user.
446 # Set exception handlers in mode requested by user.
447 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
447 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
448 IP.magic_xmode(opts_all.xmode)
448 IP.magic_xmode(opts_all.xmode)
449 otrap.release_out()
449 otrap.release_out()
450
450
451 #------------------------------------------------------------------------
451 #------------------------------------------------------------------------
452 # Execute user config
452 # Execute user config
453
453
454 # Create a valid config structure with the right precedence order:
454 # Create a valid config structure with the right precedence order:
455 # defaults < rcfile < command line. This needs to be in the instance, so
455 # defaults < rcfile < command line. This needs to be in the instance, so
456 # that method calls below that rely on it find it.
456 # that method calls below that rely on it find it.
457 IP.rc = rc_def.copy()
457 IP.rc = rc_def.copy()
458
458
459 # Work with a local alias inside this routine to avoid unnecessary
459 # Work with a local alias inside this routine to avoid unnecessary
460 # attribute lookups.
460 # attribute lookups.
461 IP_rc = IP.rc
461 IP_rc = IP.rc
462
462
463 IP_rc.update(opts_def)
463 IP_rc.update(opts_def)
464 if rcfiledata:
464 if rcfiledata:
465 # now we can update
465 # now we can update
466 IP_rc.update(rcfiledata)
466 IP_rc.update(rcfiledata)
467 IP_rc.update(opts)
467 IP_rc.update(opts)
468 IP_rc.update(rc_override)
468 IP_rc.update(rc_override)
469
469
470 # Store the original cmd line for reference:
470 # Store the original cmd line for reference:
471 IP_rc.opts = opts
471 IP_rc.opts = opts
472 IP_rc.args = args
472 IP_rc.args = args
473
473
474 # create a *runtime* Struct like rc for holding parameters which may be
474 # create a *runtime* Struct like rc for holding parameters which may be
475 # created and/or modified by runtime user extensions.
475 # created and/or modified by runtime user extensions.
476 IP.runtime_rc = Struct()
476 IP.runtime_rc = Struct()
477
477
478 # from this point on, all config should be handled through IP_rc,
478 # from this point on, all config should be handled through IP_rc,
479 # opts* shouldn't be used anymore.
479 # opts* shouldn't be used anymore.
480
480
481 # add personal .ipython dir to sys.path so that users can put things in
481 # add personal .ipython dir to sys.path so that users can put things in
482 # there for customization
482 # there for customization
483 sys.path.append(IP_rc.ipythondir)
483 sys.path.append(IP_rc.ipythondir)
484 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
484 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
485
485
486 # update IP_rc with some special things that need manual
486 # update IP_rc with some special things that need manual
487 # tweaks. Basically options which affect other options. I guess this
487 # tweaks. Basically options which affect other options. I guess this
488 # should just be written so that options are fully orthogonal and we
488 # should just be written so that options are fully orthogonal and we
489 # wouldn't worry about this stuff!
489 # wouldn't worry about this stuff!
490
490
491 if IP_rc.classic:
491 if IP_rc.classic:
492 IP_rc.quick = 1
492 IP_rc.quick = 1
493 IP_rc.cache_size = 0
493 IP_rc.cache_size = 0
494 IP_rc.pprint = 0
494 IP_rc.pprint = 0
495 IP_rc.prompt_in1 = '>>> '
495 IP_rc.prompt_in1 = '>>> '
496 IP_rc.prompt_in2 = '... '
496 IP_rc.prompt_in2 = '... '
497 IP_rc.prompt_out = ''
497 IP_rc.prompt_out = ''
498 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
498 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
499 IP_rc.colors = 'NoColor'
499 IP_rc.colors = 'NoColor'
500 IP_rc.xmode = 'Plain'
500 IP_rc.xmode = 'Plain'
501
501
502 # configure readline
502 # configure readline
503 # Define the history file for saving commands in between sessions
503 # Define the history file for saving commands in between sessions
504 if IP_rc.profile:
504 if IP_rc.profile:
505 histfname = 'history-%s' % IP_rc.profile
505 histfname = 'history-%s' % IP_rc.profile
506 else:
506 else:
507 histfname = 'history'
507 histfname = 'history'
508 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
508 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
509
509
510 # update exception handlers with rc file status
510 # update exception handlers with rc file status
511 otrap.trap_out() # I don't want these messages ever.
511 otrap.trap_out() # I don't want these messages ever.
512 IP.magic_xmode(IP_rc.xmode)
512 IP.magic_xmode(IP_rc.xmode)
513 otrap.release_out()
513 otrap.release_out()
514
514
515 # activate logging if requested and not reloading a log
515 # activate logging if requested and not reloading a log
516 if IP_rc.logplay:
516 if IP_rc.logplay:
517 IP.magic_logstart(IP_rc.logplay + ' append')
517 IP.magic_logstart(IP_rc.logplay + ' append')
518 elif IP_rc.logfile:
518 elif IP_rc.logfile:
519 IP.magic_logstart(IP_rc.logfile)
519 IP.magic_logstart(IP_rc.logfile)
520 elif IP_rc.log:
520 elif IP_rc.log:
521 IP.magic_logstart()
521 IP.magic_logstart()
522
522
523 # find user editor so that it we don't have to look it up constantly
523 # find user editor so that it we don't have to look it up constantly
524 if IP_rc.editor.strip()=='0':
524 if IP_rc.editor.strip()=='0':
525 try:
525 try:
526 ed = os.environ['EDITOR']
526 ed = os.environ['EDITOR']
527 except KeyError:
527 except KeyError:
528 if os.name == 'posix':
528 if os.name == 'posix':
529 ed = 'vi' # the only one guaranteed to be there!
529 ed = 'vi' # the only one guaranteed to be there!
530 else:
530 else:
531 ed = 'notepad' # same in Windows!
531 ed = 'notepad' # same in Windows!
532 IP_rc.editor = ed
532 IP_rc.editor = ed
533
533
534 # Keep track of whether this is an embedded instance or not (useful for
534 # Keep track of whether this is an embedded instance or not (useful for
535 # post-mortems).
535 # post-mortems).
536 IP_rc.embedded = IP.embedded
536 IP_rc.embedded = IP.embedded
537
537
538 # Recursive reload
538 # Recursive reload
539 try:
539 try:
540 from IPython import deep_reload
540 from IPython import deep_reload
541 if IP_rc.deep_reload:
541 if IP_rc.deep_reload:
542 __builtin__.reload = deep_reload.reload
542 __builtin__.reload = deep_reload.reload
543 else:
543 else:
544 __builtin__.dreload = deep_reload.reload
544 __builtin__.dreload = deep_reload.reload
545 del deep_reload
545 del deep_reload
546 except ImportError:
546 except ImportError:
547 pass
547 pass
548
548
549 # Save the current state of our namespace so that the interactive shell
549 # Save the current state of our namespace so that the interactive shell
550 # can later know which variables have been created by us from config files
550 # can later know which variables have been created by us from config files
551 # and loading. This way, loading a file (in any way) is treated just like
551 # and loading. This way, loading a file (in any way) is treated just like
552 # defining things on the command line, and %who works as expected.
552 # defining things on the command line, and %who works as expected.
553
553
554 # DON'T do anything that affects the namespace beyond this point!
554 # DON'T do anything that affects the namespace beyond this point!
555 IP.internal_ns.update(__main__.__dict__)
555 IP.internal_ns.update(__main__.__dict__)
556
556
557 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
557 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
558
558
559 # Now run through the different sections of the users's config
559 # Now run through the different sections of the users's config
560 if IP_rc.debug:
560 if IP_rc.debug:
561 print 'Trying to execute the following configuration structure:'
561 print 'Trying to execute the following configuration structure:'
562 print '(Things listed first are deeper in the inclusion tree and get'
562 print '(Things listed first are deeper in the inclusion tree and get'
563 print 'loaded first).\n'
563 print 'loaded first).\n'
564 pprint(IP_rc.__dict__)
564 pprint(IP_rc.__dict__)
565
565
566 for mod in IP_rc.import_mod:
566 for mod in IP_rc.import_mod:
567 try:
567 try:
568 exec 'import '+mod in IP.user_ns
568 exec 'import '+mod in IP.user_ns
569 except :
569 except :
570 IP.InteractiveTB()
570 IP.InteractiveTB()
571 import_fail_info(mod)
571 import_fail_info(mod)
572
572
573 for mod_fn in IP_rc.import_some:
573 for mod_fn in IP_rc.import_some:
574 if mod_fn == []: break
574 if mod_fn == []: break
575 mod,fn = mod_fn[0],','.join(mod_fn[1:])
575 mod,fn = mod_fn[0],','.join(mod_fn[1:])
576 try:
576 try:
577 exec 'from '+mod+' import '+fn in IP.user_ns
577 exec 'from '+mod+' import '+fn in IP.user_ns
578 except :
578 except :
579 IP.InteractiveTB()
579 IP.InteractiveTB()
580 import_fail_info(mod,fn)
580 import_fail_info(mod,fn)
581
581
582 for mod in IP_rc.import_all:
582 for mod in IP_rc.import_all:
583 try:
583 try:
584 exec 'from '+mod+' import *' in IP.user_ns
584 exec 'from '+mod+' import *' in IP.user_ns
585 except :
585 except :
586 IP.InteractiveTB()
586 IP.InteractiveTB()
587 import_fail_info(mod)
587 import_fail_info(mod)
588
588
589 for code in IP_rc.execute:
589 for code in IP_rc.execute:
590 try:
590 try:
591 exec code in IP.user_ns
591 exec code in IP.user_ns
592 except:
592 except:
593 IP.InteractiveTB()
593 IP.InteractiveTB()
594 warn('Failure executing code: ' + `code`)
594 warn('Failure executing code: ' + `code`)
595
595
596 # Execute the files the user wants in ipythonrc
596 # Execute the files the user wants in ipythonrc
597 for file in IP_rc.execfile:
597 for file in IP_rc.execfile:
598 try:
598 try:
599 file = filefind(file,sys.path+[IPython_dir])
599 file = filefind(file,sys.path+[IPython_dir])
600 except IOError:
600 except IOError:
601 warn(itpl('File $file not found. Skipping it.'))
601 warn(itpl('File $file not found. Skipping it.'))
602 else:
602 else:
603 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
603 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
604
604
605 # release stdout and stderr and save config log into a global summary
605 # release stdout and stderr and save config log into a global summary
606 msg.config.release_all()
606 msg.config.release_all()
607 if IP_rc.messages:
607 if IP_rc.messages:
608 msg.summary += msg.config.summary_all()
608 msg.summary += msg.config.summary_all()
609
609
610 #------------------------------------------------------------------------
610 #------------------------------------------------------------------------
611 # Setup interactive session
611 # Setup interactive session
612
612
613 # Now we should be fully configured. We can then execute files or load
613 # Now we should be fully configured. We can then execute files or load
614 # things only needed for interactive use. Then we'll open the shell.
614 # things only needed for interactive use. Then we'll open the shell.
615
615
616 # Take a snapshot of the user namespace before opening the shell. That way
616 # Take a snapshot of the user namespace before opening the shell. That way
617 # we'll be able to identify which things were interactively defined and
617 # we'll be able to identify which things were interactively defined and
618 # which were defined through config files.
618 # which were defined through config files.
619 IP.user_config_ns = IP.user_ns.copy()
619 IP.user_config_ns = IP.user_ns.copy()
620
620
621 # Force reading a file as if it were a session log. Slower but safer.
621 # Force reading a file as if it were a session log. Slower but safer.
622 if load_logplay:
622 if load_logplay:
623 print 'Replaying log...'
623 print 'Replaying log...'
624 try:
624 try:
625 if IP_rc.debug:
625 if IP_rc.debug:
626 logplay_quiet = 0
626 logplay_quiet = 0
627 else:
627 else:
628 logplay_quiet = 1
628 logplay_quiet = 1
629
629
630 msg.logplay.trap_all()
630 msg.logplay.trap_all()
631 IP.safe_execfile(load_logplay,IP.user_ns,
631 IP.safe_execfile(load_logplay,IP.user_ns,
632 islog = 1, quiet = logplay_quiet)
632 islog = 1, quiet = logplay_quiet)
633 msg.logplay.release_all()
633 msg.logplay.release_all()
634 if IP_rc.messages:
634 if IP_rc.messages:
635 msg.summary += msg.logplay.summary_all()
635 msg.summary += msg.logplay.summary_all()
636 except:
636 except:
637 warn('Problems replaying logfile %s.' % load_logplay)
637 warn('Problems replaying logfile %s.' % load_logplay)
638 IP.InteractiveTB()
638 IP.InteractiveTB()
639
639
640 # Load remaining files in command line
640 # Load remaining files in command line
641 msg.user_exec.trap_all()
641 msg.user_exec.trap_all()
642
642
643 # Do NOT execute files named in the command line as scripts to be loaded
643 # Do NOT execute files named in the command line as scripts to be loaded
644 # by embedded instances. Doing so has the potential for an infinite
644 # by embedded instances. Doing so has the potential for an infinite
645 # recursion if there are exceptions thrown in the process.
645 # recursion if there are exceptions thrown in the process.
646
646
647 # XXX FIXME: the execution of user files should be moved out to after
647 # XXX FIXME: the execution of user files should be moved out to after
648 # ipython is fully initialized, just as if they were run via %run at the
648 # ipython is fully initialized, just as if they were run via %run at the
649 # ipython prompt. This would also give them the benefit of ipython's
649 # ipython prompt. This would also give them the benefit of ipython's
650 # nice tracebacks.
650 # nice tracebacks.
651
651
652 if not embedded and IP_rc.args:
652 if not embedded and IP_rc.args:
653 name_save = IP.user_ns['__name__']
653 name_save = IP.user_ns['__name__']
654 IP.user_ns['__name__'] = '__main__'
654 IP.user_ns['__name__'] = '__main__'
655 try:
655 try:
656 # Set our own excepthook in case the user code tries to call it
656 # Set our own excepthook in case the user code tries to call it
657 # directly. This prevents triggering the IPython crash handler.
657 # directly. This prevents triggering the IPython crash handler.
658 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
658 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
659 for run in args:
659 for run in args:
660 IP.safe_execfile(run,IP.user_ns)
660 IP.safe_execfile(run,IP.user_ns)
661 finally:
661 finally:
662 # Reset our crash handler in place
662 # Reset our crash handler in place
663 sys.excepthook = old_excepthook
663 sys.excepthook = old_excepthook
664
664
665 IP.user_ns['__name__'] = name_save
665 IP.user_ns['__name__'] = name_save
666
666
667 msg.user_exec.release_all()
667 msg.user_exec.release_all()
668 if IP_rc.messages:
668 if IP_rc.messages:
669 msg.summary += msg.user_exec.summary_all()
669 msg.summary += msg.user_exec.summary_all()
670
670
671 # since we can't specify a null string on the cmd line, 0 is the equivalent:
671 # since we can't specify a null string on the cmd line, 0 is the equivalent:
672 if IP_rc.nosep:
672 if IP_rc.nosep:
673 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
673 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
674 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
674 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
675 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
675 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
676 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
676 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
677 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
677 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
678 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
678 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
679 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
679 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
680
680
681 # Determine how many lines at the bottom of the screen are needed for
681 # Determine how many lines at the bottom of the screen are needed for
682 # showing prompts, so we can know wheter long strings are to be printed or
682 # showing prompts, so we can know wheter long strings are to be printed or
683 # paged:
683 # paged:
684 num_lines_bot = IP_rc.separate_in.count('\n')+1
684 num_lines_bot = IP_rc.separate_in.count('\n')+1
685 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
685 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
686 # Initialize cache, set in/out prompts and printing system
686 # Initialize cache, set in/out prompts and printing system
687 IP.outputcache = CachedOutput(IP_rc.cache_size,
687 IP.outputcache = CachedOutput(IP_rc.cache_size,
688 IP_rc.pprint,
688 IP_rc.pprint,
689 input_sep = IP_rc.separate_in,
689 input_sep = IP_rc.separate_in,
690 output_sep = IP_rc.separate_out,
690 output_sep = IP_rc.separate_out,
691 output_sep2 = IP_rc.separate_out2,
691 output_sep2 = IP_rc.separate_out2,
692 ps1 = IP_rc.prompt_in1,
692 ps1 = IP_rc.prompt_in1,
693 ps2 = IP_rc.prompt_in2,
693 ps2 = IP_rc.prompt_in2,
694 ps_out = IP_rc.prompt_out,
694 ps_out = IP_rc.prompt_out,
695 user_ns = IP.user_ns,
695 user_ns = IP.user_ns,
696 input_hist = IP.input_hist,
696 input_hist = IP.input_hist,
697 pad_left = IP_rc.prompts_pad_left)
697 pad_left = IP_rc.prompts_pad_left)
698
698
699 # user may have over-ridden the default print hook:
699 # user may have over-ridden the default print hook:
700 try:
700 try:
701 IP.outputcache.__class__.display = IP.hooks.display
701 IP.outputcache.__class__.display = IP.hooks.display
702 except AttributeError:
702 except AttributeError:
703 pass
703 pass
704
704
705 # Set calling of pdb on exceptions
705 # Set calling of pdb on exceptions
706 IP.InteractiveTB.call_pdb = IP_rc.pdb
706 IP.InteractiveTB.call_pdb = IP_rc.pdb
707
707
708 # I don't like assigning globally to sys, because it means when embedding
708 # I don't like assigning globally to sys, because it means when embedding
709 # instances, each embedded instance overrides the previous choice. But
709 # instances, each embedded instance overrides the previous choice. But
710 # sys.displayhook seems to be called internally by exec, so I don't see a
710 # sys.displayhook seems to be called internally by exec, so I don't see a
711 # way around it.
711 # way around it.
712 sys.displayhook = IP.outputcache
712 sys.displayhook = IP.outputcache
713
713
714 # we need to know globally if we're caching i/o or not
714 # we need to know globally if we're caching i/o or not
715 IP.do_full_cache = IP.outputcache.do_full_cache
715 IP.do_full_cache = IP.outputcache.do_full_cache
716
716
717 # configure startup banner
717 # configure startup banner
718 if IP_rc.c: # regular python doesn't print the banner with -c
718 if IP_rc.c: # regular python doesn't print the banner with -c
719 IP_rc.banner = 0
719 IP_rc.banner = 0
720 if IP_rc.banner:
720 if IP_rc.banner:
721 BANN_P = IP.BANNER_PARTS
721 BANN_P = IP.BANNER_PARTS
722 else:
722 else:
723 BANN_P = []
723 BANN_P = []
724
724
725 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
725 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
726
726
727 # add message log (possibly empty)
727 # add message log (possibly empty)
728 if msg.summary: BANN_P.append(msg.summary)
728 if msg.summary: BANN_P.append(msg.summary)
729 # Final banner is a string
729 # Final banner is a string
730 IP.BANNER = '\n'.join(BANN_P)
730 IP.BANNER = '\n'.join(BANN_P)
731
731
732 # Finalize the IPython instance. This assumes the rc structure is fully
732 # Finalize the IPython instance. This assumes the rc structure is fully
733 # in place.
733 # in place.
734 IP.post_config_initialization()
734 IP.post_config_initialization()
735
735
736 return IP
736 return IP
737 #************************ end of file <ipmaker.py> **************************
737 #************************ end of file <ipmaker.py> **************************
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now