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