Show More
@@ -1,1235 +1,1236 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """IPython Shell classes. |
|
3 | 3 | |
|
4 | 4 | All the matplotlib support code was co-developed with John Hunter, |
|
5 | 5 | matplotlib's author. |
|
6 | 6 | |
|
7 | 7 | $Id: Shell.py 3024 2008-02-07 15:34:42Z darren.dale $""" |
|
8 | 8 | |
|
9 | 9 | #***************************************************************************** |
|
10 | 10 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
11 | 11 | # |
|
12 | 12 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | 13 | # the file COPYING, distributed as part of this software. |
|
14 | 14 | #***************************************************************************** |
|
15 | 15 | |
|
16 | 16 | from IPython import Release |
|
17 | 17 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
18 | 18 | __license__ = Release.license |
|
19 | 19 | |
|
20 | 20 | # Code begins |
|
21 | 21 | # Stdlib imports |
|
22 | 22 | import __builtin__ |
|
23 | 23 | import __main__ |
|
24 | 24 | import Queue |
|
25 | 25 | import inspect |
|
26 | 26 | import os |
|
27 | 27 | import sys |
|
28 | 28 | import thread |
|
29 | 29 | import threading |
|
30 | 30 | import time |
|
31 | 31 | |
|
32 | 32 | from signal import signal, SIGINT |
|
33 | 33 | |
|
34 | 34 | try: |
|
35 | 35 | import ctypes |
|
36 | 36 | HAS_CTYPES = True |
|
37 | 37 | except ImportError: |
|
38 | 38 | HAS_CTYPES = False |
|
39 | 39 | |
|
40 | 40 | # IPython imports |
|
41 | 41 | import IPython |
|
42 | 42 | from IPython import ultraTB, ipapi |
|
43 | 43 | from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no |
|
44 | 44 | from IPython.iplib import InteractiveShell |
|
45 | 45 | from IPython.ipmaker import make_IPython |
|
46 | 46 | from IPython.Magic import Magic |
|
47 | 47 | from IPython.ipstruct import Struct |
|
48 | 48 | |
|
49 | 49 | # Globals |
|
50 | 50 | # global flag to pass around information about Ctrl-C without exceptions |
|
51 | 51 | KBINT = False |
|
52 | 52 | |
|
53 | 53 | # global flag to turn on/off Tk support. |
|
54 | 54 | USE_TK = False |
|
55 | 55 | |
|
56 | 56 | # ID for the main thread, used for cross-thread exceptions |
|
57 | 57 | MAIN_THREAD_ID = thread.get_ident() |
|
58 | 58 | |
|
59 | 59 | # Tag when runcode() is active, for exception handling |
|
60 | 60 | CODE_RUN = None |
|
61 | 61 | |
|
62 | 62 | # Default timeout for waiting for multithreaded shells (in seconds) |
|
63 | 63 | GUI_TIMEOUT = 10 |
|
64 | 64 | |
|
65 | 65 | #----------------------------------------------------------------------------- |
|
66 | 66 | # This class is trivial now, but I want to have it in to publish a clean |
|
67 | 67 | # interface. Later when the internals are reorganized, code that uses this |
|
68 | 68 | # shouldn't have to change. |
|
69 | 69 | |
|
70 | 70 | class IPShell: |
|
71 | 71 | """Create an IPython instance.""" |
|
72 | 72 | |
|
73 | 73 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
74 | 74 | debug=1,shell_class=InteractiveShell): |
|
75 | 75 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
76 | 76 | user_global_ns=user_global_ns, |
|
77 | 77 | debug=debug,shell_class=shell_class) |
|
78 | 78 | |
|
79 | 79 | def mainloop(self,sys_exit=0,banner=None): |
|
80 | 80 | self.IP.mainloop(banner) |
|
81 | 81 | if sys_exit: |
|
82 | 82 | sys.exit() |
|
83 | 83 | |
|
84 | 84 | #----------------------------------------------------------------------------- |
|
85 | 85 | def kill_embedded(self,parameter_s=''): |
|
86 | 86 | """%kill_embedded : deactivate for good the current embedded IPython. |
|
87 | 87 | |
|
88 | 88 | This function (after asking for confirmation) sets an internal flag so that |
|
89 | 89 | an embedded IPython will never activate again. This is useful to |
|
90 | 90 | permanently disable a shell that is being called inside a loop: once you've |
|
91 | 91 | figured out what you needed from it, you may then kill it and the program |
|
92 | 92 | will then continue to run without the interactive shell interfering again. |
|
93 | 93 | """ |
|
94 | 94 | |
|
95 | 95 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " |
|
96 | 96 | "(y/n)? [y/N] ",'n') |
|
97 | 97 | if kill: |
|
98 | 98 | self.shell.embedded_active = False |
|
99 | 99 | print "This embedded IPython will not reactivate anymore once you exit." |
|
100 | 100 | |
|
101 | 101 | class IPShellEmbed: |
|
102 | 102 | """Allow embedding an IPython shell into a running program. |
|
103 | 103 | |
|
104 | 104 | Instances of this class are callable, with the __call__ method being an |
|
105 | 105 | alias to the embed() method of an InteractiveShell instance. |
|
106 | 106 | |
|
107 | 107 | Usage (see also the example-embed.py file for a running example): |
|
108 | 108 | |
|
109 | 109 | ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override]) |
|
110 | 110 | |
|
111 | 111 | - argv: list containing valid command-line options for IPython, as they |
|
112 | 112 | would appear in sys.argv[1:]. |
|
113 | 113 | |
|
114 | 114 | For example, the following command-line options: |
|
115 | 115 | |
|
116 | 116 | $ ipython -prompt_in1 'Input <\\#>' -colors LightBG |
|
117 | 117 | |
|
118 | 118 | would be passed in the argv list as: |
|
119 | 119 | |
|
120 | 120 | ['-prompt_in1','Input <\\#>','-colors','LightBG'] |
|
121 | 121 | |
|
122 | 122 | - banner: string which gets printed every time the interpreter starts. |
|
123 | 123 | |
|
124 | 124 | - exit_msg: string which gets printed every time the interpreter exits. |
|
125 | 125 | |
|
126 | 126 | - rc_override: a dict or Struct of configuration options such as those |
|
127 | 127 | used by IPython. These options are read from your ~/.ipython/ipythonrc |
|
128 | 128 | file when the Shell object is created. Passing an explicit rc_override |
|
129 | 129 | dict with any options you want allows you to override those values at |
|
130 | 130 | creation time without having to modify the file. This way you can create |
|
131 | 131 | embeddable instances configured in any way you want without editing any |
|
132 | 132 | global files (thus keeping your interactive IPython configuration |
|
133 | 133 | unchanged). |
|
134 | 134 | |
|
135 | 135 | Then the ipshell instance can be called anywhere inside your code: |
|
136 | 136 | |
|
137 | 137 | ipshell(header='') -> Opens up an IPython shell. |
|
138 | 138 | |
|
139 | 139 | - header: string printed by the IPython shell upon startup. This can let |
|
140 | 140 | you know where in your code you are when dropping into the shell. Note |
|
141 | 141 | that 'banner' gets prepended to all calls, so header is used for |
|
142 | 142 | location-specific information. |
|
143 | 143 | |
|
144 | 144 | For more details, see the __call__ method below. |
|
145 | 145 | |
|
146 | 146 | When the IPython shell is exited with Ctrl-D, normal program execution |
|
147 | 147 | resumes. |
|
148 | 148 | |
|
149 | 149 | This functionality was inspired by a posting on comp.lang.python by cmkl |
|
150 | 150 | <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and |
|
151 | 151 | by the IDL stop/continue commands.""" |
|
152 | 152 | |
|
153 | 153 | def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None, |
|
154 | 154 | user_ns=None): |
|
155 | 155 | """Note that argv here is a string, NOT a list.""" |
|
156 | 156 | self.set_banner(banner) |
|
157 | 157 | self.set_exit_msg(exit_msg) |
|
158 | 158 | self.set_dummy_mode(0) |
|
159 | 159 | |
|
160 | 160 | # sys.displayhook is a global, we need to save the user's original |
|
161 | 161 | # Don't rely on __displayhook__, as the user may have changed that. |
|
162 | 162 | self.sys_displayhook_ori = sys.displayhook |
|
163 | 163 | |
|
164 | 164 | # save readline completer status |
|
165 | 165 | try: |
|
166 | 166 | #print 'Save completer',sys.ipcompleter # dbg |
|
167 | 167 | self.sys_ipcompleter_ori = sys.ipcompleter |
|
168 | 168 | except: |
|
169 | 169 | pass # not nested with IPython |
|
170 | 170 | |
|
171 | 171 | self.IP = make_IPython(argv,rc_override=rc_override, |
|
172 | 172 | embedded=True, |
|
173 | 173 | user_ns=user_ns) |
|
174 | 174 | |
|
175 | 175 | ip = ipapi.IPApi(self.IP) |
|
176 | 176 | ip.expose_magic("kill_embedded",kill_embedded) |
|
177 | 177 | |
|
178 | 178 | # copy our own displayhook also |
|
179 | 179 | self.sys_displayhook_embed = sys.displayhook |
|
180 | 180 | # and leave the system's display hook clean |
|
181 | 181 | sys.displayhook = self.sys_displayhook_ori |
|
182 | 182 | # don't use the ipython crash handler so that user exceptions aren't |
|
183 | 183 | # trapped |
|
184 | 184 | sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors, |
|
185 | 185 | mode = self.IP.rc.xmode, |
|
186 | 186 | call_pdb = self.IP.rc.pdb) |
|
187 | 187 | self.restore_system_completer() |
|
188 | 188 | |
|
189 | 189 | def restore_system_completer(self): |
|
190 | 190 | """Restores the readline completer which was in place. |
|
191 | 191 | |
|
192 | 192 | This allows embedded IPython within IPython not to disrupt the |
|
193 | 193 | parent's completion. |
|
194 | 194 | """ |
|
195 | 195 | |
|
196 | 196 | try: |
|
197 | 197 | self.IP.readline.set_completer(self.sys_ipcompleter_ori) |
|
198 | 198 | sys.ipcompleter = self.sys_ipcompleter_ori |
|
199 | 199 | except: |
|
200 | 200 | pass |
|
201 | 201 | |
|
202 | 202 | def __call__(self,header='',local_ns=None,global_ns=None,dummy=None): |
|
203 | 203 | """Activate the interactive interpreter. |
|
204 | 204 | |
|
205 | 205 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start |
|
206 | 206 | the interpreter shell with the given local and global namespaces, and |
|
207 | 207 | optionally print a header string at startup. |
|
208 | 208 | |
|
209 | 209 | The shell can be globally activated/deactivated using the |
|
210 | 210 | set/get_dummy_mode methods. This allows you to turn off a shell used |
|
211 | 211 | for debugging globally. |
|
212 | 212 | |
|
213 | 213 | However, *each* time you call the shell you can override the current |
|
214 | 214 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
215 | 215 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you |
|
216 | 216 | can still have a specific call work by making it as IPShell(dummy=0). |
|
217 | 217 | |
|
218 | 218 | The optional keyword parameter dummy controls whether the call |
|
219 | 219 | actually does anything. """ |
|
220 | 220 | |
|
221 | 221 | # If the user has turned it off, go away |
|
222 | 222 | if not self.IP.embedded_active: |
|
223 | 223 | return |
|
224 | 224 | |
|
225 | 225 | # Normal exits from interactive mode set this flag, so the shell can't |
|
226 | 226 | # re-enter (it checks this variable at the start of interactive mode). |
|
227 | 227 | self.IP.exit_now = False |
|
228 | 228 | |
|
229 | 229 | # Allow the dummy parameter to override the global __dummy_mode |
|
230 | 230 | if dummy or (dummy != 0 and self.__dummy_mode): |
|
231 | 231 | return |
|
232 | 232 | |
|
233 | 233 | # Set global subsystems (display,completions) to our values |
|
234 | 234 | sys.displayhook = self.sys_displayhook_embed |
|
235 | 235 | if self.IP.has_readline: |
|
236 | 236 | self.IP.set_completer() |
|
237 | 237 | |
|
238 | 238 | if self.banner and header: |
|
239 | 239 | format = '%s\n%s\n' |
|
240 | 240 | else: |
|
241 | 241 | format = '%s%s\n' |
|
242 | 242 | banner = format % (self.banner,header) |
|
243 | 243 | |
|
244 | 244 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
245 | 245 | # our call and get the original caller's namespaces. |
|
246 | 246 | self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1) |
|
247 | 247 | |
|
248 | 248 | if self.exit_msg: |
|
249 | 249 | print self.exit_msg |
|
250 | 250 | |
|
251 | 251 | # Restore global systems (display, completion) |
|
252 | 252 | sys.displayhook = self.sys_displayhook_ori |
|
253 | 253 | self.restore_system_completer() |
|
254 | 254 | |
|
255 | 255 | def set_dummy_mode(self,dummy): |
|
256 | 256 | """Sets the embeddable shell's dummy mode parameter. |
|
257 | 257 | |
|
258 | 258 | set_dummy_mode(dummy): dummy = 0 or 1. |
|
259 | 259 | |
|
260 | 260 | This parameter is persistent and makes calls to the embeddable shell |
|
261 | 261 | silently return without performing any action. This allows you to |
|
262 | 262 | globally activate or deactivate a shell you're using with a single call. |
|
263 | 263 | |
|
264 | 264 | If you need to manually""" |
|
265 | 265 | |
|
266 | 266 | if dummy not in [0,1,False,True]: |
|
267 | 267 | raise ValueError,'dummy parameter must be boolean' |
|
268 | 268 | self.__dummy_mode = dummy |
|
269 | 269 | |
|
270 | 270 | def get_dummy_mode(self): |
|
271 | 271 | """Return the current value of the dummy mode parameter. |
|
272 | 272 | """ |
|
273 | 273 | return self.__dummy_mode |
|
274 | 274 | |
|
275 | 275 | def set_banner(self,banner): |
|
276 | 276 | """Sets the global banner. |
|
277 | 277 | |
|
278 | 278 | This banner gets prepended to every header printed when the shell |
|
279 | 279 | instance is called.""" |
|
280 | 280 | |
|
281 | 281 | self.banner = banner |
|
282 | 282 | |
|
283 | 283 | def set_exit_msg(self,exit_msg): |
|
284 | 284 | """Sets the global exit_msg. |
|
285 | 285 | |
|
286 | 286 | This exit message gets printed upon exiting every time the embedded |
|
287 | 287 | shell is called. It is None by default. """ |
|
288 | 288 | |
|
289 | 289 | self.exit_msg = exit_msg |
|
290 | 290 | |
|
291 | 291 | #----------------------------------------------------------------------------- |
|
292 | 292 | if HAS_CTYPES: |
|
293 | 293 | # Add async exception support. Trick taken from: |
|
294 | 294 | # http://sebulba.wikispaces.com/recipe+thread2 |
|
295 | 295 | def _async_raise(tid, exctype): |
|
296 | 296 | """raises the exception, performs cleanup if needed""" |
|
297 | 297 | if not inspect.isclass(exctype): |
|
298 | 298 | raise TypeError("Only types can be raised (not instances)") |
|
299 | 299 | res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, |
|
300 | 300 | ctypes.py_object(exctype)) |
|
301 | 301 | if res == 0: |
|
302 | 302 | raise ValueError("invalid thread id") |
|
303 | 303 | elif res != 1: |
|
304 | 304 | # """if it returns a number greater than one, you're in trouble, |
|
305 | 305 | # and you should call it again with exc=NULL to revert the effect""" |
|
306 | 306 | ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) |
|
307 | 307 | raise SystemError("PyThreadState_SetAsyncExc failed") |
|
308 | 308 | |
|
309 | 309 | def sigint_handler (signum,stack_frame): |
|
310 | 310 | """Sigint handler for threaded apps. |
|
311 | 311 | |
|
312 | 312 | This is a horrible hack to pass information about SIGINT _without_ |
|
313 | 313 | using exceptions, since I haven't been able to properly manage |
|
314 | 314 | cross-thread exceptions in GTK/WX. In fact, I don't think it can be |
|
315 | 315 | done (or at least that's my understanding from a c.l.py thread where |
|
316 | 316 | this was discussed).""" |
|
317 | 317 | |
|
318 | 318 | global KBINT |
|
319 | 319 | |
|
320 | 320 | if CODE_RUN: |
|
321 | 321 | _async_raise(MAIN_THREAD_ID,KeyboardInterrupt) |
|
322 | 322 | else: |
|
323 | 323 | KBINT = True |
|
324 | 324 | print '\nKeyboardInterrupt - Press <Enter> to continue.', |
|
325 | 325 | Term.cout.flush() |
|
326 | 326 | |
|
327 | 327 | else: |
|
328 | 328 | def sigint_handler (signum,stack_frame): |
|
329 | 329 | """Sigint handler for threaded apps. |
|
330 | 330 | |
|
331 | 331 | This is a horrible hack to pass information about SIGINT _without_ |
|
332 | 332 | using exceptions, since I haven't been able to properly manage |
|
333 | 333 | cross-thread exceptions in GTK/WX. In fact, I don't think it can be |
|
334 | 334 | done (or at least that's my understanding from a c.l.py thread where |
|
335 | 335 | this was discussed).""" |
|
336 | 336 | |
|
337 | 337 | global KBINT |
|
338 | 338 | |
|
339 | 339 | print '\nKeyboardInterrupt - Press <Enter> to continue.', |
|
340 | 340 | Term.cout.flush() |
|
341 | 341 | # Set global flag so that runsource can know that Ctrl-C was hit |
|
342 | 342 | KBINT = True |
|
343 | 343 | |
|
344 | 344 | |
|
345 | 345 | class MTInteractiveShell(InteractiveShell): |
|
346 | 346 | """Simple multi-threaded shell.""" |
|
347 | 347 | |
|
348 | 348 | # Threading strategy taken from: |
|
349 | 349 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian |
|
350 | 350 | # McErlean and John Finlay. Modified with corrections by Antoon Pardon, |
|
351 | 351 | # from the pygtk mailing list, to avoid lockups with system calls. |
|
352 | 352 | |
|
353 | 353 | # class attribute to indicate whether the class supports threads or not. |
|
354 | 354 | # Subclasses with thread support should override this as needed. |
|
355 | 355 | isthreaded = True |
|
356 | 356 | |
|
357 | 357 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
358 | 358 | user_ns=None,user_global_ns=None,banner2='', |
|
359 | 359 | gui_timeout=GUI_TIMEOUT,**kw): |
|
360 | 360 | """Similar to the normal InteractiveShell, but with threading control""" |
|
361 | 361 | |
|
362 | 362 | InteractiveShell.__init__(self,name,usage,rc,user_ns, |
|
363 | 363 | user_global_ns,banner2) |
|
364 | 364 | |
|
365 | 365 | # Timeout we wait for GUI thread |
|
366 | 366 | self.gui_timeout = gui_timeout |
|
367 | 367 | |
|
368 | 368 | # A queue to hold the code to be executed. |
|
369 | 369 | self.code_queue = Queue.Queue() |
|
370 | 370 | |
|
371 | 371 | # Stuff to do at closing time |
|
372 | 372 | self._kill = None |
|
373 | 373 | on_kill = kw.get('on_kill', []) |
|
374 | 374 | # Check that all things to kill are callable: |
|
375 | 375 | for t in on_kill: |
|
376 | 376 | if not callable(t): |
|
377 | 377 | raise TypeError,'on_kill must be a list of callables' |
|
378 | 378 | self.on_kill = on_kill |
|
379 | 379 | # thread identity of the "worker thread" (that may execute code directly) |
|
380 | 380 | self.worker_ident = None |
|
381 | 381 | |
|
382 | 382 | def runsource(self, source, filename="<input>", symbol="single"): |
|
383 | 383 | """Compile and run some source in the interpreter. |
|
384 | 384 | |
|
385 | 385 | Modified version of code.py's runsource(), to handle threading issues. |
|
386 | 386 | See the original for full docstring details.""" |
|
387 | 387 | |
|
388 | 388 | global KBINT |
|
389 | 389 | |
|
390 | 390 | # If Ctrl-C was typed, we reset the flag and return right away |
|
391 | 391 | if KBINT: |
|
392 | 392 | KBINT = False |
|
393 | 393 | return False |
|
394 | 394 | |
|
395 | 395 | if self._kill: |
|
396 | 396 | # can't queue new code if we are being killed |
|
397 | 397 | return True |
|
398 | 398 | |
|
399 | 399 | try: |
|
400 | 400 | code = self.compile(source, filename, symbol) |
|
401 | 401 | except (OverflowError, SyntaxError, ValueError): |
|
402 | 402 | # Case 1 |
|
403 | 403 | self.showsyntaxerror(filename) |
|
404 | 404 | return False |
|
405 | 405 | |
|
406 | 406 | if code is None: |
|
407 | 407 | # Case 2 |
|
408 | 408 | return True |
|
409 | 409 | |
|
410 | 410 | # shortcut - if we are in worker thread, or the worker thread is not |
|
411 | 411 | # running, execute directly (to allow recursion and prevent deadlock if |
|
412 | 412 | # code is run early in IPython construction) |
|
413 | 413 | |
|
414 | 414 | if (self.worker_ident is None |
|
415 | 415 | or self.worker_ident == thread.get_ident() ): |
|
416 | 416 | InteractiveShell.runcode(self,code) |
|
417 | 417 | return |
|
418 | 418 | |
|
419 | 419 | # Case 3 |
|
420 | 420 | # Store code in queue, so the execution thread can handle it. |
|
421 | 421 | |
|
422 | 422 | completed_ev, received_ev = threading.Event(), threading.Event() |
|
423 | 423 | |
|
424 | 424 | self.code_queue.put((code,completed_ev, received_ev)) |
|
425 | 425 | # first make sure the message was received, with timeout |
|
426 | 426 | received_ev.wait(self.gui_timeout) |
|
427 | 427 | if not received_ev.isSet(): |
|
428 | 428 | # the mainloop is dead, start executing code directly |
|
429 | 429 | print "Warning: Timeout for mainloop thread exceeded" |
|
430 | 430 | print "switching to nonthreaded mode (until mainloop wakes up again)" |
|
431 | 431 | self.worker_ident = None |
|
432 | 432 | else: |
|
433 | 433 | completed_ev.wait() |
|
434 | 434 | return False |
|
435 | 435 | |
|
436 | 436 | def runcode(self): |
|
437 | 437 | """Execute a code object. |
|
438 | 438 | |
|
439 | 439 | Multithreaded wrapper around IPython's runcode().""" |
|
440 | 440 | |
|
441 | 441 | global CODE_RUN |
|
442 | 442 | |
|
443 | 443 | # we are in worker thread, stash out the id for runsource() |
|
444 | 444 | self.worker_ident = thread.get_ident() |
|
445 | 445 | |
|
446 | 446 | if self._kill: |
|
447 | 447 | print >>Term.cout, 'Closing threads...', |
|
448 | 448 | Term.cout.flush() |
|
449 | 449 | for tokill in self.on_kill: |
|
450 | 450 | tokill() |
|
451 | 451 | print >>Term.cout, 'Done.' |
|
452 | 452 | # allow kill() to return |
|
453 | 453 | self._kill.set() |
|
454 | 454 | return True |
|
455 | 455 | |
|
456 | 456 | # Install sigint handler. We do it every time to ensure that if user |
|
457 | 457 | # code modifies it, we restore our own handling. |
|
458 | 458 | try: |
|
459 | 459 | signal(SIGINT,sigint_handler) |
|
460 | 460 | except SystemError: |
|
461 | 461 | # This happens under Windows, which seems to have all sorts |
|
462 | 462 | # of problems with signal handling. Oh well... |
|
463 | 463 | pass |
|
464 | 464 | |
|
465 | 465 | # Flush queue of pending code by calling the run methood of the parent |
|
466 | 466 | # class with all items which may be in the queue. |
|
467 | 467 | code_to_run = None |
|
468 | 468 | while 1: |
|
469 | 469 | try: |
|
470 | 470 | code_to_run, completed_ev, received_ev = self.code_queue.get_nowait() |
|
471 | 471 | except Queue.Empty: |
|
472 | 472 | break |
|
473 | 473 | received_ev.set() |
|
474 | 474 | |
|
475 | 475 | # Exceptions need to be raised differently depending on which |
|
476 | 476 | # thread is active. This convoluted try/except is only there to |
|
477 | 477 | # protect against asynchronous exceptions, to ensure that a KBINT |
|
478 | 478 | # at the wrong time doesn't deadlock everything. The global |
|
479 | 479 | # CODE_TO_RUN is set to true/false as close as possible to the |
|
480 | 480 | # runcode() call, so that the KBINT handler is correctly informed. |
|
481 | 481 | try: |
|
482 | 482 | try: |
|
483 | 483 | CODE_RUN = True |
|
484 | 484 | InteractiveShell.runcode(self,code_to_run) |
|
485 | 485 | except KeyboardInterrupt: |
|
486 | 486 | print "Keyboard interrupted in mainloop" |
|
487 | 487 | while not self.code_queue.empty(): |
|
488 | 488 | code, ev1,ev2 = self.code_queue.get_nowait() |
|
489 | 489 | ev1.set() |
|
490 | 490 | ev2.set() |
|
491 | 491 | break |
|
492 | 492 | finally: |
|
493 | 493 | CODE_RUN = False |
|
494 | 494 | # allow runsource() return from wait |
|
495 | 495 | completed_ev.set() |
|
496 | 496 | |
|
497 | 497 | |
|
498 | 498 | # This MUST return true for gtk threading to work |
|
499 | 499 | return True |
|
500 | 500 | |
|
501 | 501 | def kill(self): |
|
502 | 502 | """Kill the thread, returning when it has been shut down.""" |
|
503 | 503 | self._kill = threading.Event() |
|
504 | 504 | self._kill.wait() |
|
505 | 505 | |
|
506 | 506 | class MatplotlibShellBase: |
|
507 | 507 | """Mixin class to provide the necessary modifications to regular IPython |
|
508 | 508 | shell classes for matplotlib support. |
|
509 | 509 | |
|
510 | 510 | Given Python's MRO, this should be used as the FIRST class in the |
|
511 | 511 | inheritance hierarchy, so that it overrides the relevant methods.""" |
|
512 | 512 | |
|
513 | def _matplotlib_config(self,name,user_ns): | |
|
513 | def _matplotlib_config(self,name,user_ns,user_global_ns=None): | |
|
514 | 514 | """Return items needed to setup the user's shell with matplotlib""" |
|
515 | 515 | |
|
516 | 516 | # Initialize matplotlib to interactive mode always |
|
517 | 517 | import matplotlib |
|
518 | 518 | from matplotlib import backends |
|
519 | 519 | matplotlib.interactive(True) |
|
520 | 520 | |
|
521 | 521 | def use(arg): |
|
522 | 522 | """IPython wrapper for matplotlib's backend switcher. |
|
523 | 523 | |
|
524 | 524 | In interactive use, we can not allow switching to a different |
|
525 | 525 | interactive backend, since thread conflicts will most likely crash |
|
526 | 526 | the python interpreter. This routine does a safety check first, |
|
527 | 527 | and refuses to perform a dangerous switch. It still allows |
|
528 | 528 | switching to non-interactive backends.""" |
|
529 | 529 | |
|
530 | 530 | if arg in backends.interactive_bk and arg != self.mpl_backend: |
|
531 | 531 | m=('invalid matplotlib backend switch.\n' |
|
532 | 532 | 'This script attempted to switch to the interactive ' |
|
533 | 533 | 'backend: `%s`\n' |
|
534 | 534 | 'Your current choice of interactive backend is: `%s`\n\n' |
|
535 | 535 | 'Switching interactive matplotlib backends at runtime\n' |
|
536 | 536 | 'would crash the python interpreter, ' |
|
537 | 537 | 'and IPython has blocked it.\n\n' |
|
538 | 538 | 'You need to either change your choice of matplotlib backend\n' |
|
539 | 539 | 'by editing your .matplotlibrc file, or run this script as a \n' |
|
540 | 540 | 'standalone file from the command line, not using IPython.\n' % |
|
541 | 541 | (arg,self.mpl_backend) ) |
|
542 | 542 | raise RuntimeError, m |
|
543 | 543 | else: |
|
544 | 544 | self.mpl_use(arg) |
|
545 | 545 | self.mpl_use._called = True |
|
546 | 546 | |
|
547 | 547 | self.matplotlib = matplotlib |
|
548 | 548 | self.mpl_backend = matplotlib.rcParams['backend'] |
|
549 | 549 | |
|
550 | 550 | # we also need to block switching of interactive backends by use() |
|
551 | 551 | self.mpl_use = matplotlib.use |
|
552 | 552 | self.mpl_use._called = False |
|
553 | 553 | # overwrite the original matplotlib.use with our wrapper |
|
554 | 554 | matplotlib.use = use |
|
555 | 555 | |
|
556 | 556 | # This must be imported last in the matplotlib series, after |
|
557 | 557 | # backend/interactivity choices have been made |
|
558 | 558 | import matplotlib.pylab as pylab |
|
559 | 559 | self.pylab = pylab |
|
560 | 560 | |
|
561 | 561 | self.pylab.show._needmain = False |
|
562 | 562 | # We need to detect at runtime whether show() is called by the user. |
|
563 | 563 | # For this, we wrap it into a decorator which adds a 'called' flag. |
|
564 | 564 | self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive) |
|
565 | 565 | |
|
566 | 566 | # Build a user namespace initialized with matplotlib/matlab features. |
|
567 |
user_ns = IPython.ipapi.make_user_ns(user_ns |
|
|
567 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, | |
|
568 | user_global_ns) | |
|
568 | 569 | |
|
569 | 570 | # Import numpy as np/pyplot as plt are conventions we're trying to |
|
570 | 571 | # somewhat standardize on. Making them available to users by default |
|
571 | 572 | # will greatly help this. |
|
572 | 573 | exec ("import numpy\n" |
|
573 | 574 | "import numpy as np\n" |
|
574 | 575 | "import matplotlib\n" |
|
575 | 576 | "import matplotlib.pylab as pylab\n" |
|
576 | 577 | "try:\n" |
|
577 | 578 | " import matplotlib.pyplot as plt\n" |
|
578 | 579 | "except ImportError:\n" |
|
579 | 580 | " pass\n" |
|
580 | 581 | ) in user_ns |
|
581 | 582 | |
|
582 | 583 | # Build matplotlib info banner |
|
583 | 584 | b=""" |
|
584 | 585 | Welcome to pylab, a matplotlib-based Python environment. |
|
585 | 586 | For more information, type 'help(pylab)'. |
|
586 | 587 | """ |
|
587 | return user_ns,b | |
|
588 | return user_ns,user_global_ns,b | |
|
588 | 589 | |
|
589 | 590 | def mplot_exec(self,fname,*where,**kw): |
|
590 | 591 | """Execute a matplotlib script. |
|
591 | 592 | |
|
592 | 593 | This is a call to execfile(), but wrapped in safeties to properly |
|
593 | 594 | handle interactive rendering and backend switching.""" |
|
594 | 595 | |
|
595 | 596 | #print '*** Matplotlib runner ***' # dbg |
|
596 | 597 | # turn off rendering until end of script |
|
597 | 598 | isInteractive = self.matplotlib.rcParams['interactive'] |
|
598 | 599 | self.matplotlib.interactive(False) |
|
599 | 600 | self.safe_execfile(fname,*where,**kw) |
|
600 | 601 | self.matplotlib.interactive(isInteractive) |
|
601 | 602 | # make rendering call now, if the user tried to do it |
|
602 | 603 | if self.pylab.draw_if_interactive.called: |
|
603 | 604 | self.pylab.draw() |
|
604 | 605 | self.pylab.draw_if_interactive.called = False |
|
605 | 606 | |
|
606 | 607 | # if a backend switch was performed, reverse it now |
|
607 | 608 | if self.mpl_use._called: |
|
608 | 609 | self.matplotlib.rcParams['backend'] = self.mpl_backend |
|
609 | 610 | |
|
610 | 611 | def magic_run(self,parameter_s=''): |
|
611 | 612 | Magic.magic_run(self,parameter_s,runner=self.mplot_exec) |
|
612 | 613 | |
|
613 | 614 | # Fix the docstring so users see the original as well |
|
614 | 615 | magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__, |
|
615 | 616 | "\n *** Modified %run for Matplotlib," |
|
616 | 617 | " with proper interactive handling ***") |
|
617 | 618 | |
|
618 | 619 | # Now we provide 2 versions of a matplotlib-aware IPython base shells, single |
|
619 | 620 | # and multithreaded. Note that these are meant for internal use, the IPShell* |
|
620 | 621 | # classes below are the ones meant for public consumption. |
|
621 | 622 | |
|
622 | 623 | class MatplotlibShell(MatplotlibShellBase,InteractiveShell): |
|
623 | 624 | """Single-threaded shell with matplotlib support.""" |
|
624 | 625 | |
|
625 | 626 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
626 | 627 | user_ns=None,user_global_ns=None,**kw): |
|
627 | user_ns,b2 = self._matplotlib_config(name,user_ns) | |
|
628 | user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns) | |
|
628 | 629 | InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns, |
|
629 | 630 | banner2=b2,**kw) |
|
630 | 631 | |
|
631 | 632 | class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell): |
|
632 | 633 | """Multi-threaded shell with matplotlib support.""" |
|
633 | 634 | |
|
634 | 635 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
635 | 636 | user_ns=None,user_global_ns=None, **kw): |
|
636 | 637 | user_ns,b2 = self._matplotlib_config(name,user_ns) |
|
637 | 638 | MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns, |
|
638 | 639 | banner2=b2,**kw) |
|
639 | 640 | |
|
640 | 641 | #----------------------------------------------------------------------------- |
|
641 | 642 | # Utility functions for the different GUI enabled IPShell* classes. |
|
642 | 643 | |
|
643 | 644 | def get_tk(): |
|
644 | 645 | """Tries to import Tkinter and returns a withdrawn Tkinter root |
|
645 | 646 | window. If Tkinter is already imported or not available, this |
|
646 | 647 | returns None. This function calls `hijack_tk` underneath. |
|
647 | 648 | """ |
|
648 | 649 | if not USE_TK or sys.modules.has_key('Tkinter'): |
|
649 | 650 | return None |
|
650 | 651 | else: |
|
651 | 652 | try: |
|
652 | 653 | import Tkinter |
|
653 | 654 | except ImportError: |
|
654 | 655 | return None |
|
655 | 656 | else: |
|
656 | 657 | hijack_tk() |
|
657 | 658 | r = Tkinter.Tk() |
|
658 | 659 | r.withdraw() |
|
659 | 660 | return r |
|
660 | 661 | |
|
661 | 662 | def hijack_tk(): |
|
662 | 663 | """Modifies Tkinter's mainloop with a dummy so when a module calls |
|
663 | 664 | mainloop, it does not block. |
|
664 | 665 | |
|
665 | 666 | """ |
|
666 | 667 | def misc_mainloop(self, n=0): |
|
667 | 668 | pass |
|
668 | 669 | def tkinter_mainloop(n=0): |
|
669 | 670 | pass |
|
670 | 671 | |
|
671 | 672 | import Tkinter |
|
672 | 673 | Tkinter.Misc.mainloop = misc_mainloop |
|
673 | 674 | Tkinter.mainloop = tkinter_mainloop |
|
674 | 675 | |
|
675 | 676 | def update_tk(tk): |
|
676 | 677 | """Updates the Tkinter event loop. This is typically called from |
|
677 | 678 | the respective WX or GTK mainloops. |
|
678 | 679 | """ |
|
679 | 680 | if tk: |
|
680 | 681 | tk.update() |
|
681 | 682 | |
|
682 | 683 | def hijack_wx(): |
|
683 | 684 | """Modifies wxPython's MainLoop with a dummy so user code does not |
|
684 | 685 | block IPython. The hijacked mainloop function is returned. |
|
685 | 686 | """ |
|
686 | 687 | def dummy_mainloop(*args, **kw): |
|
687 | 688 | pass |
|
688 | 689 | |
|
689 | 690 | try: |
|
690 | 691 | import wx |
|
691 | 692 | except ImportError: |
|
692 | 693 | # For very old versions of WX |
|
693 | 694 | import wxPython as wx |
|
694 | 695 | |
|
695 | 696 | ver = wx.__version__ |
|
696 | 697 | orig_mainloop = None |
|
697 | 698 | if ver[:3] >= '2.5': |
|
698 | 699 | import wx |
|
699 | 700 | if hasattr(wx, '_core_'): core = getattr(wx, '_core_') |
|
700 | 701 | elif hasattr(wx, '_core'): core = getattr(wx, '_core') |
|
701 | 702 | else: raise AttributeError('Could not find wx core module') |
|
702 | 703 | orig_mainloop = core.PyApp_MainLoop |
|
703 | 704 | core.PyApp_MainLoop = dummy_mainloop |
|
704 | 705 | elif ver[:3] == '2.4': |
|
705 | 706 | orig_mainloop = wx.wxc.wxPyApp_MainLoop |
|
706 | 707 | wx.wxc.wxPyApp_MainLoop = dummy_mainloop |
|
707 | 708 | else: |
|
708 | 709 | warn("Unable to find either wxPython version 2.4 or >= 2.5.") |
|
709 | 710 | return orig_mainloop |
|
710 | 711 | |
|
711 | 712 | def hijack_gtk(): |
|
712 | 713 | """Modifies pyGTK's mainloop with a dummy so user code does not |
|
713 | 714 | block IPython. This function returns the original `gtk.mainloop` |
|
714 | 715 | function that has been hijacked. |
|
715 | 716 | """ |
|
716 | 717 | def dummy_mainloop(*args, **kw): |
|
717 | 718 | pass |
|
718 | 719 | import gtk |
|
719 | 720 | if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main |
|
720 | 721 | else: orig_mainloop = gtk.mainloop |
|
721 | 722 | gtk.mainloop = dummy_mainloop |
|
722 | 723 | gtk.main = dummy_mainloop |
|
723 | 724 | return orig_mainloop |
|
724 | 725 | |
|
725 | 726 | def hijack_qt(): |
|
726 | 727 | """Modifies PyQt's mainloop with a dummy so user code does not |
|
727 | 728 | block IPython. This function returns the original |
|
728 | 729 | `qt.qApp.exec_loop` function that has been hijacked. |
|
729 | 730 | """ |
|
730 | 731 | def dummy_mainloop(*args, **kw): |
|
731 | 732 | pass |
|
732 | 733 | import qt |
|
733 | 734 | orig_mainloop = qt.qApp.exec_loop |
|
734 | 735 | qt.qApp.exec_loop = dummy_mainloop |
|
735 | 736 | qt.QApplication.exec_loop = dummy_mainloop |
|
736 | 737 | return orig_mainloop |
|
737 | 738 | |
|
738 | 739 | def hijack_qt4(): |
|
739 | 740 | """Modifies PyQt4's mainloop with a dummy so user code does not |
|
740 | 741 | block IPython. This function returns the original |
|
741 | 742 | `QtGui.qApp.exec_` function that has been hijacked. |
|
742 | 743 | """ |
|
743 | 744 | def dummy_mainloop(*args, **kw): |
|
744 | 745 | pass |
|
745 | 746 | from PyQt4 import QtGui, QtCore |
|
746 | 747 | orig_mainloop = QtGui.qApp.exec_ |
|
747 | 748 | QtGui.qApp.exec_ = dummy_mainloop |
|
748 | 749 | QtGui.QApplication.exec_ = dummy_mainloop |
|
749 | 750 | QtCore.QCoreApplication.exec_ = dummy_mainloop |
|
750 | 751 | return orig_mainloop |
|
751 | 752 | |
|
752 | 753 | #----------------------------------------------------------------------------- |
|
753 | 754 | # The IPShell* classes below are the ones meant to be run by external code as |
|
754 | 755 | # IPython instances. Note that unless a specific threading strategy is |
|
755 | 756 | # desired, the factory function start() below should be used instead (it |
|
756 | 757 | # selects the proper threaded class). |
|
757 | 758 | |
|
758 | 759 | class IPThread(threading.Thread): |
|
759 | 760 | def run(self): |
|
760 | 761 | self.IP.mainloop(self._banner) |
|
761 | 762 | self.IP.kill() |
|
762 | 763 | |
|
763 | 764 | class IPShellGTK(IPThread): |
|
764 | 765 | """Run a gtk mainloop() in a separate thread. |
|
765 | 766 | |
|
766 | 767 | Python commands can be passed to the thread where they will be executed. |
|
767 | 768 | This is implemented by periodically checking for passed code using a |
|
768 | 769 | GTK timeout callback.""" |
|
769 | 770 | |
|
770 | 771 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
771 | 772 | |
|
772 | 773 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
773 | 774 | debug=1,shell_class=MTInteractiveShell): |
|
774 | 775 | |
|
775 | 776 | import gtk |
|
776 | 777 | |
|
777 | 778 | self.gtk = gtk |
|
778 | 779 | self.gtk_mainloop = hijack_gtk() |
|
779 | 780 | |
|
780 | 781 | # Allows us to use both Tk and GTK. |
|
781 | 782 | self.tk = get_tk() |
|
782 | 783 | |
|
783 | 784 | if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit |
|
784 | 785 | else: mainquit = self.gtk.mainquit |
|
785 | 786 | |
|
786 | 787 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
787 | 788 | user_global_ns=user_global_ns, |
|
788 | 789 | debug=debug, |
|
789 | 790 | shell_class=shell_class, |
|
790 | 791 | on_kill=[mainquit]) |
|
791 | 792 | |
|
792 | 793 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
793 | 794 | # method only and .run() needs it. The actual value will be set by |
|
794 | 795 | # .mainloop(). |
|
795 | 796 | self._banner = None |
|
796 | 797 | |
|
797 | 798 | threading.Thread.__init__(self) |
|
798 | 799 | |
|
799 | 800 | def mainloop(self,sys_exit=0,banner=None): |
|
800 | 801 | |
|
801 | 802 | self._banner = banner |
|
802 | 803 | |
|
803 | 804 | if self.gtk.pygtk_version >= (2,4,0): |
|
804 | 805 | import gobject |
|
805 | 806 | gobject.idle_add(self.on_timer) |
|
806 | 807 | else: |
|
807 | 808 | self.gtk.idle_add(self.on_timer) |
|
808 | 809 | |
|
809 | 810 | if sys.platform != 'win32': |
|
810 | 811 | try: |
|
811 | 812 | if self.gtk.gtk_version[0] >= 2: |
|
812 | 813 | self.gtk.gdk.threads_init() |
|
813 | 814 | except AttributeError: |
|
814 | 815 | pass |
|
815 | 816 | except RuntimeError: |
|
816 | 817 | error('Your pyGTK likely has not been compiled with ' |
|
817 | 818 | 'threading support.\n' |
|
818 | 819 | 'The exception printout is below.\n' |
|
819 | 820 | 'You can either rebuild pyGTK with threads, or ' |
|
820 | 821 | 'try using \n' |
|
821 | 822 | 'matplotlib with a different backend (like Tk or WX).\n' |
|
822 | 823 | 'Note that matplotlib will most likely not work in its ' |
|
823 | 824 | 'current state!') |
|
824 | 825 | self.IP.InteractiveTB() |
|
825 | 826 | |
|
826 | 827 | self.start() |
|
827 | 828 | self.gtk.gdk.threads_enter() |
|
828 | 829 | self.gtk_mainloop() |
|
829 | 830 | self.gtk.gdk.threads_leave() |
|
830 | 831 | self.join() |
|
831 | 832 | |
|
832 | 833 | def on_timer(self): |
|
833 | 834 | """Called when GTK is idle. |
|
834 | 835 | |
|
835 | 836 | Must return True always, otherwise GTK stops calling it""" |
|
836 | 837 | |
|
837 | 838 | update_tk(self.tk) |
|
838 | 839 | self.IP.runcode() |
|
839 | 840 | time.sleep(0.01) |
|
840 | 841 | return True |
|
841 | 842 | |
|
842 | 843 | |
|
843 | 844 | class IPShellWX(IPThread): |
|
844 | 845 | """Run a wx mainloop() in a separate thread. |
|
845 | 846 | |
|
846 | 847 | Python commands can be passed to the thread where they will be executed. |
|
847 | 848 | This is implemented by periodically checking for passed code using a |
|
848 | 849 | GTK timeout callback.""" |
|
849 | 850 | |
|
850 | 851 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
851 | 852 | |
|
852 | 853 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
853 | 854 | debug=1,shell_class=MTInteractiveShell): |
|
854 | 855 | |
|
855 | 856 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
856 | 857 | user_global_ns=user_global_ns, |
|
857 | 858 | debug=debug, |
|
858 | 859 | shell_class=shell_class, |
|
859 | 860 | on_kill=[self.wxexit]) |
|
860 | 861 | |
|
861 | 862 | wantedwxversion=self.IP.rc.wxversion |
|
862 | 863 | if wantedwxversion!="0": |
|
863 | 864 | try: |
|
864 | 865 | import wxversion |
|
865 | 866 | except ImportError: |
|
866 | 867 | error('The wxversion module is needed for WX version selection') |
|
867 | 868 | else: |
|
868 | 869 | try: |
|
869 | 870 | wxversion.select(wantedwxversion) |
|
870 | 871 | except: |
|
871 | 872 | self.IP.InteractiveTB() |
|
872 | 873 | error('Requested wxPython version %s could not be loaded' % |
|
873 | 874 | wantedwxversion) |
|
874 | 875 | |
|
875 | 876 | import wx |
|
876 | 877 | |
|
877 | 878 | threading.Thread.__init__(self) |
|
878 | 879 | self.wx = wx |
|
879 | 880 | self.wx_mainloop = hijack_wx() |
|
880 | 881 | |
|
881 | 882 | # Allows us to use both Tk and GTK. |
|
882 | 883 | self.tk = get_tk() |
|
883 | 884 | |
|
884 | 885 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
885 | 886 | # method only and .run() needs it. The actual value will be set by |
|
886 | 887 | # .mainloop(). |
|
887 | 888 | self._banner = None |
|
888 | 889 | |
|
889 | 890 | self.app = None |
|
890 | 891 | |
|
891 | 892 | def wxexit(self, *args): |
|
892 | 893 | if self.app is not None: |
|
893 | 894 | self.app.agent.timer.Stop() |
|
894 | 895 | self.app.ExitMainLoop() |
|
895 | 896 | |
|
896 | 897 | def mainloop(self,sys_exit=0,banner=None): |
|
897 | 898 | |
|
898 | 899 | self._banner = banner |
|
899 | 900 | |
|
900 | 901 | self.start() |
|
901 | 902 | |
|
902 | 903 | class TimerAgent(self.wx.MiniFrame): |
|
903 | 904 | wx = self.wx |
|
904 | 905 | IP = self.IP |
|
905 | 906 | tk = self.tk |
|
906 | 907 | def __init__(self, parent, interval): |
|
907 | 908 | style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ |
|
908 | 909 | self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200), |
|
909 | 910 | size=(100, 100),style=style) |
|
910 | 911 | self.Show(False) |
|
911 | 912 | self.interval = interval |
|
912 | 913 | self.timerId = self.wx.NewId() |
|
913 | 914 | |
|
914 | 915 | def StartWork(self): |
|
915 | 916 | self.timer = self.wx.Timer(self, self.timerId) |
|
916 | 917 | self.wx.EVT_TIMER(self, self.timerId, self.OnTimer) |
|
917 | 918 | self.timer.Start(self.interval) |
|
918 | 919 | |
|
919 | 920 | def OnTimer(self, event): |
|
920 | 921 | update_tk(self.tk) |
|
921 | 922 | self.IP.runcode() |
|
922 | 923 | |
|
923 | 924 | class App(self.wx.App): |
|
924 | 925 | wx = self.wx |
|
925 | 926 | TIMEOUT = self.TIMEOUT |
|
926 | 927 | def OnInit(self): |
|
927 | 928 | 'Create the main window and insert the custom frame' |
|
928 | 929 | self.agent = TimerAgent(None, self.TIMEOUT) |
|
929 | 930 | self.agent.Show(False) |
|
930 | 931 | self.agent.StartWork() |
|
931 | 932 | return True |
|
932 | 933 | |
|
933 | 934 | self.app = App(redirect=False) |
|
934 | 935 | self.wx_mainloop(self.app) |
|
935 | 936 | self.join() |
|
936 | 937 | |
|
937 | 938 | |
|
938 | 939 | class IPShellQt(IPThread): |
|
939 | 940 | """Run a Qt event loop in a separate thread. |
|
940 | 941 | |
|
941 | 942 | Python commands can be passed to the thread where they will be executed. |
|
942 | 943 | This is implemented by periodically checking for passed code using a |
|
943 | 944 | Qt timer / slot.""" |
|
944 | 945 | |
|
945 | 946 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
946 | 947 | |
|
947 | 948 | def __init__(self, argv=None, user_ns=None, user_global_ns=None, |
|
948 | 949 | debug=0, shell_class=MTInteractiveShell): |
|
949 | 950 | |
|
950 | 951 | import qt |
|
951 | 952 | |
|
952 | 953 | self.exec_loop = hijack_qt() |
|
953 | 954 | |
|
954 | 955 | # Allows us to use both Tk and QT. |
|
955 | 956 | self.tk = get_tk() |
|
956 | 957 | |
|
957 | 958 | self.IP = make_IPython(argv, |
|
958 | 959 | user_ns=user_ns, |
|
959 | 960 | user_global_ns=user_global_ns, |
|
960 | 961 | debug=debug, |
|
961 | 962 | shell_class=shell_class, |
|
962 | 963 | on_kill=[qt.qApp.exit]) |
|
963 | 964 | |
|
964 | 965 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
965 | 966 | # method only and .run() needs it. The actual value will be set by |
|
966 | 967 | # .mainloop(). |
|
967 | 968 | self._banner = None |
|
968 | 969 | |
|
969 | 970 | threading.Thread.__init__(self) |
|
970 | 971 | |
|
971 | 972 | def mainloop(self, sys_exit=0, banner=None): |
|
972 | 973 | |
|
973 | 974 | import qt |
|
974 | 975 | |
|
975 | 976 | self._banner = banner |
|
976 | 977 | |
|
977 | 978 | if qt.QApplication.startingUp(): |
|
978 | 979 | a = qt.QApplication(sys.argv) |
|
979 | 980 | |
|
980 | 981 | self.timer = qt.QTimer() |
|
981 | 982 | qt.QObject.connect(self.timer, |
|
982 | 983 | qt.SIGNAL('timeout()'), |
|
983 | 984 | self.on_timer) |
|
984 | 985 | |
|
985 | 986 | self.start() |
|
986 | 987 | self.timer.start(self.TIMEOUT, True) |
|
987 | 988 | while True: |
|
988 | 989 | if self.IP._kill: break |
|
989 | 990 | self.exec_loop() |
|
990 | 991 | self.join() |
|
991 | 992 | |
|
992 | 993 | def on_timer(self): |
|
993 | 994 | update_tk(self.tk) |
|
994 | 995 | result = self.IP.runcode() |
|
995 | 996 | self.timer.start(self.TIMEOUT, True) |
|
996 | 997 | return result |
|
997 | 998 | |
|
998 | 999 | |
|
999 | 1000 | class IPShellQt4(IPThread): |
|
1000 | 1001 | """Run a Qt event loop in a separate thread. |
|
1001 | 1002 | |
|
1002 | 1003 | Python commands can be passed to the thread where they will be executed. |
|
1003 | 1004 | This is implemented by periodically checking for passed code using a |
|
1004 | 1005 | Qt timer / slot.""" |
|
1005 | 1006 | |
|
1006 | 1007 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
1007 | 1008 | |
|
1008 | 1009 | def __init__(self, argv=None, user_ns=None, user_global_ns=None, |
|
1009 | 1010 | debug=0, shell_class=MTInteractiveShell): |
|
1010 | 1011 | |
|
1011 | 1012 | from PyQt4 import QtCore, QtGui |
|
1012 | 1013 | |
|
1013 | 1014 | try: |
|
1014 | 1015 | # present in PyQt4-4.2.1 or later |
|
1015 | 1016 | QtCore.pyqtRemoveInputHook() |
|
1016 | 1017 | except AttributeError: |
|
1017 | 1018 | pass |
|
1018 | 1019 | |
|
1019 | 1020 | if QtCore.PYQT_VERSION_STR == '4.3': |
|
1020 | 1021 | warn('''PyQt4 version 4.3 detected. |
|
1021 | 1022 | If you experience repeated threading warnings, please update PyQt4. |
|
1022 | 1023 | ''') |
|
1023 | 1024 | |
|
1024 | 1025 | self.exec_ = hijack_qt4() |
|
1025 | 1026 | |
|
1026 | 1027 | # Allows us to use both Tk and QT. |
|
1027 | 1028 | self.tk = get_tk() |
|
1028 | 1029 | |
|
1029 | 1030 | self.IP = make_IPython(argv, |
|
1030 | 1031 | user_ns=user_ns, |
|
1031 | 1032 | user_global_ns=user_global_ns, |
|
1032 | 1033 | debug=debug, |
|
1033 | 1034 | shell_class=shell_class, |
|
1034 | 1035 | on_kill=[QtGui.qApp.exit]) |
|
1035 | 1036 | |
|
1036 | 1037 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
1037 | 1038 | # method only and .run() needs it. The actual value will be set by |
|
1038 | 1039 | # .mainloop(). |
|
1039 | 1040 | self._banner = None |
|
1040 | 1041 | |
|
1041 | 1042 | threading.Thread.__init__(self) |
|
1042 | 1043 | |
|
1043 | 1044 | def mainloop(self, sys_exit=0, banner=None): |
|
1044 | 1045 | |
|
1045 | 1046 | from PyQt4 import QtCore, QtGui |
|
1046 | 1047 | |
|
1047 | 1048 | self._banner = banner |
|
1048 | 1049 | |
|
1049 | 1050 | if QtGui.QApplication.startingUp(): |
|
1050 | 1051 | a = QtGui.QApplication(sys.argv) |
|
1051 | 1052 | |
|
1052 | 1053 | self.timer = QtCore.QTimer() |
|
1053 | 1054 | QtCore.QObject.connect(self.timer, |
|
1054 | 1055 | QtCore.SIGNAL('timeout()'), |
|
1055 | 1056 | self.on_timer) |
|
1056 | 1057 | |
|
1057 | 1058 | self.start() |
|
1058 | 1059 | self.timer.start(self.TIMEOUT) |
|
1059 | 1060 | while True: |
|
1060 | 1061 | if self.IP._kill: break |
|
1061 | 1062 | self.exec_() |
|
1062 | 1063 | self.join() |
|
1063 | 1064 | |
|
1064 | 1065 | def on_timer(self): |
|
1065 | 1066 | update_tk(self.tk) |
|
1066 | 1067 | result = self.IP.runcode() |
|
1067 | 1068 | self.timer.start(self.TIMEOUT) |
|
1068 | 1069 | return result |
|
1069 | 1070 | |
|
1070 | 1071 | |
|
1071 | 1072 | # A set of matplotlib public IPython shell classes, for single-threaded (Tk* |
|
1072 | 1073 | # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use. |
|
1073 | 1074 | def _load_pylab(user_ns): |
|
1074 | 1075 | """Allow users to disable pulling all of pylab into the top-level |
|
1075 | 1076 | namespace. |
|
1076 | 1077 | |
|
1077 | 1078 | This little utility must be called AFTER the actual ipython instance is |
|
1078 | 1079 | running, since only then will the options file have been fully parsed.""" |
|
1079 | 1080 | |
|
1080 | 1081 | ip = IPython.ipapi.get() |
|
1081 | 1082 | if ip.options.pylab_import_all: |
|
1082 | 1083 | ip.ex("from matplotlib.pylab import *") |
|
1083 | 1084 | ip.IP.user_config_ns.update(ip.user_ns) |
|
1084 | 1085 | |
|
1085 | 1086 | |
|
1086 | 1087 | class IPShellMatplotlib(IPShell): |
|
1087 | 1088 | """Subclass IPShell with MatplotlibShell as the internal shell. |
|
1088 | 1089 | |
|
1089 | 1090 | Single-threaded class, meant for the Tk* and FLTK* backends. |
|
1090 | 1091 | |
|
1091 | 1092 | Having this on a separate class simplifies the external driver code.""" |
|
1092 | 1093 | |
|
1093 | 1094 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
1094 | 1095 | IPShell.__init__(self,argv,user_ns,user_global_ns,debug, |
|
1095 | 1096 | shell_class=MatplotlibShell) |
|
1096 | 1097 | _load_pylab(self.IP.user_ns) |
|
1097 | 1098 | |
|
1098 | 1099 | class IPShellMatplotlibGTK(IPShellGTK): |
|
1099 | 1100 | """Subclass IPShellGTK with MatplotlibMTShell as the internal shell. |
|
1100 | 1101 | |
|
1101 | 1102 | Multi-threaded class, meant for the GTK* backends.""" |
|
1102 | 1103 | |
|
1103 | 1104 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
1104 | 1105 | IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug, |
|
1105 | 1106 | shell_class=MatplotlibMTShell) |
|
1106 | 1107 | _load_pylab(self.IP.user_ns) |
|
1107 | 1108 | |
|
1108 | 1109 | class IPShellMatplotlibWX(IPShellWX): |
|
1109 | 1110 | """Subclass IPShellWX with MatplotlibMTShell as the internal shell. |
|
1110 | 1111 | |
|
1111 | 1112 | Multi-threaded class, meant for the WX* backends.""" |
|
1112 | 1113 | |
|
1113 | 1114 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
1114 | 1115 | IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug, |
|
1115 | 1116 | shell_class=MatplotlibMTShell) |
|
1116 | 1117 | _load_pylab(self.IP.user_ns) |
|
1117 | 1118 | |
|
1118 | 1119 | class IPShellMatplotlibQt(IPShellQt): |
|
1119 | 1120 | """Subclass IPShellQt with MatplotlibMTShell as the internal shell. |
|
1120 | 1121 | |
|
1121 | 1122 | Multi-threaded class, meant for the Qt* backends.""" |
|
1122 | 1123 | |
|
1123 | 1124 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
1124 | 1125 | IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug, |
|
1125 | 1126 | shell_class=MatplotlibMTShell) |
|
1126 | 1127 | _load_pylab(self.IP.user_ns) |
|
1127 | 1128 | |
|
1128 | 1129 | class IPShellMatplotlibQt4(IPShellQt4): |
|
1129 | 1130 | """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell. |
|
1130 | 1131 | |
|
1131 | 1132 | Multi-threaded class, meant for the Qt4* backends.""" |
|
1132 | 1133 | |
|
1133 | 1134 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
1134 | 1135 | IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug, |
|
1135 | 1136 | shell_class=MatplotlibMTShell) |
|
1136 | 1137 | _load_pylab(self.IP.user_ns) |
|
1137 | 1138 | |
|
1138 | 1139 | #----------------------------------------------------------------------------- |
|
1139 | 1140 | # Factory functions to actually start the proper thread-aware shell |
|
1140 | 1141 | |
|
1141 | 1142 | def _select_shell(argv): |
|
1142 | 1143 | """Select a shell from the given argv vector. |
|
1143 | 1144 | |
|
1144 | 1145 | This function implements the threading selection policy, allowing runtime |
|
1145 | 1146 | control of the threading mode, both for general users and for matplotlib. |
|
1146 | 1147 | |
|
1147 | 1148 | Return: |
|
1148 | 1149 | Shell class to be instantiated for runtime operation. |
|
1149 | 1150 | """ |
|
1150 | 1151 | |
|
1151 | 1152 | global USE_TK |
|
1152 | 1153 | |
|
1153 | 1154 | mpl_shell = {'gthread' : IPShellMatplotlibGTK, |
|
1154 | 1155 | 'wthread' : IPShellMatplotlibWX, |
|
1155 | 1156 | 'qthread' : IPShellMatplotlibQt, |
|
1156 | 1157 | 'q4thread' : IPShellMatplotlibQt4, |
|
1157 | 1158 | 'tkthread' : IPShellMatplotlib, # Tk is built-in |
|
1158 | 1159 | } |
|
1159 | 1160 | |
|
1160 | 1161 | th_shell = {'gthread' : IPShellGTK, |
|
1161 | 1162 | 'wthread' : IPShellWX, |
|
1162 | 1163 | 'qthread' : IPShellQt, |
|
1163 | 1164 | 'q4thread' : IPShellQt4, |
|
1164 | 1165 | 'tkthread' : IPShell, # Tk is built-in |
|
1165 | 1166 | } |
|
1166 | 1167 | |
|
1167 | 1168 | backends = {'gthread' : 'GTKAgg', |
|
1168 | 1169 | 'wthread' : 'WXAgg', |
|
1169 | 1170 | 'qthread' : 'QtAgg', |
|
1170 | 1171 | 'q4thread' :'Qt4Agg', |
|
1171 | 1172 | 'tkthread' :'TkAgg', |
|
1172 | 1173 | } |
|
1173 | 1174 | |
|
1174 | 1175 | all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread', |
|
1175 | 1176 | 'tkthread']) |
|
1176 | 1177 | user_opts = set([s.replace('-','') for s in argv[:3]]) |
|
1177 | 1178 | special_opts = user_opts & all_opts |
|
1178 | 1179 | |
|
1179 | 1180 | if 'tk' in special_opts: |
|
1180 | 1181 | USE_TK = True |
|
1181 | 1182 | special_opts.remove('tk') |
|
1182 | 1183 | |
|
1183 | 1184 | if 'pylab' in special_opts: |
|
1184 | 1185 | |
|
1185 | 1186 | try: |
|
1186 | 1187 | import matplotlib |
|
1187 | 1188 | except ImportError: |
|
1188 | 1189 | error('matplotlib could NOT be imported! Starting normal IPython.') |
|
1189 | 1190 | return IPShell |
|
1190 | 1191 | |
|
1191 | 1192 | special_opts.remove('pylab') |
|
1192 | 1193 | # If there's any option left, it means the user wants to force the |
|
1193 | 1194 | # threading backend, else it's auto-selected from the rc file |
|
1194 | 1195 | if special_opts: |
|
1195 | 1196 | th_mode = special_opts.pop() |
|
1196 | 1197 | matplotlib.rcParams['backend'] = backends[th_mode] |
|
1197 | 1198 | else: |
|
1198 | 1199 | backend = matplotlib.rcParams['backend'] |
|
1199 | 1200 | if backend.startswith('GTK'): |
|
1200 | 1201 | th_mode = 'gthread' |
|
1201 | 1202 | elif backend.startswith('WX'): |
|
1202 | 1203 | th_mode = 'wthread' |
|
1203 | 1204 | elif backend.startswith('Qt4'): |
|
1204 | 1205 | th_mode = 'q4thread' |
|
1205 | 1206 | elif backend.startswith('Qt'): |
|
1206 | 1207 | th_mode = 'qthread' |
|
1207 | 1208 | else: |
|
1208 | 1209 | # Any other backend, use plain Tk |
|
1209 | 1210 | th_mode = 'tkthread' |
|
1210 | 1211 | |
|
1211 | 1212 | return mpl_shell[th_mode] |
|
1212 | 1213 | else: |
|
1213 | 1214 | # No pylab requested, just plain threads |
|
1214 | 1215 | try: |
|
1215 | 1216 | th_mode = special_opts.pop() |
|
1216 | 1217 | except KeyError: |
|
1217 | 1218 | th_mode = 'tkthread' |
|
1218 | 1219 | return th_shell[th_mode] |
|
1219 | 1220 | |
|
1220 | 1221 | |
|
1221 | 1222 | # This is the one which should be called by external code. |
|
1222 | 1223 | def start(user_ns = None): |
|
1223 | 1224 | """Return a running shell instance, dealing with threading options. |
|
1224 | 1225 | |
|
1225 | 1226 | This is a factory function which will instantiate the proper IPython shell |
|
1226 | 1227 | based on the user's threading choice. Such a selector is needed because |
|
1227 | 1228 | different GUI toolkits require different thread handling details.""" |
|
1228 | 1229 | |
|
1229 | 1230 | shell = _select_shell(sys.argv) |
|
1230 | 1231 | return shell(user_ns = user_ns) |
|
1231 | 1232 | |
|
1232 | 1233 | # Some aliases for backwards compatibility |
|
1233 | 1234 | IPythonShell = IPShell |
|
1234 | 1235 | IPythonShellEmbed = IPShellEmbed |
|
1235 | 1236 | #************************ End of file <Shell.py> *************************** |
@@ -1,609 +1,647 b'' | |||
|
1 | 1 | """IPython customization API |
|
2 | 2 | |
|
3 | 3 | Your one-stop module for configuring & extending ipython |
|
4 | 4 | |
|
5 | 5 | The API will probably break when ipython 1.0 is released, but so |
|
6 | 6 | will the other configuration method (rc files). |
|
7 | 7 | |
|
8 | 8 | All names prefixed by underscores are for internal use, not part |
|
9 | 9 | of the public api. |
|
10 | 10 | |
|
11 | 11 | Below is an example that you can just put to a module and import from ipython. |
|
12 | 12 | |
|
13 | 13 | A good practice is to install the config script below as e.g. |
|
14 | 14 | |
|
15 | 15 | ~/.ipython/my_private_conf.py |
|
16 | 16 | |
|
17 | 17 | And do |
|
18 | 18 | |
|
19 | 19 | import_mod my_private_conf |
|
20 | 20 | |
|
21 | 21 | in ~/.ipython/ipythonrc |
|
22 | 22 | |
|
23 | 23 | That way the module is imported at startup and you can have all your |
|
24 | 24 | personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME |
|
25 | 25 | stuff) in there. |
|
26 | 26 | |
|
27 | 27 | ----------------------------------------------- |
|
28 | 28 | import IPython.ipapi |
|
29 | 29 | ip = IPython.ipapi.get() |
|
30 | 30 | |
|
31 | 31 | def ankka_f(self, arg): |
|
32 | 32 | print 'Ankka',self,'says uppercase:',arg.upper() |
|
33 | 33 | |
|
34 | 34 | ip.expose_magic('ankka',ankka_f) |
|
35 | 35 | |
|
36 | 36 | ip.magic('alias sayhi echo "Testing, hi ok"') |
|
37 | 37 | ip.magic('alias helloworld echo "Hello world"') |
|
38 | 38 | ip.system('pwd') |
|
39 | 39 | |
|
40 | 40 | ip.ex('import re') |
|
41 | 41 | ip.ex(''' |
|
42 | 42 | def funcci(a,b): |
|
43 | 43 | print a+b |
|
44 | 44 | print funcci(3,4) |
|
45 | 45 | ''') |
|
46 | 46 | ip.ex('funcci(348,9)') |
|
47 | 47 | |
|
48 | 48 | def jed_editor(self,filename, linenum=None): |
|
49 | 49 | print 'Calling my own editor, jed ... via hook!' |
|
50 | 50 | import os |
|
51 | 51 | if linenum is None: linenum = 0 |
|
52 | 52 | os.system('jed +%d %s' % (linenum, filename)) |
|
53 | 53 | print 'exiting jed' |
|
54 | 54 | |
|
55 | 55 | ip.set_hook('editor',jed_editor) |
|
56 | 56 | |
|
57 | 57 | o = ip.options |
|
58 | 58 | o.autocall = 2 # FULL autocall mode |
|
59 | 59 | |
|
60 | 60 | print 'done!' |
|
61 | 61 | """ |
|
62 | 62 | |
|
63 | 63 | #----------------------------------------------------------------------------- |
|
64 | 64 | # Modules and globals |
|
65 | 65 | |
|
66 | 66 | # stdlib imports |
|
67 | 67 | import __builtin__ |
|
68 | 68 | import sys |
|
69 | 69 | |
|
70 | 70 | # contains the most recently instantiated IPApi |
|
71 | 71 | _RECENT_IP = None |
|
72 | 72 | |
|
73 | 73 | #----------------------------------------------------------------------------- |
|
74 | 74 | # Code begins |
|
75 | 75 | |
|
76 | 76 | class TryNext(Exception): |
|
77 | 77 | """Try next hook exception. |
|
78 | 78 | |
|
79 | 79 | Raise this in your hook function to indicate that the next hook handler |
|
80 | 80 | should be used to handle the operation. If you pass arguments to the |
|
81 | 81 | constructor those arguments will be used by the next hook instead of the |
|
82 | 82 | original ones. |
|
83 | 83 | """ |
|
84 | 84 | |
|
85 | 85 | def __init__(self, *args, **kwargs): |
|
86 | 86 | self.args = args |
|
87 | 87 | self.kwargs = kwargs |
|
88 | 88 | |
|
89 | 89 | |
|
90 | 90 | class UsageError(Exception): |
|
91 | 91 | """ Error in magic function arguments, etc. |
|
92 | 92 | |
|
93 | 93 | Something that probably won't warrant a full traceback, but should |
|
94 | 94 | nevertheless interrupt a macro / batch file. |
|
95 | 95 | """ |
|
96 | 96 | |
|
97 | 97 | |
|
98 | 98 | class IPyAutocall: |
|
99 | 99 | """ Instances of this class are always autocalled |
|
100 | 100 | |
|
101 | 101 | This happens regardless of 'autocall' variable state. Use this to |
|
102 | 102 | develop macro-like mechanisms. |
|
103 | 103 | """ |
|
104 | 104 | |
|
105 | 105 | def set_ip(self,ip): |
|
106 | 106 | """ Will be used to set _ip point to current ipython instance b/f call |
|
107 | 107 | |
|
108 | 108 | Override this method if you don't want this to happen. |
|
109 | 109 | |
|
110 | 110 | """ |
|
111 | 111 | self._ip = ip |
|
112 | 112 | |
|
113 | 113 | |
|
114 | 114 | class IPythonNotRunning: |
|
115 | 115 | """Dummy do-nothing class. |
|
116 | 116 | |
|
117 | 117 | Instances of this class return a dummy attribute on all accesses, which |
|
118 | 118 | can be called and warns. This makes it easier to write scripts which use |
|
119 | 119 | the ipapi.get() object for informational purposes to operate both with and |
|
120 | 120 | without ipython. Obviously code which uses the ipython object for |
|
121 | 121 | computations will not work, but this allows a wider range of code to |
|
122 | 122 | transparently work whether ipython is being used or not.""" |
|
123 | 123 | |
|
124 | 124 | def __init__(self,warn=True): |
|
125 | 125 | if warn: |
|
126 | 126 | self.dummy = self._dummy_warn |
|
127 | 127 | else: |
|
128 | 128 | self.dummy = self._dummy_silent |
|
129 | 129 | |
|
130 | 130 | def __str__(self): |
|
131 | 131 | return "<IPythonNotRunning>" |
|
132 | 132 | |
|
133 | 133 | __repr__ = __str__ |
|
134 | 134 | |
|
135 | 135 | def __getattr__(self,name): |
|
136 | 136 | return self.dummy |
|
137 | 137 | |
|
138 | 138 | def _dummy_warn(self,*args,**kw): |
|
139 | 139 | """Dummy function, which doesn't do anything but warn.""" |
|
140 | 140 | |
|
141 | 141 | print ("IPython is not running, this is a dummy no-op function") |
|
142 | 142 | |
|
143 | 143 | def _dummy_silent(self,*args,**kw): |
|
144 | 144 | """Dummy function, which doesn't do anything and emits no warnings.""" |
|
145 | 145 | pass |
|
146 | 146 | |
|
147 | 147 | |
|
148 | 148 | def get(allow_dummy=False,dummy_warn=True): |
|
149 | 149 | """Get an IPApi object. |
|
150 | 150 | |
|
151 | 151 | If allow_dummy is true, returns an instance of IPythonNotRunning |
|
152 | 152 | instead of None if not running under IPython. |
|
153 | 153 | |
|
154 | 154 | If dummy_warn is false, the dummy instance will be completely silent. |
|
155 | 155 | |
|
156 | 156 | Running this should be the first thing you do when writing extensions that |
|
157 | 157 | can be imported as normal modules. You can then direct all the |
|
158 | 158 | configuration operations against the returned object. |
|
159 | 159 | """ |
|
160 | 160 | global _RECENT_IP |
|
161 | 161 | if allow_dummy and not _RECENT_IP: |
|
162 | 162 | _RECENT_IP = IPythonNotRunning(dummy_warn) |
|
163 | 163 | return _RECENT_IP |
|
164 | 164 | |
|
165 | 165 | |
|
166 | 166 | class IPApi(object): |
|
167 | 167 | """ The actual API class for configuring IPython |
|
168 | 168 | |
|
169 | 169 | You should do all of the IPython configuration by getting an IPApi object |
|
170 | 170 | with IPython.ipapi.get() and using the attributes and methods of the |
|
171 | 171 | returned object.""" |
|
172 | 172 | |
|
173 | 173 | def __init__(self,ip): |
|
174 | 174 | |
|
175 | 175 | global _RECENT_IP |
|
176 | 176 | |
|
177 | 177 | # All attributes exposed here are considered to be the public API of |
|
178 | 178 | # IPython. As needs dictate, some of these may be wrapped as |
|
179 | 179 | # properties. |
|
180 | 180 | |
|
181 | 181 | self.magic = ip.ipmagic |
|
182 | 182 | |
|
183 | 183 | self.system = ip.system |
|
184 | 184 | |
|
185 | 185 | self.set_hook = ip.set_hook |
|
186 | 186 | |
|
187 | 187 | self.set_custom_exc = ip.set_custom_exc |
|
188 | 188 | |
|
189 | 189 | self.user_ns = ip.user_ns |
|
190 | 190 | self.user_ns['_ip'] = self |
|
191 | 191 | |
|
192 | 192 | self.set_crash_handler = ip.set_crash_handler |
|
193 | 193 | |
|
194 | 194 | # Session-specific data store, which can be used to store |
|
195 | 195 | # data that should persist through the ipython session. |
|
196 | 196 | self.meta = ip.meta |
|
197 | 197 | |
|
198 | 198 | # The ipython instance provided |
|
199 | 199 | self.IP = ip |
|
200 | 200 | |
|
201 | 201 | self.extensions = {} |
|
202 | 202 | |
|
203 | 203 | self.dbg = DebugTools(self) |
|
204 | 204 | |
|
205 | 205 | _RECENT_IP = self |
|
206 | 206 | |
|
207 | 207 | # Use a property for some things which are added to the instance very |
|
208 | 208 | # late. I don't have time right now to disentangle the initialization |
|
209 | 209 | # order issues, so a property lets us delay item extraction while |
|
210 | 210 | # providing a normal attribute API. |
|
211 | 211 | def get_db(self): |
|
212 | 212 | """A handle to persistent dict-like database (a PickleShareDB object)""" |
|
213 | 213 | return self.IP.db |
|
214 | 214 | |
|
215 | 215 | db = property(get_db,None,None,get_db.__doc__) |
|
216 | 216 | |
|
217 | 217 | def get_options(self): |
|
218 | 218 | """All configurable variables.""" |
|
219 | 219 | |
|
220 | 220 | # catch typos by disabling new attribute creation. If new attr creation |
|
221 | 221 | # is in fact wanted (e.g. when exposing new options), do |
|
222 | 222 | # allow_new_attr(True) for the received rc struct. |
|
223 | 223 | |
|
224 | 224 | self.IP.rc.allow_new_attr(False) |
|
225 | 225 | return self.IP.rc |
|
226 | 226 | |
|
227 | 227 | options = property(get_options,None,None,get_options.__doc__) |
|
228 | 228 | |
|
229 | 229 | def expose_magic(self,magicname, func): |
|
230 | 230 | """Expose own function as magic function for ipython |
|
231 | 231 | |
|
232 | 232 | def foo_impl(self,parameter_s=''): |
|
233 | 233 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
234 | 234 | print 'Magic function. Passed parameter is between < >:' |
|
235 | 235 | print '<%s>' % parameter_s |
|
236 | 236 | print 'The self object is:',self |
|
237 | 237 | |
|
238 | 238 | ipapi.expose_magic('foo',foo_impl) |
|
239 | 239 | """ |
|
240 | 240 | |
|
241 | 241 | import new |
|
242 | 242 | im = new.instancemethod(func,self.IP, self.IP.__class__) |
|
243 | 243 | old = getattr(self.IP, "magic_" + magicname, None) |
|
244 | 244 | if old: |
|
245 | 245 | self.dbg.debug_stack("Magic redefinition '%s', old %s" % |
|
246 | 246 | (magicname,old) ) |
|
247 | 247 | |
|
248 | 248 | setattr(self.IP, "magic_" + magicname, im) |
|
249 | 249 | |
|
250 | 250 | def ex(self,cmd): |
|
251 | 251 | """ Execute a normal python statement in user namespace """ |
|
252 | 252 | exec cmd in self.user_ns |
|
253 | 253 | |
|
254 | 254 | def ev(self,expr): |
|
255 | 255 | """ Evaluate python expression expr in user namespace |
|
256 | 256 | |
|
257 | 257 | Returns the result of evaluation""" |
|
258 | 258 | return eval(expr,self.user_ns) |
|
259 | 259 | |
|
260 | 260 | def runlines(self,lines): |
|
261 | 261 | """ Run the specified lines in interpreter, honoring ipython directives. |
|
262 | 262 | |
|
263 | 263 | This allows %magic and !shell escape notations. |
|
264 | 264 | |
|
265 | 265 | Takes either all lines in one string or list of lines. |
|
266 | 266 | """ |
|
267 | 267 | |
|
268 | 268 | def cleanup_ipy_script(script): |
|
269 | 269 | """ Make a script safe for _ip.runlines() |
|
270 | 270 | |
|
271 | 271 | - Removes empty lines Suffixes all indented blocks that end with |
|
272 | 272 | - unindented lines with empty lines |
|
273 | 273 | """ |
|
274 | 274 | |
|
275 | 275 | res = [] |
|
276 | 276 | lines = script.splitlines() |
|
277 | 277 | |
|
278 | 278 | level = 0 |
|
279 | 279 | for l in lines: |
|
280 | 280 | lstripped = l.lstrip() |
|
281 | 281 | stripped = l.strip() |
|
282 | 282 | if not stripped: |
|
283 | 283 | continue |
|
284 | 284 | newlevel = len(l) - len(lstripped) |
|
285 | 285 | def is_secondary_block_start(s): |
|
286 | 286 | if not s.endswith(':'): |
|
287 | 287 | return False |
|
288 | 288 | if (s.startswith('elif') or |
|
289 | 289 | s.startswith('else') or |
|
290 | 290 | s.startswith('except') or |
|
291 | 291 | s.startswith('finally')): |
|
292 | 292 | return True |
|
293 | 293 | |
|
294 | 294 | if level > 0 and newlevel == 0 and \ |
|
295 | 295 | not is_secondary_block_start(stripped): |
|
296 | 296 | # add empty line |
|
297 | 297 | res.append('') |
|
298 | 298 | |
|
299 | 299 | res.append(l) |
|
300 | 300 | level = newlevel |
|
301 | 301 | return '\n'.join(res) + '\n' |
|
302 | 302 | |
|
303 | 303 | if isinstance(lines,basestring): |
|
304 | 304 | script = lines |
|
305 | 305 | else: |
|
306 | 306 | script = '\n'.join(lines) |
|
307 | 307 | clean=cleanup_ipy_script(script) |
|
308 | 308 | # print "_ip.runlines() script:\n",clean # dbg |
|
309 | 309 | self.IP.runlines(clean) |
|
310 | 310 | |
|
311 | 311 | def to_user_ns(self,vars, interactive = True): |
|
312 | 312 | """Inject a group of variables into the IPython user namespace. |
|
313 | 313 | |
|
314 | 314 | Inputs: |
|
315 | 315 | |
|
316 | 316 | - vars: string with variable names separated by whitespace, or a |
|
317 | 317 | dict with name/value pairs. |
|
318 | 318 | |
|
319 | 319 | - interactive: if True (default), the var will be listed with |
|
320 | 320 | %whos et. al. |
|
321 | 321 | |
|
322 | 322 | This utility routine is meant to ease interactive debugging work, |
|
323 | 323 | where you want to easily propagate some internal variable in your code |
|
324 | 324 | up to the interactive namespace for further exploration. |
|
325 | 325 | |
|
326 | 326 | When you run code via %run, globals in your script become visible at |
|
327 | 327 | the interactive prompt, but this doesn't happen for locals inside your |
|
328 | 328 | own functions and methods. Yet when debugging, it is common to want |
|
329 | 329 | to explore some internal variables further at the interactive propmt. |
|
330 | 330 | |
|
331 | 331 | Examples: |
|
332 | 332 | |
|
333 | 333 | To use this, you first must obtain a handle on the ipython object as |
|
334 | 334 | indicated above, via: |
|
335 | 335 | |
|
336 | 336 | import IPython.ipapi |
|
337 | 337 | ip = IPython.ipapi.get() |
|
338 | 338 | |
|
339 | 339 | Once this is done, inside a routine foo() where you want to expose |
|
340 | 340 | variables x and y, you do the following: |
|
341 | 341 | |
|
342 | 342 | def foo(): |
|
343 | 343 | ... |
|
344 | 344 | x = your_computation() |
|
345 | 345 | y = something_else() |
|
346 | 346 | |
|
347 | 347 | # This pushes x and y to the interactive prompt immediately, even |
|
348 | 348 | # if this routine crashes on the next line after: |
|
349 | 349 | ip.to_user_ns('x y') |
|
350 | 350 | ... |
|
351 | 351 | |
|
352 | 352 | # To expose *ALL* the local variables from the function, use: |
|
353 | 353 | ip.to_user_ns(locals()) |
|
354 | 354 | |
|
355 | 355 | ... |
|
356 | 356 | # return |
|
357 | 357 | |
|
358 | 358 | |
|
359 | 359 | If you need to rename variables, the dict input makes it easy. For |
|
360 | 360 | example, this call exposes variables 'foo' as 'x' and 'bar' as 'y' |
|
361 | 361 | in IPython user namespace: |
|
362 | 362 | |
|
363 | 363 | ip.to_user_ns(dict(x=foo,y=bar)) |
|
364 | 364 | """ |
|
365 | 365 | |
|
366 | 366 | # print 'vars given:',vars # dbg |
|
367 | 367 | |
|
368 | 368 | # We need a dict of name/value pairs to do namespace updates. |
|
369 | 369 | if isinstance(vars,dict): |
|
370 | 370 | # If a dict was given, no need to change anything. |
|
371 | 371 | vdict = vars |
|
372 | 372 | elif isinstance(vars,basestring): |
|
373 | 373 | # If a string with names was given, get the caller's frame to |
|
374 | 374 | # evaluate the given names in |
|
375 | 375 | cf = sys._getframe(1) |
|
376 | 376 | vdict = {} |
|
377 | 377 | for name in vars.split(): |
|
378 | 378 | try: |
|
379 | 379 | vdict[name] = eval(name,cf.f_globals,cf.f_locals) |
|
380 | 380 | except: |
|
381 | 381 | print ('could not get var. %s from %s' % |
|
382 | 382 | (name,cf.f_code.co_name)) |
|
383 | 383 | else: |
|
384 | 384 | raise ValueError('vars must be a string or a dict') |
|
385 | 385 | |
|
386 | 386 | # Propagate variables to user namespace |
|
387 | 387 | self.user_ns.update(vdict) |
|
388 | 388 | |
|
389 | 389 | # And configure interactive visibility |
|
390 | 390 | config_ns = self.IP.user_config_ns |
|
391 | 391 | if interactive: |
|
392 | 392 | for name,val in vdict.iteritems(): |
|
393 | 393 | config_ns.pop(name,None) |
|
394 | 394 | else: |
|
395 | 395 | for name,val in vdict.iteritems(): |
|
396 | 396 | config_ns[name] = val |
|
397 | 397 | |
|
398 | 398 | def expand_alias(self,line): |
|
399 | 399 | """ Expand an alias in the command line |
|
400 | 400 | |
|
401 | 401 | Returns the provided command line, possibly with the first word |
|
402 | 402 | (command) translated according to alias expansion rules. |
|
403 | 403 | |
|
404 | 404 | [ipython]|16> _ip.expand_aliases("np myfile.txt") |
|
405 | 405 | <16> 'q:/opt/np/notepad++.exe myfile.txt' |
|
406 | 406 | """ |
|
407 | 407 | |
|
408 | 408 | pre,fn,rest = self.IP.split_user_input(line) |
|
409 | 409 | res = pre + self.IP.expand_aliases(fn,rest) |
|
410 | 410 | return res |
|
411 | 411 | |
|
412 | 412 | def itpl(self, s, depth = 1): |
|
413 | 413 | """ Expand Itpl format string s. |
|
414 | 414 | |
|
415 | 415 | Only callable from command line (i.e. prefilter results); |
|
416 | 416 | If you use in your scripts, you need to use a bigger depth! |
|
417 | 417 | """ |
|
418 | 418 | return self.IP.var_expand(s, depth) |
|
419 | 419 | |
|
420 | 420 | def defalias(self, name, cmd): |
|
421 | 421 | """ Define a new alias |
|
422 | 422 | |
|
423 | 423 | _ip.defalias('bb','bldmake bldfiles') |
|
424 | 424 | |
|
425 | 425 | Creates a new alias named 'bb' in ipython user namespace |
|
426 | 426 | """ |
|
427 | 427 | |
|
428 | 428 | self.dbg.check_hotname(name) |
|
429 | 429 | |
|
430 | 430 | if name in self.IP.alias_table: |
|
431 | 431 | self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')" |
|
432 | 432 | % (name, cmd, self.IP.alias_table[name])) |
|
433 | 433 | |
|
434 | 434 | if callable(cmd): |
|
435 | 435 | self.IP.alias_table[name] = cmd |
|
436 | 436 | import IPython.shadowns |
|
437 | 437 | setattr(IPython.shadowns, name,cmd) |
|
438 | 438 | return |
|
439 | 439 | |
|
440 | 440 | if isinstance(cmd,basestring): |
|
441 | 441 | nargs = cmd.count('%s') |
|
442 | 442 | if nargs>0 and cmd.find('%l')>=0: |
|
443 | 443 | raise Exception('The %s and %l specifiers are mutually ' |
|
444 | 444 | 'exclusive in alias definitions.') |
|
445 | 445 | |
|
446 | 446 | self.IP.alias_table[name] = (nargs,cmd) |
|
447 | 447 | return |
|
448 | 448 | |
|
449 | 449 | # just put it in - it's probably (0,'foo') |
|
450 | 450 | self.IP.alias_table[name] = cmd |
|
451 | 451 | |
|
452 | 452 | def defmacro(self, *args): |
|
453 | 453 | """ Define a new macro |
|
454 | 454 | |
|
455 | 455 | 2 forms of calling: |
|
456 | 456 | |
|
457 | 457 | mac = _ip.defmacro('print "hello"\nprint "world"') |
|
458 | 458 | |
|
459 | 459 | (doesn't put the created macro on user namespace) |
|
460 | 460 | |
|
461 | 461 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') |
|
462 | 462 | |
|
463 | 463 | (creates a macro named 'build' in user namespace) |
|
464 | 464 | """ |
|
465 | 465 | |
|
466 | 466 | import IPython.macro |
|
467 | 467 | |
|
468 | 468 | if len(args) == 1: |
|
469 | 469 | return IPython.macro.Macro(args[0]) |
|
470 | 470 | elif len(args) == 2: |
|
471 | 471 | self.user_ns[args[0]] = IPython.macro.Macro(args[1]) |
|
472 | 472 | else: |
|
473 | 473 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") |
|
474 | 474 | |
|
475 | 475 | def set_next_input(self, s): |
|
476 | 476 | """ Sets the 'default' input string for the next command line. |
|
477 | 477 | |
|
478 | 478 | Requires readline. |
|
479 | 479 | |
|
480 | 480 | Example: |
|
481 | 481 | |
|
482 | 482 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
483 | 483 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
484 | 484 | """ |
|
485 | 485 | |
|
486 | 486 | self.IP.rl_next_input = s |
|
487 | 487 | |
|
488 | 488 | def load(self, mod): |
|
489 | 489 | """ Load an extension. |
|
490 | 490 | |
|
491 | 491 | Some modules should (or must) be 'load()':ed, rather than just imported. |
|
492 | 492 | |
|
493 | 493 | Loading will do: |
|
494 | 494 | |
|
495 | 495 | - run init_ipython(ip) |
|
496 | 496 | - run ipython_firstrun(ip) |
|
497 | 497 | """ |
|
498 | 498 | |
|
499 | 499 | if mod in self.extensions: |
|
500 | 500 | # just to make sure we don't init it twice |
|
501 | 501 | # note that if you 'load' a module that has already been |
|
502 | 502 | # imported, init_ipython gets run anyway |
|
503 | 503 | |
|
504 | 504 | return self.extensions[mod] |
|
505 | 505 | __import__(mod) |
|
506 | 506 | m = sys.modules[mod] |
|
507 | 507 | if hasattr(m,'init_ipython'): |
|
508 | 508 | m.init_ipython(self) |
|
509 | 509 | |
|
510 | 510 | if hasattr(m,'ipython_firstrun'): |
|
511 | 511 | already_loaded = self.db.get('firstrun_done', set()) |
|
512 | 512 | if mod not in already_loaded: |
|
513 | 513 | m.ipython_firstrun(self) |
|
514 | 514 | already_loaded.add(mod) |
|
515 | 515 | self.db['firstrun_done'] = already_loaded |
|
516 | 516 | |
|
517 | 517 | self.extensions[mod] = m |
|
518 | 518 | return m |
|
519 | 519 | |
|
520 | 520 | |
|
521 | 521 | class DebugTools: |
|
522 | 522 | """ Used for debugging mishaps in api usage |
|
523 | 523 | |
|
524 | 524 | So far, tracing redefinitions is supported. |
|
525 | 525 | """ |
|
526 | 526 | |
|
527 | 527 | def __init__(self, ip): |
|
528 | 528 | self.ip = ip |
|
529 | 529 | self.debugmode = False |
|
530 | 530 | self.hotnames = set() |
|
531 | 531 | |
|
532 | 532 | def hotname(self, name_to_catch): |
|
533 | 533 | self.hotnames.add(name_to_catch) |
|
534 | 534 | |
|
535 | 535 | def debug_stack(self, msg = None): |
|
536 | 536 | if not self.debugmode: |
|
537 | 537 | return |
|
538 | 538 | |
|
539 | 539 | import traceback |
|
540 | 540 | if msg is not None: |
|
541 | 541 | print '====== %s ========' % msg |
|
542 | 542 | traceback.print_stack() |
|
543 | 543 | |
|
544 | 544 | def check_hotname(self,name): |
|
545 | 545 | if name in self.hotnames: |
|
546 | 546 | self.debug_stack( "HotName '%s' caught" % name) |
|
547 | 547 | |
|
548 | 548 | |
|
549 | 549 | def launch_new_instance(user_ns = None,shellclass = None): |
|
550 | 550 | """ Make and start a new ipython instance. |
|
551 | 551 | |
|
552 | 552 | This can be called even without having an already initialized |
|
553 | 553 | ipython session running. |
|
554 | 554 | |
|
555 | 555 | This is also used as the egg entry point for the 'ipython' script. |
|
556 | 556 | |
|
557 | 557 | """ |
|
558 | 558 | ses = make_session(user_ns,shellclass) |
|
559 | 559 | ses.mainloop() |
|
560 | 560 | |
|
561 | 561 | |
|
562 | 562 | def make_user_ns(user_ns = None): |
|
563 | 563 | """Return a valid user interactive namespace. |
|
564 | 564 | |
|
565 | 565 | This builds a dict with the minimal information needed to operate as a |
|
566 | 566 | valid IPython user namespace, which you can pass to the various embedding |
|
567 | 567 | classes in ipython. |
|
568 | 568 | """ |
|
569 | 569 | |
|
570 | if user_ns is None: | |
|
571 | # Set __name__ to __main__ to better match the behavior of the | |
|
572 | # normal interpreter. | |
|
573 | user_ns = {'__name__' :'__main__', | |
|
574 | '__builtins__' : __builtin__, | |
|
575 | } | |
|
576 | else: | |
|
577 | user_ns.setdefault('__name__','__main__') | |
|
578 | user_ns.setdefault('__builtins__',__builtin__) | |
|
579 | ||
|
580 | return user_ns | |
|
570 | raise NotImplementedError | |
|
581 | 571 | |
|
582 | 572 | |
|
583 | 573 | def make_user_global_ns(ns = None): |
|
584 | 574 | """Return a valid user global namespace. |
|
585 | 575 | |
|
586 | 576 | Similar to make_user_ns(), but global namespaces are really only needed in |
|
587 | 577 | embedded applications, where there is a distinction between the user's |
|
588 | 578 | interactive namespace and the global one where ipython is running.""" |
|
589 | 579 | |
|
590 | if ns is None: ns = {} | |
|
591 | return ns | |
|
580 | raise NotImplementedError | |
|
581 | ||
|
582 | # Record the true objects in order to be able to test if the user has overridden | |
|
583 | # these API functions. | |
|
584 | _make_user_ns = make_user_ns | |
|
585 | _make_user_global_ns = make_user_global_ns | |
|
586 | ||
|
587 | ||
|
588 | def make_user_namespaces(user_ns = None,user_global_ns = None): | |
|
589 | """Return a valid local and global user interactive namespaces. | |
|
590 | ||
|
591 | This builds a dict with the minimal information needed to operate as a | |
|
592 | valid IPython user namespace, which you can pass to the various embedding | |
|
593 | classes in ipython. The default implementation returns the same dict for | |
|
594 | both the locals and the globals to allow functions to refer to variables in | |
|
595 | the namespace. Customized implementations can return different dicts. The | |
|
596 | locals dictionary can actually be anything following the basic mapping | |
|
597 | protocol of a dict, but the globals dict must be a true dict, not even | |
|
598 | a subclass. It is recommended that any custom object for the locals | |
|
599 | namespace synchronize with the globals dict somehow. | |
|
600 | ||
|
601 | Raises TypeError if the provided globals namespace is not a true dict. | |
|
602 | """ | |
|
603 | ||
|
604 | if user_ns is None: | |
|
605 | if make_user_ns is not _make_user_ns: | |
|
606 | # Old API overridden. | |
|
607 | # FIXME: Issue DeprecationWarning, or just let the old API live on? | |
|
608 | user_ns = make_user_ns(user_ns) | |
|
609 | else: | |
|
610 | # Set __name__ to __main__ to better match the behavior of the | |
|
611 | # normal interpreter. | |
|
612 | user_ns = {'__name__' :'__main__', | |
|
613 | '__builtins__' : __builtin__, | |
|
614 | } | |
|
615 | else: | |
|
616 | user_ns.setdefault('__name__','__main__') | |
|
617 | user_ns.setdefault('__builtins__',__builtin__) | |
|
618 | ||
|
619 | if user_global_ns is None: | |
|
620 | if make_user_global_ns is not _make_user_global_ns: | |
|
621 | # Old API overridden. | |
|
622 | user_global_ns = make_user_global_ns(user_global_ns) | |
|
623 | else: | |
|
624 | user_global_ns = user_ns | |
|
625 | if type(user_global_ns) is not dict: | |
|
626 | raise TypeError("user_global_ns must be a true dict; got %r" | |
|
627 | % type(user_global_ns)) | |
|
628 | ||
|
629 | return user_ns, user_global_ns | |
|
592 | 630 | |
|
593 | 631 | |
|
594 | 632 | def make_session(user_ns = None, shellclass = None): |
|
595 | 633 | """Makes, but does not launch an IPython session. |
|
596 | 634 | |
|
597 | 635 | Later on you can call obj.mainloop() on the returned object. |
|
598 | 636 | |
|
599 | 637 | Inputs: |
|
600 | 638 | |
|
601 | 639 | - user_ns(None): a dict to be used as the user's namespace with initial |
|
602 | 640 | data. |
|
603 | 641 | |
|
604 | 642 | WARNING: This should *not* be run when a session exists already.""" |
|
605 | 643 | |
|
606 | 644 | import IPython.Shell |
|
607 | 645 | if shellclass is None: |
|
608 | 646 | return IPython.Shell.start(user_ns) |
|
609 | 647 | return shellclass(user_ns = user_ns) |
@@ -1,2696 +1,2686 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | IPython -- An enhanced Interactive Python |
|
4 | 4 | |
|
5 | 5 | Requires Python 2.3 or newer. |
|
6 | 6 | |
|
7 | 7 | This file contains all the classes and helper functions specific to IPython. |
|
8 | 8 | |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | 11 | #***************************************************************************** |
|
12 | 12 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
13 | 13 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
14 | 14 | # |
|
15 | 15 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | 16 | # the file COPYING, distributed as part of this software. |
|
17 | 17 | # |
|
18 | 18 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
19 | 19 | # Python standard library. Over time, all of that class has been copied |
|
20 | 20 | # verbatim here for modifications which could not be accomplished by |
|
21 | 21 | # subclassing. At this point, there are no dependencies at all on the code |
|
22 | 22 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
23 | 23 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
24 | 24 | # due. |
|
25 | 25 | #***************************************************************************** |
|
26 | 26 | |
|
27 | 27 | #**************************************************************************** |
|
28 | 28 | # Modules and globals |
|
29 | 29 | |
|
30 | 30 | from IPython import Release |
|
31 | 31 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
32 | 32 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
33 | 33 | __license__ = Release.license |
|
34 | 34 | __version__ = Release.version |
|
35 | 35 | |
|
36 | 36 | # Python standard modules |
|
37 | 37 | import __main__ |
|
38 | 38 | import __builtin__ |
|
39 | 39 | import StringIO |
|
40 | 40 | import bdb |
|
41 | 41 | import cPickle as pickle |
|
42 | 42 | import codeop |
|
43 | 43 | import exceptions |
|
44 | 44 | import glob |
|
45 | 45 | import inspect |
|
46 | 46 | import keyword |
|
47 | 47 | import new |
|
48 | 48 | import os |
|
49 | 49 | import pydoc |
|
50 | 50 | import re |
|
51 | 51 | import shutil |
|
52 | 52 | import string |
|
53 | 53 | import sys |
|
54 | 54 | import tempfile |
|
55 | 55 | import traceback |
|
56 | 56 | import types |
|
57 | 57 | import warnings |
|
58 | 58 | warnings.filterwarnings('ignore', r'.*sets module*') |
|
59 | 59 | from sets import Set |
|
60 | 60 | from pprint import pprint, pformat |
|
61 | 61 | |
|
62 | 62 | # IPython's own modules |
|
63 | 63 | #import IPython |
|
64 | 64 | from IPython import Debugger,OInspect,PyColorize,ultraTB |
|
65 | 65 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
66 | 66 | from IPython.Extensions import pickleshare |
|
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 |
|
71 | 71 | from IPython.Prompts import CachedOutput |
|
72 | 72 | from IPython.ipstruct import Struct |
|
73 | 73 | from IPython.background_jobs import BackgroundJobManager |
|
74 | 74 | from IPython.usage import cmd_line_usage,interactive_usage |
|
75 | 75 | from IPython.genutils import * |
|
76 | 76 | from IPython.strdispatch import StrDispatch |
|
77 | 77 | import IPython.ipapi |
|
78 | 78 | import IPython.history |
|
79 | 79 | import IPython.prefilter as prefilter |
|
80 | 80 | import IPython.shadowns |
|
81 | 81 | # Globals |
|
82 | 82 | |
|
83 | 83 | # store the builtin raw_input globally, and use this always, in case user code |
|
84 | 84 | # overwrites it (like wx.py.PyShell does) |
|
85 | 85 | raw_input_original = raw_input |
|
86 | 86 | |
|
87 | 87 | # compiled regexps for autoindent management |
|
88 | 88 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
89 | 89 | |
|
90 | 90 | |
|
91 | 91 | #**************************************************************************** |
|
92 | 92 | # Some utility function definitions |
|
93 | 93 | |
|
94 | 94 | ini_spaces_re = re.compile(r'^(\s+)') |
|
95 | 95 | |
|
96 | 96 | def num_ini_spaces(strng): |
|
97 | 97 | """Return the number of initial spaces in a string""" |
|
98 | 98 | |
|
99 | 99 | ini_spaces = ini_spaces_re.match(strng) |
|
100 | 100 | if ini_spaces: |
|
101 | 101 | return ini_spaces.end() |
|
102 | 102 | else: |
|
103 | 103 | return 0 |
|
104 | 104 | |
|
105 | 105 | def softspace(file, newvalue): |
|
106 | 106 | """Copied from code.py, to remove the dependency""" |
|
107 | 107 | |
|
108 | 108 | oldvalue = 0 |
|
109 | 109 | try: |
|
110 | 110 | oldvalue = file.softspace |
|
111 | 111 | except AttributeError: |
|
112 | 112 | pass |
|
113 | 113 | try: |
|
114 | 114 | file.softspace = newvalue |
|
115 | 115 | except (AttributeError, TypeError): |
|
116 | 116 | # "attribute-less object" or "read-only attributes" |
|
117 | 117 | pass |
|
118 | 118 | return oldvalue |
|
119 | 119 | |
|
120 | 120 | |
|
121 | 121 | #**************************************************************************** |
|
122 | 122 | # Local use exceptions |
|
123 | 123 | class SpaceInInput(exceptions.Exception): pass |
|
124 | 124 | |
|
125 | 125 | |
|
126 | 126 | #**************************************************************************** |
|
127 | 127 | # Local use classes |
|
128 | 128 | class Bunch: pass |
|
129 | 129 | |
|
130 | 130 | class Undefined: pass |
|
131 | 131 | |
|
132 | 132 | class Quitter(object): |
|
133 | 133 | """Simple class to handle exit, similar to Python 2.5's. |
|
134 | 134 | |
|
135 | 135 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
136 | 136 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
137 | 137 | |
|
138 | 138 | def __init__(self,shell,name): |
|
139 | 139 | self.shell = shell |
|
140 | 140 | self.name = name |
|
141 | 141 | |
|
142 | 142 | def __repr__(self): |
|
143 | 143 | return 'Type %s() to exit.' % self.name |
|
144 | 144 | __str__ = __repr__ |
|
145 | 145 | |
|
146 | 146 | def __call__(self): |
|
147 | 147 | self.shell.exit() |
|
148 | 148 | |
|
149 | 149 | class InputList(list): |
|
150 | 150 | """Class to store user input. |
|
151 | 151 | |
|
152 | 152 | It's basically a list, but slices return a string instead of a list, thus |
|
153 | 153 | allowing things like (assuming 'In' is an instance): |
|
154 | 154 | |
|
155 | 155 | exec In[4:7] |
|
156 | 156 | |
|
157 | 157 | or |
|
158 | 158 | |
|
159 | 159 | exec In[5:9] + In[14] + In[21:25]""" |
|
160 | 160 | |
|
161 | 161 | def __getslice__(self,i,j): |
|
162 | 162 | return ''.join(list.__getslice__(self,i,j)) |
|
163 | 163 | |
|
164 | 164 | class SyntaxTB(ultraTB.ListTB): |
|
165 | 165 | """Extension which holds some state: the last exception value""" |
|
166 | 166 | |
|
167 | 167 | def __init__(self,color_scheme = 'NoColor'): |
|
168 | 168 | ultraTB.ListTB.__init__(self,color_scheme) |
|
169 | 169 | self.last_syntax_error = None |
|
170 | 170 | |
|
171 | 171 | def __call__(self, etype, value, elist): |
|
172 | 172 | self.last_syntax_error = value |
|
173 | 173 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
174 | 174 | |
|
175 | 175 | def clear_err_state(self): |
|
176 | 176 | """Return the current error state and clear it""" |
|
177 | 177 | e = self.last_syntax_error |
|
178 | 178 | self.last_syntax_error = None |
|
179 | 179 | return e |
|
180 | 180 | |
|
181 | 181 | #**************************************************************************** |
|
182 | 182 | # Main IPython class |
|
183 | 183 | |
|
184 | 184 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
185 | 185 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
186 | 186 | # attributes and methods, but too much user code out there relies on the |
|
187 | 187 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
188 | 188 | # |
|
189 | 189 | # But at least now, all the pieces have been separated and we could, in |
|
190 | 190 | # principle, stop using the mixin. This will ease the transition to the |
|
191 | 191 | # chainsaw branch. |
|
192 | 192 | |
|
193 | 193 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
194 | 194 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
195 | 195 | # class, to prevent clashes. |
|
196 | 196 | |
|
197 | 197 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
198 | 198 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
199 | 199 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
200 | 200 | # 'self.value'] |
|
201 | 201 | |
|
202 | 202 | class InteractiveShell(object,Magic): |
|
203 | 203 | """An enhanced console for Python.""" |
|
204 | 204 | |
|
205 | 205 | # class attribute to indicate whether the class supports threads or not. |
|
206 | 206 | # Subclasses with thread support should override this as needed. |
|
207 | 207 | isthreaded = False |
|
208 | 208 | |
|
209 | 209 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
210 |
user_ns |
|
|
210 | user_ns=None,user_global_ns=None,banner2='', | |
|
211 | 211 | custom_exceptions=((),None),embedded=False): |
|
212 | 212 | |
|
213 | 213 | # log system |
|
214 | 214 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
215 | 215 | |
|
216 | 216 | # Job manager (for jobs run as background threads) |
|
217 | 217 | self.jobs = BackgroundJobManager() |
|
218 | 218 | |
|
219 | 219 | # Store the actual shell's name |
|
220 | 220 | self.name = name |
|
221 | 221 | self.more = False |
|
222 | 222 | |
|
223 | 223 | # We need to know whether the instance is meant for embedding, since |
|
224 | 224 | # global/local namespaces need to be handled differently in that case |
|
225 | 225 | self.embedded = embedded |
|
226 | 226 | if embedded: |
|
227 | 227 | # Control variable so users can, from within the embedded instance, |
|
228 | 228 | # permanently deactivate it. |
|
229 | 229 | self.embedded_active = True |
|
230 | 230 | |
|
231 | 231 | # command compiler |
|
232 | 232 | self.compile = codeop.CommandCompiler() |
|
233 | 233 | |
|
234 | 234 | # User input buffer |
|
235 | 235 | self.buffer = [] |
|
236 | 236 | |
|
237 | 237 | # Default name given in compilation of code |
|
238 | 238 | self.filename = '<ipython console>' |
|
239 | 239 | |
|
240 | 240 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
241 | 241 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
242 | 242 | __builtin__.exit = Quitter(self,'exit') |
|
243 | 243 | __builtin__.quit = Quitter(self,'quit') |
|
244 | 244 | |
|
245 | 245 | # Make an empty namespace, which extension writers can rely on both |
|
246 | 246 | # existing and NEVER being used by ipython itself. This gives them a |
|
247 | 247 | # convenient location for storing additional information and state |
|
248 | 248 | # their extensions may require, without fear of collisions with other |
|
249 | 249 | # ipython names that may develop later. |
|
250 | 250 | self.meta = Struct() |
|
251 | 251 | |
|
252 | 252 | # Create the namespace where the user will operate. user_ns is |
|
253 | 253 | # normally the only one used, and it is passed to the exec calls as |
|
254 | 254 | # the locals argument. But we do carry a user_global_ns namespace |
|
255 | 255 | # given as the exec 'globals' argument, This is useful in embedding |
|
256 | 256 | # situations where the ipython shell opens in a context where the |
|
257 | # distinction between locals and globals is meaningful. | |
|
257 | # distinction between locals and globals is meaningful. For | |
|
258 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
|
258 | 259 | |
|
259 | 260 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
260 | 261 | # level as a dict instead of a module. This is a manual fix, but I |
|
261 | 262 | # should really track down where the problem is coming from. Alex |
|
262 | 263 | # Schmolck reported this problem first. |
|
263 | 264 | |
|
264 | 265 | # A useful post by Alex Martelli on this topic: |
|
265 | 266 | # Re: inconsistent value from __builtins__ |
|
266 | 267 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
267 | 268 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
268 | 269 | # Gruppen: comp.lang.python |
|
269 | 270 | |
|
270 | 271 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
271 | 272 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
272 | 273 | # > <type 'dict'> |
|
273 | 274 | # > >>> print type(__builtins__) |
|
274 | 275 | # > <type 'module'> |
|
275 | 276 | # > Is this difference in return value intentional? |
|
276 | 277 | |
|
277 | 278 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
278 | 279 | # or a module, and it's been that way for a long time. Whether it's |
|
279 | 280 | # intentional (or sensible), I don't know. In any case, the idea is |
|
280 | 281 | # that if you need to access the built-in namespace directly, you |
|
281 | 282 | # should start with "import __builtin__" (note, no 's') which will |
|
282 | 283 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
283 | 284 | |
|
284 | 285 | # These routines return properly built dicts as needed by the rest of |
|
285 | 286 | # the code, and can also be used by extension writers to generate |
|
286 | 287 | # properly initialized namespaces. |
|
287 |
user_ns = IPython.ipapi.make_user_ns(user_ns |
|
|
288 | user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns) | |
|
289 | ||
|
288 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, | |
|
289 | user_global_ns) | |
|
290 | ||
|
290 | 291 | # Assign namespaces |
|
291 | 292 | # This is the namespace where all normal user variables live |
|
292 | 293 | self.user_ns = user_ns |
|
293 | # Embedded instances require a separate namespace for globals. | |
|
294 | # Normally this one is unused by non-embedded instances. | |
|
295 | 294 | self.user_global_ns = user_global_ns |
|
296 | 295 | # A namespace to keep track of internal data structures to prevent |
|
297 | 296 | # them from cluttering user-visible stuff. Will be updated later |
|
298 | 297 | self.internal_ns = {} |
|
299 | 298 | |
|
300 | 299 | # Namespace of system aliases. Each entry in the alias |
|
301 | 300 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
302 | 301 | # of positional arguments of the alias. |
|
303 | 302 | self.alias_table = {} |
|
304 | 303 | |
|
305 | 304 | # A table holding all the namespaces IPython deals with, so that |
|
306 | 305 | # introspection facilities can search easily. |
|
307 | 306 | self.ns_table = {'user':user_ns, |
|
308 | 307 | 'user_global':user_global_ns, |
|
309 | 308 | 'alias':self.alias_table, |
|
310 | 309 | 'internal':self.internal_ns, |
|
311 | 310 | 'builtin':__builtin__.__dict__ |
|
312 | 311 | } |
|
313 | 312 | # The user namespace MUST have a pointer to the shell itself. |
|
314 | 313 | self.user_ns[name] = self |
|
315 | 314 | |
|
316 | 315 | # We need to insert into sys.modules something that looks like a |
|
317 | 316 | # module but which accesses the IPython namespace, for shelve and |
|
318 | 317 | # pickle to work interactively. Normally they rely on getting |
|
319 | 318 | # everything out of __main__, but for embedding purposes each IPython |
|
320 | 319 | # instance has its own private namespace, so we can't go shoving |
|
321 | 320 | # everything into __main__. |
|
322 | 321 | |
|
323 | 322 | # note, however, that we should only do this for non-embedded |
|
324 | 323 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
325 | 324 | # namespace. Embedded instances, on the other hand, should not do |
|
326 | 325 | # this because they need to manage the user local/global namespaces |
|
327 | 326 | # only, but they live within a 'normal' __main__ (meaning, they |
|
328 | 327 | # shouldn't overtake the execution environment of the script they're |
|
329 | 328 | # embedded in). |
|
330 | 329 | |
|
331 | 330 | if not embedded: |
|
332 | 331 | try: |
|
333 | 332 | main_name = self.user_ns['__name__'] |
|
334 | 333 | except KeyError: |
|
335 | 334 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
336 | 335 | else: |
|
337 | 336 | #print "pickle hack in place" # dbg |
|
338 | 337 | #print 'main_name:',main_name # dbg |
|
339 | 338 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
340 | 339 | |
|
341 | 340 | # Now that FakeModule produces a real module, we've run into a nasty |
|
342 | 341 | # problem: after script execution (via %run), the module where the user |
|
343 | 342 | # code ran is deleted. Now that this object is a true module (needed |
|
344 | 343 | # so docetst and other tools work correctly), the Python module |
|
345 | 344 | # teardown mechanism runs over it, and sets to None every variable |
|
346 | 345 | # present in that module. This means that later calls to functions |
|
347 | 346 | # defined in the script (which have become interactively visible after |
|
348 | 347 | # script exit) fail, because they hold references to objects that have |
|
349 | 348 | # become overwritten into None. The only solution I see right now is |
|
350 | 349 | # to protect every FakeModule used by %run by holding an internal |
|
351 | 350 | # reference to it. This private list will be used for that. The |
|
352 | 351 | # %reset command will flush it as well. |
|
353 | 352 | self._user_main_modules = [] |
|
354 | 353 | |
|
355 | 354 | # List of input with multi-line handling. |
|
356 | 355 | # Fill its zero entry, user counter starts at 1 |
|
357 | 356 | self.input_hist = InputList(['\n']) |
|
358 | 357 | # This one will hold the 'raw' input history, without any |
|
359 | 358 | # pre-processing. This will allow users to retrieve the input just as |
|
360 | 359 | # it was exactly typed in by the user, with %hist -r. |
|
361 | 360 | self.input_hist_raw = InputList(['\n']) |
|
362 | 361 | |
|
363 | 362 | # list of visited directories |
|
364 | 363 | try: |
|
365 | 364 | self.dir_hist = [os.getcwd()] |
|
366 | 365 | except OSError: |
|
367 | 366 | self.dir_hist = [] |
|
368 | 367 | |
|
369 | 368 | # dict of output history |
|
370 | 369 | self.output_hist = {} |
|
371 | 370 | |
|
372 | 371 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
373 | 372 | # under Win32 have it set to None, and we need to have a known valid |
|
374 | 373 | # encoding to use in the raw_input() method |
|
375 | 374 | try: |
|
376 | 375 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
377 | 376 | except AttributeError: |
|
378 | 377 | self.stdin_encoding = 'ascii' |
|
379 | 378 | |
|
380 | 379 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
381 | 380 | no_alias = {} |
|
382 | 381 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
383 | 382 | for key in keyword.kwlist + no_alias_magics: |
|
384 | 383 | no_alias[key] = 1 |
|
385 | 384 | no_alias.update(__builtin__.__dict__) |
|
386 | 385 | self.no_alias = no_alias |
|
387 | 386 | |
|
388 | 387 | # make global variables for user access to these |
|
389 | 388 | self.user_ns['_ih'] = self.input_hist |
|
390 | 389 | self.user_ns['_oh'] = self.output_hist |
|
391 | 390 | self.user_ns['_dh'] = self.dir_hist |
|
392 | 391 | |
|
393 | 392 | # user aliases to input and output histories |
|
394 | 393 | self.user_ns['In'] = self.input_hist |
|
395 | 394 | self.user_ns['Out'] = self.output_hist |
|
396 | 395 | |
|
397 | 396 | self.user_ns['_sh'] = IPython.shadowns |
|
398 | 397 | # Object variable to store code object waiting execution. This is |
|
399 | 398 | # used mainly by the multithreaded shells, but it can come in handy in |
|
400 | 399 | # other situations. No need to use a Queue here, since it's a single |
|
401 | 400 | # item which gets cleared once run. |
|
402 | 401 | self.code_to_run = None |
|
403 | 402 | |
|
404 | 403 | # escapes for automatic behavior on the command line |
|
405 | 404 | self.ESC_SHELL = '!' |
|
406 | 405 | self.ESC_SH_CAP = '!!' |
|
407 | 406 | self.ESC_HELP = '?' |
|
408 | 407 | self.ESC_MAGIC = '%' |
|
409 | 408 | self.ESC_QUOTE = ',' |
|
410 | 409 | self.ESC_QUOTE2 = ';' |
|
411 | 410 | self.ESC_PAREN = '/' |
|
412 | 411 | |
|
413 | 412 | # And their associated handlers |
|
414 | 413 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
415 | 414 | self.ESC_QUOTE : self.handle_auto, |
|
416 | 415 | self.ESC_QUOTE2 : self.handle_auto, |
|
417 | 416 | self.ESC_MAGIC : self.handle_magic, |
|
418 | 417 | self.ESC_HELP : self.handle_help, |
|
419 | 418 | self.ESC_SHELL : self.handle_shell_escape, |
|
420 | 419 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
421 | 420 | } |
|
422 | 421 | |
|
423 | 422 | # class initializations |
|
424 | 423 | Magic.__init__(self,self) |
|
425 | 424 | |
|
426 | 425 | # Python source parser/formatter for syntax highlighting |
|
427 | 426 | pyformat = PyColorize.Parser().format |
|
428 | 427 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
429 | 428 | |
|
430 | 429 | # hooks holds pointers used for user-side customizations |
|
431 | 430 | self.hooks = Struct() |
|
432 | 431 | |
|
433 | 432 | self.strdispatchers = {} |
|
434 | 433 | |
|
435 | 434 | # Set all default hooks, defined in the IPython.hooks module. |
|
436 | 435 | hooks = IPython.hooks |
|
437 | 436 | for hook_name in hooks.__all__: |
|
438 | 437 | # default hooks have priority 100, i.e. low; user hooks should have |
|
439 | 438 | # 0-100 priority |
|
440 | 439 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
441 | 440 | #print "bound hook",hook_name |
|
442 | 441 | |
|
443 | 442 | # Flag to mark unconditional exit |
|
444 | 443 | self.exit_now = False |
|
445 | 444 | |
|
446 | 445 | self.usage_min = """\ |
|
447 | 446 | An enhanced console for Python. |
|
448 | 447 | Some of its features are: |
|
449 | 448 | - Readline support if the readline library is present. |
|
450 | 449 | - Tab completion in the local namespace. |
|
451 | 450 | - Logging of input, see command-line options. |
|
452 | 451 | - System shell escape via ! , eg !ls. |
|
453 | 452 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
454 | 453 | - Keeps track of locally defined variables via %who, %whos. |
|
455 | 454 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
456 | 455 | """ |
|
457 | 456 | if usage: self.usage = usage |
|
458 | 457 | else: self.usage = self.usage_min |
|
459 | 458 | |
|
460 | 459 | # Storage |
|
461 | 460 | self.rc = rc # This will hold all configuration information |
|
462 | 461 | self.pager = 'less' |
|
463 | 462 | # temporary files used for various purposes. Deleted at exit. |
|
464 | 463 | self.tempfiles = [] |
|
465 | 464 | |
|
466 | 465 | # Keep track of readline usage (later set by init_readline) |
|
467 | 466 | self.has_readline = False |
|
468 | 467 | |
|
469 | 468 | # template for logfile headers. It gets resolved at runtime by the |
|
470 | 469 | # logstart method. |
|
471 | 470 | self.loghead_tpl = \ |
|
472 | 471 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
473 | 472 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
474 | 473 | #log# opts = %s |
|
475 | 474 | #log# args = %s |
|
476 | 475 | #log# It is safe to make manual edits below here. |
|
477 | 476 | #log#----------------------------------------------------------------------- |
|
478 | 477 | """ |
|
479 | 478 | # for pushd/popd management |
|
480 | 479 | try: |
|
481 | 480 | self.home_dir = get_home_dir() |
|
482 | 481 | except HomeDirError,msg: |
|
483 | 482 | fatal(msg) |
|
484 | 483 | |
|
485 | 484 | self.dir_stack = [] |
|
486 | 485 | |
|
487 | 486 | # Functions to call the underlying shell. |
|
488 | 487 | |
|
489 | 488 | # The first is similar to os.system, but it doesn't return a value, |
|
490 | 489 | # and it allows interpolation of variables in the user's namespace. |
|
491 | 490 | self.system = lambda cmd: \ |
|
492 | 491 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) |
|
493 | 492 | |
|
494 | 493 | # These are for getoutput and getoutputerror: |
|
495 | 494 | self.getoutput = lambda cmd: \ |
|
496 | 495 | getoutput(self.var_expand(cmd,depth=2), |
|
497 | 496 | header=self.rc.system_header, |
|
498 | 497 | verbose=self.rc.system_verbose) |
|
499 | 498 | |
|
500 | 499 | self.getoutputerror = lambda cmd: \ |
|
501 | 500 | getoutputerror(self.var_expand(cmd,depth=2), |
|
502 | 501 | header=self.rc.system_header, |
|
503 | 502 | verbose=self.rc.system_verbose) |
|
504 | 503 | |
|
505 | 504 | |
|
506 | 505 | # keep track of where we started running (mainly for crash post-mortem) |
|
507 | 506 | self.starting_dir = os.getcwd() |
|
508 | 507 | |
|
509 | 508 | # Various switches which can be set |
|
510 | 509 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
511 | 510 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
512 | 511 | self.banner2 = banner2 |
|
513 | 512 | |
|
514 | 513 | # TraceBack handlers: |
|
515 | 514 | |
|
516 | 515 | # Syntax error handler. |
|
517 | 516 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
518 | 517 | |
|
519 | 518 | # The interactive one is initialized with an offset, meaning we always |
|
520 | 519 | # want to remove the topmost item in the traceback, which is our own |
|
521 | 520 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
522 | 521 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
523 | 522 | color_scheme='NoColor', |
|
524 | 523 | tb_offset = 1) |
|
525 | 524 | |
|
526 | 525 | # IPython itself shouldn't crash. This will produce a detailed |
|
527 | 526 | # post-mortem if it does. But we only install the crash handler for |
|
528 | 527 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
529 | 528 | # and lose the crash handler. This is because exceptions in the main |
|
530 | 529 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
531 | 530 | # and there's no point in printing crash dumps for every user exception. |
|
532 | 531 | if self.isthreaded: |
|
533 | 532 | ipCrashHandler = ultraTB.FormattedTB() |
|
534 | 533 | else: |
|
535 | 534 | from IPython import CrashHandler |
|
536 | 535 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
537 | 536 | self.set_crash_handler(ipCrashHandler) |
|
538 | 537 | |
|
539 | 538 | # and add any custom exception handlers the user may have specified |
|
540 | 539 | self.set_custom_exc(*custom_exceptions) |
|
541 | 540 | |
|
542 | 541 | # indentation management |
|
543 | 542 | self.autoindent = False |
|
544 | 543 | self.indent_current_nsp = 0 |
|
545 | 544 | |
|
546 | 545 | # Make some aliases automatically |
|
547 | 546 | # Prepare list of shell aliases to auto-define |
|
548 | 547 | if os.name == 'posix': |
|
549 | 548 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
550 | 549 | 'mv mv -i','rm rm -i','cp cp -i', |
|
551 | 550 | 'cat cat','less less','clear clear', |
|
552 | 551 | # a better ls |
|
553 | 552 | 'ls ls -F', |
|
554 | 553 | # long ls |
|
555 | 554 | 'll ls -lF') |
|
556 | 555 | # Extra ls aliases with color, which need special treatment on BSD |
|
557 | 556 | # variants |
|
558 | 557 | ls_extra = ( # color ls |
|
559 | 558 | 'lc ls -F -o --color', |
|
560 | 559 | # ls normal files only |
|
561 | 560 | 'lf ls -F -o --color %l | grep ^-', |
|
562 | 561 | # ls symbolic links |
|
563 | 562 | 'lk ls -F -o --color %l | grep ^l', |
|
564 | 563 | # directories or links to directories, |
|
565 | 564 | 'ldir ls -F -o --color %l | grep /$', |
|
566 | 565 | # things which are executable |
|
567 | 566 | 'lx ls -F -o --color %l | grep ^-..x', |
|
568 | 567 | ) |
|
569 | 568 | # The BSDs don't ship GNU ls, so they don't understand the |
|
570 | 569 | # --color switch out of the box |
|
571 | 570 | if 'bsd' in sys.platform: |
|
572 | 571 | ls_extra = ( # ls normal files only |
|
573 | 572 | 'lf ls -lF | grep ^-', |
|
574 | 573 | # ls symbolic links |
|
575 | 574 | 'lk ls -lF | grep ^l', |
|
576 | 575 | # directories or links to directories, |
|
577 | 576 | 'ldir ls -lF | grep /$', |
|
578 | 577 | # things which are executable |
|
579 | 578 | 'lx ls -lF | grep ^-..x', |
|
580 | 579 | ) |
|
581 | 580 | auto_alias = auto_alias + ls_extra |
|
582 | 581 | elif os.name in ['nt','dos']: |
|
583 | 582 | auto_alias = ('ls dir /on', |
|
584 | 583 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
585 | 584 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
586 | 585 | 'ren ren','cls cls','copy copy') |
|
587 | 586 | else: |
|
588 | 587 | auto_alias = () |
|
589 | 588 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
590 | 589 | |
|
591 | 590 | |
|
592 | 591 | # Produce a public API instance |
|
593 | 592 | self.api = IPython.ipapi.IPApi(self) |
|
594 | 593 | |
|
595 | 594 | # Call the actual (public) initializer |
|
596 | 595 | self.init_auto_alias() |
|
597 | 596 | |
|
598 | 597 | # track which builtins we add, so we can clean up later |
|
599 | 598 | self.builtins_added = {} |
|
600 | 599 | # This method will add the necessary builtins for operation, but |
|
601 | 600 | # tracking what it did via the builtins_added dict. |
|
602 | 601 | |
|
603 | 602 | #TODO: remove this, redundant |
|
604 | 603 | self.add_builtins() |
|
605 | 604 | |
|
606 | 605 | |
|
607 | 606 | |
|
608 | 607 | |
|
609 | 608 | # end __init__ |
|
610 | 609 | |
|
611 | 610 | def var_expand(self,cmd,depth=0): |
|
612 | 611 | """Expand python variables in a string. |
|
613 | 612 | |
|
614 | 613 | The depth argument indicates how many frames above the caller should |
|
615 | 614 | be walked to look for the local namespace where to expand variables. |
|
616 | 615 | |
|
617 | 616 | The global namespace for expansion is always the user's interactive |
|
618 | 617 | namespace. |
|
619 | 618 | """ |
|
620 | 619 | |
|
621 | 620 | return str(ItplNS(cmd, |
|
622 | 621 | self.user_ns, # globals |
|
623 | 622 | # Skip our own frame in searching for locals: |
|
624 | 623 | sys._getframe(depth+1).f_locals # locals |
|
625 | 624 | )) |
|
626 | 625 | |
|
627 | 626 | def pre_config_initialization(self): |
|
628 | 627 | """Pre-configuration init method |
|
629 | 628 | |
|
630 | 629 | This is called before the configuration files are processed to |
|
631 | 630 | prepare the services the config files might need. |
|
632 | 631 | |
|
633 | 632 | self.rc already has reasonable default values at this point. |
|
634 | 633 | """ |
|
635 | 634 | rc = self.rc |
|
636 | 635 | try: |
|
637 | 636 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
638 | 637 | except exceptions.UnicodeDecodeError: |
|
639 | 638 | print "Your ipythondir can't be decoded to unicode!" |
|
640 | 639 | print "Please set HOME environment variable to something that" |
|
641 | 640 | print r"only has ASCII characters, e.g. c:\home" |
|
642 | 641 | print "Now it is",rc.ipythondir |
|
643 | 642 | sys.exit() |
|
644 | 643 | self.shadowhist = IPython.history.ShadowHist(self.db) |
|
645 | 644 | |
|
646 | 645 | |
|
647 | 646 | def post_config_initialization(self): |
|
648 | 647 | """Post configuration init method |
|
649 | 648 | |
|
650 | 649 | This is called after the configuration files have been processed to |
|
651 | 650 | 'finalize' the initialization.""" |
|
652 | 651 | |
|
653 | 652 | rc = self.rc |
|
654 | 653 | |
|
655 | 654 | # Object inspector |
|
656 | 655 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
657 | 656 | PyColorize.ANSICodeColors, |
|
658 | 657 | 'NoColor', |
|
659 | 658 | rc.object_info_string_level) |
|
660 | 659 | |
|
661 | 660 | self.rl_next_input = None |
|
662 | 661 | self.rl_do_indent = False |
|
663 | 662 | # Load readline proper |
|
664 | 663 | if rc.readline: |
|
665 | 664 | self.init_readline() |
|
666 | 665 | |
|
667 | 666 | |
|
668 | 667 | # local shortcut, this is used a LOT |
|
669 | 668 | self.log = self.logger.log |
|
670 | 669 | |
|
671 | 670 | # Initialize cache, set in/out prompts and printing system |
|
672 | 671 | self.outputcache = CachedOutput(self, |
|
673 | 672 | rc.cache_size, |
|
674 | 673 | rc.pprint, |
|
675 | 674 | input_sep = rc.separate_in, |
|
676 | 675 | output_sep = rc.separate_out, |
|
677 | 676 | output_sep2 = rc.separate_out2, |
|
678 | 677 | ps1 = rc.prompt_in1, |
|
679 | 678 | ps2 = rc.prompt_in2, |
|
680 | 679 | ps_out = rc.prompt_out, |
|
681 | 680 | pad_left = rc.prompts_pad_left) |
|
682 | 681 | |
|
683 | 682 | # user may have over-ridden the default print hook: |
|
684 | 683 | try: |
|
685 | 684 | self.outputcache.__class__.display = self.hooks.display |
|
686 | 685 | except AttributeError: |
|
687 | 686 | pass |
|
688 | 687 | |
|
689 | 688 | # I don't like assigning globally to sys, because it means when |
|
690 | 689 | # embedding instances, each embedded instance overrides the previous |
|
691 | 690 | # choice. But sys.displayhook seems to be called internally by exec, |
|
692 | 691 | # so I don't see a way around it. We first save the original and then |
|
693 | 692 | # overwrite it. |
|
694 | 693 | self.sys_displayhook = sys.displayhook |
|
695 | 694 | sys.displayhook = self.outputcache |
|
696 | 695 | |
|
697 | 696 | # Do a proper resetting of doctest, including the necessary displayhook |
|
698 | 697 | # monkeypatching |
|
699 | 698 | try: |
|
700 | 699 | doctest_reload() |
|
701 | 700 | except ImportError: |
|
702 | 701 | warn("doctest module does not exist.") |
|
703 | 702 | |
|
704 | 703 | # Set user colors (don't do it in the constructor above so that it |
|
705 | 704 | # doesn't crash if colors option is invalid) |
|
706 | 705 | self.magic_colors(rc.colors) |
|
707 | 706 | |
|
708 | 707 | # Set calling of pdb on exceptions |
|
709 | 708 | self.call_pdb = rc.pdb |
|
710 | 709 | |
|
711 | 710 | # Load user aliases |
|
712 | 711 | for alias in rc.alias: |
|
713 | 712 | self.magic_alias(alias) |
|
714 | 713 | |
|
715 | 714 | self.hooks.late_startup_hook() |
|
716 | 715 | |
|
717 | 716 | for cmd in self.rc.autoexec: |
|
718 | 717 | #print "autoexec>",cmd #dbg |
|
719 | 718 | self.api.runlines(cmd) |
|
720 | 719 | |
|
721 | 720 | batchrun = False |
|
722 | 721 | for batchfile in [path(arg) for arg in self.rc.args |
|
723 | 722 | if arg.lower().endswith('.ipy')]: |
|
724 | 723 | if not batchfile.isfile(): |
|
725 | 724 | print "No such batch file:", batchfile |
|
726 | 725 | continue |
|
727 | 726 | self.api.runlines(batchfile.text()) |
|
728 | 727 | batchrun = True |
|
729 | 728 | # without -i option, exit after running the batch file |
|
730 | 729 | if batchrun and not self.rc.interact: |
|
731 | 730 | self.ask_exit() |
|
732 | 731 | |
|
733 | 732 | def add_builtins(self): |
|
734 | 733 | """Store ipython references into the builtin namespace. |
|
735 | 734 | |
|
736 | 735 | Some parts of ipython operate via builtins injected here, which hold a |
|
737 | 736 | reference to IPython itself.""" |
|
738 | 737 | |
|
739 | 738 | # TODO: deprecate all of these, they are unsafe |
|
740 | 739 | builtins_new = dict(__IPYTHON__ = self, |
|
741 | 740 | ip_set_hook = self.set_hook, |
|
742 | 741 | jobs = self.jobs, |
|
743 | 742 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
744 | 743 | ipalias = wrap_deprecated(self.ipalias), |
|
745 | 744 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
746 | 745 | #_ip = self.api |
|
747 | 746 | ) |
|
748 | 747 | for biname,bival in builtins_new.items(): |
|
749 | 748 | try: |
|
750 | 749 | # store the orignal value so we can restore it |
|
751 | 750 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
752 | 751 | except KeyError: |
|
753 | 752 | # or mark that it wasn't defined, and we'll just delete it at |
|
754 | 753 | # cleanup |
|
755 | 754 | self.builtins_added[biname] = Undefined |
|
756 | 755 | __builtin__.__dict__[biname] = bival |
|
757 | 756 | |
|
758 | 757 | # Keep in the builtins a flag for when IPython is active. We set it |
|
759 | 758 | # with setdefault so that multiple nested IPythons don't clobber one |
|
760 | 759 | # another. Each will increase its value by one upon being activated, |
|
761 | 760 | # which also gives us a way to determine the nesting level. |
|
762 | 761 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
763 | 762 | |
|
764 | 763 | def clean_builtins(self): |
|
765 | 764 | """Remove any builtins which might have been added by add_builtins, or |
|
766 | 765 | restore overwritten ones to their previous values.""" |
|
767 | 766 | for biname,bival in self.builtins_added.items(): |
|
768 | 767 | if bival is Undefined: |
|
769 | 768 | del __builtin__.__dict__[biname] |
|
770 | 769 | else: |
|
771 | 770 | __builtin__.__dict__[biname] = bival |
|
772 | 771 | self.builtins_added.clear() |
|
773 | 772 | |
|
774 | 773 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
775 | 774 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
776 | 775 | |
|
777 | 776 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
778 | 777 | adding your function to one of these hooks, you can modify IPython's |
|
779 | 778 | behavior to call at runtime your own routines.""" |
|
780 | 779 | |
|
781 | 780 | # At some point in the future, this should validate the hook before it |
|
782 | 781 | # accepts it. Probably at least check that the hook takes the number |
|
783 | 782 | # of args it's supposed to. |
|
784 | 783 | |
|
785 | 784 | f = new.instancemethod(hook,self,self.__class__) |
|
786 | 785 | |
|
787 | 786 | # check if the hook is for strdispatcher first |
|
788 | 787 | if str_key is not None: |
|
789 | 788 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
790 | 789 | sdp.add_s(str_key, f, priority ) |
|
791 | 790 | self.strdispatchers[name] = sdp |
|
792 | 791 | return |
|
793 | 792 | if re_key is not None: |
|
794 | 793 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
795 | 794 | sdp.add_re(re.compile(re_key), f, priority ) |
|
796 | 795 | self.strdispatchers[name] = sdp |
|
797 | 796 | return |
|
798 | 797 | |
|
799 | 798 | dp = getattr(self.hooks, name, None) |
|
800 | 799 | if name not in IPython.hooks.__all__: |
|
801 | 800 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
802 | 801 | if not dp: |
|
803 | 802 | dp = IPython.hooks.CommandChainDispatcher() |
|
804 | 803 | |
|
805 | 804 | try: |
|
806 | 805 | dp.add(f,priority) |
|
807 | 806 | except AttributeError: |
|
808 | 807 | # it was not commandchain, plain old func - replace |
|
809 | 808 | dp = f |
|
810 | 809 | |
|
811 | 810 | setattr(self.hooks,name, dp) |
|
812 | 811 | |
|
813 | 812 | |
|
814 | 813 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
815 | 814 | |
|
816 | 815 | def set_crash_handler(self,crashHandler): |
|
817 | 816 | """Set the IPython crash handler. |
|
818 | 817 | |
|
819 | 818 | This must be a callable with a signature suitable for use as |
|
820 | 819 | sys.excepthook.""" |
|
821 | 820 | |
|
822 | 821 | # Install the given crash handler as the Python exception hook |
|
823 | 822 | sys.excepthook = crashHandler |
|
824 | 823 | |
|
825 | 824 | # The instance will store a pointer to this, so that runtime code |
|
826 | 825 | # (such as magics) can access it. This is because during the |
|
827 | 826 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
828 | 827 | # frameworks). |
|
829 | 828 | self.sys_excepthook = sys.excepthook |
|
830 | 829 | |
|
831 | 830 | |
|
832 | 831 | def set_custom_exc(self,exc_tuple,handler): |
|
833 | 832 | """set_custom_exc(exc_tuple,handler) |
|
834 | 833 | |
|
835 | 834 | Set a custom exception handler, which will be called if any of the |
|
836 | 835 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
837 | 836 | runcode() method. |
|
838 | 837 | |
|
839 | 838 | Inputs: |
|
840 | 839 | |
|
841 | 840 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
842 | 841 | handler for. It is very important that you use a tuple, and NOT A |
|
843 | 842 | LIST here, because of the way Python's except statement works. If |
|
844 | 843 | you only want to trap a single exception, use a singleton tuple: |
|
845 | 844 | |
|
846 | 845 | exc_tuple == (MyCustomException,) |
|
847 | 846 | |
|
848 | 847 | - handler: this must be defined as a function with the following |
|
849 | 848 | basic interface: def my_handler(self,etype,value,tb). |
|
850 | 849 | |
|
851 | 850 | This will be made into an instance method (via new.instancemethod) |
|
852 | 851 | of IPython itself, and it will be called if any of the exceptions |
|
853 | 852 | listed in the exc_tuple are caught. If the handler is None, an |
|
854 | 853 | internal basic one is used, which just prints basic info. |
|
855 | 854 | |
|
856 | 855 | WARNING: by putting in your own exception handler into IPython's main |
|
857 | 856 | execution loop, you run a very good chance of nasty crashes. This |
|
858 | 857 | facility should only be used if you really know what you are doing.""" |
|
859 | 858 | |
|
860 | 859 | assert type(exc_tuple)==type(()) , \ |
|
861 | 860 | "The custom exceptions must be given AS A TUPLE." |
|
862 | 861 | |
|
863 | 862 | def dummy_handler(self,etype,value,tb): |
|
864 | 863 | print '*** Simple custom exception handler ***' |
|
865 | 864 | print 'Exception type :',etype |
|
866 | 865 | print 'Exception value:',value |
|
867 | 866 | print 'Traceback :',tb |
|
868 | 867 | print 'Source code :','\n'.join(self.buffer) |
|
869 | 868 | |
|
870 | 869 | if handler is None: handler = dummy_handler |
|
871 | 870 | |
|
872 | 871 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
873 | 872 | self.custom_exceptions = exc_tuple |
|
874 | 873 | |
|
875 | 874 | def set_custom_completer(self,completer,pos=0): |
|
876 | 875 | """set_custom_completer(completer,pos=0) |
|
877 | 876 | |
|
878 | 877 | Adds a new custom completer function. |
|
879 | 878 | |
|
880 | 879 | The position argument (defaults to 0) is the index in the completers |
|
881 | 880 | list where you want the completer to be inserted.""" |
|
882 | 881 | |
|
883 | 882 | newcomp = new.instancemethod(completer,self.Completer, |
|
884 | 883 | self.Completer.__class__) |
|
885 | 884 | self.Completer.matchers.insert(pos,newcomp) |
|
886 | 885 | |
|
887 | 886 | def set_completer(self): |
|
888 | 887 | """reset readline's completer to be our own.""" |
|
889 | 888 | self.readline.set_completer(self.Completer.complete) |
|
890 | 889 | |
|
891 | 890 | def _get_call_pdb(self): |
|
892 | 891 | return self._call_pdb |
|
893 | 892 | |
|
894 | 893 | def _set_call_pdb(self,val): |
|
895 | 894 | |
|
896 | 895 | if val not in (0,1,False,True): |
|
897 | 896 | raise ValueError,'new call_pdb value must be boolean' |
|
898 | 897 | |
|
899 | 898 | # store value in instance |
|
900 | 899 | self._call_pdb = val |
|
901 | 900 | |
|
902 | 901 | # notify the actual exception handlers |
|
903 | 902 | self.InteractiveTB.call_pdb = val |
|
904 | 903 | if self.isthreaded: |
|
905 | 904 | try: |
|
906 | 905 | self.sys_excepthook.call_pdb = val |
|
907 | 906 | except: |
|
908 | 907 | warn('Failed to activate pdb for threaded exception handler') |
|
909 | 908 | |
|
910 | 909 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
911 | 910 | 'Control auto-activation of pdb at exceptions') |
|
912 | 911 | |
|
913 | 912 | |
|
914 | 913 | # These special functions get installed in the builtin namespace, to |
|
915 | 914 | # provide programmatic (pure python) access to magics, aliases and system |
|
916 | 915 | # calls. This is important for logging, user scripting, and more. |
|
917 | 916 | |
|
918 | 917 | # We are basically exposing, via normal python functions, the three |
|
919 | 918 | # mechanisms in which ipython offers special call modes (magics for |
|
920 | 919 | # internal control, aliases for direct system access via pre-selected |
|
921 | 920 | # names, and !cmd for calling arbitrary system commands). |
|
922 | 921 | |
|
923 | 922 | def ipmagic(self,arg_s): |
|
924 | 923 | """Call a magic function by name. |
|
925 | 924 | |
|
926 | 925 | Input: a string containing the name of the magic function to call and any |
|
927 | 926 | additional arguments to be passed to the magic. |
|
928 | 927 | |
|
929 | 928 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
930 | 929 | prompt: |
|
931 | 930 | |
|
932 | 931 | In[1]: %name -opt foo bar |
|
933 | 932 | |
|
934 | 933 | To call a magic without arguments, simply use ipmagic('name'). |
|
935 | 934 | |
|
936 | 935 | This provides a proper Python function to call IPython's magics in any |
|
937 | 936 | valid Python code you can type at the interpreter, including loops and |
|
938 | 937 | compound statements. It is added by IPython to the Python builtin |
|
939 | 938 | namespace upon initialization.""" |
|
940 | 939 | |
|
941 | 940 | args = arg_s.split(' ',1) |
|
942 | 941 | magic_name = args[0] |
|
943 | 942 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
944 | 943 | |
|
945 | 944 | try: |
|
946 | 945 | magic_args = args[1] |
|
947 | 946 | except IndexError: |
|
948 | 947 | magic_args = '' |
|
949 | 948 | fn = getattr(self,'magic_'+magic_name,None) |
|
950 | 949 | if fn is None: |
|
951 | 950 | error("Magic function `%s` not found." % magic_name) |
|
952 | 951 | else: |
|
953 | 952 | magic_args = self.var_expand(magic_args,1) |
|
954 | 953 | return fn(magic_args) |
|
955 | 954 | |
|
956 | 955 | def ipalias(self,arg_s): |
|
957 | 956 | """Call an alias by name. |
|
958 | 957 | |
|
959 | 958 | Input: a string containing the name of the alias to call and any |
|
960 | 959 | additional arguments to be passed to the magic. |
|
961 | 960 | |
|
962 | 961 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
963 | 962 | prompt: |
|
964 | 963 | |
|
965 | 964 | In[1]: name -opt foo bar |
|
966 | 965 | |
|
967 | 966 | To call an alias without arguments, simply use ipalias('name'). |
|
968 | 967 | |
|
969 | 968 | This provides a proper Python function to call IPython's aliases in any |
|
970 | 969 | valid Python code you can type at the interpreter, including loops and |
|
971 | 970 | compound statements. It is added by IPython to the Python builtin |
|
972 | 971 | namespace upon initialization.""" |
|
973 | 972 | |
|
974 | 973 | args = arg_s.split(' ',1) |
|
975 | 974 | alias_name = args[0] |
|
976 | 975 | try: |
|
977 | 976 | alias_args = args[1] |
|
978 | 977 | except IndexError: |
|
979 | 978 | alias_args = '' |
|
980 | 979 | if alias_name in self.alias_table: |
|
981 | 980 | self.call_alias(alias_name,alias_args) |
|
982 | 981 | else: |
|
983 | 982 | error("Alias `%s` not found." % alias_name) |
|
984 | 983 | |
|
985 | 984 | def ipsystem(self,arg_s): |
|
986 | 985 | """Make a system call, using IPython.""" |
|
987 | 986 | |
|
988 | 987 | self.system(arg_s) |
|
989 | 988 | |
|
990 | 989 | def complete(self,text): |
|
991 | 990 | """Return a sorted list of all possible completions on text. |
|
992 | 991 | |
|
993 | 992 | Inputs: |
|
994 | 993 | |
|
995 | 994 | - text: a string of text to be completed on. |
|
996 | 995 | |
|
997 | 996 | This is a wrapper around the completion mechanism, similar to what |
|
998 | 997 | readline does at the command line when the TAB key is hit. By |
|
999 | 998 | exposing it as a method, it can be used by other non-readline |
|
1000 | 999 | environments (such as GUIs) for text completion. |
|
1001 | 1000 | |
|
1002 | 1001 | Simple usage example: |
|
1003 | 1002 | |
|
1004 | 1003 | In [7]: x = 'hello' |
|
1005 | 1004 | |
|
1006 | 1005 | In [8]: x |
|
1007 | 1006 | Out[8]: 'hello' |
|
1008 | 1007 | |
|
1009 | 1008 | In [9]: print x |
|
1010 | 1009 | hello |
|
1011 | 1010 | |
|
1012 | 1011 | In [10]: _ip.IP.complete('x.l') |
|
1013 | 1012 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] # random |
|
1014 | 1013 | """ |
|
1015 | 1014 | |
|
1016 | 1015 | complete = self.Completer.complete |
|
1017 | 1016 | state = 0 |
|
1018 | 1017 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1019 | 1018 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1020 | 1019 | # start using sets instead, which are faster. |
|
1021 | 1020 | comps = {} |
|
1022 | 1021 | while True: |
|
1023 | 1022 | newcomp = complete(text,state,line_buffer=text) |
|
1024 | 1023 | if newcomp is None: |
|
1025 | 1024 | break |
|
1026 | 1025 | comps[newcomp] = 1 |
|
1027 | 1026 | state += 1 |
|
1028 | 1027 | outcomps = comps.keys() |
|
1029 | 1028 | outcomps.sort() |
|
1030 | 1029 | #print "T:",text,"OC:",outcomps # dbg |
|
1031 | 1030 | #print "vars:",self.user_ns.keys() |
|
1032 | 1031 | return outcomps |
|
1033 | 1032 | |
|
1034 | 1033 | def set_completer_frame(self, frame=None): |
|
1035 | 1034 | if frame: |
|
1036 | 1035 | self.Completer.namespace = frame.f_locals |
|
1037 | 1036 | self.Completer.global_namespace = frame.f_globals |
|
1038 | 1037 | else: |
|
1039 | 1038 | self.Completer.namespace = self.user_ns |
|
1040 | 1039 | self.Completer.global_namespace = self.user_global_ns |
|
1041 | 1040 | |
|
1042 | 1041 | def init_auto_alias(self): |
|
1043 | 1042 | """Define some aliases automatically. |
|
1044 | 1043 | |
|
1045 | 1044 | These are ALL parameter-less aliases""" |
|
1046 | 1045 | |
|
1047 | 1046 | for alias,cmd in self.auto_alias: |
|
1048 | 1047 | self.getapi().defalias(alias,cmd) |
|
1049 | 1048 | |
|
1050 | 1049 | |
|
1051 | 1050 | def alias_table_validate(self,verbose=0): |
|
1052 | 1051 | """Update information about the alias table. |
|
1053 | 1052 | |
|
1054 | 1053 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1055 | 1054 | |
|
1056 | 1055 | no_alias = self.no_alias |
|
1057 | 1056 | for k in self.alias_table.keys(): |
|
1058 | 1057 | if k in no_alias: |
|
1059 | 1058 | del self.alias_table[k] |
|
1060 | 1059 | if verbose: |
|
1061 | 1060 | print ("Deleting alias <%s>, it's a Python " |
|
1062 | 1061 | "keyword or builtin." % k) |
|
1063 | 1062 | |
|
1064 | 1063 | def set_autoindent(self,value=None): |
|
1065 | 1064 | """Set the autoindent flag, checking for readline support. |
|
1066 | 1065 | |
|
1067 | 1066 | If called with no arguments, it acts as a toggle.""" |
|
1068 | 1067 | |
|
1069 | 1068 | if not self.has_readline: |
|
1070 | 1069 | if os.name == 'posix': |
|
1071 | 1070 | warn("The auto-indent feature requires the readline library") |
|
1072 | 1071 | self.autoindent = 0 |
|
1073 | 1072 | return |
|
1074 | 1073 | if value is None: |
|
1075 | 1074 | self.autoindent = not self.autoindent |
|
1076 | 1075 | else: |
|
1077 | 1076 | self.autoindent = value |
|
1078 | 1077 | |
|
1079 | 1078 | def rc_set_toggle(self,rc_field,value=None): |
|
1080 | 1079 | """Set or toggle a field in IPython's rc config. structure. |
|
1081 | 1080 | |
|
1082 | 1081 | If called with no arguments, it acts as a toggle. |
|
1083 | 1082 | |
|
1084 | 1083 | If called with a non-existent field, the resulting AttributeError |
|
1085 | 1084 | exception will propagate out.""" |
|
1086 | 1085 | |
|
1087 | 1086 | rc_val = getattr(self.rc,rc_field) |
|
1088 | 1087 | if value is None: |
|
1089 | 1088 | value = not rc_val |
|
1090 | 1089 | setattr(self.rc,rc_field,value) |
|
1091 | 1090 | |
|
1092 | 1091 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1093 | 1092 | """Install the user configuration directory. |
|
1094 | 1093 | |
|
1095 | 1094 | Can be called when running for the first time or to upgrade the user's |
|
1096 | 1095 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
1097 | 1096 | and 'upgrade'.""" |
|
1098 | 1097 | |
|
1099 | 1098 | def wait(): |
|
1100 | 1099 | try: |
|
1101 | 1100 | raw_input("Please press <RETURN> to start IPython.") |
|
1102 | 1101 | except EOFError: |
|
1103 | 1102 | print >> Term.cout |
|
1104 | 1103 | print '*'*70 |
|
1105 | 1104 | |
|
1106 | 1105 | cwd = os.getcwd() # remember where we started |
|
1107 | 1106 | glb = glob.glob |
|
1108 | 1107 | print '*'*70 |
|
1109 | 1108 | if mode == 'install': |
|
1110 | 1109 | print \ |
|
1111 | 1110 | """Welcome to IPython. I will try to create a personal configuration directory |
|
1112 | 1111 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1113 | 1112 | else: |
|
1114 | 1113 | print 'I am going to upgrade your configuration in:' |
|
1115 | 1114 | |
|
1116 | 1115 | print ipythondir |
|
1117 | 1116 | |
|
1118 | 1117 | rcdirend = os.path.join('IPython','UserConfig') |
|
1119 | 1118 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1120 | 1119 | try: |
|
1121 | 1120 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1122 | 1121 | print "Initializing from configuration",rcdir |
|
1123 | 1122 | except IndexError: |
|
1124 | 1123 | warning = """ |
|
1125 | 1124 | Installation error. IPython's directory was not found. |
|
1126 | 1125 | |
|
1127 | 1126 | Check the following: |
|
1128 | 1127 | |
|
1129 | 1128 | The ipython/IPython directory should be in a directory belonging to your |
|
1130 | 1129 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1131 | 1130 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1132 | 1131 | |
|
1133 | 1132 | IPython will create a minimal default configuration for you. |
|
1134 | 1133 | |
|
1135 | 1134 | """ |
|
1136 | 1135 | warn(warning) |
|
1137 | 1136 | wait() |
|
1138 | 1137 | |
|
1139 | 1138 | if sys.platform =='win32': |
|
1140 | 1139 | inif = 'ipythonrc.ini' |
|
1141 | 1140 | else: |
|
1142 | 1141 | inif = 'ipythonrc' |
|
1143 | 1142 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' } |
|
1144 | 1143 | os.makedirs(ipythondir, mode = 0777) |
|
1145 | 1144 | for f, cont in minimal_setup.items(): |
|
1146 | 1145 | open(ipythondir + '/' + f,'w').write(cont) |
|
1147 | 1146 | |
|
1148 | 1147 | return |
|
1149 | 1148 | |
|
1150 | 1149 | if mode == 'install': |
|
1151 | 1150 | try: |
|
1152 | 1151 | shutil.copytree(rcdir,ipythondir) |
|
1153 | 1152 | os.chdir(ipythondir) |
|
1154 | 1153 | rc_files = glb("ipythonrc*") |
|
1155 | 1154 | for rc_file in rc_files: |
|
1156 | 1155 | os.rename(rc_file,rc_file+rc_suffix) |
|
1157 | 1156 | except: |
|
1158 | 1157 | warning = """ |
|
1159 | 1158 | |
|
1160 | 1159 | There was a problem with the installation: |
|
1161 | 1160 | %s |
|
1162 | 1161 | Try to correct it or contact the developers if you think it's a bug. |
|
1163 | 1162 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1164 | 1163 | warn(warning) |
|
1165 | 1164 | wait() |
|
1166 | 1165 | return |
|
1167 | 1166 | |
|
1168 | 1167 | elif mode == 'upgrade': |
|
1169 | 1168 | try: |
|
1170 | 1169 | os.chdir(ipythondir) |
|
1171 | 1170 | except: |
|
1172 | 1171 | print """ |
|
1173 | 1172 | Can not upgrade: changing to directory %s failed. Details: |
|
1174 | 1173 | %s |
|
1175 | 1174 | """ % (ipythondir,sys.exc_info()[1]) |
|
1176 | 1175 | wait() |
|
1177 | 1176 | return |
|
1178 | 1177 | else: |
|
1179 | 1178 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1180 | 1179 | for new_full_path in sources: |
|
1181 | 1180 | new_filename = os.path.basename(new_full_path) |
|
1182 | 1181 | if new_filename.startswith('ipythonrc'): |
|
1183 | 1182 | new_filename = new_filename + rc_suffix |
|
1184 | 1183 | # The config directory should only contain files, skip any |
|
1185 | 1184 | # directories which may be there (like CVS) |
|
1186 | 1185 | if os.path.isdir(new_full_path): |
|
1187 | 1186 | continue |
|
1188 | 1187 | if os.path.exists(new_filename): |
|
1189 | 1188 | old_file = new_filename+'.old' |
|
1190 | 1189 | if os.path.exists(old_file): |
|
1191 | 1190 | os.remove(old_file) |
|
1192 | 1191 | os.rename(new_filename,old_file) |
|
1193 | 1192 | shutil.copy(new_full_path,new_filename) |
|
1194 | 1193 | else: |
|
1195 | 1194 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1196 | 1195 | |
|
1197 | 1196 | # Fix line-endings to those native to each platform in the config |
|
1198 | 1197 | # directory. |
|
1199 | 1198 | try: |
|
1200 | 1199 | os.chdir(ipythondir) |
|
1201 | 1200 | except: |
|
1202 | 1201 | print """ |
|
1203 | 1202 | Problem: changing to directory %s failed. |
|
1204 | 1203 | Details: |
|
1205 | 1204 | %s |
|
1206 | 1205 | |
|
1207 | 1206 | Some configuration files may have incorrect line endings. This should not |
|
1208 | 1207 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1209 | 1208 | wait() |
|
1210 | 1209 | else: |
|
1211 | 1210 | for fname in glb('ipythonrc*'): |
|
1212 | 1211 | try: |
|
1213 | 1212 | native_line_ends(fname,backup=0) |
|
1214 | 1213 | except IOError: |
|
1215 | 1214 | pass |
|
1216 | 1215 | |
|
1217 | 1216 | if mode == 'install': |
|
1218 | 1217 | print """ |
|
1219 | 1218 | Successful installation! |
|
1220 | 1219 | |
|
1221 | 1220 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1222 | 1221 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1223 | 1222 | distribution) to make sure that your system environment is properly configured |
|
1224 | 1223 | to take advantage of IPython's features. |
|
1225 | 1224 | |
|
1226 | 1225 | Important note: the configuration system has changed! The old system is |
|
1227 | 1226 | still in place, but its setting may be partly overridden by the settings in |
|
1228 | 1227 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
1229 | 1228 | if some of the new settings bother you. |
|
1230 | 1229 | |
|
1231 | 1230 | """ |
|
1232 | 1231 | else: |
|
1233 | 1232 | print """ |
|
1234 | 1233 | Successful upgrade! |
|
1235 | 1234 | |
|
1236 | 1235 | All files in your directory: |
|
1237 | 1236 | %(ipythondir)s |
|
1238 | 1237 | which would have been overwritten by the upgrade were backed up with a .old |
|
1239 | 1238 | extension. If you had made particular customizations in those files you may |
|
1240 | 1239 | want to merge them back into the new files.""" % locals() |
|
1241 | 1240 | wait() |
|
1242 | 1241 | os.chdir(cwd) |
|
1243 | 1242 | # end user_setup() |
|
1244 | 1243 | |
|
1245 | 1244 | def atexit_operations(self): |
|
1246 | 1245 | """This will be executed at the time of exit. |
|
1247 | 1246 | |
|
1248 | 1247 | Saving of persistent data should be performed here. """ |
|
1249 | 1248 | |
|
1250 | 1249 | #print '*** IPython exit cleanup ***' # dbg |
|
1251 | 1250 | # input history |
|
1252 | 1251 | self.savehist() |
|
1253 | 1252 | |
|
1254 | 1253 | # Cleanup all tempfiles left around |
|
1255 | 1254 | for tfile in self.tempfiles: |
|
1256 | 1255 | try: |
|
1257 | 1256 | os.unlink(tfile) |
|
1258 | 1257 | except OSError: |
|
1259 | 1258 | pass |
|
1260 | 1259 | |
|
1261 | 1260 | self.hooks.shutdown_hook() |
|
1262 | 1261 | |
|
1263 | 1262 | def savehist(self): |
|
1264 | 1263 | """Save input history to a file (via readline library).""" |
|
1265 | 1264 | |
|
1266 | 1265 | if not self.has_readline: |
|
1267 | 1266 | return |
|
1268 | 1267 | |
|
1269 | 1268 | try: |
|
1270 | 1269 | self.readline.write_history_file(self.histfile) |
|
1271 | 1270 | except: |
|
1272 | 1271 | print 'Unable to save IPython command history to file: ' + \ |
|
1273 | 1272 | `self.histfile` |
|
1274 | 1273 | |
|
1275 | 1274 | def reloadhist(self): |
|
1276 | 1275 | """Reload the input history from disk file.""" |
|
1277 | 1276 | |
|
1278 | 1277 | if self.has_readline: |
|
1279 | 1278 | try: |
|
1280 | 1279 | self.readline.clear_history() |
|
1281 | 1280 | self.readline.read_history_file(self.shell.histfile) |
|
1282 | 1281 | except AttributeError: |
|
1283 | 1282 | pass |
|
1284 | 1283 | |
|
1285 | 1284 | |
|
1286 | 1285 | def history_saving_wrapper(self, func): |
|
1287 | 1286 | """ Wrap func for readline history saving |
|
1288 | 1287 | |
|
1289 | 1288 | Convert func into callable that saves & restores |
|
1290 | 1289 | history around the call """ |
|
1291 | 1290 | |
|
1292 | 1291 | if not self.has_readline: |
|
1293 | 1292 | return func |
|
1294 | 1293 | |
|
1295 | 1294 | def wrapper(): |
|
1296 | 1295 | self.savehist() |
|
1297 | 1296 | try: |
|
1298 | 1297 | func() |
|
1299 | 1298 | finally: |
|
1300 | 1299 | readline.read_history_file(self.histfile) |
|
1301 | 1300 | return wrapper |
|
1302 | 1301 | |
|
1303 | 1302 | |
|
1304 | 1303 | def pre_readline(self): |
|
1305 | 1304 | """readline hook to be used at the start of each line. |
|
1306 | 1305 | |
|
1307 | 1306 | Currently it handles auto-indent only.""" |
|
1308 | 1307 | |
|
1309 | 1308 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1310 | 1309 | |
|
1311 | 1310 | if self.rl_do_indent: |
|
1312 | 1311 | self.readline.insert_text(self.indent_current_str()) |
|
1313 | 1312 | if self.rl_next_input is not None: |
|
1314 | 1313 | self.readline.insert_text(self.rl_next_input) |
|
1315 | 1314 | self.rl_next_input = None |
|
1316 | 1315 | |
|
1317 | 1316 | def init_readline(self): |
|
1318 | 1317 | """Command history completion/saving/reloading.""" |
|
1319 | 1318 | |
|
1320 | 1319 | |
|
1321 | 1320 | import IPython.rlineimpl as readline |
|
1322 | 1321 | |
|
1323 | 1322 | if not readline.have_readline: |
|
1324 | 1323 | self.has_readline = 0 |
|
1325 | 1324 | self.readline = None |
|
1326 | 1325 | # no point in bugging windows users with this every time: |
|
1327 | 1326 | warn('Readline services not available on this platform.') |
|
1328 | 1327 | else: |
|
1329 | 1328 | sys.modules['readline'] = readline |
|
1330 | 1329 | import atexit |
|
1331 | 1330 | from IPython.completer import IPCompleter |
|
1332 | 1331 | self.Completer = IPCompleter(self, |
|
1333 | 1332 | self.user_ns, |
|
1334 | 1333 | self.user_global_ns, |
|
1335 | 1334 | self.rc.readline_omit__names, |
|
1336 | 1335 | self.alias_table) |
|
1337 | 1336 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1338 | 1337 | self.strdispatchers['complete_command'] = sdisp |
|
1339 | 1338 | self.Completer.custom_completers = sdisp |
|
1340 | 1339 | # Platform-specific configuration |
|
1341 | 1340 | if os.name == 'nt': |
|
1342 | 1341 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1343 | 1342 | else: |
|
1344 | 1343 | self.readline_startup_hook = readline.set_startup_hook |
|
1345 | 1344 | |
|
1346 | 1345 | # Load user's initrc file (readline config) |
|
1347 | 1346 | # Or if libedit is used, load editrc. |
|
1348 | 1347 | inputrc_name = os.environ.get('INPUTRC') |
|
1349 | 1348 | if inputrc_name is None: |
|
1350 | 1349 | home_dir = get_home_dir() |
|
1351 | 1350 | if home_dir is not None: |
|
1352 | 1351 | inputrc_name = '.inputrc' |
|
1353 | 1352 | if readline.uses_libedit: |
|
1354 | 1353 | inputrc_name = '.editrc' |
|
1355 | 1354 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1356 | 1355 | if os.path.isfile(inputrc_name): |
|
1357 | 1356 | try: |
|
1358 | 1357 | readline.read_init_file(inputrc_name) |
|
1359 | 1358 | except: |
|
1360 | 1359 | warn('Problems reading readline initialization file <%s>' |
|
1361 | 1360 | % inputrc_name) |
|
1362 | 1361 | |
|
1363 | 1362 | self.has_readline = 1 |
|
1364 | 1363 | self.readline = readline |
|
1365 | 1364 | # save this in sys so embedded copies can restore it properly |
|
1366 | 1365 | sys.ipcompleter = self.Completer.complete |
|
1367 | 1366 | self.set_completer() |
|
1368 | 1367 | |
|
1369 | 1368 | # Configure readline according to user's prefs |
|
1370 | 1369 | # This is only done if GNU readline is being used. If libedit |
|
1371 | 1370 | # is being used (as on Leopard) the readline config is |
|
1372 | 1371 | # not run as the syntax for libedit is different. |
|
1373 | 1372 | if not readline.uses_libedit: |
|
1374 | 1373 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1375 | 1374 | readline.parse_and_bind(rlcommand) |
|
1376 | 1375 | |
|
1377 | 1376 | # remove some chars from the delimiters list |
|
1378 | 1377 | delims = readline.get_completer_delims() |
|
1379 | 1378 | delims = delims.translate(string._idmap, |
|
1380 | 1379 | self.rc.readline_remove_delims) |
|
1381 | 1380 | readline.set_completer_delims(delims) |
|
1382 | 1381 | # otherwise we end up with a monster history after a while: |
|
1383 | 1382 | readline.set_history_length(1000) |
|
1384 | 1383 | try: |
|
1385 | 1384 | #print '*** Reading readline history' # dbg |
|
1386 | 1385 | readline.read_history_file(self.histfile) |
|
1387 | 1386 | except IOError: |
|
1388 | 1387 | pass # It doesn't exist yet. |
|
1389 | 1388 | |
|
1390 | 1389 | atexit.register(self.atexit_operations) |
|
1391 | 1390 | del atexit |
|
1392 | 1391 | |
|
1393 | 1392 | # Configure auto-indent for all platforms |
|
1394 | 1393 | self.set_autoindent(self.rc.autoindent) |
|
1395 | 1394 | |
|
1396 | 1395 | def ask_yes_no(self,prompt,default=True): |
|
1397 | 1396 | if self.rc.quiet: |
|
1398 | 1397 | return True |
|
1399 | 1398 | return ask_yes_no(prompt,default) |
|
1400 | 1399 | |
|
1401 | 1400 | def _should_recompile(self,e): |
|
1402 | 1401 | """Utility routine for edit_syntax_error""" |
|
1403 | 1402 | |
|
1404 | 1403 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1405 | 1404 | '<console>','<BackgroundJob compilation>', |
|
1406 | 1405 | None): |
|
1407 | 1406 | |
|
1408 | 1407 | return False |
|
1409 | 1408 | try: |
|
1410 | 1409 | if (self.rc.autoedit_syntax and |
|
1411 | 1410 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1412 | 1411 | '[Y/n] ','y')): |
|
1413 | 1412 | return False |
|
1414 | 1413 | except EOFError: |
|
1415 | 1414 | return False |
|
1416 | 1415 | |
|
1417 | 1416 | def int0(x): |
|
1418 | 1417 | try: |
|
1419 | 1418 | return int(x) |
|
1420 | 1419 | except TypeError: |
|
1421 | 1420 | return 0 |
|
1422 | 1421 | # always pass integer line and offset values to editor hook |
|
1423 | 1422 | self.hooks.fix_error_editor(e.filename, |
|
1424 | 1423 | int0(e.lineno),int0(e.offset),e.msg) |
|
1425 | 1424 | return True |
|
1426 | 1425 | |
|
1427 | 1426 | def edit_syntax_error(self): |
|
1428 | 1427 | """The bottom half of the syntax error handler called in the main loop. |
|
1429 | 1428 | |
|
1430 | 1429 | Loop until syntax error is fixed or user cancels. |
|
1431 | 1430 | """ |
|
1432 | 1431 | |
|
1433 | 1432 | while self.SyntaxTB.last_syntax_error: |
|
1434 | 1433 | # copy and clear last_syntax_error |
|
1435 | 1434 | err = self.SyntaxTB.clear_err_state() |
|
1436 | 1435 | if not self._should_recompile(err): |
|
1437 | 1436 | return |
|
1438 | 1437 | try: |
|
1439 | 1438 | # may set last_syntax_error again if a SyntaxError is raised |
|
1440 | 1439 | self.safe_execfile(err.filename,self.user_ns) |
|
1441 | 1440 | except: |
|
1442 | 1441 | self.showtraceback() |
|
1443 | 1442 | else: |
|
1444 | 1443 | try: |
|
1445 | 1444 | f = file(err.filename) |
|
1446 | 1445 | try: |
|
1447 | 1446 | sys.displayhook(f.read()) |
|
1448 | 1447 | finally: |
|
1449 | 1448 | f.close() |
|
1450 | 1449 | except: |
|
1451 | 1450 | self.showtraceback() |
|
1452 | 1451 | |
|
1453 | 1452 | def showsyntaxerror(self, filename=None): |
|
1454 | 1453 | """Display the syntax error that just occurred. |
|
1455 | 1454 | |
|
1456 | 1455 | This doesn't display a stack trace because there isn't one. |
|
1457 | 1456 | |
|
1458 | 1457 | If a filename is given, it is stuffed in the exception instead |
|
1459 | 1458 | of what was there before (because Python's parser always uses |
|
1460 | 1459 | "<string>" when reading from a string). |
|
1461 | 1460 | """ |
|
1462 | 1461 | etype, value, last_traceback = sys.exc_info() |
|
1463 | 1462 | |
|
1464 | 1463 | # See note about these variables in showtraceback() below |
|
1465 | 1464 | sys.last_type = etype |
|
1466 | 1465 | sys.last_value = value |
|
1467 | 1466 | sys.last_traceback = last_traceback |
|
1468 | 1467 | |
|
1469 | 1468 | if filename and etype is SyntaxError: |
|
1470 | 1469 | # Work hard to stuff the correct filename in the exception |
|
1471 | 1470 | try: |
|
1472 | 1471 | msg, (dummy_filename, lineno, offset, line) = value |
|
1473 | 1472 | except: |
|
1474 | 1473 | # Not the format we expect; leave it alone |
|
1475 | 1474 | pass |
|
1476 | 1475 | else: |
|
1477 | 1476 | # Stuff in the right filename |
|
1478 | 1477 | try: |
|
1479 | 1478 | # Assume SyntaxError is a class exception |
|
1480 | 1479 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1481 | 1480 | except: |
|
1482 | 1481 | # If that failed, assume SyntaxError is a string |
|
1483 | 1482 | value = msg, (filename, lineno, offset, line) |
|
1484 | 1483 | self.SyntaxTB(etype,value,[]) |
|
1485 | 1484 | |
|
1486 | 1485 | def debugger(self,force=False): |
|
1487 | 1486 | """Call the pydb/pdb debugger. |
|
1488 | 1487 | |
|
1489 | 1488 | Keywords: |
|
1490 | 1489 | |
|
1491 | 1490 | - force(False): by default, this routine checks the instance call_pdb |
|
1492 | 1491 | flag and does not actually invoke the debugger if the flag is false. |
|
1493 | 1492 | The 'force' option forces the debugger to activate even if the flag |
|
1494 | 1493 | is false. |
|
1495 | 1494 | """ |
|
1496 | 1495 | |
|
1497 | 1496 | if not (force or self.call_pdb): |
|
1498 | 1497 | return |
|
1499 | 1498 | |
|
1500 | 1499 | if not hasattr(sys,'last_traceback'): |
|
1501 | 1500 | error('No traceback has been produced, nothing to debug.') |
|
1502 | 1501 | return |
|
1503 | 1502 | |
|
1504 | 1503 | # use pydb if available |
|
1505 | 1504 | if Debugger.has_pydb: |
|
1506 | 1505 | from pydb import pm |
|
1507 | 1506 | else: |
|
1508 | 1507 | # fallback to our internal debugger |
|
1509 | 1508 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1510 | 1509 | self.history_saving_wrapper(pm)() |
|
1511 | 1510 | |
|
1512 | 1511 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1513 | 1512 | """Display the exception that just occurred. |
|
1514 | 1513 | |
|
1515 | 1514 | If nothing is known about the exception, this is the method which |
|
1516 | 1515 | should be used throughout the code for presenting user tracebacks, |
|
1517 | 1516 | rather than directly invoking the InteractiveTB object. |
|
1518 | 1517 | |
|
1519 | 1518 | A specific showsyntaxerror() also exists, but this method can take |
|
1520 | 1519 | care of calling it if needed, so unless you are explicitly catching a |
|
1521 | 1520 | SyntaxError exception, don't try to analyze the stack manually and |
|
1522 | 1521 | simply call this method.""" |
|
1523 | 1522 | |
|
1524 | 1523 | |
|
1525 | 1524 | # Though this won't be called by syntax errors in the input line, |
|
1526 | 1525 | # there may be SyntaxError cases whith imported code. |
|
1527 | 1526 | |
|
1528 | 1527 | try: |
|
1529 | 1528 | if exc_tuple is None: |
|
1530 | 1529 | etype, value, tb = sys.exc_info() |
|
1531 | 1530 | else: |
|
1532 | 1531 | etype, value, tb = exc_tuple |
|
1533 | 1532 | |
|
1534 | 1533 | if etype is SyntaxError: |
|
1535 | 1534 | self.showsyntaxerror(filename) |
|
1536 | 1535 | elif etype is IPython.ipapi.UsageError: |
|
1537 | 1536 | print "UsageError:", value |
|
1538 | 1537 | else: |
|
1539 | 1538 | # WARNING: these variables are somewhat deprecated and not |
|
1540 | 1539 | # necessarily safe to use in a threaded environment, but tools |
|
1541 | 1540 | # like pdb depend on their existence, so let's set them. If we |
|
1542 | 1541 | # find problems in the field, we'll need to revisit their use. |
|
1543 | 1542 | sys.last_type = etype |
|
1544 | 1543 | sys.last_value = value |
|
1545 | 1544 | sys.last_traceback = tb |
|
1546 | 1545 | |
|
1547 | 1546 | if etype in self.custom_exceptions: |
|
1548 | 1547 | self.CustomTB(etype,value,tb) |
|
1549 | 1548 | else: |
|
1550 | 1549 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1551 | 1550 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1552 | 1551 | # pdb mucks up readline, fix it back |
|
1553 | 1552 | self.set_completer() |
|
1554 | 1553 | except KeyboardInterrupt: |
|
1555 | 1554 | self.write("\nKeyboardInterrupt\n") |
|
1556 | 1555 | |
|
1557 | 1556 | |
|
1558 | 1557 | |
|
1559 | 1558 | def mainloop(self,banner=None): |
|
1560 | 1559 | """Creates the local namespace and starts the mainloop. |
|
1561 | 1560 | |
|
1562 | 1561 | If an optional banner argument is given, it will override the |
|
1563 | 1562 | internally created default banner.""" |
|
1564 | 1563 | |
|
1565 | 1564 | if self.rc.c: # Emulate Python's -c option |
|
1566 | 1565 | self.exec_init_cmd() |
|
1567 | 1566 | if banner is None: |
|
1568 | 1567 | if not self.rc.banner: |
|
1569 | 1568 | banner = '' |
|
1570 | 1569 | # banner is string? Use it directly! |
|
1571 | 1570 | elif isinstance(self.rc.banner,basestring): |
|
1572 | 1571 | banner = self.rc.banner |
|
1573 | 1572 | else: |
|
1574 | 1573 | banner = self.BANNER+self.banner2 |
|
1575 | 1574 | |
|
1576 | 1575 | while 1: |
|
1577 | 1576 | try: |
|
1578 | 1577 | self.interact(banner) |
|
1579 | 1578 | #self.interact_with_readline() |
|
1580 | 1579 | # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above |
|
1581 | 1580 | |
|
1582 | 1581 | break |
|
1583 | 1582 | except KeyboardInterrupt: |
|
1584 | 1583 | # this should not be necessary, but KeyboardInterrupt |
|
1585 | 1584 | # handling seems rather unpredictable... |
|
1586 | 1585 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1587 | 1586 | |
|
1588 | 1587 | def exec_init_cmd(self): |
|
1589 | 1588 | """Execute a command given at the command line. |
|
1590 | 1589 | |
|
1591 | 1590 | This emulates Python's -c option.""" |
|
1592 | 1591 | |
|
1593 | 1592 | #sys.argv = ['-c'] |
|
1594 | 1593 | self.push(self.prefilter(self.rc.c, False)) |
|
1595 | 1594 | if not self.rc.interact: |
|
1596 | 1595 | self.ask_exit() |
|
1597 | 1596 | |
|
1598 | 1597 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1599 | 1598 | """Embeds IPython into a running python program. |
|
1600 | 1599 | |
|
1601 | 1600 | Input: |
|
1602 | 1601 | |
|
1603 | 1602 | - header: An optional header message can be specified. |
|
1604 | 1603 | |
|
1605 | 1604 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1606 | 1605 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1607 | 1606 | program variables become visible but user-specific configuration |
|
1608 | 1607 | remains possible. |
|
1609 | 1608 | |
|
1610 | 1609 | - stack_depth: specifies how many levels in the stack to go to |
|
1611 | 1610 | looking for namespaces (when local_ns and global_ns are None). This |
|
1612 | 1611 | allows an intermediate caller to make sure that this function gets |
|
1613 | 1612 | the namespace from the intended level in the stack. By default (0) |
|
1614 | 1613 | it will get its locals and globals from the immediate caller. |
|
1615 | 1614 | |
|
1616 | 1615 | Warning: it's possible to use this in a program which is being run by |
|
1617 | 1616 | IPython itself (via %run), but some funny things will happen (a few |
|
1618 | 1617 | globals get overwritten). In the future this will be cleaned up, as |
|
1619 | 1618 | there is no fundamental reason why it can't work perfectly.""" |
|
1620 | 1619 | |
|
1621 | 1620 | # Get locals and globals from caller |
|
1622 | 1621 | if local_ns is None or global_ns is None: |
|
1623 | 1622 | call_frame = sys._getframe(stack_depth).f_back |
|
1624 | 1623 | |
|
1625 | 1624 | if local_ns is None: |
|
1626 | 1625 | local_ns = call_frame.f_locals |
|
1627 | 1626 | if global_ns is None: |
|
1628 | 1627 | global_ns = call_frame.f_globals |
|
1629 | 1628 | |
|
1630 | 1629 | # Update namespaces and fire up interpreter |
|
1631 | 1630 | |
|
1632 | 1631 | # The global one is easy, we can just throw it in |
|
1633 | 1632 | self.user_global_ns = global_ns |
|
1634 | 1633 | |
|
1635 | 1634 | # but the user/local one is tricky: ipython needs it to store internal |
|
1636 | 1635 | # data, but we also need the locals. We'll copy locals in the user |
|
1637 | 1636 | # one, but will track what got copied so we can delete them at exit. |
|
1638 | 1637 | # This is so that a later embedded call doesn't see locals from a |
|
1639 | 1638 | # previous call (which most likely existed in a separate scope). |
|
1640 | 1639 | local_varnames = local_ns.keys() |
|
1641 | 1640 | self.user_ns.update(local_ns) |
|
1642 | 1641 | #self.user_ns['local_ns'] = local_ns # dbg |
|
1643 | 1642 | |
|
1644 | 1643 | # Patch for global embedding to make sure that things don't overwrite |
|
1645 | 1644 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1646 | 1645 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1647 | 1646 | if local_ns is None and global_ns is None: |
|
1648 | 1647 | self.user_global_ns.update(__main__.__dict__) |
|
1649 | 1648 | |
|
1650 | 1649 | # make sure the tab-completer has the correct frame information, so it |
|
1651 | 1650 | # actually completes using the frame's locals/globals |
|
1652 | 1651 | self.set_completer_frame() |
|
1653 | 1652 | |
|
1654 | 1653 | # before activating the interactive mode, we need to make sure that |
|
1655 | 1654 | # all names in the builtin namespace needed by ipython point to |
|
1656 | 1655 | # ourselves, and not to other instances. |
|
1657 | 1656 | self.add_builtins() |
|
1658 | 1657 | |
|
1659 | 1658 | self.interact(header) |
|
1660 | 1659 | |
|
1661 | 1660 | # now, purge out the user namespace from anything we might have added |
|
1662 | 1661 | # from the caller's local namespace |
|
1663 | 1662 | delvar = self.user_ns.pop |
|
1664 | 1663 | for var in local_varnames: |
|
1665 | 1664 | delvar(var,None) |
|
1666 | 1665 | # and clean builtins we may have overridden |
|
1667 | 1666 | self.clean_builtins() |
|
1668 | 1667 | |
|
1669 | 1668 | def interact_prompt(self): |
|
1670 | 1669 | """ Print the prompt (in read-eval-print loop) |
|
1671 | 1670 | |
|
1672 | 1671 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1673 | 1672 | used in standard IPython flow. |
|
1674 | 1673 | """ |
|
1675 | 1674 | if self.more: |
|
1676 | 1675 | try: |
|
1677 | 1676 | prompt = self.hooks.generate_prompt(True) |
|
1678 | 1677 | except: |
|
1679 | 1678 | self.showtraceback() |
|
1680 | 1679 | if self.autoindent: |
|
1681 | 1680 | self.rl_do_indent = True |
|
1682 | 1681 | |
|
1683 | 1682 | else: |
|
1684 | 1683 | try: |
|
1685 | 1684 | prompt = self.hooks.generate_prompt(False) |
|
1686 | 1685 | except: |
|
1687 | 1686 | self.showtraceback() |
|
1688 | 1687 | self.write(prompt) |
|
1689 | 1688 | |
|
1690 | 1689 | def interact_handle_input(self,line): |
|
1691 | 1690 | """ Handle the input line (in read-eval-print loop) |
|
1692 | 1691 | |
|
1693 | 1692 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1694 | 1693 | used in standard IPython flow. |
|
1695 | 1694 | """ |
|
1696 | 1695 | if line.lstrip() == line: |
|
1697 | 1696 | self.shadowhist.add(line.strip()) |
|
1698 | 1697 | lineout = self.prefilter(line,self.more) |
|
1699 | 1698 | |
|
1700 | 1699 | if line.strip(): |
|
1701 | 1700 | if self.more: |
|
1702 | 1701 | self.input_hist_raw[-1] += '%s\n' % line |
|
1703 | 1702 | else: |
|
1704 | 1703 | self.input_hist_raw.append('%s\n' % line) |
|
1705 | 1704 | |
|
1706 | 1705 | |
|
1707 | 1706 | self.more = self.push(lineout) |
|
1708 | 1707 | if (self.SyntaxTB.last_syntax_error and |
|
1709 | 1708 | self.rc.autoedit_syntax): |
|
1710 | 1709 | self.edit_syntax_error() |
|
1711 | 1710 | |
|
1712 | 1711 | def interact_with_readline(self): |
|
1713 | 1712 | """ Demo of using interact_handle_input, interact_prompt |
|
1714 | 1713 | |
|
1715 | 1714 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1716 | 1715 | it should work like this. |
|
1717 | 1716 | """ |
|
1718 | 1717 | self.readline_startup_hook(self.pre_readline) |
|
1719 | 1718 | while not self.exit_now: |
|
1720 | 1719 | self.interact_prompt() |
|
1721 | 1720 | if self.more: |
|
1722 | 1721 | self.rl_do_indent = True |
|
1723 | 1722 | else: |
|
1724 | 1723 | self.rl_do_indent = False |
|
1725 | 1724 | line = raw_input_original().decode(self.stdin_encoding) |
|
1726 | 1725 | self.interact_handle_input(line) |
|
1727 | 1726 | |
|
1728 | 1727 | |
|
1729 | 1728 | def interact(self, banner=None): |
|
1730 | 1729 | """Closely emulate the interactive Python console. |
|
1731 | 1730 | |
|
1732 | 1731 | The optional banner argument specify the banner to print |
|
1733 | 1732 | before the first interaction; by default it prints a banner |
|
1734 | 1733 | similar to the one printed by the real Python interpreter, |
|
1735 | 1734 | followed by the current class name in parentheses (so as not |
|
1736 | 1735 | to confuse this with the real interpreter -- since it's so |
|
1737 | 1736 | close!). |
|
1738 | 1737 | |
|
1739 | 1738 | """ |
|
1740 | 1739 | |
|
1741 | 1740 | if self.exit_now: |
|
1742 | 1741 | # batch run -> do not interact |
|
1743 | 1742 | return |
|
1744 | 1743 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1745 | 1744 | if banner is None: |
|
1746 | 1745 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1747 | 1746 | (sys.version, sys.platform, cprt, |
|
1748 | 1747 | self.__class__.__name__)) |
|
1749 | 1748 | else: |
|
1750 | 1749 | self.write(banner) |
|
1751 | 1750 | |
|
1752 | 1751 | more = 0 |
|
1753 | 1752 | |
|
1754 | 1753 | # Mark activity in the builtins |
|
1755 | 1754 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1756 | 1755 | |
|
1757 | 1756 | if self.has_readline: |
|
1758 | 1757 | self.readline_startup_hook(self.pre_readline) |
|
1759 | 1758 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1760 | 1759 | # ask_exit callback. |
|
1761 | 1760 | |
|
1762 | 1761 | while not self.exit_now: |
|
1763 | 1762 | self.hooks.pre_prompt_hook() |
|
1764 | 1763 | if more: |
|
1765 | 1764 | try: |
|
1766 | 1765 | prompt = self.hooks.generate_prompt(True) |
|
1767 | 1766 | except: |
|
1768 | 1767 | self.showtraceback() |
|
1769 | 1768 | if self.autoindent: |
|
1770 | 1769 | self.rl_do_indent = True |
|
1771 | 1770 | |
|
1772 | 1771 | else: |
|
1773 | 1772 | try: |
|
1774 | 1773 | prompt = self.hooks.generate_prompt(False) |
|
1775 | 1774 | except: |
|
1776 | 1775 | self.showtraceback() |
|
1777 | 1776 | try: |
|
1778 | 1777 | line = self.raw_input(prompt,more) |
|
1779 | 1778 | if self.exit_now: |
|
1780 | 1779 | # quick exit on sys.std[in|out] close |
|
1781 | 1780 | break |
|
1782 | 1781 | if self.autoindent: |
|
1783 | 1782 | self.rl_do_indent = False |
|
1784 | 1783 | |
|
1785 | 1784 | except KeyboardInterrupt: |
|
1786 | 1785 | #double-guard against keyboardinterrupts during kbdint handling |
|
1787 | 1786 | try: |
|
1788 | 1787 | self.write('\nKeyboardInterrupt\n') |
|
1789 | 1788 | self.resetbuffer() |
|
1790 | 1789 | # keep cache in sync with the prompt counter: |
|
1791 | 1790 | self.outputcache.prompt_count -= 1 |
|
1792 | 1791 | |
|
1793 | 1792 | if self.autoindent: |
|
1794 | 1793 | self.indent_current_nsp = 0 |
|
1795 | 1794 | more = 0 |
|
1796 | 1795 | except KeyboardInterrupt: |
|
1797 | 1796 | pass |
|
1798 | 1797 | except EOFError: |
|
1799 | 1798 | if self.autoindent: |
|
1800 | 1799 | self.rl_do_indent = False |
|
1801 | 1800 | self.readline_startup_hook(None) |
|
1802 | 1801 | self.write('\n') |
|
1803 | 1802 | self.exit() |
|
1804 | 1803 | except bdb.BdbQuit: |
|
1805 | 1804 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1806 | 1805 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1807 | 1806 | 'for IPython to properly format this particular exception.\n' |
|
1808 | 1807 | 'IPython will resume normal operation.') |
|
1809 | 1808 | except: |
|
1810 | 1809 | # exceptions here are VERY RARE, but they can be triggered |
|
1811 | 1810 | # asynchronously by signal handlers, for example. |
|
1812 | 1811 | self.showtraceback() |
|
1813 | 1812 | else: |
|
1814 | 1813 | more = self.push(line) |
|
1815 | 1814 | if (self.SyntaxTB.last_syntax_error and |
|
1816 | 1815 | self.rc.autoedit_syntax): |
|
1817 | 1816 | self.edit_syntax_error() |
|
1818 | 1817 | |
|
1819 | 1818 | # We are off again... |
|
1820 | 1819 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1821 | 1820 | |
|
1822 | 1821 | def excepthook(self, etype, value, tb): |
|
1823 | 1822 | """One more defense for GUI apps that call sys.excepthook. |
|
1824 | 1823 | |
|
1825 | 1824 | GUI frameworks like wxPython trap exceptions and call |
|
1826 | 1825 | sys.excepthook themselves. I guess this is a feature that |
|
1827 | 1826 | enables them to keep running after exceptions that would |
|
1828 | 1827 | otherwise kill their mainloop. This is a bother for IPython |
|
1829 | 1828 | which excepts to catch all of the program exceptions with a try: |
|
1830 | 1829 | except: statement. |
|
1831 | 1830 | |
|
1832 | 1831 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1833 | 1832 | any app directly invokes sys.excepthook, it will look to the user like |
|
1834 | 1833 | IPython crashed. In order to work around this, we can disable the |
|
1835 | 1834 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1836 | 1835 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1837 | 1836 | call sys.excepthook will generate a regular-looking exception from |
|
1838 | 1837 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1839 | 1838 | crashes. |
|
1840 | 1839 | |
|
1841 | 1840 | This hook should be used sparingly, only in places which are not likely |
|
1842 | 1841 | to be true IPython errors. |
|
1843 | 1842 | """ |
|
1844 | 1843 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1845 | 1844 | |
|
1846 | 1845 | def expand_aliases(self,fn,rest): |
|
1847 | 1846 | """ Expand multiple levels of aliases: |
|
1848 | 1847 | |
|
1849 | 1848 | if: |
|
1850 | 1849 | |
|
1851 | 1850 | alias foo bar /tmp |
|
1852 | 1851 | alias baz foo |
|
1853 | 1852 | |
|
1854 | 1853 | then: |
|
1855 | 1854 | |
|
1856 | 1855 | baz huhhahhei -> bar /tmp huhhahhei |
|
1857 | 1856 | |
|
1858 | 1857 | """ |
|
1859 | 1858 | line = fn + " " + rest |
|
1860 | 1859 | |
|
1861 | 1860 | done = Set() |
|
1862 | 1861 | while 1: |
|
1863 | 1862 | pre,fn,rest = prefilter.splitUserInput(line, |
|
1864 | 1863 | prefilter.shell_line_split) |
|
1865 | 1864 | if fn in self.alias_table: |
|
1866 | 1865 | if fn in done: |
|
1867 | 1866 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
1868 | 1867 | return "" |
|
1869 | 1868 | done.add(fn) |
|
1870 | 1869 | |
|
1871 | 1870 | l2 = self.transform_alias(fn,rest) |
|
1872 | 1871 | # dir -> dir |
|
1873 | 1872 | # print "alias",line, "->",l2 #dbg |
|
1874 | 1873 | if l2 == line: |
|
1875 | 1874 | break |
|
1876 | 1875 | # ls -> ls -F should not recurse forever |
|
1877 | 1876 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
1878 | 1877 | line = l2 |
|
1879 | 1878 | break |
|
1880 | 1879 | |
|
1881 | 1880 | line=l2 |
|
1882 | 1881 | |
|
1883 | 1882 | |
|
1884 | 1883 | # print "al expand to",line #dbg |
|
1885 | 1884 | else: |
|
1886 | 1885 | break |
|
1887 | 1886 | |
|
1888 | 1887 | return line |
|
1889 | 1888 | |
|
1890 | 1889 | def transform_alias(self, alias,rest=''): |
|
1891 | 1890 | """ Transform alias to system command string. |
|
1892 | 1891 | """ |
|
1893 | 1892 | trg = self.alias_table[alias] |
|
1894 | 1893 | |
|
1895 | 1894 | nargs,cmd = trg |
|
1896 | 1895 | # print trg #dbg |
|
1897 | 1896 | if ' ' in cmd and os.path.isfile(cmd): |
|
1898 | 1897 | cmd = '"%s"' % cmd |
|
1899 | 1898 | |
|
1900 | 1899 | # Expand the %l special to be the user's input line |
|
1901 | 1900 | if cmd.find('%l') >= 0: |
|
1902 | 1901 | cmd = cmd.replace('%l',rest) |
|
1903 | 1902 | rest = '' |
|
1904 | 1903 | if nargs==0: |
|
1905 | 1904 | # Simple, argument-less aliases |
|
1906 | 1905 | cmd = '%s %s' % (cmd,rest) |
|
1907 | 1906 | else: |
|
1908 | 1907 | # Handle aliases with positional arguments |
|
1909 | 1908 | args = rest.split(None,nargs) |
|
1910 | 1909 | if len(args)< nargs: |
|
1911 | 1910 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1912 | 1911 | (alias,nargs,len(args))) |
|
1913 | 1912 | return None |
|
1914 | 1913 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1915 | 1914 | # Now call the macro, evaluating in the user's namespace |
|
1916 | 1915 | #print 'new command: <%r>' % cmd # dbg |
|
1917 | 1916 | return cmd |
|
1918 | 1917 | |
|
1919 | 1918 | def call_alias(self,alias,rest=''): |
|
1920 | 1919 | """Call an alias given its name and the rest of the line. |
|
1921 | 1920 | |
|
1922 | 1921 | This is only used to provide backwards compatibility for users of |
|
1923 | 1922 | ipalias(), use of which is not recommended for anymore.""" |
|
1924 | 1923 | |
|
1925 | 1924 | # Now call the macro, evaluating in the user's namespace |
|
1926 | 1925 | cmd = self.transform_alias(alias, rest) |
|
1927 | 1926 | try: |
|
1928 | 1927 | self.system(cmd) |
|
1929 | 1928 | except: |
|
1930 | 1929 | self.showtraceback() |
|
1931 | 1930 | |
|
1932 | 1931 | def indent_current_str(self): |
|
1933 | 1932 | """return the current level of indentation as a string""" |
|
1934 | 1933 | return self.indent_current_nsp * ' ' |
|
1935 | 1934 | |
|
1936 | 1935 | def autoindent_update(self,line): |
|
1937 | 1936 | """Keep track of the indent level.""" |
|
1938 | 1937 | |
|
1939 | 1938 | #debugx('line') |
|
1940 | 1939 | #debugx('self.indent_current_nsp') |
|
1941 | 1940 | if self.autoindent: |
|
1942 | 1941 | if line: |
|
1943 | 1942 | inisp = num_ini_spaces(line) |
|
1944 | 1943 | if inisp < self.indent_current_nsp: |
|
1945 | 1944 | self.indent_current_nsp = inisp |
|
1946 | 1945 | |
|
1947 | 1946 | if line[-1] == ':': |
|
1948 | 1947 | self.indent_current_nsp += 4 |
|
1949 | 1948 | elif dedent_re.match(line): |
|
1950 | 1949 | self.indent_current_nsp -= 4 |
|
1951 | 1950 | else: |
|
1952 | 1951 | self.indent_current_nsp = 0 |
|
1953 | 1952 | |
|
1954 | 1953 | def runlines(self,lines): |
|
1955 | 1954 | """Run a string of one or more lines of source. |
|
1956 | 1955 | |
|
1957 | 1956 | This method is capable of running a string containing multiple source |
|
1958 | 1957 | lines, as if they had been entered at the IPython prompt. Since it |
|
1959 | 1958 | exposes IPython's processing machinery, the given strings can contain |
|
1960 | 1959 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1961 | 1960 | |
|
1962 | 1961 | # We must start with a clean buffer, in case this is run from an |
|
1963 | 1962 | # interactive IPython session (via a magic, for example). |
|
1964 | 1963 | self.resetbuffer() |
|
1965 | 1964 | lines = lines.split('\n') |
|
1966 | 1965 | more = 0 |
|
1967 | 1966 | |
|
1968 | 1967 | for line in lines: |
|
1969 | 1968 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1970 | 1969 | # NOT skip even a blank line if we are in a code block (more is |
|
1971 | 1970 | # true) |
|
1972 | 1971 | |
|
1973 | 1972 | |
|
1974 | 1973 | if line or more: |
|
1975 | 1974 | # push to raw history, so hist line numbers stay in sync |
|
1976 | 1975 | self.input_hist_raw.append("# " + line + "\n") |
|
1977 | 1976 | more = self.push(self.prefilter(line,more)) |
|
1978 | 1977 | # IPython's runsource returns None if there was an error |
|
1979 | 1978 | # compiling the code. This allows us to stop processing right |
|
1980 | 1979 | # away, so the user gets the error message at the right place. |
|
1981 | 1980 | if more is None: |
|
1982 | 1981 | break |
|
1983 | 1982 | else: |
|
1984 | 1983 | self.input_hist_raw.append("\n") |
|
1985 | 1984 | # final newline in case the input didn't have it, so that the code |
|
1986 | 1985 | # actually does get executed |
|
1987 | 1986 | if more: |
|
1988 | 1987 | self.push('\n') |
|
1989 | 1988 | |
|
1990 | 1989 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1991 | 1990 | """Compile and run some source in the interpreter. |
|
1992 | 1991 | |
|
1993 | 1992 | Arguments are as for compile_command(). |
|
1994 | 1993 | |
|
1995 | 1994 | One several things can happen: |
|
1996 | 1995 | |
|
1997 | 1996 | 1) The input is incorrect; compile_command() raised an |
|
1998 | 1997 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1999 | 1998 | will be printed by calling the showsyntaxerror() method. |
|
2000 | 1999 | |
|
2001 | 2000 | 2) The input is incomplete, and more input is required; |
|
2002 | 2001 | compile_command() returned None. Nothing happens. |
|
2003 | 2002 | |
|
2004 | 2003 | 3) The input is complete; compile_command() returned a code |
|
2005 | 2004 | object. The code is executed by calling self.runcode() (which |
|
2006 | 2005 | also handles run-time exceptions, except for SystemExit). |
|
2007 | 2006 | |
|
2008 | 2007 | The return value is: |
|
2009 | 2008 | |
|
2010 | 2009 | - True in case 2 |
|
2011 | 2010 | |
|
2012 | 2011 | - False in the other cases, unless an exception is raised, where |
|
2013 | 2012 | None is returned instead. This can be used by external callers to |
|
2014 | 2013 | know whether to continue feeding input or not. |
|
2015 | 2014 | |
|
2016 | 2015 | The return value can be used to decide whether to use sys.ps1 or |
|
2017 | 2016 | sys.ps2 to prompt the next line.""" |
|
2018 | 2017 | |
|
2019 | 2018 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2020 | 2019 | # this allows execution of indented pasted code. It is tempting |
|
2021 | 2020 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2022 | 2021 | # directly, but this fails for more complicated scenarios |
|
2023 | 2022 | source=source.encode(self.stdin_encoding) |
|
2024 | 2023 | if source[:1] in [' ', '\t']: |
|
2025 | 2024 | source = 'if 1:\n%s' % source |
|
2026 | 2025 | |
|
2027 | 2026 | try: |
|
2028 | 2027 | code = self.compile(source,filename,symbol) |
|
2029 | 2028 | except (OverflowError, SyntaxError, ValueError, TypeError): |
|
2030 | 2029 | # Case 1 |
|
2031 | 2030 | self.showsyntaxerror(filename) |
|
2032 | 2031 | return None |
|
2033 | 2032 | |
|
2034 | 2033 | if code is None: |
|
2035 | 2034 | # Case 2 |
|
2036 | 2035 | return True |
|
2037 | 2036 | |
|
2038 | 2037 | # Case 3 |
|
2039 | 2038 | # We store the code object so that threaded shells and |
|
2040 | 2039 | # custom exception handlers can access all this info if needed. |
|
2041 | 2040 | # The source corresponding to this can be obtained from the |
|
2042 | 2041 | # buffer attribute as '\n'.join(self.buffer). |
|
2043 | 2042 | self.code_to_run = code |
|
2044 | 2043 | # now actually execute the code object |
|
2045 | 2044 | if self.runcode(code) == 0: |
|
2046 | 2045 | return False |
|
2047 | 2046 | else: |
|
2048 | 2047 | return None |
|
2049 | 2048 | |
|
2050 | 2049 | def runcode(self,code_obj): |
|
2051 | 2050 | """Execute a code object. |
|
2052 | 2051 | |
|
2053 | 2052 | When an exception occurs, self.showtraceback() is called to display a |
|
2054 | 2053 | traceback. |
|
2055 | 2054 | |
|
2056 | 2055 | Return value: a flag indicating whether the code to be run completed |
|
2057 | 2056 | successfully: |
|
2058 | 2057 | |
|
2059 | 2058 | - 0: successful execution. |
|
2060 | 2059 | - 1: an error occurred. |
|
2061 | 2060 | """ |
|
2062 | 2061 | |
|
2063 | 2062 | # Set our own excepthook in case the user code tries to call it |
|
2064 | 2063 | # directly, so that the IPython crash handler doesn't get triggered |
|
2065 | 2064 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2066 | 2065 | |
|
2067 | 2066 | # we save the original sys.excepthook in the instance, in case config |
|
2068 | 2067 | # code (such as magics) needs access to it. |
|
2069 | 2068 | self.sys_excepthook = old_excepthook |
|
2070 | 2069 | outflag = 1 # happens in more places, so it's easier as default |
|
2071 | 2070 | try: |
|
2072 | 2071 | try: |
|
2073 | 2072 | self.hooks.pre_runcode_hook() |
|
2074 | # Embedded instances require separate global/local namespaces | |
|
2075 | # so they can see both the surrounding (local) namespace and | |
|
2076 | # the module-level globals when called inside another function. | |
|
2077 | if self.embedded: | |
|
2078 | exec code_obj in self.user_global_ns, self.user_ns | |
|
2079 | # Normal (non-embedded) instances should only have a single | |
|
2080 | # namespace for user code execution, otherwise functions won't | |
|
2081 | # see interactive top-level globals. | |
|
2082 | else: | |
|
2083 | exec code_obj in self.user_ns | |
|
2073 | exec code_obj in self.user_global_ns, self.user_ns | |
|
2084 | 2074 | finally: |
|
2085 | 2075 | # Reset our crash handler in place |
|
2086 | 2076 | sys.excepthook = old_excepthook |
|
2087 | 2077 | except SystemExit: |
|
2088 | 2078 | self.resetbuffer() |
|
2089 | 2079 | self.showtraceback() |
|
2090 | 2080 | warn("Type %exit or %quit to exit IPython " |
|
2091 | 2081 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2092 | 2082 | except self.custom_exceptions: |
|
2093 | 2083 | etype,value,tb = sys.exc_info() |
|
2094 | 2084 | self.CustomTB(etype,value,tb) |
|
2095 | 2085 | except: |
|
2096 | 2086 | self.showtraceback() |
|
2097 | 2087 | else: |
|
2098 | 2088 | outflag = 0 |
|
2099 | 2089 | if softspace(sys.stdout, 0): |
|
2100 | 2090 | |
|
2101 | 2091 | # Flush out code object which has been run (and source) |
|
2102 | 2092 | self.code_to_run = None |
|
2103 | 2093 | return outflag |
|
2104 | 2094 | |
|
2105 | 2095 | def push(self, line): |
|
2106 | 2096 | """Push a line to the interpreter. |
|
2107 | 2097 | |
|
2108 | 2098 | The line should not have a trailing newline; it may have |
|
2109 | 2099 | internal newlines. The line is appended to a buffer and the |
|
2110 | 2100 | interpreter's runsource() method is called with the |
|
2111 | 2101 | concatenated contents of the buffer as source. If this |
|
2112 | 2102 | indicates that the command was executed or invalid, the buffer |
|
2113 | 2103 | is reset; otherwise, the command is incomplete, and the buffer |
|
2114 | 2104 | is left as it was after the line was appended. The return |
|
2115 | 2105 | value is 1 if more input is required, 0 if the line was dealt |
|
2116 | 2106 | with in some way (this is the same as runsource()). |
|
2117 | 2107 | """ |
|
2118 | 2108 | |
|
2119 | 2109 | # autoindent management should be done here, and not in the |
|
2120 | 2110 | # interactive loop, since that one is only seen by keyboard input. We |
|
2121 | 2111 | # need this done correctly even for code run via runlines (which uses |
|
2122 | 2112 | # push). |
|
2123 | 2113 | |
|
2124 | 2114 | #print 'push line: <%s>' % line # dbg |
|
2125 | 2115 | for subline in line.splitlines(): |
|
2126 | 2116 | self.autoindent_update(subline) |
|
2127 | 2117 | self.buffer.append(line) |
|
2128 | 2118 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2129 | 2119 | if not more: |
|
2130 | 2120 | self.resetbuffer() |
|
2131 | 2121 | return more |
|
2132 | 2122 | |
|
2133 | 2123 | def split_user_input(self, line): |
|
2134 | 2124 | # This is really a hold-over to support ipapi and some extensions |
|
2135 | 2125 | return prefilter.splitUserInput(line) |
|
2136 | 2126 | |
|
2137 | 2127 | def resetbuffer(self): |
|
2138 | 2128 | """Reset the input buffer.""" |
|
2139 | 2129 | self.buffer[:] = [] |
|
2140 | 2130 | |
|
2141 | 2131 | def raw_input(self,prompt='',continue_prompt=False): |
|
2142 | 2132 | """Write a prompt and read a line. |
|
2143 | 2133 | |
|
2144 | 2134 | The returned line does not include the trailing newline. |
|
2145 | 2135 | When the user enters the EOF key sequence, EOFError is raised. |
|
2146 | 2136 | |
|
2147 | 2137 | Optional inputs: |
|
2148 | 2138 | |
|
2149 | 2139 | - prompt(''): a string to be printed to prompt the user. |
|
2150 | 2140 | |
|
2151 | 2141 | - continue_prompt(False): whether this line is the first one or a |
|
2152 | 2142 | continuation in a sequence of inputs. |
|
2153 | 2143 | """ |
|
2154 | 2144 | |
|
2155 | 2145 | # Code run by the user may have modified the readline completer state. |
|
2156 | 2146 | # We must ensure that our completer is back in place. |
|
2157 | 2147 | if self.has_readline: |
|
2158 | 2148 | self.set_completer() |
|
2159 | 2149 | |
|
2160 | 2150 | try: |
|
2161 | 2151 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2162 | 2152 | except ValueError: |
|
2163 | 2153 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2164 | 2154 | " or sys.stdout.close()!\nExiting IPython!") |
|
2165 | 2155 | self.ask_exit() |
|
2166 | 2156 | return "" |
|
2167 | 2157 | |
|
2168 | 2158 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2169 | 2159 | # than necessary. We do this by trimming out the auto-indent initial |
|
2170 | 2160 | # spaces, if the user's actual input started itself with whitespace. |
|
2171 | 2161 | #debugx('self.buffer[-1]') |
|
2172 | 2162 | |
|
2173 | 2163 | if self.autoindent: |
|
2174 | 2164 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2175 | 2165 | line = line[self.indent_current_nsp:] |
|
2176 | 2166 | self.indent_current_nsp = 0 |
|
2177 | 2167 | |
|
2178 | 2168 | # store the unfiltered input before the user has any chance to modify |
|
2179 | 2169 | # it. |
|
2180 | 2170 | if line.strip(): |
|
2181 | 2171 | if continue_prompt: |
|
2182 | 2172 | self.input_hist_raw[-1] += '%s\n' % line |
|
2183 | 2173 | if self.has_readline: # and some config option is set? |
|
2184 | 2174 | try: |
|
2185 | 2175 | histlen = self.readline.get_current_history_length() |
|
2186 | 2176 | if histlen > 1: |
|
2187 | 2177 | newhist = self.input_hist_raw[-1].rstrip() |
|
2188 | 2178 | self.readline.remove_history_item(histlen-1) |
|
2189 | 2179 | self.readline.replace_history_item(histlen-2, |
|
2190 | 2180 | newhist.encode(self.stdin_encoding)) |
|
2191 | 2181 | except AttributeError: |
|
2192 | 2182 | pass # re{move,place}_history_item are new in 2.4. |
|
2193 | 2183 | else: |
|
2194 | 2184 | self.input_hist_raw.append('%s\n' % line) |
|
2195 | 2185 | # only entries starting at first column go to shadow history |
|
2196 | 2186 | if line.lstrip() == line: |
|
2197 | 2187 | self.shadowhist.add(line.strip()) |
|
2198 | 2188 | elif not continue_prompt: |
|
2199 | 2189 | self.input_hist_raw.append('\n') |
|
2200 | 2190 | try: |
|
2201 | 2191 | lineout = self.prefilter(line,continue_prompt) |
|
2202 | 2192 | except: |
|
2203 | 2193 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2204 | 2194 | # can't take all of ipython with it. |
|
2205 | 2195 | self.showtraceback() |
|
2206 | 2196 | return '' |
|
2207 | 2197 | else: |
|
2208 | 2198 | return lineout |
|
2209 | 2199 | |
|
2210 | 2200 | def _prefilter(self, line, continue_prompt): |
|
2211 | 2201 | """Calls different preprocessors, depending on the form of line.""" |
|
2212 | 2202 | |
|
2213 | 2203 | # All handlers *must* return a value, even if it's blank (''). |
|
2214 | 2204 | |
|
2215 | 2205 | # Lines are NOT logged here. Handlers should process the line as |
|
2216 | 2206 | # needed, update the cache AND log it (so that the input cache array |
|
2217 | 2207 | # stays synced). |
|
2218 | 2208 | |
|
2219 | 2209 | #..................................................................... |
|
2220 | 2210 | # Code begins |
|
2221 | 2211 | |
|
2222 | 2212 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2223 | 2213 | |
|
2224 | 2214 | # save the line away in case we crash, so the post-mortem handler can |
|
2225 | 2215 | # record it |
|
2226 | 2216 | self._last_input_line = line |
|
2227 | 2217 | |
|
2228 | 2218 | #print '***line: <%s>' % line # dbg |
|
2229 | 2219 | |
|
2230 | 2220 | if not line: |
|
2231 | 2221 | # Return immediately on purely empty lines, so that if the user |
|
2232 | 2222 | # previously typed some whitespace that started a continuation |
|
2233 | 2223 | # prompt, he can break out of that loop with just an empty line. |
|
2234 | 2224 | # This is how the default python prompt works. |
|
2235 | 2225 | |
|
2236 | 2226 | # Only return if the accumulated input buffer was just whitespace! |
|
2237 | 2227 | if ''.join(self.buffer).isspace(): |
|
2238 | 2228 | self.buffer[:] = [] |
|
2239 | 2229 | return '' |
|
2240 | 2230 | |
|
2241 | 2231 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2242 | 2232 | |
|
2243 | 2233 | # the input history needs to track even empty lines |
|
2244 | 2234 | stripped = line.strip() |
|
2245 | 2235 | |
|
2246 | 2236 | if not stripped: |
|
2247 | 2237 | if not continue_prompt: |
|
2248 | 2238 | self.outputcache.prompt_count -= 1 |
|
2249 | 2239 | return self.handle_normal(line_info) |
|
2250 | 2240 | |
|
2251 | 2241 | # print '***cont',continue_prompt # dbg |
|
2252 | 2242 | # special handlers are only allowed for single line statements |
|
2253 | 2243 | if continue_prompt and not self.rc.multi_line_specials: |
|
2254 | 2244 | return self.handle_normal(line_info) |
|
2255 | 2245 | |
|
2256 | 2246 | |
|
2257 | 2247 | # See whether any pre-existing handler can take care of it |
|
2258 | 2248 | rewritten = self.hooks.input_prefilter(stripped) |
|
2259 | 2249 | if rewritten != stripped: # ok, some prefilter did something |
|
2260 | 2250 | rewritten = line_info.pre + rewritten # add indentation |
|
2261 | 2251 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2262 | 2252 | continue_prompt)) |
|
2263 | 2253 | |
|
2264 | 2254 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2265 | 2255 | |
|
2266 | 2256 | return prefilter.prefilter(line_info, self) |
|
2267 | 2257 | |
|
2268 | 2258 | |
|
2269 | 2259 | def _prefilter_dumb(self, line, continue_prompt): |
|
2270 | 2260 | """simple prefilter function, for debugging""" |
|
2271 | 2261 | return self.handle_normal(line,continue_prompt) |
|
2272 | 2262 | |
|
2273 | 2263 | |
|
2274 | 2264 | def multiline_prefilter(self, line, continue_prompt): |
|
2275 | 2265 | """ Run _prefilter for each line of input |
|
2276 | 2266 | |
|
2277 | 2267 | Covers cases where there are multiple lines in the user entry, |
|
2278 | 2268 | which is the case when the user goes back to a multiline history |
|
2279 | 2269 | entry and presses enter. |
|
2280 | 2270 | |
|
2281 | 2271 | """ |
|
2282 | 2272 | out = [] |
|
2283 | 2273 | for l in line.rstrip('\n').split('\n'): |
|
2284 | 2274 | out.append(self._prefilter(l, continue_prompt)) |
|
2285 | 2275 | return '\n'.join(out) |
|
2286 | 2276 | |
|
2287 | 2277 | # Set the default prefilter() function (this can be user-overridden) |
|
2288 | 2278 | prefilter = multiline_prefilter |
|
2289 | 2279 | |
|
2290 | 2280 | def handle_normal(self,line_info): |
|
2291 | 2281 | """Handle normal input lines. Use as a template for handlers.""" |
|
2292 | 2282 | |
|
2293 | 2283 | # With autoindent on, we need some way to exit the input loop, and I |
|
2294 | 2284 | # don't want to force the user to have to backspace all the way to |
|
2295 | 2285 | # clear the line. The rule will be in this case, that either two |
|
2296 | 2286 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2297 | 2287 | # of a size different to the indent level, will exit the input loop. |
|
2298 | 2288 | line = line_info.line |
|
2299 | 2289 | continue_prompt = line_info.continue_prompt |
|
2300 | 2290 | |
|
2301 | 2291 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2302 | 2292 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2303 | 2293 | (self.buffer[-1]).isspace() )): |
|
2304 | 2294 | line = '' |
|
2305 | 2295 | |
|
2306 | 2296 | self.log(line,line,continue_prompt) |
|
2307 | 2297 | return line |
|
2308 | 2298 | |
|
2309 | 2299 | def handle_alias(self,line_info): |
|
2310 | 2300 | """Handle alias input lines. """ |
|
2311 | 2301 | tgt = self.alias_table[line_info.iFun] |
|
2312 | 2302 | # print "=>",tgt #dbg |
|
2313 | 2303 | if callable(tgt): |
|
2314 | 2304 | if '$' in line_info.line: |
|
2315 | 2305 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2316 | 2306 | else: |
|
2317 | 2307 | call_meth = '(_ip,%s)' |
|
2318 | 2308 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2319 | 2309 | line_info.iFun, |
|
2320 | 2310 | make_quoted_expr(line_info.line)) |
|
2321 | 2311 | else: |
|
2322 | 2312 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2323 | 2313 | |
|
2324 | 2314 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2325 | 2315 | # aliases won't work in indented sections. |
|
2326 | 2316 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2327 | 2317 | make_quoted_expr( transformed )) |
|
2328 | 2318 | |
|
2329 | 2319 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2330 | 2320 | #print 'line out:',line_out # dbg |
|
2331 | 2321 | return line_out |
|
2332 | 2322 | |
|
2333 | 2323 | def handle_shell_escape(self, line_info): |
|
2334 | 2324 | """Execute the line in a shell, empty return value""" |
|
2335 | 2325 | #print 'line in :', `line` # dbg |
|
2336 | 2326 | line = line_info.line |
|
2337 | 2327 | if line.lstrip().startswith('!!'): |
|
2338 | 2328 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2339 | 2329 | # call to %sx and the actual command to be executed, so |
|
2340 | 2330 | # handle_magic can work correctly. Note that this works even if |
|
2341 | 2331 | # the line is indented, so it handles multi_line_specials |
|
2342 | 2332 | # properly. |
|
2343 | 2333 | new_rest = line.lstrip()[2:] |
|
2344 | 2334 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2345 | 2335 | line_info.iFun = 'sx' |
|
2346 | 2336 | line_info.theRest = new_rest |
|
2347 | 2337 | return self.handle_magic(line_info) |
|
2348 | 2338 | else: |
|
2349 | 2339 | cmd = line.lstrip().lstrip('!') |
|
2350 | 2340 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2351 | 2341 | make_quoted_expr(cmd)) |
|
2352 | 2342 | # update cache/log and return |
|
2353 | 2343 | self.log(line,line_out,line_info.continue_prompt) |
|
2354 | 2344 | return line_out |
|
2355 | 2345 | |
|
2356 | 2346 | def handle_magic(self, line_info): |
|
2357 | 2347 | """Execute magic functions.""" |
|
2358 | 2348 | iFun = line_info.iFun |
|
2359 | 2349 | theRest = line_info.theRest |
|
2360 | 2350 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2361 | 2351 | make_quoted_expr(iFun + " " + theRest)) |
|
2362 | 2352 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2363 | 2353 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2364 | 2354 | return cmd |
|
2365 | 2355 | |
|
2366 | 2356 | def handle_auto(self, line_info): |
|
2367 | 2357 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2368 | 2358 | |
|
2369 | 2359 | line = line_info.line |
|
2370 | 2360 | iFun = line_info.iFun |
|
2371 | 2361 | theRest = line_info.theRest |
|
2372 | 2362 | pre = line_info.pre |
|
2373 | 2363 | continue_prompt = line_info.continue_prompt |
|
2374 | 2364 | obj = line_info.ofind(self)['obj'] |
|
2375 | 2365 | |
|
2376 | 2366 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2377 | 2367 | |
|
2378 | 2368 | # This should only be active for single-line input! |
|
2379 | 2369 | if continue_prompt: |
|
2380 | 2370 | self.log(line,line,continue_prompt) |
|
2381 | 2371 | return line |
|
2382 | 2372 | |
|
2383 | 2373 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) |
|
2384 | 2374 | auto_rewrite = True |
|
2385 | 2375 | |
|
2386 | 2376 | if pre == self.ESC_QUOTE: |
|
2387 | 2377 | # Auto-quote splitting on whitespace |
|
2388 | 2378 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2389 | 2379 | elif pre == self.ESC_QUOTE2: |
|
2390 | 2380 | # Auto-quote whole string |
|
2391 | 2381 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2392 | 2382 | elif pre == self.ESC_PAREN: |
|
2393 | 2383 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2394 | 2384 | else: |
|
2395 | 2385 | # Auto-paren. |
|
2396 | 2386 | # We only apply it to argument-less calls if the autocall |
|
2397 | 2387 | # parameter is set to 2. We only need to check that autocall is < |
|
2398 | 2388 | # 2, since this function isn't called unless it's at least 1. |
|
2399 | 2389 | if not theRest and (self.rc.autocall < 2) and not force_auto: |
|
2400 | 2390 | newcmd = '%s %s' % (iFun,theRest) |
|
2401 | 2391 | auto_rewrite = False |
|
2402 | 2392 | else: |
|
2403 | 2393 | if not force_auto and theRest.startswith('['): |
|
2404 | 2394 | if hasattr(obj,'__getitem__'): |
|
2405 | 2395 | # Don't autocall in this case: item access for an object |
|
2406 | 2396 | # which is BOTH callable and implements __getitem__. |
|
2407 | 2397 | newcmd = '%s %s' % (iFun,theRest) |
|
2408 | 2398 | auto_rewrite = False |
|
2409 | 2399 | else: |
|
2410 | 2400 | # if the object doesn't support [] access, go ahead and |
|
2411 | 2401 | # autocall |
|
2412 | 2402 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2413 | 2403 | elif theRest.endswith(';'): |
|
2414 | 2404 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2415 | 2405 | else: |
|
2416 | 2406 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2417 | 2407 | |
|
2418 | 2408 | if auto_rewrite: |
|
2419 | 2409 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2420 | 2410 | |
|
2421 | 2411 | try: |
|
2422 | 2412 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2423 | 2413 | # we use it and only print uncolored rewrite if we have unicode |
|
2424 | 2414 | rw = str(rw) |
|
2425 | 2415 | print >>Term.cout, rw |
|
2426 | 2416 | except UnicodeEncodeError: |
|
2427 | 2417 | print "-------------->" + newcmd |
|
2428 | 2418 | |
|
2429 | 2419 | # log what is now valid Python, not the actual user input (without the |
|
2430 | 2420 | # final newline) |
|
2431 | 2421 | self.log(line,newcmd,continue_prompt) |
|
2432 | 2422 | return newcmd |
|
2433 | 2423 | |
|
2434 | 2424 | def handle_help(self, line_info): |
|
2435 | 2425 | """Try to get some help for the object. |
|
2436 | 2426 | |
|
2437 | 2427 | obj? or ?obj -> basic information. |
|
2438 | 2428 | obj?? or ??obj -> more details. |
|
2439 | 2429 | """ |
|
2440 | 2430 | |
|
2441 | 2431 | line = line_info.line |
|
2442 | 2432 | # We need to make sure that we don't process lines which would be |
|
2443 | 2433 | # otherwise valid python, such as "x=1 # what?" |
|
2444 | 2434 | try: |
|
2445 | 2435 | codeop.compile_command(line) |
|
2446 | 2436 | except SyntaxError: |
|
2447 | 2437 | # We should only handle as help stuff which is NOT valid syntax |
|
2448 | 2438 | if line[0]==self.ESC_HELP: |
|
2449 | 2439 | line = line[1:] |
|
2450 | 2440 | elif line[-1]==self.ESC_HELP: |
|
2451 | 2441 | line = line[:-1] |
|
2452 | 2442 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2453 | 2443 | if line: |
|
2454 | 2444 | #print 'line:<%r>' % line # dbg |
|
2455 | 2445 | self.magic_pinfo(line) |
|
2456 | 2446 | else: |
|
2457 | 2447 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2458 | 2448 | return '' # Empty string is needed here! |
|
2459 | 2449 | except: |
|
2460 | 2450 | # Pass any other exceptions through to the normal handler |
|
2461 | 2451 | return self.handle_normal(line_info) |
|
2462 | 2452 | else: |
|
2463 | 2453 | # If the code compiles ok, we should handle it normally |
|
2464 | 2454 | return self.handle_normal(line_info) |
|
2465 | 2455 | |
|
2466 | 2456 | def getapi(self): |
|
2467 | 2457 | """ Get an IPApi object for this shell instance |
|
2468 | 2458 | |
|
2469 | 2459 | Getting an IPApi object is always preferable to accessing the shell |
|
2470 | 2460 | directly, but this holds true especially for extensions. |
|
2471 | 2461 | |
|
2472 | 2462 | It should always be possible to implement an extension with IPApi |
|
2473 | 2463 | alone. If not, contact maintainer to request an addition. |
|
2474 | 2464 | |
|
2475 | 2465 | """ |
|
2476 | 2466 | return self.api |
|
2477 | 2467 | |
|
2478 | 2468 | def handle_emacs(self, line_info): |
|
2479 | 2469 | """Handle input lines marked by python-mode.""" |
|
2480 | 2470 | |
|
2481 | 2471 | # Currently, nothing is done. Later more functionality can be added |
|
2482 | 2472 | # here if needed. |
|
2483 | 2473 | |
|
2484 | 2474 | # The input cache shouldn't be updated |
|
2485 | 2475 | return line_info.line |
|
2486 | 2476 | |
|
2487 | 2477 | |
|
2488 | 2478 | def mktempfile(self,data=None): |
|
2489 | 2479 | """Make a new tempfile and return its filename. |
|
2490 | 2480 | |
|
2491 | 2481 | This makes a call to tempfile.mktemp, but it registers the created |
|
2492 | 2482 | filename internally so ipython cleans it up at exit time. |
|
2493 | 2483 | |
|
2494 | 2484 | Optional inputs: |
|
2495 | 2485 | |
|
2496 | 2486 | - data(None): if data is given, it gets written out to the temp file |
|
2497 | 2487 | immediately, and the file is closed again.""" |
|
2498 | 2488 | |
|
2499 | 2489 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2500 | 2490 | self.tempfiles.append(filename) |
|
2501 | 2491 | |
|
2502 | 2492 | if data: |
|
2503 | 2493 | tmp_file = open(filename,'w') |
|
2504 | 2494 | tmp_file.write(data) |
|
2505 | 2495 | tmp_file.close() |
|
2506 | 2496 | return filename |
|
2507 | 2497 | |
|
2508 | 2498 | def write(self,data): |
|
2509 | 2499 | """Write a string to the default output""" |
|
2510 | 2500 | Term.cout.write(data) |
|
2511 | 2501 | |
|
2512 | 2502 | def write_err(self,data): |
|
2513 | 2503 | """Write a string to the default error output""" |
|
2514 | 2504 | Term.cerr.write(data) |
|
2515 | 2505 | |
|
2516 | 2506 | def ask_exit(self): |
|
2517 | 2507 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2518 | 2508 | self.exit_now = True |
|
2519 | 2509 | |
|
2520 | 2510 | def exit(self): |
|
2521 | 2511 | """Handle interactive exit. |
|
2522 | 2512 | |
|
2523 | 2513 | This method calls the ask_exit callback.""" |
|
2524 | 2514 | |
|
2525 | 2515 | if self.rc.confirm_exit: |
|
2526 | 2516 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2527 | 2517 | self.ask_exit() |
|
2528 | 2518 | else: |
|
2529 | 2519 | self.ask_exit() |
|
2530 | 2520 | |
|
2531 | 2521 | def safe_execfile(self,fname,*where,**kw): |
|
2532 | 2522 | """A safe version of the builtin execfile(). |
|
2533 | 2523 | |
|
2534 | 2524 | This version will never throw an exception, and knows how to handle |
|
2535 | 2525 | ipython logs as well. |
|
2536 | 2526 | |
|
2537 | 2527 | :Parameters: |
|
2538 | 2528 | fname : string |
|
2539 | 2529 | Name of the file to be executed. |
|
2540 | 2530 | |
|
2541 | 2531 | where : tuple |
|
2542 | 2532 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2543 | 2533 | If only one is given, it is passed as both. |
|
2544 | 2534 | |
|
2545 | 2535 | :Keywords: |
|
2546 | 2536 | islog : boolean (False) |
|
2547 | 2537 | |
|
2548 | 2538 | quiet : boolean (True) |
|
2549 | 2539 | |
|
2550 | 2540 | exit_ignore : boolean (False) |
|
2551 | 2541 | """ |
|
2552 | 2542 | |
|
2553 | 2543 | def syspath_cleanup(): |
|
2554 | 2544 | """Internal cleanup routine for sys.path.""" |
|
2555 | 2545 | if add_dname: |
|
2556 | 2546 | try: |
|
2557 | 2547 | sys.path.remove(dname) |
|
2558 | 2548 | except ValueError: |
|
2559 | 2549 | # For some reason the user has already removed it, ignore. |
|
2560 | 2550 | pass |
|
2561 | 2551 | |
|
2562 | 2552 | fname = os.path.expanduser(fname) |
|
2563 | 2553 | |
|
2564 | 2554 | # Find things also in current directory. This is needed to mimic the |
|
2565 | 2555 | # behavior of running a script from the system command line, where |
|
2566 | 2556 | # Python inserts the script's directory into sys.path |
|
2567 | 2557 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2568 | 2558 | add_dname = False |
|
2569 | 2559 | if dname not in sys.path: |
|
2570 | 2560 | sys.path.insert(0,dname) |
|
2571 | 2561 | add_dname = True |
|
2572 | 2562 | |
|
2573 | 2563 | try: |
|
2574 | 2564 | xfile = open(fname) |
|
2575 | 2565 | except: |
|
2576 | 2566 | print >> Term.cerr, \ |
|
2577 | 2567 | 'Could not open file <%s> for safe execution.' % fname |
|
2578 | 2568 | syspath_cleanup() |
|
2579 | 2569 | return None |
|
2580 | 2570 | |
|
2581 | 2571 | kw.setdefault('islog',0) |
|
2582 | 2572 | kw.setdefault('quiet',1) |
|
2583 | 2573 | kw.setdefault('exit_ignore',0) |
|
2584 | 2574 | |
|
2585 | 2575 | first = xfile.readline() |
|
2586 | 2576 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2587 | 2577 | xfile.close() |
|
2588 | 2578 | # line by line execution |
|
2589 | 2579 | if first.startswith(loghead) or kw['islog']: |
|
2590 | 2580 | print 'Loading log file <%s> one line at a time...' % fname |
|
2591 | 2581 | if kw['quiet']: |
|
2592 | 2582 | stdout_save = sys.stdout |
|
2593 | 2583 | sys.stdout = StringIO.StringIO() |
|
2594 | 2584 | try: |
|
2595 | 2585 | globs,locs = where[0:2] |
|
2596 | 2586 | except: |
|
2597 | 2587 | try: |
|
2598 | 2588 | globs = locs = where[0] |
|
2599 | 2589 | except: |
|
2600 | 2590 | globs = locs = globals() |
|
2601 | 2591 | badblocks = [] |
|
2602 | 2592 | |
|
2603 | 2593 | # we also need to identify indented blocks of code when replaying |
|
2604 | 2594 | # logs and put them together before passing them to an exec |
|
2605 | 2595 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2606 | 2596 | # file. It's easiest if we swallow the whole thing in memory |
|
2607 | 2597 | # first, and manually walk through the lines list moving the |
|
2608 | 2598 | # counter ourselves. |
|
2609 | 2599 | indent_re = re.compile('\s+\S') |
|
2610 | 2600 | xfile = open(fname) |
|
2611 | 2601 | filelines = xfile.readlines() |
|
2612 | 2602 | xfile.close() |
|
2613 | 2603 | nlines = len(filelines) |
|
2614 | 2604 | lnum = 0 |
|
2615 | 2605 | while lnum < nlines: |
|
2616 | 2606 | line = filelines[lnum] |
|
2617 | 2607 | lnum += 1 |
|
2618 | 2608 | # don't re-insert logger status info into cache |
|
2619 | 2609 | if line.startswith('#log#'): |
|
2620 | 2610 | continue |
|
2621 | 2611 | else: |
|
2622 | 2612 | # build a block of code (maybe a single line) for execution |
|
2623 | 2613 | block = line |
|
2624 | 2614 | try: |
|
2625 | 2615 | next = filelines[lnum] # lnum has already incremented |
|
2626 | 2616 | except: |
|
2627 | 2617 | next = None |
|
2628 | 2618 | while next and indent_re.match(next): |
|
2629 | 2619 | block += next |
|
2630 | 2620 | lnum += 1 |
|
2631 | 2621 | try: |
|
2632 | 2622 | next = filelines[lnum] |
|
2633 | 2623 | except: |
|
2634 | 2624 | next = None |
|
2635 | 2625 | # now execute the block of one or more lines |
|
2636 | 2626 | try: |
|
2637 | 2627 | exec block in globs,locs |
|
2638 | 2628 | except SystemExit: |
|
2639 | 2629 | pass |
|
2640 | 2630 | except: |
|
2641 | 2631 | badblocks.append(block.rstrip()) |
|
2642 | 2632 | if kw['quiet']: # restore stdout |
|
2643 | 2633 | sys.stdout.close() |
|
2644 | 2634 | sys.stdout = stdout_save |
|
2645 | 2635 | print 'Finished replaying log file <%s>' % fname |
|
2646 | 2636 | if badblocks: |
|
2647 | 2637 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2648 | 2638 | '<%s> reported errors:' % fname) |
|
2649 | 2639 | |
|
2650 | 2640 | for badline in badblocks: |
|
2651 | 2641 | print >> sys.stderr, badline |
|
2652 | 2642 | else: # regular file execution |
|
2653 | 2643 | try: |
|
2654 | 2644 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2655 | 2645 | # Work around a bug in Python for Windows. The bug was |
|
2656 | 2646 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2657 | 2647 | # SVN Python as of March/07. For details, see: |
|
2658 | 2648 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2659 | 2649 | try: |
|
2660 | 2650 | globs,locs = where[0:2] |
|
2661 | 2651 | except: |
|
2662 | 2652 | try: |
|
2663 | 2653 | globs = locs = where[0] |
|
2664 | 2654 | except: |
|
2665 | 2655 | globs = locs = globals() |
|
2666 | 2656 | exec file(fname) in globs,locs |
|
2667 | 2657 | else: |
|
2668 | 2658 | execfile(fname,*where) |
|
2669 | 2659 | except SyntaxError: |
|
2670 | 2660 | self.showsyntaxerror() |
|
2671 | 2661 | warn('Failure executing file: <%s>' % fname) |
|
2672 | 2662 | except SystemExit,status: |
|
2673 | 2663 | # Code that correctly sets the exit status flag to success (0) |
|
2674 | 2664 | # shouldn't be bothered with a traceback. Note that a plain |
|
2675 | 2665 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2676 | 2666 | # will still get a traceback. Note that the structure of the |
|
2677 | 2667 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2678 | 2668 | # the checks must be done in a version-dependent way. |
|
2679 | 2669 | show = False |
|
2680 | 2670 | |
|
2681 | 2671 | if sys.version_info[:2] > (2,5): |
|
2682 | 2672 | if status.message!=0 and not kw['exit_ignore']: |
|
2683 | 2673 | show = True |
|
2684 | 2674 | else: |
|
2685 | 2675 | if status.code and not kw['exit_ignore']: |
|
2686 | 2676 | show = True |
|
2687 | 2677 | if show: |
|
2688 | 2678 | self.showtraceback() |
|
2689 | 2679 | warn('Failure executing file: <%s>' % fname) |
|
2690 | 2680 | except: |
|
2691 | 2681 | self.showtraceback() |
|
2692 | 2682 | warn('Failure executing file: <%s>' % fname) |
|
2693 | 2683 | |
|
2694 | 2684 | syspath_cleanup() |
|
2695 | 2685 | |
|
2696 | 2686 | #************************* end of file <iplib.py> ***************************** |
General Comments 0
You need to be logged in to leave comments.
Login now