##// END OF EJS Templates
Added --gui to match %gui use, better docs and behavior for %pylab code....
Fernando Perez -
Show More
@@ -1,555 +1,587 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The :class:`~IPython.core.application.Application` object for the command
5 5 line :command:`ipython` program.
6 6
7 7 Authors:
8 8
9 9 * Brian Granger
10 10 * Fernando Perez
11 11
12 12 Notes
13 13 -----
14 14 """
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Copyright (C) 2008-2009 The IPython Development Team
18 18 #
19 19 # Distributed under the terms of the BSD License. The full license is in
20 20 # the file COPYING, distributed as part of this software.
21 21 #-----------------------------------------------------------------------------
22 22
23 23 #-----------------------------------------------------------------------------
24 24 # Imports
25 25 #-----------------------------------------------------------------------------
26 26
27 27 import logging
28 28 import os
29 29 import sys
30 30
31 31 from IPython.core import release
32 32 from IPython.core.application import Application, BaseAppArgParseConfigLoader
33 33 from IPython.core.error import UsageError
34 34 from IPython.core.iplib import InteractiveShell
35 35 from IPython.core.pylabtools import pylab_activate
36 36 from IPython.config.loader import (
37 37 NoConfigDefault,
38 38 Config,
39 39 PyFileConfigLoader
40 40 )
41 41 from IPython.lib import inputhook
42 42 from IPython.utils.genutils import filefind, get_ipython_dir
43 43
44 44 #-----------------------------------------------------------------------------
45 45 # Utilities and helpers
46 46 #-----------------------------------------------------------------------------
47 47
48 48 ipython_desc = """
49 49 A Python shell with automatic history (input and output), dynamic object
50 50 introspection, easier configuration, command completion, access to the system
51 51 shell and more.
52 52 """
53 53
54 54 #-----------------------------------------------------------------------------
55 55 # Main classes and functions
56 56 #-----------------------------------------------------------------------------
57 57
58 58 cl_args = (
59 59 (('--autocall',), dict(
60 60 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
61 61 help='Set the autocall value (0,1,2).',
62 62 metavar='InteractiveShell.autocall')
63 63 ),
64 64 (('--autoindent',), dict(
65 65 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
66 66 help='Turn on autoindenting.')
67 67 ),
68 68 (('--no-autoindent',), dict(
69 69 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
70 70 help='Turn off autoindenting.')
71 71 ),
72 72 (('--automagic',), dict(
73 73 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
74 74 help='Turn on the auto calling of magic commands.')
75 75 ),
76 76 (('--no-automagic',), dict(
77 77 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
78 78 help='Turn off the auto calling of magic commands.')
79 79 ),
80 80 (('--autoedit-syntax',), dict(
81 81 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
82 82 help='Turn on auto editing of files with syntax errors.')
83 83 ),
84 84 (('--no-autoedit-syntax',), dict(
85 85 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
86 86 help='Turn off auto editing of files with syntax errors.')
87 87 ),
88 88 (('--banner',), dict(
89 89 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
90 90 help='Display a banner upon starting IPython.')
91 91 ),
92 92 (('--no-banner',), dict(
93 93 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
94 94 help="Don't display a banner upon starting IPython.")
95 95 ),
96 96 (('--cache-size',), dict(
97 97 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
98 98 help="Set the size of the output cache.",
99 99 metavar='InteractiveShell.cache_size')
100 100 ),
101 101 (('--classic',), dict(
102 102 action='store_true', dest='Global.classic', default=NoConfigDefault,
103 103 help="Gives IPython a similar feel to the classic Python prompt.")
104 104 ),
105 105 (('--colors',), dict(
106 106 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
107 107 help="Set the color scheme (NoColor, Linux, and LightBG).",
108 108 metavar='InteractiveShell.colors')
109 109 ),
110 110 (('--color-info',), dict(
111 111 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
112 112 help="Enable using colors for info related things.")
113 113 ),
114 114 (('--no-color-info',), dict(
115 115 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
116 116 help="Disable using colors for info related things.")
117 117 ),
118 118 (('--confirm-exit',), dict(
119 119 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
120 120 help="Prompt the user when existing.")
121 121 ),
122 122 (('--no-confirm-exit',), dict(
123 123 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
124 124 help="Don't prompt the user when existing.")
125 125 ),
126 126 (('--deep-reload',), dict(
127 127 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
128 128 help="Enable deep (recursive) reloading by default.")
129 129 ),
130 130 (('--no-deep-reload',), dict(
131 131 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
132 132 help="Disable deep (recursive) reloading by default.")
133 133 ),
134 134 (('--editor',), dict(
135 135 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
136 136 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
137 137 metavar='InteractiveShell.editor')
138 138 ),
139 139 (('--log','-l'), dict(
140 140 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
141 141 help="Start logging to the default file (./ipython_log.py).")
142 142 ),
143 143 (('--logfile','-lf'), dict(
144 144 type=unicode, dest='InteractiveShell.logfile', default=NoConfigDefault,
145 145 help="Start logging to logfile.",
146 146 metavar='InteractiveShell.logfile')
147 147 ),
148 148 (('--log-append','-la'), dict(
149 149 type=unicode, dest='InteractiveShell.logappend', default=NoConfigDefault,
150 150 help="Start logging to the give file in append mode.",
151 151 metavar='InteractiveShell.logfile')
152 152 ),
153 153 (('--pdb',), dict(
154 154 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
155 155 help="Enable auto calling the pdb debugger after every exception.")
156 156 ),
157 157 (('--no-pdb',), dict(
158 158 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
159 159 help="Disable auto calling the pdb debugger after every exception.")
160 160 ),
161 161 (('--pprint',), dict(
162 162 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
163 163 help="Enable auto pretty printing of results.")
164 164 ),
165 165 (('--no-pprint',), dict(
166 166 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
167 167 help="Disable auto auto pretty printing of results.")
168 168 ),
169 169 (('--prompt-in1','-pi1'), dict(
170 170 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
171 171 help="Set the main input prompt ('In [\#]: ')",
172 172 metavar='InteractiveShell.prompt_in1')
173 173 ),
174 174 (('--prompt-in2','-pi2'), dict(
175 175 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
176 176 help="Set the secondary input prompt (' .\D.: ')",
177 177 metavar='InteractiveShell.prompt_in2')
178 178 ),
179 179 (('--prompt-out','-po'), dict(
180 180 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
181 181 help="Set the output prompt ('Out[\#]:')",
182 182 metavar='InteractiveShell.prompt_out')
183 183 ),
184 184 (('--quick',), dict(
185 185 action='store_true', dest='Global.quick', default=NoConfigDefault,
186 186 help="Enable quick startup with no config files.")
187 187 ),
188 188 (('--readline',), dict(
189 189 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
190 190 help="Enable readline for command line usage.")
191 191 ),
192 192 (('--no-readline',), dict(
193 193 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
194 194 help="Disable readline for command line usage.")
195 195 ),
196 196 (('--screen-length','-sl'), dict(
197 197 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
198 198 help='Number of lines on screen, used to control printing of long strings.',
199 199 metavar='InteractiveShell.screen_length')
200 200 ),
201 201 (('--separate-in','-si'), dict(
202 202 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
203 203 help="Separator before input prompts. Default '\n'.",
204 204 metavar='InteractiveShell.separate_in')
205 205 ),
206 206 (('--separate-out','-so'), dict(
207 207 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
208 208 help="Separator before output prompts. Default 0 (nothing).",
209 209 metavar='InteractiveShell.separate_out')
210 210 ),
211 211 (('--separate-out2','-so2'), dict(
212 212 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
213 213 help="Separator after output prompts. Default 0 (nonight).",
214 214 metavar='InteractiveShell.separate_out2')
215 215 ),
216 216 (('-no-sep',), dict(
217 217 action='store_true', dest='Global.nosep', default=NoConfigDefault,
218 218 help="Eliminate all spacing between prompts.")
219 219 ),
220 220 (('--term-title',), dict(
221 221 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
222 222 help="Enable auto setting the terminal title.")
223 223 ),
224 224 (('--no-term-title',), dict(
225 225 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
226 226 help="Disable auto setting the terminal title.")
227 227 ),
228 228 (('--xmode',), dict(
229 229 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
230 230 help="Exception mode ('Plain','Context','Verbose')",
231 231 metavar='InteractiveShell.xmode')
232 232 ),
233 233 (('--ext',), dict(
234 234 type=str, dest='Global.extra_extension', default=NoConfigDefault,
235 235 help="The dotted module name of an IPython extension to load.",
236 236 metavar='Global.extra_extension')
237 237 ),
238 238 (('-c',), dict(
239 239 type=str, dest='Global.code_to_run', default=NoConfigDefault,
240 240 help="Execute the given command string.",
241 241 metavar='Global.code_to_run')
242 242 ),
243 243 (('-i',), dict(
244 244 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
245 245 help="If running code from the command line, become interactive afterwards.")
246 246 ),
247
248 # Options to start with GUI control enabled from the beginning
249 (('--gui',), dict(
250 type=str, dest='Global.gui', default=NoConfigDefault,
251 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
252 metavar='gui-mode')
253 ),
254
255 (('--pylab',), dict(
256 type=str, dest='Global.pylab', default=NoConfigDefault,
257 nargs='?', const='auto', metavar='gui-mode',
258 help="Pre-load matplotlib and numpy for interactive use. "+
259 "If no value is given, the gui backend is matplotlib's, else use "+
260 "one of: ['tk', 'qt', 'wx', 'gtk'].")
261 ),
262
263 # Legacy GUI options. Leave them in for backwards compatibility, but the
264 # 'thread' names are really a misnomer now.
247 265 (('--wthread','-wthread'), dict(
248 266 action='store_true', dest='Global.wthread', default=NoConfigDefault,
249 help="Enable wxPython event loop integration.")
267 help="Enable wxPython event loop integration "+
268 "(DEPRECATED, use --gui wx)")
250 269 ),
251 270 (('--q4thread','--qthread','-q4thread','-qthread'), dict(
252 271 action='store_true', dest='Global.q4thread', default=NoConfigDefault,
253 help="Enable Qt4 event loop integration. Qt3 is no longer supported.")
272 help="Enable Qt4 event loop integration. Qt3 is no longer supported. "+
273 "(DEPRECATED, use --gui qt)")
254 274 ),
255 275 (('--gthread','-gthread'), dict(
256 276 action='store_true', dest='Global.gthread', default=NoConfigDefault,
257 help="Enable GTK event loop integration.")
277 help="Enable GTK event loop integration. "+
278 "(DEPRECATED, use --gui gtk)")
258 279 ),
259 (('--pylab',), dict(
260 action='store_true', dest='Global.pylab', default=NoConfigDefault,
261 help="Pre-load matplotlib and numpy for interactive use.")
262 )
263 280 )
264 281
265 282
266 283 class IPythonAppCLConfigLoader(BaseAppArgParseConfigLoader):
267 284
268 285 arguments = cl_args
269 286
270 287 def load_config(self):
271 288 """Do actions just before loading the command line config."""
272 289
273 290 # Special hack: there are countless uses of 'ipython -pylab' (with one
274 291 # dash) in the wild, including in printed books. Since argparse does
275 292 # will interpret -pylab as '-p ylab', sending us in a search for a
276 293 # profile named 'ylab', instead we special-case here -pylab as the
277 294 # first or second option only (this is how old ipython used to work)
278 295 # and convert this use to --pylab. Ugly, but needed for this one
279 296 # very widely used case.
280 297 firstargs = sys.argv[:3]
281 298 try:
282 299 idx = firstargs.index('-pylab')
283 300 except ValueError:
284 301 pass
285 302 else:
286 303 sys.argv[idx] = '--pylab'
287 304 return super(IPythonAppCLConfigLoader, self).load_config()
288 305
289 306 default_config_file_name = u'ipython_config.py'
290 307
291 308
292 309 class IPythonApp(Application):
293 310 name = u'ipython'
294 311 description = 'IPython: an enhanced interactive Python shell.'
295 312 config_file_name = default_config_file_name
296 313
297 314 def create_default_config(self):
298 315 super(IPythonApp, self).create_default_config()
299 316 # Eliminate multiple lookups
300 317 Global = self.default_config.Global
318
301 319 # Set all default values
302 320 Global.display_banner = True
303 321
304 322 # If the -c flag is given or a file is given to run at the cmd line
305 323 # like "ipython foo.py", normally we exit without starting the main
306 324 # loop. The force_interact config variable allows a user to override
307 325 # this and interact. It is also set by the -i cmd line flag, just
308 326 # like Python.
309 327 Global.force_interact = False
310 328
311 329 # By default always interact by starting the IPython mainloop.
312 330 Global.interact = True
313 331
314 332 # No GUI integration by default
315 Global.wthread = False
316 Global.q4thread = False
317 Global.gthread = False
318
333 Global.gui = False
319 334 # Pylab off by default
320 335 Global.pylab = False
321 336
337 # Deprecated versions of gui support that used threading, we support
338 # them just for bacwards compatibility as an alternate spelling for
339 # '--gui X'
340 Global.qthread = False
341 Global.q4thread = False
342 Global.wthread = False
343 Global.gthread = False
344
322 345 def create_command_line_config(self):
323 346 """Create and return a command line config loader."""
324 347 return IPythonAppCLConfigLoader(
325 348 description=self.description,
326 349 version=release.version
327 350 )
328 351
329 352
330 353 def load_file_config(self):
331 354 if hasattr(self.command_line_config.Global, 'quick'):
332 355 if self.command_line_config.Global.quick:
333 356 self.file_config = Config()
334 357 return
335 358 super(IPythonApp, self).load_file_config()
336 359
337 360 def post_load_file_config(self):
338 361 if hasattr(self.command_line_config.Global, 'extra_extension'):
339 362 if not hasattr(self.file_config.Global, 'extensions'):
340 363 self.file_config.Global.extensions = []
341 364 self.file_config.Global.extensions.append(
342 365 self.command_line_config.Global.extra_extension)
343 366 del self.command_line_config.Global.extra_extension
344 367
345 368 def pre_construct(self):
346 369 config = self.master_config
347 370
348 371 if hasattr(config.Global, 'classic'):
349 372 if config.Global.classic:
350 373 config.InteractiveShell.cache_size = 0
351 374 config.InteractiveShell.pprint = 0
352 375 config.InteractiveShell.prompt_in1 = '>>> '
353 376 config.InteractiveShell.prompt_in2 = '... '
354 377 config.InteractiveShell.prompt_out = ''
355 378 config.InteractiveShell.separate_in = \
356 379 config.InteractiveShell.separate_out = \
357 380 config.InteractiveShell.separate_out2 = ''
358 381 config.InteractiveShell.colors = 'NoColor'
359 382 config.InteractiveShell.xmode = 'Plain'
360 383
361 384 if hasattr(config.Global, 'nosep'):
362 385 if config.Global.nosep:
363 386 config.InteractiveShell.separate_in = \
364 387 config.InteractiveShell.separate_out = \
365 388 config.InteractiveShell.separate_out2 = ''
366 389
367 390 # if there is code of files to run from the cmd line, don't interact
368 391 # unless the -i flag (Global.force_interact) is true.
369 392 code_to_run = config.Global.get('code_to_run','')
370 393 file_to_run = False
371 394 if len(self.extra_args)>=1:
372 395 if self.extra_args[0]:
373 396 file_to_run = True
374 397 if file_to_run or code_to_run:
375 398 if not config.Global.force_interact:
376 399 config.Global.interact = False
377 400
378 401 def construct(self):
379 402 # I am a little hesitant to put these into InteractiveShell itself.
380 403 # But that might be the place for them
381 404 sys.path.insert(0, '')
382 405
383 406 # Create an InteractiveShell instance
384 407 self.shell = InteractiveShell(
385 408 parent=None,
386 409 config=self.master_config
387 410 )
388 411
389 412 def post_construct(self):
390 413 """Do actions after construct, but before starting the app."""
391 414 config = self.master_config
392 415
393 416 # shell.display_banner should always be False for the terminal
394 417 # based app, because we call shell.show_banner() by hand below
395 418 # so the banner shows *before* all extension loading stuff.
396 419 self.shell.display_banner = False
397 420
398 421 if config.Global.display_banner and \
399 422 config.Global.interact:
400 423 self.shell.show_banner()
401 424
402 425 # Make sure there is a space below the banner.
403 426 if self.log_level <= logging.INFO: print
404 427
405 428 # Now a variety of things that happen after the banner is printed.
406 429 self._enable_gui_pylab()
407 430 self._load_extensions()
408 431 self._run_exec_lines()
409 432 self._run_exec_files()
410 433 self._run_cmd_line_code()
411 434 self._configure_xmode()
412 435
413 436 def _enable_gui_pylab(self):
414 437 """Enable GUI event loop integration, taking pylab into account."""
415 438 Global = self.master_config.Global
416 439
417 440 # Select which gui to use
418 if Global.wthread:
441 if Global.gui:
442 gui = Global.gui
443 # The following are deprecated, but there's likely to be a lot of use
444 # of this form out there, so we might as well support it for now. But
445 # the --gui option above takes precedence.
446 elif Global.wthread:
419 447 gui = inputhook.GUI_WX
420 elif Global.q4thread:
448 elif Global.qthread:
421 449 gui = inputhook.GUI_QT
422 450 elif Global.gthread:
423 451 gui = inputhook.GUI_GTK
424 452 else:
425 453 gui = None
426 454
455 # Using --pylab will also require gui activation, though which toolkit
456 # to use may be chosen automatically based on mpl configuration.
427 457 if Global.pylab:
428 458 activate = self.shell.enable_pylab
459 if Global.pylab == 'auto':
460 gui = None
461 else:
462 gui = Global.pylab
429 463 else:
430 464 # Enable only GUI integration, no pylab
431 465 activate = inputhook.enable_gui
432 466
433 467 if gui or Global.pylab:
434 468 try:
435 m = "Enabling GUI event loop integration, toolkit=%s, pylab=%s"\
436 % (gui, Global.pylab)
437 self.log.info(m)
469 self.log.info("Enabling GUI event loop integration, "
470 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
438 471 activate(gui)
439 472 except:
440 473 self.log.warn("Error in enabling GUI event loop integration:")
441 474 self.shell.showtraceback()
442 475
443
444 476 def _load_extensions(self):
445 477 """Load all IPython extensions in Global.extensions.
446 478
447 479 This uses the :meth:`InteractiveShell.load_extensions` to load all
448 480 the extensions listed in ``self.master_config.Global.extensions``.
449 481 """
450 482 try:
451 483 if hasattr(self.master_config.Global, 'extensions'):
452 484 self.log.debug("Loading IPython extensions...")
453 485 extensions = self.master_config.Global.extensions
454 486 for ext in extensions:
455 487 try:
456 488 self.log.info("Loading IPython extension: %s" % ext)
457 489 self.shell.load_extension(ext)
458 490 except:
459 491 self.log.warn("Error in loading extension: %s" % ext)
460 492 self.shell.showtraceback()
461 493 except:
462 494 self.log.warn("Unknown error in loading extensions:")
463 495 self.shell.showtraceback()
464 496
465 497 def _run_exec_lines(self):
466 498 """Run lines of code in Global.exec_lines in the user's namespace."""
467 499 try:
468 500 if hasattr(self.master_config.Global, 'exec_lines'):
469 501 self.log.debug("Running code from Global.exec_lines...")
470 502 exec_lines = self.master_config.Global.exec_lines
471 503 for line in exec_lines:
472 504 try:
473 505 self.log.info("Running code in user namespace: %s" % line)
474 506 self.shell.runlines(line)
475 507 except:
476 508 self.log.warn("Error in executing line in user namespace: %s" % line)
477 509 self.shell.showtraceback()
478 510 except:
479 511 self.log.warn("Unknown error in handling Global.exec_lines:")
480 512 self.shell.showtraceback()
481 513
482 514 def _exec_file(self, fname):
483 515 full_filename = filefind(fname, [u'.', self.ipython_dir])
484 516 if os.path.isfile(full_filename):
485 517 if full_filename.endswith(u'.py'):
486 518 self.log.info("Running file in user namespace: %s" % full_filename)
487 519 self.shell.safe_execfile(full_filename, self.shell.user_ns)
488 520 elif full_filename.endswith('.ipy'):
489 521 self.log.info("Running file in user namespace: %s" % full_filename)
490 522 self.shell.safe_execfile_ipy(full_filename)
491 523 else:
492 524 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
493 525
494 526 def _run_exec_files(self):
495 527 try:
496 528 if hasattr(self.master_config.Global, 'exec_files'):
497 529 self.log.debug("Running files in Global.exec_files...")
498 530 exec_files = self.master_config.Global.exec_files
499 531 for fname in exec_files:
500 532 self._exec_file(fname)
501 533 except:
502 534 self.log.warn("Unknown error in handling Global.exec_files:")
503 535 self.shell.showtraceback()
504 536
505 537 def _run_cmd_line_code(self):
506 538 if hasattr(self.master_config.Global, 'code_to_run'):
507 539 line = self.master_config.Global.code_to_run
508 540 try:
509 541 self.log.info("Running code given at command line (-c): %s" % line)
510 542 self.shell.runlines(line)
511 543 except:
512 544 self.log.warn("Error in executing line in user namespace: %s" % line)
513 545 self.shell.showtraceback()
514 546 return
515 547 # Like Python itself, ignore the second if the first of these is present
516 548 try:
517 549 fname = self.extra_args[0]
518 550 except:
519 551 pass
520 552 else:
521 553 try:
522 554 self._exec_file(fname)
523 555 except:
524 556 self.log.warn("Error in executing file in user namespace: %s" % fname)
525 557 self.shell.showtraceback()
526 558
527 559 def _configure_xmode(self):
528 560 # XXX - shouldn't this be read from the config? I'm still a little
529 561 # lost with all the details of handling the new config guys...
530 562 self.shell.InteractiveTB.set_mode(mode=self.shell.xmode)
531 563
532 564 def start_app(self):
533 565 if self.master_config.Global.interact:
534 566 self.log.debug("Starting IPython's mainloop...")
535 567 self.shell.mainloop()
536 568
537 569
538 570
539 571 def load_default_config(ipython_dir=None):
540 572 """Load the default config file from the default ipython_dir.
541 573
542 574 This is useful for embedded shells.
543 575 """
544 576 if ipython_dir is None:
545 577 ipython_dir = get_ipython_dir()
546 578 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
547 579 config = cl.load_config()
548 580 return config
549 581
550 582
551 583 def launch_new_instance():
552 584 """Create and run a full blown IPython instance"""
553 585 app = IPythonApp()
554 586 app.start()
555 587
@@ -1,2502 +1,2525 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Main IPython Component
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 9 # Copyright (C) 2008-2009 The IPython Development Team
10 10 #
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-----------------------------------------------------------------------------
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Imports
17 17 #-----------------------------------------------------------------------------
18 18
19 19 from __future__ import with_statement
20 20
21 21 import __builtin__
22 22 import StringIO
23 23 import bdb
24 24 import codeop
25 25 import exceptions
26 26 import new
27 27 import os
28 28 import re
29 29 import string
30 30 import sys
31 31 import tempfile
32 32 from contextlib import nested
33 33
34 34 from IPython.core import debugger, oinspect
35 35 from IPython.core import history as ipcorehist
36 36 from IPython.core import prefilter
37 37 from IPython.core import shadowns
38 38 from IPython.core import ultratb
39 39 from IPython.core.alias import AliasManager
40 40 from IPython.core.builtin_trap import BuiltinTrap
41 41 from IPython.core.component import Component
42 42 from IPython.core.display_trap import DisplayTrap
43 43 from IPython.core.error import TryNext, UsageError
44 44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
45 45 from IPython.core.logger import Logger
46 46 from IPython.core.magic import Magic
47 47 from IPython.core.prefilter import PrefilterManager
48 48 from IPython.core.prompts import CachedOutput
49 49 from IPython.core.pylabtools import pylab_activate
50 50 from IPython.core.usage import interactive_usage, default_banner
51 51 from IPython.external.Itpl import ItplNS
52 52 from IPython.lib.inputhook import enable_gui
53 53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 54 from IPython.utils import PyColorize
55 55 from IPython.utils import pickleshare
56 56 from IPython.utils.genutils import get_ipython_dir
57 57 from IPython.utils.ipstruct import Struct
58 58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
59 59 from IPython.utils.strdispatch import StrDispatch
60 60 from IPython.utils.syspathcontext import prepended_to_syspath
61 61
62 62 # XXX - need to clean up this import * line
63 63 from IPython.utils.genutils import *
64 64
65 65 # from IPython.utils import growl
66 66 # growl.start("IPython")
67 67
68 68 from IPython.utils.traitlets import (
69 69 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
70 70 )
71 71
72 72 #-----------------------------------------------------------------------------
73 73 # Globals
74 74 #-----------------------------------------------------------------------------
75 75
76 76 # store the builtin raw_input globally, and use this always, in case user code
77 77 # overwrites it (like wx.py.PyShell does)
78 78 raw_input_original = raw_input
79 79
80 80 # compiled regexps for autoindent management
81 81 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
82 82
83 83 #-----------------------------------------------------------------------------
84 84 # Utilities
85 85 #-----------------------------------------------------------------------------
86 86
87 87 ini_spaces_re = re.compile(r'^(\s+)')
88 88
89 89
90 90 def num_ini_spaces(strng):
91 91 """Return the number of initial spaces in a string"""
92 92
93 93 ini_spaces = ini_spaces_re.match(strng)
94 94 if ini_spaces:
95 95 return ini_spaces.end()
96 96 else:
97 97 return 0
98 98
99 99
100 100 def softspace(file, newvalue):
101 101 """Copied from code.py, to remove the dependency"""
102 102
103 103 oldvalue = 0
104 104 try:
105 105 oldvalue = file.softspace
106 106 except AttributeError:
107 107 pass
108 108 try:
109 109 file.softspace = newvalue
110 110 except (AttributeError, TypeError):
111 111 # "attribute-less object" or "read-only attributes"
112 112 pass
113 113 return oldvalue
114 114
115 115
116 116 def no_op(*a, **kw): pass
117 117
118 118 class SpaceInInput(exceptions.Exception): pass
119 119
120 120 class Bunch: pass
121 121
122 122 class InputList(list):
123 123 """Class to store user input.
124 124
125 125 It's basically a list, but slices return a string instead of a list, thus
126 126 allowing things like (assuming 'In' is an instance):
127 127
128 128 exec In[4:7]
129 129
130 130 or
131 131
132 132 exec In[5:9] + In[14] + In[21:25]"""
133 133
134 134 def __getslice__(self,i,j):
135 135 return ''.join(list.__getslice__(self,i,j))
136 136
137 137
138 138 class SyntaxTB(ultratb.ListTB):
139 139 """Extension which holds some state: the last exception value"""
140 140
141 141 def __init__(self,color_scheme = 'NoColor'):
142 142 ultratb.ListTB.__init__(self,color_scheme)
143 143 self.last_syntax_error = None
144 144
145 145 def __call__(self, etype, value, elist):
146 146 self.last_syntax_error = value
147 147 ultratb.ListTB.__call__(self,etype,value,elist)
148 148
149 149 def clear_err_state(self):
150 150 """Return the current error state and clear it"""
151 151 e = self.last_syntax_error
152 152 self.last_syntax_error = None
153 153 return e
154 154
155 155
156 156 def get_default_editor():
157 157 try:
158 158 ed = os.environ['EDITOR']
159 159 except KeyError:
160 160 if os.name == 'posix':
161 161 ed = 'vi' # the only one guaranteed to be there!
162 162 else:
163 163 ed = 'notepad' # same in Windows!
164 164 return ed
165 165
166 166
167 167 def get_default_colors():
168 168 if sys.platform=='darwin':
169 169 return "LightBG"
170 170 elif os.name=='nt':
171 171 return 'Linux'
172 172 else:
173 173 return 'Linux'
174 174
175 175
176 176 class SeparateStr(Str):
177 177 """A Str subclass to validate separate_in, separate_out, etc.
178 178
179 179 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
180 180 """
181 181
182 182 def validate(self, obj, value):
183 183 if value == '0': value = ''
184 184 value = value.replace('\\n','\n')
185 185 return super(SeparateStr, self).validate(obj, value)
186 186
187 187
188 188 #-----------------------------------------------------------------------------
189 189 # Main IPython class
190 190 #-----------------------------------------------------------------------------
191 191
192 192
193 193 class InteractiveShell(Component, Magic):
194 194 """An enhanced, interactive shell for Python."""
195 195
196 196 autocall = Enum((0,1,2), default_value=1, config=True)
197 197 autoedit_syntax = CBool(False, config=True)
198 198 autoindent = CBool(True, config=True)
199 199 automagic = CBool(True, config=True)
200 200 banner = Str('')
201 201 banner1 = Str(default_banner, config=True)
202 202 banner2 = Str('', config=True)
203 203 cache_size = Int(1000, config=True)
204 204 color_info = CBool(True, config=True)
205 205 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
206 206 default_value=get_default_colors(), config=True)
207 207 confirm_exit = CBool(True, config=True)
208 208 debug = CBool(False, config=True)
209 209 deep_reload = CBool(False, config=True)
210 210 # This display_banner only controls whether or not self.show_banner()
211 211 # is called when mainloop/interact are called. The default is False
212 212 # because for the terminal based application, the banner behavior
213 213 # is controlled by Global.display_banner, which IPythonApp looks at
214 214 # to determine if *it* should call show_banner() by hand or not.
215 215 display_banner = CBool(False) # This isn't configurable!
216 216 embedded = CBool(False)
217 217 embedded_active = CBool(False)
218 218 editor = Str(get_default_editor(), config=True)
219 219 filename = Str("<ipython console>")
220 220 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
221 221 logstart = CBool(False, config=True)
222 222 logfile = Str('', config=True)
223 223 logappend = Str('', config=True)
224 224 object_info_string_level = Enum((0,1,2), default_value=0,
225 225 config=True)
226 226 pager = Str('less', config=True)
227 227 pdb = CBool(False, config=True)
228 228 pprint = CBool(True, config=True)
229 229 profile = Str('', config=True)
230 230 prompt_in1 = Str('In [\\#]: ', config=True)
231 231 prompt_in2 = Str(' .\\D.: ', config=True)
232 232 prompt_out = Str('Out[\\#]: ', config=True)
233 233 prompts_pad_left = CBool(True, config=True)
234 234 quiet = CBool(False, config=True)
235 235
236 236 readline_use = CBool(True, config=True)
237 237 readline_merge_completions = CBool(True, config=True)
238 238 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
239 239 readline_remove_delims = Str('-/~', config=True)
240 240 readline_parse_and_bind = List([
241 241 'tab: complete',
242 242 '"\C-l": possible-completions',
243 243 'set show-all-if-ambiguous on',
244 244 '"\C-o": tab-insert',
245 245 '"\M-i": " "',
246 246 '"\M-o": "\d\d\d\d"',
247 247 '"\M-I": "\d\d\d\d"',
248 248 '"\C-r": reverse-search-history',
249 249 '"\C-s": forward-search-history',
250 250 '"\C-p": history-search-backward',
251 251 '"\C-n": history-search-forward',
252 252 '"\e[A": history-search-backward',
253 253 '"\e[B": history-search-forward',
254 254 '"\C-k": kill-line',
255 255 '"\C-u": unix-line-discard',
256 256 ], allow_none=False, config=True)
257 257
258 258 screen_length = Int(0, config=True)
259 259
260 260 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
261 261 separate_in = SeparateStr('\n', config=True)
262 262 separate_out = SeparateStr('', config=True)
263 263 separate_out2 = SeparateStr('', config=True)
264 264
265 265 system_header = Str('IPython system call: ', config=True)
266 266 system_verbose = CBool(False, config=True)
267 267 term_title = CBool(False, config=True)
268 268 wildcards_case_sensitive = CBool(True, config=True)
269 269 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
270 270 default_value='Context', config=True)
271 271
272 272 autoexec = List(allow_none=False)
273 273
274 274 # class attribute to indicate whether the class supports threads or not.
275 275 # Subclasses with thread support should override this as needed.
276 276 isthreaded = False
277 277
278 278 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
279 279 user_ns=None, user_global_ns=None,
280 280 banner1=None, banner2=None, display_banner=None,
281 281 custom_exceptions=((),None)):
282 282
283 283 # This is where traitlets with a config_key argument are updated
284 284 # from the values on config.
285 285 super(InteractiveShell, self).__init__(parent, config=config)
286 286
287 287 # These are relatively independent and stateless
288 288 self.init_ipython_dir(ipython_dir)
289 289 self.init_instance_attrs()
290 290 self.init_term_title()
291 291 self.init_usage(usage)
292 292 self.init_banner(banner1, banner2, display_banner)
293 293
294 294 # Create namespaces (user_ns, user_global_ns, etc.)
295 295 self.init_create_namespaces(user_ns, user_global_ns)
296 296 # This has to be done after init_create_namespaces because it uses
297 297 # something in self.user_ns, but before init_sys_modules, which
298 298 # is the first thing to modify sys.
299 299 self.save_sys_module_state()
300 300 self.init_sys_modules()
301 301
302 302 self.init_history()
303 303 self.init_encoding()
304 304 self.init_prefilter()
305 305
306 306 Magic.__init__(self, self)
307 307
308 308 self.init_syntax_highlighting()
309 309 self.init_hooks()
310 310 self.init_pushd_popd_magic()
311 311 self.init_traceback_handlers(custom_exceptions)
312 312 self.init_user_ns()
313 313 self.init_logger()
314 314 self.init_alias()
315 315 self.init_builtins()
316 316
317 317 # pre_config_initialization
318 318 self.init_shadow_hist()
319 319
320 320 # The next section should contain averything that was in ipmaker.
321 321 self.init_logstart()
322 322
323 323 # The following was in post_config_initialization
324 324 self.init_inspector()
325 325 self.init_readline()
326 326 self.init_prompts()
327 327 self.init_displayhook()
328 328 self.init_reload_doctest()
329 329 self.init_magics()
330 330 self.init_pdb()
331 331 self.hooks.late_startup_hook()
332 332
333 333 def get_ipython(self):
334 334 return self
335 335
336 336 #-------------------------------------------------------------------------
337 337 # Traitlet changed handlers
338 338 #-------------------------------------------------------------------------
339 339
340 340 def _banner1_changed(self):
341 341 self.compute_banner()
342 342
343 343 def _banner2_changed(self):
344 344 self.compute_banner()
345 345
346 346 def _ipython_dir_changed(self, name, new):
347 347 if not os.path.isdir(new):
348 348 os.makedirs(new, mode = 0777)
349 349 if not os.path.isdir(self.ipython_extension_dir):
350 350 os.makedirs(self.ipython_extension_dir, mode = 0777)
351 351
352 352 @property
353 353 def ipython_extension_dir(self):
354 354 return os.path.join(self.ipython_dir, 'extensions')
355 355
356 356 @property
357 357 def usable_screen_length(self):
358 358 if self.screen_length == 0:
359 359 return 0
360 360 else:
361 361 num_lines_bot = self.separate_in.count('\n')+1
362 362 return self.screen_length - num_lines_bot
363 363
364 364 def _term_title_changed(self, name, new_value):
365 365 self.init_term_title()
366 366
367 367 def set_autoindent(self,value=None):
368 368 """Set the autoindent flag, checking for readline support.
369 369
370 370 If called with no arguments, it acts as a toggle."""
371 371
372 372 if not self.has_readline:
373 373 if os.name == 'posix':
374 374 warn("The auto-indent feature requires the readline library")
375 375 self.autoindent = 0
376 376 return
377 377 if value is None:
378 378 self.autoindent = not self.autoindent
379 379 else:
380 380 self.autoindent = value
381 381
382 382 #-------------------------------------------------------------------------
383 383 # init_* methods called by __init__
384 384 #-------------------------------------------------------------------------
385 385
386 386 def init_ipython_dir(self, ipython_dir):
387 387 if ipython_dir is not None:
388 388 self.ipython_dir = ipython_dir
389 389 self.config.Global.ipython_dir = self.ipython_dir
390 390 return
391 391
392 392 if hasattr(self.config.Global, 'ipython_dir'):
393 393 self.ipython_dir = self.config.Global.ipython_dir
394 394 else:
395 395 self.ipython_dir = get_ipython_dir()
396 396
397 397 # All children can just read this
398 398 self.config.Global.ipython_dir = self.ipython_dir
399 399
400 400 def init_instance_attrs(self):
401 401 self.jobs = BackgroundJobManager()
402 402 self.more = False
403 403
404 404 # command compiler
405 405 self.compile = codeop.CommandCompiler()
406 406
407 407 # User input buffer
408 408 self.buffer = []
409 409
410 410 # Make an empty namespace, which extension writers can rely on both
411 411 # existing and NEVER being used by ipython itself. This gives them a
412 412 # convenient location for storing additional information and state
413 413 # their extensions may require, without fear of collisions with other
414 414 # ipython names that may develop later.
415 415 self.meta = Struct()
416 416
417 417 # Object variable to store code object waiting execution. This is
418 418 # used mainly by the multithreaded shells, but it can come in handy in
419 419 # other situations. No need to use a Queue here, since it's a single
420 420 # item which gets cleared once run.
421 421 self.code_to_run = None
422 422
423 423 # Flag to mark unconditional exit
424 424 self.exit_now = False
425 425
426 426 # Temporary files used for various purposes. Deleted at exit.
427 427 self.tempfiles = []
428 428
429 429 # Keep track of readline usage (later set by init_readline)
430 430 self.has_readline = False
431 431
432 432 # keep track of where we started running (mainly for crash post-mortem)
433 433 # This is not being used anywhere currently.
434 434 self.starting_dir = os.getcwd()
435 435
436 436 # Indentation management
437 437 self.indent_current_nsp = 0
438 438
439 439 def init_term_title(self):
440 440 # Enable or disable the terminal title.
441 441 if self.term_title:
442 442 toggle_set_term_title(True)
443 443 set_term_title('IPython: ' + abbrev_cwd())
444 444 else:
445 445 toggle_set_term_title(False)
446 446
447 447 def init_usage(self, usage=None):
448 448 if usage is None:
449 449 self.usage = interactive_usage
450 450 else:
451 451 self.usage = usage
452 452
453 453 def init_encoding(self):
454 454 # Get system encoding at startup time. Certain terminals (like Emacs
455 455 # under Win32 have it set to None, and we need to have a known valid
456 456 # encoding to use in the raw_input() method
457 457 try:
458 458 self.stdin_encoding = sys.stdin.encoding or 'ascii'
459 459 except AttributeError:
460 460 self.stdin_encoding = 'ascii'
461 461
462 462 def init_syntax_highlighting(self):
463 463 # Python source parser/formatter for syntax highlighting
464 464 pyformat = PyColorize.Parser().format
465 465 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
466 466
467 467 def init_pushd_popd_magic(self):
468 468 # for pushd/popd management
469 469 try:
470 470 self.home_dir = get_home_dir()
471 471 except HomeDirError, msg:
472 472 fatal(msg)
473 473
474 474 self.dir_stack = []
475 475
476 476 def init_logger(self):
477 477 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
478 478 # local shortcut, this is used a LOT
479 479 self.log = self.logger.log
480 480
481 481 def init_logstart(self):
482 482 if self.logappend:
483 483 self.magic_logstart(self.logappend + ' append')
484 484 elif self.logfile:
485 485 self.magic_logstart(self.logfile)
486 486 elif self.logstart:
487 487 self.magic_logstart()
488 488
489 489 def init_builtins(self):
490 490 self.builtin_trap = BuiltinTrap(self)
491 491
492 492 def init_inspector(self):
493 493 # Object inspector
494 494 self.inspector = oinspect.Inspector(oinspect.InspectColors,
495 495 PyColorize.ANSICodeColors,
496 496 'NoColor',
497 497 self.object_info_string_level)
498 498
499 499 def init_prompts(self):
500 500 # Initialize cache, set in/out prompts and printing system
501 501 self.outputcache = CachedOutput(self,
502 502 self.cache_size,
503 503 self.pprint,
504 504 input_sep = self.separate_in,
505 505 output_sep = self.separate_out,
506 506 output_sep2 = self.separate_out2,
507 507 ps1 = self.prompt_in1,
508 508 ps2 = self.prompt_in2,
509 509 ps_out = self.prompt_out,
510 510 pad_left = self.prompts_pad_left)
511 511
512 512 # user may have over-ridden the default print hook:
513 513 try:
514 514 self.outputcache.__class__.display = self.hooks.display
515 515 except AttributeError:
516 516 pass
517 517
518 518 def init_displayhook(self):
519 519 self.display_trap = DisplayTrap(self, self.outputcache)
520 520
521 521 def init_reload_doctest(self):
522 522 # Do a proper resetting of doctest, including the necessary displayhook
523 523 # monkeypatching
524 524 try:
525 525 doctest_reload()
526 526 except ImportError:
527 527 warn("doctest module does not exist.")
528 528
529 529 #-------------------------------------------------------------------------
530 530 # Things related to the banner
531 531 #-------------------------------------------------------------------------
532 532
533 533 def init_banner(self, banner1, banner2, display_banner):
534 534 if banner1 is not None:
535 535 self.banner1 = banner1
536 536 if banner2 is not None:
537 537 self.banner2 = banner2
538 538 if display_banner is not None:
539 539 self.display_banner = display_banner
540 540 self.compute_banner()
541 541
542 542 def show_banner(self, banner=None):
543 543 if banner is None:
544 544 banner = self.banner
545 545 self.write(banner)
546 546
547 547 def compute_banner(self):
548 548 self.banner = self.banner1 + '\n'
549 549 if self.profile:
550 550 self.banner += '\nIPython profile: %s\n' % self.profile
551 551 if self.banner2:
552 552 self.banner += '\n' + self.banner2 + '\n'
553 553
554 554 #-------------------------------------------------------------------------
555 555 # Things related to injections into the sys module
556 556 #-------------------------------------------------------------------------
557 557
558 558 def save_sys_module_state(self):
559 559 """Save the state of hooks in the sys module.
560 560
561 561 This has to be called after self.user_ns is created.
562 562 """
563 563 self._orig_sys_module_state = {}
564 564 self._orig_sys_module_state['stdin'] = sys.stdin
565 565 self._orig_sys_module_state['stdout'] = sys.stdout
566 566 self._orig_sys_module_state['stderr'] = sys.stderr
567 567 self._orig_sys_module_state['excepthook'] = sys.excepthook
568 568 try:
569 569 self._orig_sys_modules_main_name = self.user_ns['__name__']
570 570 except KeyError:
571 571 pass
572 572
573 573 def restore_sys_module_state(self):
574 574 """Restore the state of the sys module."""
575 575 try:
576 576 for k, v in self._orig_sys_module_state.items():
577 577 setattr(sys, k, v)
578 578 except AttributeError:
579 579 pass
580 580 try:
581 581 delattr(sys, 'ipcompleter')
582 582 except AttributeError:
583 583 pass
584 584 # Reset what what done in self.init_sys_modules
585 585 try:
586 586 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
587 587 except (AttributeError, KeyError):
588 588 pass
589 589
590 590 #-------------------------------------------------------------------------
591 591 # Things related to hooks
592 592 #-------------------------------------------------------------------------
593 593
594 594 def init_hooks(self):
595 595 # hooks holds pointers used for user-side customizations
596 596 self.hooks = Struct()
597 597
598 598 self.strdispatchers = {}
599 599
600 600 # Set all default hooks, defined in the IPython.hooks module.
601 601 import IPython.core.hooks
602 602 hooks = IPython.core.hooks
603 603 for hook_name in hooks.__all__:
604 604 # default hooks have priority 100, i.e. low; user hooks should have
605 605 # 0-100 priority
606 606 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
607 607
608 608 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
609 609 """set_hook(name,hook) -> sets an internal IPython hook.
610 610
611 611 IPython exposes some of its internal API as user-modifiable hooks. By
612 612 adding your function to one of these hooks, you can modify IPython's
613 613 behavior to call at runtime your own routines."""
614 614
615 615 # At some point in the future, this should validate the hook before it
616 616 # accepts it. Probably at least check that the hook takes the number
617 617 # of args it's supposed to.
618 618
619 619 f = new.instancemethod(hook,self,self.__class__)
620 620
621 621 # check if the hook is for strdispatcher first
622 622 if str_key is not None:
623 623 sdp = self.strdispatchers.get(name, StrDispatch())
624 624 sdp.add_s(str_key, f, priority )
625 625 self.strdispatchers[name] = sdp
626 626 return
627 627 if re_key is not None:
628 628 sdp = self.strdispatchers.get(name, StrDispatch())
629 629 sdp.add_re(re.compile(re_key), f, priority )
630 630 self.strdispatchers[name] = sdp
631 631 return
632 632
633 633 dp = getattr(self.hooks, name, None)
634 634 if name not in IPython.core.hooks.__all__:
635 635 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
636 636 if not dp:
637 637 dp = IPython.core.hooks.CommandChainDispatcher()
638 638
639 639 try:
640 640 dp.add(f,priority)
641 641 except AttributeError:
642 642 # it was not commandchain, plain old func - replace
643 643 dp = f
644 644
645 645 setattr(self.hooks,name, dp)
646 646
647 647 #-------------------------------------------------------------------------
648 648 # Things related to the "main" module
649 649 #-------------------------------------------------------------------------
650 650
651 651 def new_main_mod(self,ns=None):
652 652 """Return a new 'main' module object for user code execution.
653 653 """
654 654 main_mod = self._user_main_module
655 655 init_fakemod_dict(main_mod,ns)
656 656 return main_mod
657 657
658 658 def cache_main_mod(self,ns,fname):
659 659 """Cache a main module's namespace.
660 660
661 661 When scripts are executed via %run, we must keep a reference to the
662 662 namespace of their __main__ module (a FakeModule instance) around so
663 663 that Python doesn't clear it, rendering objects defined therein
664 664 useless.
665 665
666 666 This method keeps said reference in a private dict, keyed by the
667 667 absolute path of the module object (which corresponds to the script
668 668 path). This way, for multiple executions of the same script we only
669 669 keep one copy of the namespace (the last one), thus preventing memory
670 670 leaks from old references while allowing the objects from the last
671 671 execution to be accessible.
672 672
673 673 Note: we can not allow the actual FakeModule instances to be deleted,
674 674 because of how Python tears down modules (it hard-sets all their
675 675 references to None without regard for reference counts). This method
676 676 must therefore make a *copy* of the given namespace, to allow the
677 677 original module's __dict__ to be cleared and reused.
678 678
679 679
680 680 Parameters
681 681 ----------
682 682 ns : a namespace (a dict, typically)
683 683
684 684 fname : str
685 685 Filename associated with the namespace.
686 686
687 687 Examples
688 688 --------
689 689
690 690 In [10]: import IPython
691 691
692 692 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
693 693
694 694 In [12]: IPython.__file__ in _ip._main_ns_cache
695 695 Out[12]: True
696 696 """
697 697 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
698 698
699 699 def clear_main_mod_cache(self):
700 700 """Clear the cache of main modules.
701 701
702 702 Mainly for use by utilities like %reset.
703 703
704 704 Examples
705 705 --------
706 706
707 707 In [15]: import IPython
708 708
709 709 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
710 710
711 711 In [17]: len(_ip._main_ns_cache) > 0
712 712 Out[17]: True
713 713
714 714 In [18]: _ip.clear_main_mod_cache()
715 715
716 716 In [19]: len(_ip._main_ns_cache) == 0
717 717 Out[19]: True
718 718 """
719 719 self._main_ns_cache.clear()
720 720
721 721 #-------------------------------------------------------------------------
722 722 # Things related to debugging
723 723 #-------------------------------------------------------------------------
724 724
725 725 def init_pdb(self):
726 726 # Set calling of pdb on exceptions
727 727 # self.call_pdb is a property
728 728 self.call_pdb = self.pdb
729 729
730 730 def _get_call_pdb(self):
731 731 return self._call_pdb
732 732
733 733 def _set_call_pdb(self,val):
734 734
735 735 if val not in (0,1,False,True):
736 736 raise ValueError,'new call_pdb value must be boolean'
737 737
738 738 # store value in instance
739 739 self._call_pdb = val
740 740
741 741 # notify the actual exception handlers
742 742 self.InteractiveTB.call_pdb = val
743 743 if self.isthreaded:
744 744 try:
745 745 self.sys_excepthook.call_pdb = val
746 746 except:
747 747 warn('Failed to activate pdb for threaded exception handler')
748 748
749 749 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
750 750 'Control auto-activation of pdb at exceptions')
751 751
752 752 def debugger(self,force=False):
753 753 """Call the pydb/pdb debugger.
754 754
755 755 Keywords:
756 756
757 757 - force(False): by default, this routine checks the instance call_pdb
758 758 flag and does not actually invoke the debugger if the flag is false.
759 759 The 'force' option forces the debugger to activate even if the flag
760 760 is false.
761 761 """
762 762
763 763 if not (force or self.call_pdb):
764 764 return
765 765
766 766 if not hasattr(sys,'last_traceback'):
767 767 error('No traceback has been produced, nothing to debug.')
768 768 return
769 769
770 770 # use pydb if available
771 771 if debugger.has_pydb:
772 772 from pydb import pm
773 773 else:
774 774 # fallback to our internal debugger
775 775 pm = lambda : self.InteractiveTB.debugger(force=True)
776 776 self.history_saving_wrapper(pm)()
777 777
778 778 #-------------------------------------------------------------------------
779 779 # Things related to IPython's various namespaces
780 780 #-------------------------------------------------------------------------
781 781
782 782 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
783 783 # Create the namespace where the user will operate. user_ns is
784 784 # normally the only one used, and it is passed to the exec calls as
785 785 # the locals argument. But we do carry a user_global_ns namespace
786 786 # given as the exec 'globals' argument, This is useful in embedding
787 787 # situations where the ipython shell opens in a context where the
788 788 # distinction between locals and globals is meaningful. For
789 789 # non-embedded contexts, it is just the same object as the user_ns dict.
790 790
791 791 # FIXME. For some strange reason, __builtins__ is showing up at user
792 792 # level as a dict instead of a module. This is a manual fix, but I
793 793 # should really track down where the problem is coming from. Alex
794 794 # Schmolck reported this problem first.
795 795
796 796 # A useful post by Alex Martelli on this topic:
797 797 # Re: inconsistent value from __builtins__
798 798 # Von: Alex Martelli <aleaxit@yahoo.com>
799 799 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
800 800 # Gruppen: comp.lang.python
801 801
802 802 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
803 803 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
804 804 # > <type 'dict'>
805 805 # > >>> print type(__builtins__)
806 806 # > <type 'module'>
807 807 # > Is this difference in return value intentional?
808 808
809 809 # Well, it's documented that '__builtins__' can be either a dictionary
810 810 # or a module, and it's been that way for a long time. Whether it's
811 811 # intentional (or sensible), I don't know. In any case, the idea is
812 812 # that if you need to access the built-in namespace directly, you
813 813 # should start with "import __builtin__" (note, no 's') which will
814 814 # definitely give you a module. Yeah, it's somewhat confusing:-(.
815 815
816 816 # These routines return properly built dicts as needed by the rest of
817 817 # the code, and can also be used by extension writers to generate
818 818 # properly initialized namespaces.
819 819 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
820 820 user_global_ns)
821 821
822 822 # Assign namespaces
823 823 # This is the namespace where all normal user variables live
824 824 self.user_ns = user_ns
825 825 self.user_global_ns = user_global_ns
826 826
827 827 # An auxiliary namespace that checks what parts of the user_ns were
828 828 # loaded at startup, so we can list later only variables defined in
829 829 # actual interactive use. Since it is always a subset of user_ns, it
830 # doesn't need to be seaparately tracked in the ns_table
830 # doesn't need to be separately tracked in the ns_table.
831 831 self.user_config_ns = {}
832 832
833 833 # A namespace to keep track of internal data structures to prevent
834 834 # them from cluttering user-visible stuff. Will be updated later
835 835 self.internal_ns = {}
836 836
837 837 # Now that FakeModule produces a real module, we've run into a nasty
838 838 # problem: after script execution (via %run), the module where the user
839 839 # code ran is deleted. Now that this object is a true module (needed
840 840 # so docetst and other tools work correctly), the Python module
841 841 # teardown mechanism runs over it, and sets to None every variable
842 842 # present in that module. Top-level references to objects from the
843 843 # script survive, because the user_ns is updated with them. However,
844 844 # calling functions defined in the script that use other things from
845 845 # the script will fail, because the function's closure had references
846 846 # to the original objects, which are now all None. So we must protect
847 847 # these modules from deletion by keeping a cache.
848 848 #
849 849 # To avoid keeping stale modules around (we only need the one from the
850 850 # last run), we use a dict keyed with the full path to the script, so
851 851 # only the last version of the module is held in the cache. Note,
852 852 # however, that we must cache the module *namespace contents* (their
853 853 # __dict__). Because if we try to cache the actual modules, old ones
854 854 # (uncached) could be destroyed while still holding references (such as
855 855 # those held by GUI objects that tend to be long-lived)>
856 856 #
857 857 # The %reset command will flush this cache. See the cache_main_mod()
858 858 # and clear_main_mod_cache() methods for details on use.
859 859
860 860 # This is the cache used for 'main' namespaces
861 861 self._main_ns_cache = {}
862 862 # And this is the single instance of FakeModule whose __dict__ we keep
863 863 # copying and clearing for reuse on each %run
864 864 self._user_main_module = FakeModule()
865 865
866 866 # A table holding all the namespaces IPython deals with, so that
867 867 # introspection facilities can search easily.
868 868 self.ns_table = {'user':user_ns,
869 869 'user_global':user_global_ns,
870 870 'internal':self.internal_ns,
871 871 'builtin':__builtin__.__dict__
872 872 }
873 873
874 874 # Similarly, track all namespaces where references can be held and that
875 875 # we can safely clear (so it can NOT include builtin). This one can be
876 876 # a simple list.
877 877 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
878 878 self.internal_ns, self._main_ns_cache ]
879 879
880 880 def init_sys_modules(self):
881 881 # We need to insert into sys.modules something that looks like a
882 882 # module but which accesses the IPython namespace, for shelve and
883 883 # pickle to work interactively. Normally they rely on getting
884 884 # everything out of __main__, but for embedding purposes each IPython
885 885 # instance has its own private namespace, so we can't go shoving
886 886 # everything into __main__.
887 887
888 888 # note, however, that we should only do this for non-embedded
889 889 # ipythons, which really mimic the __main__.__dict__ with their own
890 890 # namespace. Embedded instances, on the other hand, should not do
891 891 # this because they need to manage the user local/global namespaces
892 892 # only, but they live within a 'normal' __main__ (meaning, they
893 893 # shouldn't overtake the execution environment of the script they're
894 894 # embedded in).
895 895
896 896 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
897 897
898 898 try:
899 899 main_name = self.user_ns['__name__']
900 900 except KeyError:
901 901 raise KeyError('user_ns dictionary MUST have a "__name__" key')
902 902 else:
903 903 sys.modules[main_name] = FakeModule(self.user_ns)
904 904
905 905 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
906 906 """Return a valid local and global user interactive namespaces.
907 907
908 908 This builds a dict with the minimal information needed to operate as a
909 909 valid IPython user namespace, which you can pass to the various
910 910 embedding classes in ipython. The default implementation returns the
911 911 same dict for both the locals and the globals to allow functions to
912 912 refer to variables in the namespace. Customized implementations can
913 913 return different dicts. The locals dictionary can actually be anything
914 914 following the basic mapping protocol of a dict, but the globals dict
915 915 must be a true dict, not even a subclass. It is recommended that any
916 916 custom object for the locals namespace synchronize with the globals
917 917 dict somehow.
918 918
919 919 Raises TypeError if the provided globals namespace is not a true dict.
920 920
921 921 :Parameters:
922 922 user_ns : dict-like, optional
923 923 The current user namespace. The items in this namespace should
924 924 be included in the output. If None, an appropriate blank
925 925 namespace should be created.
926 926 user_global_ns : dict, optional
927 927 The current user global namespace. The items in this namespace
928 928 should be included in the output. If None, an appropriate
929 929 blank namespace should be created.
930 930
931 931 :Returns:
932 932 A tuple pair of dictionary-like object to be used as the local namespace
933 933 of the interpreter and a dict to be used as the global namespace.
934 934 """
935 935
936 936 if user_ns is None:
937 937 # Set __name__ to __main__ to better match the behavior of the
938 938 # normal interpreter.
939 939 user_ns = {'__name__' :'__main__',
940 940 '__builtins__' : __builtin__,
941 941 }
942 942 else:
943 943 user_ns.setdefault('__name__','__main__')
944 944 user_ns.setdefault('__builtins__',__builtin__)
945 945
946 946 if user_global_ns is None:
947 947 user_global_ns = user_ns
948 948 if type(user_global_ns) is not dict:
949 949 raise TypeError("user_global_ns must be a true dict; got %r"
950 950 % type(user_global_ns))
951 951
952 952 return user_ns, user_global_ns
953 953
954 954 def init_user_ns(self):
955 955 """Initialize all user-visible namespaces to their minimum defaults.
956 956
957 957 Certain history lists are also initialized here, as they effectively
958 958 act as user namespaces.
959 959
960 960 Notes
961 961 -----
962 962 All data structures here are only filled in, they are NOT reset by this
963 963 method. If they were not empty before, data will simply be added to
964 964 therm.
965 965 """
966 966 # Store myself as the public api!!!
967 967 self.user_ns['get_ipython'] = self.get_ipython
968 968
969 969 # make global variables for user access to the histories
970 970 self.user_ns['_ih'] = self.input_hist
971 971 self.user_ns['_oh'] = self.output_hist
972 972 self.user_ns['_dh'] = self.dir_hist
973 973
974 974 # user aliases to input and output histories
975 975 self.user_ns['In'] = self.input_hist
976 976 self.user_ns['Out'] = self.output_hist
977 977
978 978 self.user_ns['_sh'] = shadowns
979 979
980 980 # Put 'help' in the user namespace
981 981 try:
982 982 from site import _Helper
983 983 self.user_ns['help'] = _Helper()
984 984 except ImportError:
985 985 warn('help() not available - check site.py')
986 986
987 987 def reset(self):
988 988 """Clear all internal namespaces.
989 989
990 990 Note that this is much more aggressive than %reset, since it clears
991 991 fully all namespaces, as well as all input/output lists.
992 992 """
993 993 for ns in self.ns_refs_table:
994 994 ns.clear()
995 995
996 996 self.alias_manager.clear_aliases()
997 997
998 998 # Clear input and output histories
999 999 self.input_hist[:] = []
1000 1000 self.input_hist_raw[:] = []
1001 1001 self.output_hist.clear()
1002 1002
1003 1003 # Restore the user namespaces to minimal usability
1004 1004 self.init_user_ns()
1005 1005
1006 1006 # Restore the default and user aliases
1007 1007 self.alias_manager.init_aliases()
1008 1008
1009 1009 def push(self, variables, interactive=True):
1010 1010 """Inject a group of variables into the IPython user namespace.
1011 1011
1012 1012 Parameters
1013 1013 ----------
1014 1014 variables : dict, str or list/tuple of str
1015 1015 The variables to inject into the user's namespace. If a dict,
1016 1016 a simple update is done. If a str, the string is assumed to
1017 1017 have variable names separated by spaces. A list/tuple of str
1018 1018 can also be used to give the variable names. If just the variable
1019 1019 names are give (list/tuple/str) then the variable values looked
1020 1020 up in the callers frame.
1021 1021 interactive : bool
1022 1022 If True (default), the variables will be listed with the ``who``
1023 1023 magic.
1024 1024 """
1025 1025 vdict = None
1026 1026
1027 1027 # We need a dict of name/value pairs to do namespace updates.
1028 1028 if isinstance(variables, dict):
1029 1029 vdict = variables
1030 1030 elif isinstance(variables, (basestring, list, tuple)):
1031 1031 if isinstance(variables, basestring):
1032 1032 vlist = variables.split()
1033 1033 else:
1034 1034 vlist = variables
1035 1035 vdict = {}
1036 1036 cf = sys._getframe(1)
1037 1037 for name in vlist:
1038 1038 try:
1039 1039 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1040 1040 except:
1041 1041 print ('Could not get variable %s from %s' %
1042 1042 (name,cf.f_code.co_name))
1043 1043 else:
1044 1044 raise ValueError('variables must be a dict/str/list/tuple')
1045 1045
1046 1046 # Propagate variables to user namespace
1047 1047 self.user_ns.update(vdict)
1048 1048
1049 1049 # And configure interactive visibility
1050 1050 config_ns = self.user_config_ns
1051 1051 if interactive:
1052 1052 for name, val in vdict.iteritems():
1053 1053 config_ns.pop(name, None)
1054 1054 else:
1055 1055 for name,val in vdict.iteritems():
1056 1056 config_ns[name] = val
1057 1057
1058 1058 #-------------------------------------------------------------------------
1059 1059 # Things related to history management
1060 1060 #-------------------------------------------------------------------------
1061 1061
1062 1062 def init_history(self):
1063 1063 # List of input with multi-line handling.
1064 1064 self.input_hist = InputList()
1065 1065 # This one will hold the 'raw' input history, without any
1066 1066 # pre-processing. This will allow users to retrieve the input just as
1067 1067 # it was exactly typed in by the user, with %hist -r.
1068 1068 self.input_hist_raw = InputList()
1069 1069
1070 1070 # list of visited directories
1071 1071 try:
1072 1072 self.dir_hist = [os.getcwd()]
1073 1073 except OSError:
1074 1074 self.dir_hist = []
1075 1075
1076 1076 # dict of output history
1077 1077 self.output_hist = {}
1078 1078
1079 1079 # Now the history file
1080 1080 if self.profile:
1081 1081 histfname = 'history-%s' % self.profile
1082 1082 else:
1083 1083 histfname = 'history'
1084 1084 self.histfile = os.path.join(self.ipython_dir, histfname)
1085 1085
1086 1086 # Fill the history zero entry, user counter starts at 1
1087 1087 self.input_hist.append('\n')
1088 1088 self.input_hist_raw.append('\n')
1089 1089
1090 1090 def init_shadow_hist(self):
1091 1091 try:
1092 1092 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1093 1093 except exceptions.UnicodeDecodeError:
1094 1094 print "Your ipython_dir can't be decoded to unicode!"
1095 1095 print "Please set HOME environment variable to something that"
1096 1096 print r"only has ASCII characters, e.g. c:\home"
1097 1097 print "Now it is", self.ipython_dir
1098 1098 sys.exit()
1099 1099 self.shadowhist = ipcorehist.ShadowHist(self.db)
1100 1100
1101 1101 def savehist(self):
1102 1102 """Save input history to a file (via readline library)."""
1103 1103
1104 1104 try:
1105 1105 self.readline.write_history_file(self.histfile)
1106 1106 except:
1107 1107 print 'Unable to save IPython command history to file: ' + \
1108 1108 `self.histfile`
1109 1109
1110 1110 def reloadhist(self):
1111 1111 """Reload the input history from disk file."""
1112 1112
1113 1113 try:
1114 1114 self.readline.clear_history()
1115 1115 self.readline.read_history_file(self.shell.histfile)
1116 1116 except AttributeError:
1117 1117 pass
1118 1118
1119 1119 def history_saving_wrapper(self, func):
1120 1120 """ Wrap func for readline history saving
1121 1121
1122 1122 Convert func into callable that saves & restores
1123 1123 history around the call """
1124 1124
1125 1125 if not self.has_readline:
1126 1126 return func
1127 1127
1128 1128 def wrapper():
1129 1129 self.savehist()
1130 1130 try:
1131 1131 func()
1132 1132 finally:
1133 1133 readline.read_history_file(self.histfile)
1134 1134 return wrapper
1135 1135
1136 1136 #-------------------------------------------------------------------------
1137 1137 # Things related to exception handling and tracebacks (not debugging)
1138 1138 #-------------------------------------------------------------------------
1139 1139
1140 1140 def init_traceback_handlers(self, custom_exceptions):
1141 1141 # Syntax error handler.
1142 1142 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1143 1143
1144 1144 # The interactive one is initialized with an offset, meaning we always
1145 1145 # want to remove the topmost item in the traceback, which is our own
1146 1146 # internal code. Valid modes: ['Plain','Context','Verbose']
1147 1147 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1148 1148 color_scheme='NoColor',
1149 1149 tb_offset = 1)
1150 1150
1151 1151 # IPython itself shouldn't crash. This will produce a detailed
1152 1152 # post-mortem if it does. But we only install the crash handler for
1153 1153 # non-threaded shells, the threaded ones use a normal verbose reporter
1154 1154 # and lose the crash handler. This is because exceptions in the main
1155 1155 # thread (such as in GUI code) propagate directly to sys.excepthook,
1156 1156 # and there's no point in printing crash dumps for every user exception.
1157 1157 if self.isthreaded:
1158 1158 ipCrashHandler = ultratb.FormattedTB()
1159 1159 else:
1160 1160 from IPython.core import crashhandler
1161 1161 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1162 1162 self.set_crash_handler(ipCrashHandler)
1163 1163
1164 1164 # and add any custom exception handlers the user may have specified
1165 1165 self.set_custom_exc(*custom_exceptions)
1166 1166
1167 1167 def set_crash_handler(self, crashHandler):
1168 1168 """Set the IPython crash handler.
1169 1169
1170 1170 This must be a callable with a signature suitable for use as
1171 1171 sys.excepthook."""
1172 1172
1173 1173 # Install the given crash handler as the Python exception hook
1174 1174 sys.excepthook = crashHandler
1175 1175
1176 1176 # The instance will store a pointer to this, so that runtime code
1177 1177 # (such as magics) can access it. This is because during the
1178 1178 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1179 1179 # frameworks).
1180 1180 self.sys_excepthook = sys.excepthook
1181 1181
1182 1182 def set_custom_exc(self,exc_tuple,handler):
1183 1183 """set_custom_exc(exc_tuple,handler)
1184 1184
1185 1185 Set a custom exception handler, which will be called if any of the
1186 1186 exceptions in exc_tuple occur in the mainloop (specifically, in the
1187 1187 runcode() method.
1188 1188
1189 1189 Inputs:
1190 1190
1191 1191 - exc_tuple: a *tuple* of valid exceptions to call the defined
1192 1192 handler for. It is very important that you use a tuple, and NOT A
1193 1193 LIST here, because of the way Python's except statement works. If
1194 1194 you only want to trap a single exception, use a singleton tuple:
1195 1195
1196 1196 exc_tuple == (MyCustomException,)
1197 1197
1198 1198 - handler: this must be defined as a function with the following
1199 1199 basic interface: def my_handler(self,etype,value,tb).
1200 1200
1201 1201 This will be made into an instance method (via new.instancemethod)
1202 1202 of IPython itself, and it will be called if any of the exceptions
1203 1203 listed in the exc_tuple are caught. If the handler is None, an
1204 1204 internal basic one is used, which just prints basic info.
1205 1205
1206 1206 WARNING: by putting in your own exception handler into IPython's main
1207 1207 execution loop, you run a very good chance of nasty crashes. This
1208 1208 facility should only be used if you really know what you are doing."""
1209 1209
1210 1210 assert type(exc_tuple)==type(()) , \
1211 1211 "The custom exceptions must be given AS A TUPLE."
1212 1212
1213 1213 def dummy_handler(self,etype,value,tb):
1214 1214 print '*** Simple custom exception handler ***'
1215 1215 print 'Exception type :',etype
1216 1216 print 'Exception value:',value
1217 1217 print 'Traceback :',tb
1218 1218 print 'Source code :','\n'.join(self.buffer)
1219 1219
1220 1220 if handler is None: handler = dummy_handler
1221 1221
1222 1222 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1223 1223 self.custom_exceptions = exc_tuple
1224 1224
1225 1225 def excepthook(self, etype, value, tb):
1226 1226 """One more defense for GUI apps that call sys.excepthook.
1227 1227
1228 1228 GUI frameworks like wxPython trap exceptions and call
1229 1229 sys.excepthook themselves. I guess this is a feature that
1230 1230 enables them to keep running after exceptions that would
1231 1231 otherwise kill their mainloop. This is a bother for IPython
1232 1232 which excepts to catch all of the program exceptions with a try:
1233 1233 except: statement.
1234 1234
1235 1235 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1236 1236 any app directly invokes sys.excepthook, it will look to the user like
1237 1237 IPython crashed. In order to work around this, we can disable the
1238 1238 CrashHandler and replace it with this excepthook instead, which prints a
1239 1239 regular traceback using our InteractiveTB. In this fashion, apps which
1240 1240 call sys.excepthook will generate a regular-looking exception from
1241 1241 IPython, and the CrashHandler will only be triggered by real IPython
1242 1242 crashes.
1243 1243
1244 1244 This hook should be used sparingly, only in places which are not likely
1245 1245 to be true IPython errors.
1246 1246 """
1247 1247 self.showtraceback((etype,value,tb),tb_offset=0)
1248 1248
1249 1249 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1250 1250 """Display the exception that just occurred.
1251 1251
1252 1252 If nothing is known about the exception, this is the method which
1253 1253 should be used throughout the code for presenting user tracebacks,
1254 1254 rather than directly invoking the InteractiveTB object.
1255 1255
1256 1256 A specific showsyntaxerror() also exists, but this method can take
1257 1257 care of calling it if needed, so unless you are explicitly catching a
1258 1258 SyntaxError exception, don't try to analyze the stack manually and
1259 1259 simply call this method."""
1260 1260
1261 1261
1262 1262 # Though this won't be called by syntax errors in the input line,
1263 1263 # there may be SyntaxError cases whith imported code.
1264 1264
1265 1265 try:
1266 1266 if exc_tuple is None:
1267 1267 etype, value, tb = sys.exc_info()
1268 1268 else:
1269 1269 etype, value, tb = exc_tuple
1270 1270
1271 1271 if etype is SyntaxError:
1272 1272 self.showsyntaxerror(filename)
1273 1273 elif etype is UsageError:
1274 1274 print "UsageError:", value
1275 1275 else:
1276 1276 # WARNING: these variables are somewhat deprecated and not
1277 1277 # necessarily safe to use in a threaded environment, but tools
1278 1278 # like pdb depend on their existence, so let's set them. If we
1279 1279 # find problems in the field, we'll need to revisit their use.
1280 1280 sys.last_type = etype
1281 1281 sys.last_value = value
1282 1282 sys.last_traceback = tb
1283 1283
1284 1284 if etype in self.custom_exceptions:
1285 1285 self.CustomTB(etype,value,tb)
1286 1286 else:
1287 1287 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1288 1288 if self.InteractiveTB.call_pdb:
1289 1289 # pdb mucks up readline, fix it back
1290 1290 self.set_completer()
1291 1291 except KeyboardInterrupt:
1292 1292 self.write("\nKeyboardInterrupt\n")
1293 1293
1294 1294 def showsyntaxerror(self, filename=None):
1295 1295 """Display the syntax error that just occurred.
1296 1296
1297 1297 This doesn't display a stack trace because there isn't one.
1298 1298
1299 1299 If a filename is given, it is stuffed in the exception instead
1300 1300 of what was there before (because Python's parser always uses
1301 1301 "<string>" when reading from a string).
1302 1302 """
1303 1303 etype, value, last_traceback = sys.exc_info()
1304 1304
1305 1305 # See note about these variables in showtraceback() below
1306 1306 sys.last_type = etype
1307 1307 sys.last_value = value
1308 1308 sys.last_traceback = last_traceback
1309 1309
1310 1310 if filename and etype is SyntaxError:
1311 1311 # Work hard to stuff the correct filename in the exception
1312 1312 try:
1313 1313 msg, (dummy_filename, lineno, offset, line) = value
1314 1314 except:
1315 1315 # Not the format we expect; leave it alone
1316 1316 pass
1317 1317 else:
1318 1318 # Stuff in the right filename
1319 1319 try:
1320 1320 # Assume SyntaxError is a class exception
1321 1321 value = SyntaxError(msg, (filename, lineno, offset, line))
1322 1322 except:
1323 1323 # If that failed, assume SyntaxError is a string
1324 1324 value = msg, (filename, lineno, offset, line)
1325 1325 self.SyntaxTB(etype,value,[])
1326 1326
1327 1327 def edit_syntax_error(self):
1328 1328 """The bottom half of the syntax error handler called in the main loop.
1329 1329
1330 1330 Loop until syntax error is fixed or user cancels.
1331 1331 """
1332 1332
1333 1333 while self.SyntaxTB.last_syntax_error:
1334 1334 # copy and clear last_syntax_error
1335 1335 err = self.SyntaxTB.clear_err_state()
1336 1336 if not self._should_recompile(err):
1337 1337 return
1338 1338 try:
1339 1339 # may set last_syntax_error again if a SyntaxError is raised
1340 1340 self.safe_execfile(err.filename,self.user_ns)
1341 1341 except:
1342 1342 self.showtraceback()
1343 1343 else:
1344 1344 try:
1345 1345 f = file(err.filename)
1346 1346 try:
1347 1347 # This should be inside a display_trap block and I
1348 1348 # think it is.
1349 1349 sys.displayhook(f.read())
1350 1350 finally:
1351 1351 f.close()
1352 1352 except:
1353 1353 self.showtraceback()
1354 1354
1355 1355 def _should_recompile(self,e):
1356 1356 """Utility routine for edit_syntax_error"""
1357 1357
1358 1358 if e.filename in ('<ipython console>','<input>','<string>',
1359 1359 '<console>','<BackgroundJob compilation>',
1360 1360 None):
1361 1361
1362 1362 return False
1363 1363 try:
1364 1364 if (self.autoedit_syntax and
1365 1365 not self.ask_yes_no('Return to editor to correct syntax error? '
1366 1366 '[Y/n] ','y')):
1367 1367 return False
1368 1368 except EOFError:
1369 1369 return False
1370 1370
1371 1371 def int0(x):
1372 1372 try:
1373 1373 return int(x)
1374 1374 except TypeError:
1375 1375 return 0
1376 1376 # always pass integer line and offset values to editor hook
1377 1377 try:
1378 1378 self.hooks.fix_error_editor(e.filename,
1379 1379 int0(e.lineno),int0(e.offset),e.msg)
1380 1380 except TryNext:
1381 1381 warn('Could not open editor')
1382 1382 return False
1383 1383 return True
1384 1384
1385 1385 #-------------------------------------------------------------------------
1386 1386 # Things related to tab completion
1387 1387 #-------------------------------------------------------------------------
1388 1388
1389 1389 def complete(self, text):
1390 1390 """Return a sorted list of all possible completions on text.
1391 1391
1392 1392 Inputs:
1393 1393
1394 1394 - text: a string of text to be completed on.
1395 1395
1396 1396 This is a wrapper around the completion mechanism, similar to what
1397 1397 readline does at the command line when the TAB key is hit. By
1398 1398 exposing it as a method, it can be used by other non-readline
1399 1399 environments (such as GUIs) for text completion.
1400 1400
1401 1401 Simple usage example:
1402 1402
1403 1403 In [7]: x = 'hello'
1404 1404
1405 1405 In [8]: x
1406 1406 Out[8]: 'hello'
1407 1407
1408 1408 In [9]: print x
1409 1409 hello
1410 1410
1411 1411 In [10]: _ip.complete('x.l')
1412 1412 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1413 1413 """
1414 1414
1415 1415 # Inject names into __builtin__ so we can complete on the added names.
1416 1416 with self.builtin_trap:
1417 1417 complete = self.Completer.complete
1418 1418 state = 0
1419 1419 # use a dict so we get unique keys, since ipyhton's multiple
1420 1420 # completers can return duplicates. When we make 2.4 a requirement,
1421 1421 # start using sets instead, which are faster.
1422 1422 comps = {}
1423 1423 while True:
1424 1424 newcomp = complete(text,state,line_buffer=text)
1425 1425 if newcomp is None:
1426 1426 break
1427 1427 comps[newcomp] = 1
1428 1428 state += 1
1429 1429 outcomps = comps.keys()
1430 1430 outcomps.sort()
1431 1431 #print "T:",text,"OC:",outcomps # dbg
1432 1432 #print "vars:",self.user_ns.keys()
1433 1433 return outcomps
1434 1434
1435 1435 def set_custom_completer(self,completer,pos=0):
1436 1436 """Adds a new custom completer function.
1437 1437
1438 1438 The position argument (defaults to 0) is the index in the completers
1439 1439 list where you want the completer to be inserted."""
1440 1440
1441 1441 newcomp = new.instancemethod(completer,self.Completer,
1442 1442 self.Completer.__class__)
1443 1443 self.Completer.matchers.insert(pos,newcomp)
1444 1444
1445 1445 def set_completer(self):
1446 1446 """Reset readline's completer to be our own."""
1447 1447 self.readline.set_completer(self.Completer.complete)
1448 1448
1449 1449 def set_completer_frame(self, frame=None):
1450 1450 """Set the frame of the completer."""
1451 1451 if frame:
1452 1452 self.Completer.namespace = frame.f_locals
1453 1453 self.Completer.global_namespace = frame.f_globals
1454 1454 else:
1455 1455 self.Completer.namespace = self.user_ns
1456 1456 self.Completer.global_namespace = self.user_global_ns
1457 1457
1458 1458 #-------------------------------------------------------------------------
1459 1459 # Things related to readline
1460 1460 #-------------------------------------------------------------------------
1461 1461
1462 1462 def init_readline(self):
1463 1463 """Command history completion/saving/reloading."""
1464 1464
1465 1465 if self.readline_use:
1466 1466 import IPython.utils.rlineimpl as readline
1467 1467
1468 1468 self.rl_next_input = None
1469 1469 self.rl_do_indent = False
1470 1470
1471 1471 if not self.readline_use or not readline.have_readline:
1472 1472 self.has_readline = False
1473 1473 self.readline = None
1474 1474 # Set a number of methods that depend on readline to be no-op
1475 1475 self.savehist = no_op
1476 1476 self.reloadhist = no_op
1477 1477 self.set_completer = no_op
1478 1478 self.set_custom_completer = no_op
1479 1479 self.set_completer_frame = no_op
1480 1480 warn('Readline services not available or not loaded.')
1481 1481 else:
1482 1482 self.has_readline = True
1483 1483 self.readline = readline
1484 1484 sys.modules['readline'] = readline
1485 1485 import atexit
1486 1486 from IPython.core.completer import IPCompleter
1487 1487 self.Completer = IPCompleter(self,
1488 1488 self.user_ns,
1489 1489 self.user_global_ns,
1490 1490 self.readline_omit__names,
1491 1491 self.alias_manager.alias_table)
1492 1492 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1493 1493 self.strdispatchers['complete_command'] = sdisp
1494 1494 self.Completer.custom_completers = sdisp
1495 1495 # Platform-specific configuration
1496 1496 if os.name == 'nt':
1497 1497 self.readline_startup_hook = readline.set_pre_input_hook
1498 1498 else:
1499 1499 self.readline_startup_hook = readline.set_startup_hook
1500 1500
1501 1501 # Load user's initrc file (readline config)
1502 1502 # Or if libedit is used, load editrc.
1503 1503 inputrc_name = os.environ.get('INPUTRC')
1504 1504 if inputrc_name is None:
1505 1505 home_dir = get_home_dir()
1506 1506 if home_dir is not None:
1507 1507 inputrc_name = '.inputrc'
1508 1508 if readline.uses_libedit:
1509 1509 inputrc_name = '.editrc'
1510 1510 inputrc_name = os.path.join(home_dir, inputrc_name)
1511 1511 if os.path.isfile(inputrc_name):
1512 1512 try:
1513 1513 readline.read_init_file(inputrc_name)
1514 1514 except:
1515 1515 warn('Problems reading readline initialization file <%s>'
1516 1516 % inputrc_name)
1517 1517
1518 1518 # save this in sys so embedded copies can restore it properly
1519 1519 sys.ipcompleter = self.Completer.complete
1520 1520 self.set_completer()
1521 1521
1522 1522 # Configure readline according to user's prefs
1523 1523 # This is only done if GNU readline is being used. If libedit
1524 1524 # is being used (as on Leopard) the readline config is
1525 1525 # not run as the syntax for libedit is different.
1526 1526 if not readline.uses_libedit:
1527 1527 for rlcommand in self.readline_parse_and_bind:
1528 1528 #print "loading rl:",rlcommand # dbg
1529 1529 readline.parse_and_bind(rlcommand)
1530 1530
1531 1531 # Remove some chars from the delimiters list. If we encounter
1532 1532 # unicode chars, discard them.
1533 1533 delims = readline.get_completer_delims().encode("ascii", "ignore")
1534 1534 delims = delims.translate(string._idmap,
1535 1535 self.readline_remove_delims)
1536 1536 readline.set_completer_delims(delims)
1537 1537 # otherwise we end up with a monster history after a while:
1538 1538 readline.set_history_length(1000)
1539 1539 try:
1540 1540 #print '*** Reading readline history' # dbg
1541 1541 readline.read_history_file(self.histfile)
1542 1542 except IOError:
1543 1543 pass # It doesn't exist yet.
1544 1544
1545 1545 atexit.register(self.atexit_operations)
1546 1546 del atexit
1547 1547
1548 1548 # Configure auto-indent for all platforms
1549 1549 self.set_autoindent(self.autoindent)
1550 1550
1551 1551 def set_next_input(self, s):
1552 1552 """ Sets the 'default' input string for the next command line.
1553 1553
1554 1554 Requires readline.
1555 1555
1556 1556 Example:
1557 1557
1558 1558 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1559 1559 [D:\ipython]|2> Hello Word_ # cursor is here
1560 1560 """
1561 1561
1562 1562 self.rl_next_input = s
1563 1563
1564 1564 def pre_readline(self):
1565 1565 """readline hook to be used at the start of each line.
1566 1566
1567 1567 Currently it handles auto-indent only."""
1568 1568
1569 1569 #debugx('self.indent_current_nsp','pre_readline:')
1570 1570
1571 1571 if self.rl_do_indent:
1572 1572 self.readline.insert_text(self._indent_current_str())
1573 1573 if self.rl_next_input is not None:
1574 1574 self.readline.insert_text(self.rl_next_input)
1575 1575 self.rl_next_input = None
1576 1576
1577 1577 def _indent_current_str(self):
1578 1578 """return the current level of indentation as a string"""
1579 1579 return self.indent_current_nsp * ' '
1580 1580
1581 1581 #-------------------------------------------------------------------------
1582 1582 # Things related to magics
1583 1583 #-------------------------------------------------------------------------
1584 1584
1585 1585 def init_magics(self):
1586 1586 # Set user colors (don't do it in the constructor above so that it
1587 1587 # doesn't crash if colors option is invalid)
1588 1588 self.magic_colors(self.colors)
1589 1589
1590 1590 def magic(self,arg_s):
1591 1591 """Call a magic function by name.
1592 1592
1593 1593 Input: a string containing the name of the magic function to call and any
1594 1594 additional arguments to be passed to the magic.
1595 1595
1596 1596 magic('name -opt foo bar') is equivalent to typing at the ipython
1597 1597 prompt:
1598 1598
1599 1599 In[1]: %name -opt foo bar
1600 1600
1601 1601 To call a magic without arguments, simply use magic('name').
1602 1602
1603 1603 This provides a proper Python function to call IPython's magics in any
1604 1604 valid Python code you can type at the interpreter, including loops and
1605 1605 compound statements.
1606 1606 """
1607 1607
1608 1608 args = arg_s.split(' ',1)
1609 1609 magic_name = args[0]
1610 1610 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1611 1611
1612 1612 try:
1613 1613 magic_args = args[1]
1614 1614 except IndexError:
1615 1615 magic_args = ''
1616 1616 fn = getattr(self,'magic_'+magic_name,None)
1617 1617 if fn is None:
1618 1618 error("Magic function `%s` not found." % magic_name)
1619 1619 else:
1620 1620 magic_args = self.var_expand(magic_args,1)
1621 1621 with nested(self.builtin_trap,):
1622 1622 result = fn(magic_args)
1623 1623 return result
1624 1624
1625 1625 def define_magic(self, magicname, func):
1626 1626 """Expose own function as magic function for ipython
1627 1627
1628 1628 def foo_impl(self,parameter_s=''):
1629 1629 'My very own magic!. (Use docstrings, IPython reads them).'
1630 1630 print 'Magic function. Passed parameter is between < >:'
1631 1631 print '<%s>' % parameter_s
1632 1632 print 'The self object is:',self
1633 1633
1634 1634 self.define_magic('foo',foo_impl)
1635 1635 """
1636 1636
1637 1637 import new
1638 1638 im = new.instancemethod(func,self, self.__class__)
1639 1639 old = getattr(self, "magic_" + magicname, None)
1640 1640 setattr(self, "magic_" + magicname, im)
1641 1641 return old
1642 1642
1643 1643 #-------------------------------------------------------------------------
1644 1644 # Things related to macros
1645 1645 #-------------------------------------------------------------------------
1646 1646
1647 1647 def define_macro(self, name, themacro):
1648 1648 """Define a new macro
1649 1649
1650 1650 Parameters
1651 1651 ----------
1652 1652 name : str
1653 1653 The name of the macro.
1654 1654 themacro : str or Macro
1655 1655 The action to do upon invoking the macro. If a string, a new
1656 1656 Macro object is created by passing the string to it.
1657 1657 """
1658 1658
1659 1659 from IPython.core import macro
1660 1660
1661 1661 if isinstance(themacro, basestring):
1662 1662 themacro = macro.Macro(themacro)
1663 1663 if not isinstance(themacro, macro.Macro):
1664 1664 raise ValueError('A macro must be a string or a Macro instance.')
1665 1665 self.user_ns[name] = themacro
1666 1666
1667 1667 #-------------------------------------------------------------------------
1668 1668 # Things related to the running of system commands
1669 1669 #-------------------------------------------------------------------------
1670 1670
1671 1671 def system(self, cmd):
1672 1672 """Make a system call, using IPython."""
1673 1673 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1674 1674
1675 1675 #-------------------------------------------------------------------------
1676 1676 # Things related to aliases
1677 1677 #-------------------------------------------------------------------------
1678 1678
1679 1679 def init_alias(self):
1680 1680 self.alias_manager = AliasManager(self, config=self.config)
1681 1681 self.ns_table['alias'] = self.alias_manager.alias_table,
1682 1682
1683 1683 #-------------------------------------------------------------------------
1684 1684 # Things related to the running of code
1685 1685 #-------------------------------------------------------------------------
1686 1686
1687 1687 def ex(self, cmd):
1688 1688 """Execute a normal python statement in user namespace."""
1689 1689 with nested(self.builtin_trap,):
1690 1690 exec cmd in self.user_global_ns, self.user_ns
1691 1691
1692 1692 def ev(self, expr):
1693 1693 """Evaluate python expression expr in user namespace.
1694 1694
1695 1695 Returns the result of evaluation
1696 1696 """
1697 1697 with nested(self.builtin_trap,):
1698 1698 return eval(expr, self.user_global_ns, self.user_ns)
1699 1699
1700 1700 def mainloop(self, display_banner=None):
1701 1701 """Start the mainloop.
1702 1702
1703 1703 If an optional banner argument is given, it will override the
1704 1704 internally created default banner.
1705 1705 """
1706 1706
1707 1707 with nested(self.builtin_trap, self.display_trap):
1708 1708
1709 1709 # if you run stuff with -c <cmd>, raw hist is not updated
1710 1710 # ensure that it's in sync
1711 1711 if len(self.input_hist) != len (self.input_hist_raw):
1712 1712 self.input_hist_raw = InputList(self.input_hist)
1713 1713
1714 1714 while 1:
1715 1715 try:
1716 1716 self.interact(display_banner=display_banner)
1717 1717 #self.interact_with_readline()
1718 1718 # XXX for testing of a readline-decoupled repl loop, call
1719 1719 # interact_with_readline above
1720 1720 break
1721 1721 except KeyboardInterrupt:
1722 1722 # this should not be necessary, but KeyboardInterrupt
1723 1723 # handling seems rather unpredictable...
1724 1724 self.write("\nKeyboardInterrupt in interact()\n")
1725 1725
1726 1726 def interact_prompt(self):
1727 1727 """ Print the prompt (in read-eval-print loop)
1728 1728
1729 1729 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1730 1730 used in standard IPython flow.
1731 1731 """
1732 1732 if self.more:
1733 1733 try:
1734 1734 prompt = self.hooks.generate_prompt(True)
1735 1735 except:
1736 1736 self.showtraceback()
1737 1737 if self.autoindent:
1738 1738 self.rl_do_indent = True
1739 1739
1740 1740 else:
1741 1741 try:
1742 1742 prompt = self.hooks.generate_prompt(False)
1743 1743 except:
1744 1744 self.showtraceback()
1745 1745 self.write(prompt)
1746 1746
1747 1747 def interact_handle_input(self,line):
1748 1748 """ Handle the input line (in read-eval-print loop)
1749 1749
1750 1750 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1751 1751 used in standard IPython flow.
1752 1752 """
1753 1753 if line.lstrip() == line:
1754 1754 self.shadowhist.add(line.strip())
1755 1755 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1756 1756
1757 1757 if line.strip():
1758 1758 if self.more:
1759 1759 self.input_hist_raw[-1] += '%s\n' % line
1760 1760 else:
1761 1761 self.input_hist_raw.append('%s\n' % line)
1762 1762
1763 1763
1764 1764 self.more = self.push_line(lineout)
1765 1765 if (self.SyntaxTB.last_syntax_error and
1766 1766 self.autoedit_syntax):
1767 1767 self.edit_syntax_error()
1768 1768
1769 1769 def interact_with_readline(self):
1770 1770 """ Demo of using interact_handle_input, interact_prompt
1771 1771
1772 1772 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1773 1773 it should work like this.
1774 1774 """
1775 1775 self.readline_startup_hook(self.pre_readline)
1776 1776 while not self.exit_now:
1777 1777 self.interact_prompt()
1778 1778 if self.more:
1779 1779 self.rl_do_indent = True
1780 1780 else:
1781 1781 self.rl_do_indent = False
1782 1782 line = raw_input_original().decode(self.stdin_encoding)
1783 1783 self.interact_handle_input(line)
1784 1784
1785 1785 def interact(self, display_banner=None):
1786 1786 """Closely emulate the interactive Python console."""
1787 1787
1788 1788 # batch run -> do not interact
1789 1789 if self.exit_now:
1790 1790 return
1791 1791
1792 1792 if display_banner is None:
1793 1793 display_banner = self.display_banner
1794 1794 if display_banner:
1795 1795 self.show_banner()
1796 1796
1797 1797 more = 0
1798 1798
1799 1799 # Mark activity in the builtins
1800 1800 __builtin__.__dict__['__IPYTHON__active'] += 1
1801 1801
1802 1802 if self.has_readline:
1803 1803 self.readline_startup_hook(self.pre_readline)
1804 1804 # exit_now is set by a call to %Exit or %Quit, through the
1805 1805 # ask_exit callback.
1806 1806
1807 1807 while not self.exit_now:
1808 1808 self.hooks.pre_prompt_hook()
1809 1809 if more:
1810 1810 try:
1811 1811 prompt = self.hooks.generate_prompt(True)
1812 1812 except:
1813 1813 self.showtraceback()
1814 1814 if self.autoindent:
1815 1815 self.rl_do_indent = True
1816 1816
1817 1817 else:
1818 1818 try:
1819 1819 prompt = self.hooks.generate_prompt(False)
1820 1820 except:
1821 1821 self.showtraceback()
1822 1822 try:
1823 1823 line = self.raw_input(prompt, more)
1824 1824 if self.exit_now:
1825 1825 # quick exit on sys.std[in|out] close
1826 1826 break
1827 1827 if self.autoindent:
1828 1828 self.rl_do_indent = False
1829 1829
1830 1830 except KeyboardInterrupt:
1831 1831 #double-guard against keyboardinterrupts during kbdint handling
1832 1832 try:
1833 1833 self.write('\nKeyboardInterrupt\n')
1834 1834 self.resetbuffer()
1835 1835 # keep cache in sync with the prompt counter:
1836 1836 self.outputcache.prompt_count -= 1
1837 1837
1838 1838 if self.autoindent:
1839 1839 self.indent_current_nsp = 0
1840 1840 more = 0
1841 1841 except KeyboardInterrupt:
1842 1842 pass
1843 1843 except EOFError:
1844 1844 if self.autoindent:
1845 1845 self.rl_do_indent = False
1846 1846 if self.has_readline:
1847 1847 self.readline_startup_hook(None)
1848 1848 self.write('\n')
1849 1849 self.exit()
1850 1850 except bdb.BdbQuit:
1851 1851 warn('The Python debugger has exited with a BdbQuit exception.\n'
1852 1852 'Because of how pdb handles the stack, it is impossible\n'
1853 1853 'for IPython to properly format this particular exception.\n'
1854 1854 'IPython will resume normal operation.')
1855 1855 except:
1856 1856 # exceptions here are VERY RARE, but they can be triggered
1857 1857 # asynchronously by signal handlers, for example.
1858 1858 self.showtraceback()
1859 1859 else:
1860 1860 more = self.push_line(line)
1861 1861 if (self.SyntaxTB.last_syntax_error and
1862 1862 self.autoedit_syntax):
1863 1863 self.edit_syntax_error()
1864 1864
1865 1865 # We are off again...
1866 1866 __builtin__.__dict__['__IPYTHON__active'] -= 1
1867 1867
1868 1868 def safe_execfile(self, fname, *where, **kw):
1869 1869 """A safe version of the builtin execfile().
1870 1870
1871 1871 This version will never throw an exception, but instead print
1872 1872 helpful error messages to the screen. This only works on pure
1873 1873 Python files with the .py extension.
1874 1874
1875 1875 Parameters
1876 1876 ----------
1877 1877 fname : string
1878 1878 The name of the file to be executed.
1879 1879 where : tuple
1880 1880 One or two namespaces, passed to execfile() as (globals,locals).
1881 1881 If only one is given, it is passed as both.
1882 1882 exit_ignore : bool (False)
1883 1883 If True, then don't print errors for non-zero exit statuses.
1884 1884 """
1885 1885 kw.setdefault('exit_ignore', False)
1886 1886
1887 1887 fname = os.path.abspath(os.path.expanduser(fname))
1888 1888
1889 1889 # Make sure we have a .py file
1890 1890 if not fname.endswith('.py'):
1891 1891 warn('File must end with .py to be run using execfile: <%s>' % fname)
1892 1892
1893 1893 # Make sure we can open the file
1894 1894 try:
1895 1895 with open(fname) as thefile:
1896 1896 pass
1897 1897 except:
1898 1898 warn('Could not open file <%s> for safe execution.' % fname)
1899 1899 return
1900 1900
1901 1901 # Find things also in current directory. This is needed to mimic the
1902 1902 # behavior of running a script from the system command line, where
1903 1903 # Python inserts the script's directory into sys.path
1904 1904 dname = os.path.dirname(fname)
1905 1905
1906 1906 with prepended_to_syspath(dname):
1907 1907 try:
1908 1908 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1909 1909 # Work around a bug in Python for Windows. The bug was
1910 1910 # fixed in in Python 2.5 r54159 and 54158, but that's still
1911 1911 # SVN Python as of March/07. For details, see:
1912 1912 # http://projects.scipy.org/ipython/ipython/ticket/123
1913 1913 try:
1914 1914 globs,locs = where[0:2]
1915 1915 except:
1916 1916 try:
1917 1917 globs = locs = where[0]
1918 1918 except:
1919 1919 globs = locs = globals()
1920 1920 exec file(fname) in globs,locs
1921 1921 else:
1922 1922 execfile(fname,*where)
1923 1923 except SyntaxError:
1924 1924 self.showsyntaxerror()
1925 1925 warn('Failure executing file: <%s>' % fname)
1926 1926 except SystemExit, status:
1927 1927 # Code that correctly sets the exit status flag to success (0)
1928 1928 # shouldn't be bothered with a traceback. Note that a plain
1929 1929 # sys.exit() does NOT set the message to 0 (it's empty) so that
1930 1930 # will still get a traceback. Note that the structure of the
1931 1931 # SystemExit exception changed between Python 2.4 and 2.5, so
1932 1932 # the checks must be done in a version-dependent way.
1933 1933 show = False
1934 1934 if status.args[0]==0 and not kw['exit_ignore']:
1935 1935 show = True
1936 1936 if show:
1937 1937 self.showtraceback()
1938 1938 warn('Failure executing file: <%s>' % fname)
1939 1939 except:
1940 1940 self.showtraceback()
1941 1941 warn('Failure executing file: <%s>' % fname)
1942 1942
1943 1943 def safe_execfile_ipy(self, fname):
1944 1944 """Like safe_execfile, but for .ipy files with IPython syntax.
1945 1945
1946 1946 Parameters
1947 1947 ----------
1948 1948 fname : str
1949 1949 The name of the file to execute. The filename must have a
1950 1950 .ipy extension.
1951 1951 """
1952 1952 fname = os.path.abspath(os.path.expanduser(fname))
1953 1953
1954 1954 # Make sure we have a .py file
1955 1955 if not fname.endswith('.ipy'):
1956 1956 warn('File must end with .py to be run using execfile: <%s>' % fname)
1957 1957
1958 1958 # Make sure we can open the file
1959 1959 try:
1960 1960 with open(fname) as thefile:
1961 1961 pass
1962 1962 except:
1963 1963 warn('Could not open file <%s> for safe execution.' % fname)
1964 1964 return
1965 1965
1966 1966 # Find things also in current directory. This is needed to mimic the
1967 1967 # behavior of running a script from the system command line, where
1968 1968 # Python inserts the script's directory into sys.path
1969 1969 dname = os.path.dirname(fname)
1970 1970
1971 1971 with prepended_to_syspath(dname):
1972 1972 try:
1973 1973 with open(fname) as thefile:
1974 1974 script = thefile.read()
1975 1975 # self.runlines currently captures all exceptions
1976 1976 # raise in user code. It would be nice if there were
1977 1977 # versions of runlines, execfile that did raise, so
1978 1978 # we could catch the errors.
1979 1979 self.runlines(script, clean=True)
1980 1980 except:
1981 1981 self.showtraceback()
1982 1982 warn('Unknown failure executing file: <%s>' % fname)
1983 1983
1984 1984 def _is_secondary_block_start(self, s):
1985 1985 if not s.endswith(':'):
1986 1986 return False
1987 1987 if (s.startswith('elif') or
1988 1988 s.startswith('else') or
1989 1989 s.startswith('except') or
1990 1990 s.startswith('finally')):
1991 1991 return True
1992 1992
1993 1993 def cleanup_ipy_script(self, script):
1994 1994 """Make a script safe for self.runlines()
1995 1995
1996 1996 Currently, IPython is lines based, with blocks being detected by
1997 1997 empty lines. This is a problem for block based scripts that may
1998 1998 not have empty lines after blocks. This script adds those empty
1999 1999 lines to make scripts safe for running in the current line based
2000 2000 IPython.
2001 2001 """
2002 2002 res = []
2003 2003 lines = script.splitlines()
2004 2004 level = 0
2005 2005
2006 2006 for l in lines:
2007 2007 lstripped = l.lstrip()
2008 2008 stripped = l.strip()
2009 2009 if not stripped:
2010 2010 continue
2011 2011 newlevel = len(l) - len(lstripped)
2012 2012 if level > 0 and newlevel == 0 and \
2013 2013 not self._is_secondary_block_start(stripped):
2014 2014 # add empty line
2015 2015 res.append('')
2016 2016 res.append(l)
2017 2017 level = newlevel
2018 2018
2019 2019 return '\n'.join(res) + '\n'
2020 2020
2021 2021 def runlines(self, lines, clean=False):
2022 2022 """Run a string of one or more lines of source.
2023 2023
2024 2024 This method is capable of running a string containing multiple source
2025 2025 lines, as if they had been entered at the IPython prompt. Since it
2026 2026 exposes IPython's processing machinery, the given strings can contain
2027 2027 magic calls (%magic), special shell access (!cmd), etc.
2028 2028 """
2029 2029
2030 2030 if isinstance(lines, (list, tuple)):
2031 2031 lines = '\n'.join(lines)
2032 2032
2033 2033 if clean:
2034 2034 lines = self.cleanup_ipy_script(lines)
2035 2035
2036 2036 # We must start with a clean buffer, in case this is run from an
2037 2037 # interactive IPython session (via a magic, for example).
2038 2038 self.resetbuffer()
2039 2039 lines = lines.splitlines()
2040 2040 more = 0
2041 2041
2042 2042 with nested(self.builtin_trap, self.display_trap):
2043 2043 for line in lines:
2044 2044 # skip blank lines so we don't mess up the prompt counter, but do
2045 2045 # NOT skip even a blank line if we are in a code block (more is
2046 2046 # true)
2047 2047
2048 2048 if line or more:
2049 2049 # push to raw history, so hist line numbers stay in sync
2050 2050 self.input_hist_raw.append("# " + line + "\n")
2051 2051 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2052 2052 more = self.push_line(prefiltered)
2053 2053 # IPython's runsource returns None if there was an error
2054 2054 # compiling the code. This allows us to stop processing right
2055 2055 # away, so the user gets the error message at the right place.
2056 2056 if more is None:
2057 2057 break
2058 2058 else:
2059 2059 self.input_hist_raw.append("\n")
2060 2060 # final newline in case the input didn't have it, so that the code
2061 2061 # actually does get executed
2062 2062 if more:
2063 2063 self.push_line('\n')
2064 2064
2065 2065 def runsource(self, source, filename='<input>', symbol='single'):
2066 2066 """Compile and run some source in the interpreter.
2067 2067
2068 2068 Arguments are as for compile_command().
2069 2069
2070 2070 One several things can happen:
2071 2071
2072 2072 1) The input is incorrect; compile_command() raised an
2073 2073 exception (SyntaxError or OverflowError). A syntax traceback
2074 2074 will be printed by calling the showsyntaxerror() method.
2075 2075
2076 2076 2) The input is incomplete, and more input is required;
2077 2077 compile_command() returned None. Nothing happens.
2078 2078
2079 2079 3) The input is complete; compile_command() returned a code
2080 2080 object. The code is executed by calling self.runcode() (which
2081 2081 also handles run-time exceptions, except for SystemExit).
2082 2082
2083 2083 The return value is:
2084 2084
2085 2085 - True in case 2
2086 2086
2087 2087 - False in the other cases, unless an exception is raised, where
2088 2088 None is returned instead. This can be used by external callers to
2089 2089 know whether to continue feeding input or not.
2090 2090
2091 2091 The return value can be used to decide whether to use sys.ps1 or
2092 2092 sys.ps2 to prompt the next line."""
2093 2093
2094 2094 # if the source code has leading blanks, add 'if 1:\n' to it
2095 2095 # this allows execution of indented pasted code. It is tempting
2096 2096 # to add '\n' at the end of source to run commands like ' a=1'
2097 2097 # directly, but this fails for more complicated scenarios
2098 2098 source=source.encode(self.stdin_encoding)
2099 2099 if source[:1] in [' ', '\t']:
2100 2100 source = 'if 1:\n%s' % source
2101 2101
2102 2102 try:
2103 2103 code = self.compile(source,filename,symbol)
2104 2104 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2105 2105 # Case 1
2106 2106 self.showsyntaxerror(filename)
2107 2107 return None
2108 2108
2109 2109 if code is None:
2110 2110 # Case 2
2111 2111 return True
2112 2112
2113 2113 # Case 3
2114 2114 # We store the code object so that threaded shells and
2115 2115 # custom exception handlers can access all this info if needed.
2116 2116 # The source corresponding to this can be obtained from the
2117 2117 # buffer attribute as '\n'.join(self.buffer).
2118 2118 self.code_to_run = code
2119 2119 # now actually execute the code object
2120 2120 if self.runcode(code) == 0:
2121 2121 return False
2122 2122 else:
2123 2123 return None
2124 2124
2125 2125 def runcode(self,code_obj):
2126 2126 """Execute a code object.
2127 2127
2128 2128 When an exception occurs, self.showtraceback() is called to display a
2129 2129 traceback.
2130 2130
2131 2131 Return value: a flag indicating whether the code to be run completed
2132 2132 successfully:
2133 2133
2134 2134 - 0: successful execution.
2135 2135 - 1: an error occurred.
2136 2136 """
2137 2137
2138 2138 # Set our own excepthook in case the user code tries to call it
2139 2139 # directly, so that the IPython crash handler doesn't get triggered
2140 2140 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2141 2141
2142 2142 # we save the original sys.excepthook in the instance, in case config
2143 2143 # code (such as magics) needs access to it.
2144 2144 self.sys_excepthook = old_excepthook
2145 2145 outflag = 1 # happens in more places, so it's easier as default
2146 2146 try:
2147 2147 try:
2148 2148 self.hooks.pre_runcode_hook()
2149 2149 exec code_obj in self.user_global_ns, self.user_ns
2150 2150 finally:
2151 2151 # Reset our crash handler in place
2152 2152 sys.excepthook = old_excepthook
2153 2153 except SystemExit:
2154 2154 self.resetbuffer()
2155 2155 self.showtraceback()
2156 2156 warn("Type %exit or %quit to exit IPython "
2157 2157 "(%Exit or %Quit do so unconditionally).",level=1)
2158 2158 except self.custom_exceptions:
2159 2159 etype,value,tb = sys.exc_info()
2160 2160 self.CustomTB(etype,value,tb)
2161 2161 except:
2162 2162 self.showtraceback()
2163 2163 else:
2164 2164 outflag = 0
2165 2165 if softspace(sys.stdout, 0):
2166 2166 print
2167 2167 # Flush out code object which has been run (and source)
2168 2168 self.code_to_run = None
2169 2169 return outflag
2170 2170
2171 2171 def push_line(self, line):
2172 2172 """Push a line to the interpreter.
2173 2173
2174 2174 The line should not have a trailing newline; it may have
2175 2175 internal newlines. The line is appended to a buffer and the
2176 2176 interpreter's runsource() method is called with the
2177 2177 concatenated contents of the buffer as source. If this
2178 2178 indicates that the command was executed or invalid, the buffer
2179 2179 is reset; otherwise, the command is incomplete, and the buffer
2180 2180 is left as it was after the line was appended. The return
2181 2181 value is 1 if more input is required, 0 if the line was dealt
2182 2182 with in some way (this is the same as runsource()).
2183 2183 """
2184 2184
2185 2185 # autoindent management should be done here, and not in the
2186 2186 # interactive loop, since that one is only seen by keyboard input. We
2187 2187 # need this done correctly even for code run via runlines (which uses
2188 2188 # push).
2189 2189
2190 2190 #print 'push line: <%s>' % line # dbg
2191 2191 for subline in line.splitlines():
2192 2192 self._autoindent_update(subline)
2193 2193 self.buffer.append(line)
2194 2194 more = self.runsource('\n'.join(self.buffer), self.filename)
2195 2195 if not more:
2196 2196 self.resetbuffer()
2197 2197 return more
2198 2198
2199 2199 def _autoindent_update(self,line):
2200 2200 """Keep track of the indent level."""
2201 2201
2202 2202 #debugx('line')
2203 2203 #debugx('self.indent_current_nsp')
2204 2204 if self.autoindent:
2205 2205 if line:
2206 2206 inisp = num_ini_spaces(line)
2207 2207 if inisp < self.indent_current_nsp:
2208 2208 self.indent_current_nsp = inisp
2209 2209
2210 2210 if line[-1] == ':':
2211 2211 self.indent_current_nsp += 4
2212 2212 elif dedent_re.match(line):
2213 2213 self.indent_current_nsp -= 4
2214 2214 else:
2215 2215 self.indent_current_nsp = 0
2216 2216
2217 2217 def resetbuffer(self):
2218 2218 """Reset the input buffer."""
2219 2219 self.buffer[:] = []
2220 2220
2221 2221 def raw_input(self,prompt='',continue_prompt=False):
2222 2222 """Write a prompt and read a line.
2223 2223
2224 2224 The returned line does not include the trailing newline.
2225 2225 When the user enters the EOF key sequence, EOFError is raised.
2226 2226
2227 2227 Optional inputs:
2228 2228
2229 2229 - prompt(''): a string to be printed to prompt the user.
2230 2230
2231 2231 - continue_prompt(False): whether this line is the first one or a
2232 2232 continuation in a sequence of inputs.
2233 2233 """
2234 2234 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2235 2235
2236 2236 # Code run by the user may have modified the readline completer state.
2237 2237 # We must ensure that our completer is back in place.
2238 2238
2239 2239 if self.has_readline:
2240 2240 self.set_completer()
2241 2241
2242 2242 try:
2243 2243 line = raw_input_original(prompt).decode(self.stdin_encoding)
2244 2244 except ValueError:
2245 2245 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2246 2246 " or sys.stdout.close()!\nExiting IPython!")
2247 2247 self.ask_exit()
2248 2248 return ""
2249 2249
2250 2250 # Try to be reasonably smart about not re-indenting pasted input more
2251 2251 # than necessary. We do this by trimming out the auto-indent initial
2252 2252 # spaces, if the user's actual input started itself with whitespace.
2253 2253 #debugx('self.buffer[-1]')
2254 2254
2255 2255 if self.autoindent:
2256 2256 if num_ini_spaces(line) > self.indent_current_nsp:
2257 2257 line = line[self.indent_current_nsp:]
2258 2258 self.indent_current_nsp = 0
2259 2259
2260 2260 # store the unfiltered input before the user has any chance to modify
2261 2261 # it.
2262 2262 if line.strip():
2263 2263 if continue_prompt:
2264 2264 self.input_hist_raw[-1] += '%s\n' % line
2265 2265 if self.has_readline and self.readline_use:
2266 2266 try:
2267 2267 histlen = self.readline.get_current_history_length()
2268 2268 if histlen > 1:
2269 2269 newhist = self.input_hist_raw[-1].rstrip()
2270 2270 self.readline.remove_history_item(histlen-1)
2271 2271 self.readline.replace_history_item(histlen-2,
2272 2272 newhist.encode(self.stdin_encoding))
2273 2273 except AttributeError:
2274 2274 pass # re{move,place}_history_item are new in 2.4.
2275 2275 else:
2276 2276 self.input_hist_raw.append('%s\n' % line)
2277 2277 # only entries starting at first column go to shadow history
2278 2278 if line.lstrip() == line:
2279 2279 self.shadowhist.add(line.strip())
2280 2280 elif not continue_prompt:
2281 2281 self.input_hist_raw.append('\n')
2282 2282 try:
2283 2283 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2284 2284 except:
2285 2285 # blanket except, in case a user-defined prefilter crashes, so it
2286 2286 # can't take all of ipython with it.
2287 2287 self.showtraceback()
2288 2288 return ''
2289 2289 else:
2290 2290 return lineout
2291 2291
2292 2292 #-------------------------------------------------------------------------
2293 2293 # Working with components
2294 2294 #-------------------------------------------------------------------------
2295 2295
2296 2296 def get_component(self, name=None, klass=None):
2297 2297 """Fetch a component by name and klass in my tree."""
2298 2298 c = Component.get_instances(root=self, name=name, klass=klass)
2299 2299 if len(c) == 0:
2300 2300 return None
2301 2301 if len(c) == 1:
2302 2302 return c[0]
2303 2303 else:
2304 2304 return c
2305 2305
2306 2306 #-------------------------------------------------------------------------
2307 2307 # IPython extensions
2308 2308 #-------------------------------------------------------------------------
2309 2309
2310 2310 def load_extension(self, module_str):
2311 2311 """Load an IPython extension by its module name.
2312 2312
2313 2313 An IPython extension is an importable Python module that has
2314 2314 a function with the signature::
2315 2315
2316 2316 def load_ipython_extension(ipython):
2317 2317 # Do things with ipython
2318 2318
2319 2319 This function is called after your extension is imported and the
2320 2320 currently active :class:`InteractiveShell` instance is passed as
2321 2321 the only argument. You can do anything you want with IPython at
2322 2322 that point, including defining new magic and aliases, adding new
2323 2323 components, etc.
2324 2324
2325 2325 The :func:`load_ipython_extension` will be called again is you
2326 2326 load or reload the extension again. It is up to the extension
2327 2327 author to add code to manage that.
2328 2328
2329 2329 You can put your extension modules anywhere you want, as long as
2330 2330 they can be imported by Python's standard import mechanism. However,
2331 2331 to make it easy to write extensions, you can also put your extensions
2332 2332 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2333 2333 is added to ``sys.path`` automatically.
2334 2334 """
2335 2335 from IPython.utils.syspathcontext import prepended_to_syspath
2336 2336
2337 2337 if module_str not in sys.modules:
2338 2338 with prepended_to_syspath(self.ipython_extension_dir):
2339 2339 __import__(module_str)
2340 2340 mod = sys.modules[module_str]
2341 2341 self._call_load_ipython_extension(mod)
2342 2342
2343 2343 def unload_extension(self, module_str):
2344 2344 """Unload an IPython extension by its module name.
2345 2345
2346 2346 This function looks up the extension's name in ``sys.modules`` and
2347 2347 simply calls ``mod.unload_ipython_extension(self)``.
2348 2348 """
2349 2349 if module_str in sys.modules:
2350 2350 mod = sys.modules[module_str]
2351 2351 self._call_unload_ipython_extension(mod)
2352 2352
2353 2353 def reload_extension(self, module_str):
2354 2354 """Reload an IPython extension by calling reload.
2355 2355
2356 2356 If the module has not been loaded before,
2357 2357 :meth:`InteractiveShell.load_extension` is called. Otherwise
2358 2358 :func:`reload` is called and then the :func:`load_ipython_extension`
2359 2359 function of the module, if it exists is called.
2360 2360 """
2361 2361 from IPython.utils.syspathcontext import prepended_to_syspath
2362 2362
2363 2363 with prepended_to_syspath(self.ipython_extension_dir):
2364 2364 if module_str in sys.modules:
2365 2365 mod = sys.modules[module_str]
2366 2366 reload(mod)
2367 2367 self._call_load_ipython_extension(mod)
2368 2368 else:
2369 2369 self.load_extension(module_str)
2370 2370
2371 2371 def _call_load_ipython_extension(self, mod):
2372 2372 if hasattr(mod, 'load_ipython_extension'):
2373 2373 mod.load_ipython_extension(self)
2374 2374
2375 2375 def _call_unload_ipython_extension(self, mod):
2376 2376 if hasattr(mod, 'unload_ipython_extension'):
2377 2377 mod.unload_ipython_extension(self)
2378 2378
2379 2379 #-------------------------------------------------------------------------
2380 2380 # Things related to the prefilter
2381 2381 #-------------------------------------------------------------------------
2382 2382
2383 2383 def init_prefilter(self):
2384 2384 self.prefilter_manager = PrefilterManager(self, config=self.config)
2385 2385
2386 2386 #-------------------------------------------------------------------------
2387 2387 # Utilities
2388 2388 #-------------------------------------------------------------------------
2389 2389
2390 2390 def getoutput(self, cmd):
2391 2391 return getoutput(self.var_expand(cmd,depth=2),
2392 2392 header=self.system_header,
2393 2393 verbose=self.system_verbose)
2394 2394
2395 2395 def getoutputerror(self, cmd):
2396 2396 return getoutputerror(self.var_expand(cmd,depth=2),
2397 2397 header=self.system_header,
2398 2398 verbose=self.system_verbose)
2399 2399
2400 2400 def var_expand(self,cmd,depth=0):
2401 2401 """Expand python variables in a string.
2402 2402
2403 2403 The depth argument indicates how many frames above the caller should
2404 2404 be walked to look for the local namespace where to expand variables.
2405 2405
2406 2406 The global namespace for expansion is always the user's interactive
2407 2407 namespace.
2408 2408 """
2409 2409
2410 2410 return str(ItplNS(cmd,
2411 2411 self.user_ns, # globals
2412 2412 # Skip our own frame in searching for locals:
2413 2413 sys._getframe(depth+1).f_locals # locals
2414 2414 ))
2415 2415
2416 2416 def mktempfile(self,data=None):
2417 2417 """Make a new tempfile and return its filename.
2418 2418
2419 2419 This makes a call to tempfile.mktemp, but it registers the created
2420 2420 filename internally so ipython cleans it up at exit time.
2421 2421
2422 2422 Optional inputs:
2423 2423
2424 2424 - data(None): if data is given, it gets written out to the temp file
2425 2425 immediately, and the file is closed again."""
2426 2426
2427 2427 filename = tempfile.mktemp('.py','ipython_edit_')
2428 2428 self.tempfiles.append(filename)
2429 2429
2430 2430 if data:
2431 2431 tmp_file = open(filename,'w')
2432 2432 tmp_file.write(data)
2433 2433 tmp_file.close()
2434 2434 return filename
2435 2435
2436 2436 def write(self,data):
2437 2437 """Write a string to the default output"""
2438 2438 Term.cout.write(data)
2439 2439
2440 2440 def write_err(self,data):
2441 2441 """Write a string to the default error output"""
2442 2442 Term.cerr.write(data)
2443 2443
2444 2444 def ask_yes_no(self,prompt,default=True):
2445 2445 if self.quiet:
2446 2446 return True
2447 2447 return ask_yes_no(prompt,default)
2448 2448
2449 2449 #-------------------------------------------------------------------------
2450 2450 # Things related to GUI support and pylab
2451 2451 #-------------------------------------------------------------------------
2452 2452
2453 2453 def enable_pylab(self, gui=None):
2454 """Activate pylab support at runtime.
2455
2456 This turns on support for matplotlib, preloads into the interactive
2457 namespace all of numpy and pylab, and configures IPython to correcdtly
2458 interact with the GUI event loop. The GUI backend to be used can be
2459 optionally selected with the optional :param:`gui` argument.
2460
2461 Parameters
2462 ----------
2463 gui : optional, string
2464
2465 If given, dictates the choice of matplotlib GUI backend to use
2466 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2467 'gtk'), otherwise we use the default chosen by matplotlib (as
2468 dictated by the matplotlib build-time options plus the user's
2469 matplotlibrc configuration file).
2454 2470 """
2455 """
2456 gui = pylab_activate(self.user_ns, gui)
2471 # We want to prevent the loading of pylab to pollute the user's
2472 # namespace as shown by the %who* magics, so we execute the activation
2473 # code in an empty namespace, and we update *both* user_ns and
2474 # user_config_ns with this information.
2475 ns = {}
2476 gui = pylab_activate(ns, gui)
2477 self.user_ns.update(ns)
2478 self.user_config_ns.update(ns)
2479 # Now we must activate the gui pylab wants to use, and fix %run to take
2480 # plot updates into account
2457 2481 enable_gui(gui)
2458 2482 self.magic_run = self._pylab_magic_run
2459 2483
2460
2461 2484 #-------------------------------------------------------------------------
2462 2485 # Things related to IPython exiting
2463 2486 #-------------------------------------------------------------------------
2464 2487
2465 2488 def ask_exit(self):
2466 2489 """ Ask the shell to exit. Can be overiden and used as a callback. """
2467 2490 self.exit_now = True
2468 2491
2469 2492 def exit(self):
2470 2493 """Handle interactive exit.
2471 2494
2472 2495 This method calls the ask_exit callback."""
2473 2496 if self.confirm_exit:
2474 2497 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2475 2498 self.ask_exit()
2476 2499 else:
2477 2500 self.ask_exit()
2478 2501
2479 2502 def atexit_operations(self):
2480 2503 """This will be executed at the time of exit.
2481 2504
2482 2505 Saving of persistent data should be performed here.
2483 2506 """
2484 2507 self.savehist()
2485 2508
2486 2509 # Cleanup all tempfiles left around
2487 2510 for tfile in self.tempfiles:
2488 2511 try:
2489 2512 os.unlink(tfile)
2490 2513 except OSError:
2491 2514 pass
2492 2515
2493 2516 # Clear all user namespaces to release all references cleanly.
2494 2517 self.reset()
2495 2518
2496 2519 # Run user hooks
2497 2520 self.hooks.shutdown_hook()
2498 2521
2499 2522 def cleanup(self):
2500 2523 self.restore_sys_module_state()
2501 2524
2502 2525
@@ -1,999 +1,994 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 Prefiltering components.
5 5
6 6 Prefilters transform user input before it is exec'd by Python. These
7 7 transforms are used to implement additional syntax such as !ls and %magic.
8 8
9 9 Authors:
10 10
11 11 * Brian Granger
12 12 * Fernando Perez
13 13 * Dan Milstein
14 14 * Ville Vainio
15 15 """
16 16
17 17 #-----------------------------------------------------------------------------
18 18 # Copyright (C) 2008-2009 The IPython Development Team
19 19 #
20 20 # Distributed under the terms of the BSD License. The full license is in
21 21 # the file COPYING, distributed as part of this software.
22 22 #-----------------------------------------------------------------------------
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Imports
26 26 #-----------------------------------------------------------------------------
27 27
28 28 import __builtin__
29 29 import codeop
30 30 import keyword
31 31 import os
32 32 import re
33 33 import sys
34 34
35 35 from IPython.core.alias import AliasManager
36 36 from IPython.core.autocall import IPyAutocall
37 37 from IPython.core.component import Component
38 38 from IPython.core.splitinput import split_user_input
39 39 from IPython.core.page import page
40 40
41 41 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool
42 42 from IPython.utils.genutils import make_quoted_expr, Term
43 43 from IPython.utils.autoattr import auto_attr
44 44
45 45 #-----------------------------------------------------------------------------
46 46 # Global utilities, errors and constants
47 47 #-----------------------------------------------------------------------------
48 48
49 49 # Warning, these cannot be changed unless various regular expressions
50 50 # are updated in a number of places. Not great, but at least we told you.
51 51 ESC_SHELL = '!'
52 52 ESC_SH_CAP = '!!'
53 53 ESC_HELP = '?'
54 54 ESC_MAGIC = '%'
55 55 ESC_QUOTE = ','
56 56 ESC_QUOTE2 = ';'
57 57 ESC_PAREN = '/'
58 58
59 59
60 60 class PrefilterError(Exception):
61 61 pass
62 62
63 63
64 64 # RegExp to identify potential function names
65 65 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
66 66
67 67 # RegExp to exclude strings with this start from autocalling. In
68 68 # particular, all binary operators should be excluded, so that if foo is
69 69 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
70 70 # characters '!=()' don't need to be checked for, as the checkPythonChars
71 71 # routine explicitely does so, to catch direct calls and rebindings of
72 72 # existing names.
73 73
74 74 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
75 75 # it affects the rest of the group in square brackets.
76 76 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
77 77 r'|^is |^not |^in |^and |^or ')
78 78
79 79 # try to catch also methods for stuff in lists/tuples/dicts: off
80 80 # (experimental). For this to work, the line_split regexp would need
81 81 # to be modified so it wouldn't break things at '['. That line is
82 82 # nasty enough that I shouldn't change it until I can test it _well_.
83 83 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
84 84
85 85
86 86 # Handler Check Utilities
87 87 def is_shadowed(identifier, ip):
88 88 """Is the given identifier defined in one of the namespaces which shadow
89 89 the alias and magic namespaces? Note that an identifier is different
90 90 than ifun, because it can not contain a '.' character."""
91 91 # This is much safer than calling ofind, which can change state
92 92 return (identifier in ip.user_ns \
93 93 or identifier in ip.internal_ns \
94 94 or identifier in ip.ns_table['builtin'])
95 95
96 96
97 97 #-----------------------------------------------------------------------------
98 98 # The LineInfo class used throughout
99 99 #-----------------------------------------------------------------------------
100 100
101 101
102 102 class LineInfo(object):
103 103 """A single line of input and associated info.
104 104
105 105 Includes the following as properties:
106 106
107 107 line
108 108 The original, raw line
109 109
110 110 continue_prompt
111 111 Is this line a continuation in a sequence of multiline input?
112 112
113 113 pre
114 114 The initial esc character or whitespace.
115 115
116 116 pre_char
117 117 The escape character(s) in pre or the empty string if there isn't one.
118 118 Note that '!!' is a possible value for pre_char. Otherwise it will
119 119 always be a single character.
120 120
121 121 pre_whitespace
122 122 The leading whitespace from pre if it exists. If there is a pre_char,
123 123 this is just ''.
124 124
125 125 ifun
126 126 The 'function part', which is basically the maximal initial sequence
127 127 of valid python identifiers and the '.' character. This is what is
128 128 checked for alias and magic transformations, used for auto-calling,
129 129 etc.
130 130
131 131 the_rest
132 132 Everything else on the line.
133 133 """
134 134 def __init__(self, line, continue_prompt):
135 135 self.line = line
136 136 self.continue_prompt = continue_prompt
137 137 self.pre, self.ifun, self.the_rest = split_user_input(line)
138 138
139 139 self.pre_char = self.pre.strip()
140 140 if self.pre_char:
141 141 self.pre_whitespace = '' # No whitespace allowd before esc chars
142 142 else:
143 143 self.pre_whitespace = self.pre
144 144
145 145 self._oinfo = None
146 146
147 147 def ofind(self, ip):
148 148 """Do a full, attribute-walking lookup of the ifun in the various
149 149 namespaces for the given IPython InteractiveShell instance.
150 150
151 151 Return a dict with keys: found,obj,ospace,ismagic
152 152
153 153 Note: can cause state changes because of calling getattr, but should
154 154 only be run if autocall is on and if the line hasn't matched any
155 155 other, less dangerous handlers.
156 156
157 157 Does cache the results of the call, so can be called multiple times
158 158 without worrying about *further* damaging state.
159 159 """
160 160 if not self._oinfo:
161 161 self._oinfo = ip.shell._ofind(self.ifun)
162 162 return self._oinfo
163 163
164 164 def __str__(self):
165 165 return "Lineinfo [%s|%s|%s]" %(self.pre,self.ifun,self.the_rest)
166 166
167 167
168 168 #-----------------------------------------------------------------------------
169 169 # Main Prefilter manager
170 170 #-----------------------------------------------------------------------------
171 171
172 172
173 173 class PrefilterManager(Component):
174 174 """Main prefilter component.
175 175
176 176 The IPython prefilter is run on all user input before it is run. The
177 177 prefilter consumes lines of input and produces transformed lines of
178 178 input.
179 179
180 180 The iplementation consists of two phases:
181 181
182 182 1. Transformers
183 183 2. Checkers and handlers
184 184
185 185 Over time, we plan on deprecating the checkers and handlers and doing
186 186 everything in the transformers.
187 187
188 188 The transformers are instances of :class:`PrefilterTransformer` and have
189 189 a single method :meth:`transform` that takes a line and returns a
190 190 transformed line. The transformation can be accomplished using any
191 191 tool, but our current ones use regular expressions for speed. We also
192 192 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
193 193
194 194 After all the transformers have been run, the line is fed to the checkers,
195 195 which are instances of :class:`PrefilterChecker`. The line is passed to
196 196 the :meth:`check` method, which either returns `None` or a
197 197 :class:`PrefilterHandler` instance. If `None` is returned, the other
198 198 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
199 199 the line is passed to the :meth:`handle` method of the returned
200 200 handler and no further checkers are tried.
201 201
202 202 Both transformers and checkers have a `priority` attribute, that determines
203 203 the order in which they are called. Smaller priorities are tried first.
204 204
205 205 Both transformers and checkers also have `enabled` attribute, which is
206 206 a boolean that determines if the instance is used.
207 207
208 208 Users or developers can change the priority or enabled attribute of
209 209 transformers or checkers, but they must call the :meth:`sort_checkers`
210 210 or :meth:`sort_transformers` method after changing the priority.
211 211 """
212 212
213 213 multi_line_specials = CBool(True, config=True)
214 214
215 215 def __init__(self, parent, config=None):
216 216 super(PrefilterManager, self).__init__(parent, config=config)
217 217 self.init_transformers()
218 218 self.init_handlers()
219 219 self.init_checkers()
220 220
221 221 @auto_attr
222 222 def shell(self):
223 223 return Component.get_instances(
224 224 root=self.root,
225 225 klass='IPython.core.iplib.InteractiveShell')[0]
226 226
227 227 #-------------------------------------------------------------------------
228 228 # API for managing transformers
229 229 #-------------------------------------------------------------------------
230 230
231 231 def init_transformers(self):
232 232 """Create the default transformers."""
233 233 self._transformers = []
234 234 for transformer_cls in _default_transformers:
235 235 transformer_cls(self, config=self.config)
236 236
237 237 def sort_transformers(self):
238 238 """Sort the transformers by priority.
239 239
240 240 This must be called after the priority of a transformer is changed.
241 241 The :meth:`register_transformer` method calls this automatically.
242 242 """
243 243 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
244 244
245 245 @property
246 246 def transformers(self):
247 247 """Return a list of checkers, sorted by priority."""
248 248 return self._transformers
249 249
250 250 def register_transformer(self, transformer):
251 251 """Register a transformer instance."""
252 252 if transformer not in self._transformers:
253 253 self._transformers.append(transformer)
254 254 self.sort_transformers()
255 255
256 256 def unregister_transformer(self, transformer):
257 257 """Unregister a transformer instance."""
258 258 if transformer in self._transformers:
259 259 self._transformers.remove(transformer)
260 260
261 261 #-------------------------------------------------------------------------
262 262 # API for managing checkers
263 263 #-------------------------------------------------------------------------
264 264
265 265 def init_checkers(self):
266 266 """Create the default checkers."""
267 267 self._checkers = []
268 268 for checker in _default_checkers:
269 269 checker(self, config=self.config)
270 270
271 271 def sort_checkers(self):
272 272 """Sort the checkers by priority.
273 273
274 274 This must be called after the priority of a checker is changed.
275 275 The :meth:`register_checker` method calls this automatically.
276 276 """
277 277 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
278 278
279 279 @property
280 280 def checkers(self):
281 281 """Return a list of checkers, sorted by priority."""
282 282 return self._checkers
283 283
284 284 def register_checker(self, checker):
285 285 """Register a checker instance."""
286 286 if checker not in self._checkers:
287 287 self._checkers.append(checker)
288 288 self.sort_checkers()
289 289
290 290 def unregister_checker(self, checker):
291 291 """Unregister a checker instance."""
292 292 if checker in self._checkers:
293 293 self._checkers.remove(checker)
294 294
295 295 #-------------------------------------------------------------------------
296 296 # API for managing checkers
297 297 #-------------------------------------------------------------------------
298 298
299 299 def init_handlers(self):
300 300 """Create the default handlers."""
301 301 self._handlers = {}
302 302 self._esc_handlers = {}
303 303 for handler in _default_handlers:
304 304 handler(self, config=self.config)
305 305
306 306 @property
307 307 def handlers(self):
308 308 """Return a dict of all the handlers."""
309 309 return self._handlers
310 310
311 311 def register_handler(self, name, handler, esc_strings):
312 312 """Register a handler instance by name with esc_strings."""
313 313 self._handlers[name] = handler
314 314 for esc_str in esc_strings:
315 315 self._esc_handlers[esc_str] = handler
316 316
317 317 def unregister_handler(self, name, handler, esc_strings):
318 318 """Unregister a handler instance by name with esc_strings."""
319 319 try:
320 320 del self._handlers[name]
321 321 except KeyError:
322 322 pass
323 323 for esc_str in esc_strings:
324 324 h = self._esc_handlers.get(esc_str)
325 325 if h is handler:
326 326 del self._esc_handlers[esc_str]
327 327
328 328 def get_handler_by_name(self, name):
329 329 """Get a handler by its name."""
330 330 return self._handlers.get(name)
331 331
332 332 def get_handler_by_esc(self, esc_str):
333 333 """Get a handler by its escape string."""
334 334 return self._esc_handlers.get(esc_str)
335 335
336 336 #-------------------------------------------------------------------------
337 337 # Main prefiltering API
338 338 #-------------------------------------------------------------------------
339 339
340 340 def prefilter_line_info(self, line_info):
341 341 """Prefilter a line that has been converted to a LineInfo object.
342 342
343 343 This implements the checker/handler part of the prefilter pipe.
344 344 """
345 345 # print "prefilter_line_info: ", line_info
346 346 handler = self.find_handler(line_info)
347 347 return handler.handle(line_info)
348 348
349 349 def find_handler(self, line_info):
350 350 """Find a handler for the line_info by trying checkers."""
351 351 for checker in self.checkers:
352 352 if checker.enabled:
353 353 handler = checker.check(line_info)
354 354 if handler:
355 355 return handler
356 356 return self.get_handler_by_name('normal')
357 357
358 358 def transform_line(self, line, continue_prompt):
359 359 """Calls the enabled transformers in order of increasing priority."""
360 360 for transformer in self.transformers:
361 361 if transformer.enabled:
362 362 line = transformer.transform(line, continue_prompt)
363 363 return line
364 364
365 365 def prefilter_line(self, line, continue_prompt):
366 366 """Prefilter a single input line as text.
367 367
368 368 This method prefilters a single line of text by calling the
369 369 transformers and then the checkers/handlers.
370 370 """
371 371
372 372 # print "prefilter_line: ", line, continue_prompt
373 373 # All handlers *must* return a value, even if it's blank ('').
374 374
375 375 # Lines are NOT logged here. Handlers should process the line as
376 376 # needed, update the cache AND log it (so that the input cache array
377 377 # stays synced).
378 378
379 379 # save the line away in case we crash, so the post-mortem handler can
380 380 # record it
381 381 self.shell._last_input_line = line
382 382
383 383 if not line:
384 384 # Return immediately on purely empty lines, so that if the user
385 385 # previously typed some whitespace that started a continuation
386 386 # prompt, he can break out of that loop with just an empty line.
387 387 # This is how the default python prompt works.
388 388
389 389 # Only return if the accumulated input buffer was just whitespace!
390 390 if ''.join(self.shell.buffer).isspace():
391 391 self.shell.buffer[:] = []
392 392 return ''
393 393
394 394 # At this point, we invoke our transformers.
395 395 if not continue_prompt or (continue_prompt and self.multi_line_specials):
396 396 line = self.transform_line(line, continue_prompt)
397 397
398 398 # Now we compute line_info for the checkers and handlers
399 399 line_info = LineInfo(line, continue_prompt)
400 400
401 401 # the input history needs to track even empty lines
402 402 stripped = line.strip()
403 403
404 404 normal_handler = self.get_handler_by_name('normal')
405 405 if not stripped:
406 406 if not continue_prompt:
407 407 self.shell.outputcache.prompt_count -= 1
408 408
409 409 return normal_handler.handle(line_info)
410 410
411 411 # special handlers are only allowed for single line statements
412 412 if continue_prompt and not self.multi_line_specials:
413 413 return normal_handler.handle(line_info)
414 414
415 415 prefiltered = self.prefilter_line_info(line_info)
416 416 # print "prefiltered line: %r" % prefiltered
417 417 return prefiltered
418 418
419 419 def prefilter_lines(self, lines, continue_prompt):
420 420 """Prefilter multiple input lines of text.
421 421
422 422 This is the main entry point for prefiltering multiple lines of
423 423 input. This simply calls :meth:`prefilter_line` for each line of
424 424 input.
425 425
426 426 This covers cases where there are multiple lines in the user entry,
427 427 which is the case when the user goes back to a multiline history
428 428 entry and presses enter.
429 429 """
430 430 out = []
431 431 for line in lines.rstrip('\n').split('\n'):
432 432 out.append(self.prefilter_line(line, continue_prompt))
433 433 return '\n'.join(out)
434 434
435 435
436 436 #-----------------------------------------------------------------------------
437 437 # Prefilter transformers
438 438 #-----------------------------------------------------------------------------
439 439
440 440
441 441 class PrefilterTransformer(Component):
442 442 """Transform a line of user input."""
443 443
444 444 priority = Int(100, config=True)
445 445 shell = Any
446 446 prefilter_manager = Any
447 447 enabled = Bool(True, config=True)
448 448
449 449 def __init__(self, parent, config=None):
450 450 super(PrefilterTransformer, self).__init__(parent, config=config)
451 451 self.prefilter_manager.register_transformer(self)
452 452
453 453 @auto_attr
454 454 def shell(self):
455 455 return Component.get_instances(
456 456 root=self.root,
457 457 klass='IPython.core.iplib.InteractiveShell')[0]
458 458
459 459 @auto_attr
460 460 def prefilter_manager(self):
461 461 return PrefilterManager.get_instances(root=self.root)[0]
462 462
463 463 def transform(self, line, continue_prompt):
464 464 """Transform a line, returning the new one."""
465 465 return None
466 466
467 467 def __repr__(self):
468 468 return "<%s(priority=%r, enabled=%r)>" % (
469 469 self.__class__.__name__, self.priority, self.enabled)
470 470
471 471
472 472 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
473 473 r'\s*=\s*!(?P<cmd>.*)')
474 474
475 475
476 476 class AssignSystemTransformer(PrefilterTransformer):
477 477 """Handle the `files = !ls` syntax."""
478 478
479 479 priority = Int(100, config=True)
480 480
481 481 def transform(self, line, continue_prompt):
482 482 m = _assign_system_re.match(line)
483 483 if m is not None:
484 484 cmd = m.group('cmd')
485 485 lhs = m.group('lhs')
486 486 expr = make_quoted_expr("sc -l =%s" % cmd)
487 487 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
488 488 return new_line
489 489 return line
490 490
491 491
492 492 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
493 493 r'\s*=\s*%(?P<cmd>.*)')
494 494
495 495 class AssignMagicTransformer(PrefilterTransformer):
496 496 """Handle the `a = %who` syntax."""
497 497
498 498 priority = Int(200, config=True)
499 499
500 500 def transform(self, line, continue_prompt):
501 501 m = _assign_magic_re.match(line)
502 502 if m is not None:
503 503 cmd = m.group('cmd')
504 504 lhs = m.group('lhs')
505 505 expr = make_quoted_expr(cmd)
506 506 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
507 507 return new_line
508 508 return line
509 509
510 510
511 511 #-----------------------------------------------------------------------------
512 512 # Prefilter checkers
513 513 #-----------------------------------------------------------------------------
514 514
515 515
516 516 class PrefilterChecker(Component):
517 517 """Inspect an input line and return a handler for that line."""
518 518
519 519 priority = Int(100, config=True)
520 520 shell = Any
521 521 prefilter_manager = Any
522 522 enabled = Bool(True, config=True)
523 523
524 524 def __init__(self, parent, config=None):
525 525 super(PrefilterChecker, self).__init__(parent, config=config)
526 526 self.prefilter_manager.register_checker(self)
527 527
528 528 @auto_attr
529 529 def shell(self):
530 530 return Component.get_instances(
531 531 root=self.root,
532 532 klass='IPython.core.iplib.InteractiveShell')[0]
533 533
534 534 @auto_attr
535 535 def prefilter_manager(self):
536 536 return PrefilterManager.get_instances(root=self.root)[0]
537 537
538 538 def check(self, line_info):
539 539 """Inspect line_info and return a handler instance or None."""
540 540 return None
541 541
542 542 def __repr__(self):
543 543 return "<%s(priority=%r, enabled=%r)>" % (
544 544 self.__class__.__name__, self.priority, self.enabled)
545 545
546 546
547 547 class EmacsChecker(PrefilterChecker):
548 548
549 549 priority = Int(100, config=True)
550 550 enabled = Bool(False, config=True)
551 551
552 552 def check(self, line_info):
553 553 "Emacs ipython-mode tags certain input lines."
554 554 if line_info.line.endswith('# PYTHON-MODE'):
555 555 return self.prefilter_manager.get_handler_by_name('emacs')
556 556 else:
557 557 return None
558 558
559 559
560 560 class ShellEscapeChecker(PrefilterChecker):
561 561
562 562 priority = Int(200, config=True)
563 563
564 564 def check(self, line_info):
565 565 if line_info.line.lstrip().startswith(ESC_SHELL):
566 566 return self.prefilter_manager.get_handler_by_name('shell')
567 567
568 568
569 569 class IPyAutocallChecker(PrefilterChecker):
570 570
571 571 priority = Int(300, config=True)
572 572
573 573 def check(self, line_info):
574 574 "Instances of IPyAutocall in user_ns get autocalled immediately"
575 575 obj = self.shell.user_ns.get(line_info.ifun, None)
576 576 if isinstance(obj, IPyAutocall):
577 577 obj.set_ip(self.shell)
578 578 return self.prefilter_manager.get_handler_by_name('auto')
579 579 else:
580 580 return None
581 581
582 582
583 583 class MultiLineMagicChecker(PrefilterChecker):
584 584
585 585 priority = Int(400, config=True)
586 586
587 587 def check(self, line_info):
588 588 "Allow ! and !! in multi-line statements if multi_line_specials is on"
589 589 # Note that this one of the only places we check the first character of
590 590 # ifun and *not* the pre_char. Also note that the below test matches
591 591 # both ! and !!.
592 592 if line_info.continue_prompt \
593 593 and self.prefilter_manager.multi_line_specials:
594 594 if line_info.ifun.startswith(ESC_MAGIC):
595 595 return self.prefilter_manager.get_handler_by_name('magic')
596 596 else:
597 597 return None
598 598
599 599
600 600 class EscCharsChecker(PrefilterChecker):
601 601
602 602 priority = Int(500, config=True)
603 603
604 604 def check(self, line_info):
605 605 """Check for escape character and return either a handler to handle it,
606 606 or None if there is no escape char."""
607 607 if line_info.line[-1] == ESC_HELP \
608 608 and line_info.pre_char != ESC_SHELL \
609 609 and line_info.pre_char != ESC_SH_CAP:
610 610 # the ? can be at the end, but *not* for either kind of shell escape,
611 611 # because a ? can be a vaild final char in a shell cmd
612 612 return self.prefilter_manager.get_handler_by_name('help')
613 613 else:
614 614 # This returns None like it should if no handler exists
615 615 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
616 616
617 617
618 618 class AssignmentChecker(PrefilterChecker):
619 619
620 620 priority = Int(600, config=True)
621 621
622 622 def check(self, line_info):
623 623 """Check to see if user is assigning to a var for the first time, in
624 624 which case we want to avoid any sort of automagic / autocall games.
625 625
626 626 This allows users to assign to either alias or magic names true python
627 627 variables (the magic/alias systems always take second seat to true
628 628 python code). E.g. ls='hi', or ls,that=1,2"""
629 629 if line_info.the_rest:
630 630 if line_info.the_rest[0] in '=,':
631 631 return self.prefilter_manager.get_handler_by_name('normal')
632 632 else:
633 633 return None
634 634
635 635
636 636 class AutoMagicChecker(PrefilterChecker):
637 637
638 638 priority = Int(700, config=True)
639 639
640 640 def check(self, line_info):
641 641 """If the ifun is magic, and automagic is on, run it. Note: normal,
642 642 non-auto magic would already have been triggered via '%' in
643 643 check_esc_chars. This just checks for automagic. Also, before
644 644 triggering the magic handler, make sure that there is nothing in the
645 645 user namespace which could shadow it."""
646 646 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
647 647 return None
648 648
649 649 # We have a likely magic method. Make sure we should actually call it.
650 650 if line_info.continue_prompt and not self.shell.multi_line_specials:
651 651 return None
652 652
653 653 head = line_info.ifun.split('.',1)[0]
654 654 if is_shadowed(head, self.shell):
655 655 return None
656 656
657 657 return self.prefilter_manager.get_handler_by_name('magic')
658 658
659 659
660 660 class AliasChecker(PrefilterChecker):
661 661
662 662 priority = Int(800, config=True)
663 663
664 664 @auto_attr
665 665 def alias_manager(self):
666 666 return AliasManager.get_instances(root=self.root)[0]
667 667
668 668 def check(self, line_info):
669 669 "Check if the initital identifier on the line is an alias."
670 670 # Note: aliases can not contain '.'
671 671 head = line_info.ifun.split('.',1)[0]
672 672 if line_info.ifun not in self.alias_manager \
673 673 or head not in self.alias_manager \
674 674 or is_shadowed(head, self.shell):
675 675 return None
676 676
677 677 return self.prefilter_manager.get_handler_by_name('alias')
678 678
679 679
680 680 class PythonOpsChecker(PrefilterChecker):
681 681
682 682 priority = Int(900, config=True)
683 683
684 684 def check(self, line_info):
685 685 """If the 'rest' of the line begins with a function call or pretty much
686 686 any python operator, we should simply execute the line (regardless of
687 687 whether or not there's a possible autocall expansion). This avoids
688 688 spurious (and very confusing) geattr() accesses."""
689 689 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
690 690 return self.prefilter_manager.get_handler_by_name('normal')
691 691 else:
692 692 return None
693 693
694 694
695 695 class AutocallChecker(PrefilterChecker):
696 696
697 697 priority = Int(1000, config=True)
698 698
699 699 def check(self, line_info):
700 700 "Check if the initial word/function is callable and autocall is on."
701 701 if not self.shell.autocall:
702 702 return None
703 703
704 704 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
705 705 if not oinfo['found']:
706 706 return None
707 707
708 708 if callable(oinfo['obj']) \
709 709 and (not re_exclude_auto.match(line_info.the_rest)) \
710 710 and re_fun_name.match(line_info.ifun):
711 711 return self.prefilter_manager.get_handler_by_name('auto')
712 712 else:
713 713 return None
714 714
715 715
716 716 #-----------------------------------------------------------------------------
717 717 # Prefilter handlers
718 718 #-----------------------------------------------------------------------------
719 719
720 720
721 721 class PrefilterHandler(Component):
722 722
723 723 handler_name = Str('normal')
724 724 esc_strings = List([])
725 725 shell = Any
726 726 prefilter_manager = Any
727 727
728 728 def __init__(self, parent, config=None):
729 729 super(PrefilterHandler, self).__init__(parent, config=config)
730 730 self.prefilter_manager.register_handler(
731 731 self.handler_name,
732 732 self,
733 733 self.esc_strings
734 734 )
735 735
736 736 @auto_attr
737 737 def shell(self):
738 738 return Component.get_instances(
739 739 root=self.root,
740 740 klass='IPython.core.iplib.InteractiveShell')[0]
741 741
742 742 @auto_attr
743 743 def prefilter_manager(self):
744 744 return PrefilterManager.get_instances(root=self.root)[0]
745 745
746 746 def handle(self, line_info):
747 747 # print "normal: ", line_info
748 748 """Handle normal input lines. Use as a template for handlers."""
749 749
750 750 # With autoindent on, we need some way to exit the input loop, and I
751 751 # don't want to force the user to have to backspace all the way to
752 752 # clear the line. The rule will be in this case, that either two
753 753 # lines of pure whitespace in a row, or a line of pure whitespace but
754 754 # of a size different to the indent level, will exit the input loop.
755 755 line = line_info.line
756 756 continue_prompt = line_info.continue_prompt
757 757
758 758 if (continue_prompt and self.shell.autoindent and line.isspace() and
759 759 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2 or
760 760 (self.shell.buffer[-1]).isspace() )):
761 761 line = ''
762 762
763 763 self.shell.log(line, line, continue_prompt)
764 764 return line
765 765
766 766 def __str__(self):
767 767 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
768 768
769 769
770 770 class AliasHandler(PrefilterHandler):
771 771
772 772 handler_name = Str('alias')
773 773
774 774 @auto_attr
775 775 def alias_manager(self):
776 776 return AliasManager.get_instances(root=self.root)[0]
777 777
778 778 def handle(self, line_info):
779 779 """Handle alias input lines. """
780 780 transformed = self.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
781 781 # pre is needed, because it carries the leading whitespace. Otherwise
782 782 # aliases won't work in indented sections.
783 783 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
784 784 make_quoted_expr(transformed))
785 785
786 786 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
787 787 return line_out
788 788
789 789
790 790 class ShellEscapeHandler(PrefilterHandler):
791 791
792 792 handler_name = Str('shell')
793 793 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
794 794
795 795 def handle(self, line_info):
796 796 """Execute the line in a shell, empty return value"""
797 797 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
798 798
799 799 line = line_info.line
800 800 if line.lstrip().startswith(ESC_SH_CAP):
801 801 # rewrite LineInfo's line, ifun and the_rest to properly hold the
802 802 # call to %sx and the actual command to be executed, so
803 803 # handle_magic can work correctly. Note that this works even if
804 804 # the line is indented, so it handles multi_line_specials
805 805 # properly.
806 806 new_rest = line.lstrip()[2:]
807 807 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
808 808 line_info.ifun = 'sx'
809 809 line_info.the_rest = new_rest
810 810 return magic_handler.handle(line_info)
811 811 else:
812 812 cmd = line.lstrip().lstrip(ESC_SHELL)
813 813 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
814 814 make_quoted_expr(cmd))
815 815 # update cache/log and return
816 816 self.shell.log(line, line_out, line_info.continue_prompt)
817 817 return line_out
818 818
819 819
820 820 class MagicHandler(PrefilterHandler):
821 821
822 822 handler_name = Str('magic')
823 823 esc_strings = List([ESC_MAGIC])
824 824
825 825 def handle(self, line_info):
826 826 """Execute magic functions."""
827 827 ifun = line_info.ifun
828 828 the_rest = line_info.the_rest
829 829 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
830 830 make_quoted_expr(ifun + " " + the_rest))
831 831 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
832 832 return cmd
833 833
834 834
835 835 class AutoHandler(PrefilterHandler):
836 836
837 837 handler_name = Str('auto')
838 838 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
839 839
840 840 def handle(self, line_info):
841 841 """Hande lines which can be auto-executed, quoting if requested."""
842 842 line = line_info.line
843 843 ifun = line_info.ifun
844 844 the_rest = line_info.the_rest
845 845 pre = line_info.pre
846 846 continue_prompt = line_info.continue_prompt
847 847 obj = line_info.ofind(self)['obj']
848
849 848 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
850 849
851 850 # This should only be active for single-line input!
852 851 if continue_prompt:
853 # XXX - Ugly hack! We are breaking on multiline input and I'm out
854 # of time tonight to disentangle the component hirerarchy issue
855 # here... Fix this more cleanly later.
856 852 self.shell.log(line,line,continue_prompt)
857
858 853 return line
859 854
860 855 force_auto = isinstance(obj, IPyAutocall)
861 856 auto_rewrite = True
862 857
863 858 if pre == ESC_QUOTE:
864 859 # Auto-quote splitting on whitespace
865 860 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
866 861 elif pre == ESC_QUOTE2:
867 862 # Auto-quote whole string
868 863 newcmd = '%s("%s")' % (ifun,the_rest)
869 864 elif pre == ESC_PAREN:
870 865 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
871 866 else:
872 867 # Auto-paren.
873 868 # We only apply it to argument-less calls if the autocall
874 869 # parameter is set to 2. We only need to check that autocall is <
875 870 # 2, since this function isn't called unless it's at least 1.
876 871 if not the_rest and (self.shell.autocall < 2) and not force_auto:
877 872 newcmd = '%s %s' % (ifun,the_rest)
878 873 auto_rewrite = False
879 874 else:
880 875 if not force_auto and the_rest.startswith('['):
881 876 if hasattr(obj,'__getitem__'):
882 877 # Don't autocall in this case: item access for an object
883 878 # which is BOTH callable and implements __getitem__.
884 879 newcmd = '%s %s' % (ifun,the_rest)
885 880 auto_rewrite = False
886 881 else:
887 882 # if the object doesn't support [] access, go ahead and
888 883 # autocall
889 884 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
890 885 elif the_rest.endswith(';'):
891 886 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
892 887 else:
893 888 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
894 889
895 890 if auto_rewrite:
896 891 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
897 892
898 893 try:
899 894 # plain ascii works better w/ pyreadline, on some machines, so
900 895 # we use it and only print uncolored rewrite if we have unicode
901 896 rw = str(rw)
902 897 print >>Term.cout, rw
903 898 except UnicodeEncodeError:
904 899 print "-------------->" + newcmd
905 900
906 901 # log what is now valid Python, not the actual user input (without the
907 902 # final newline)
908 903 self.shell.log(line,newcmd,continue_prompt)
909 904 return newcmd
910 905
911 906
912 907 class HelpHandler(PrefilterHandler):
913 908
914 909 handler_name = Str('help')
915 910 esc_strings = List([ESC_HELP])
916 911
917 912 def handle(self, line_info):
918 913 """Try to get some help for the object.
919 914
920 915 obj? or ?obj -> basic information.
921 916 obj?? or ??obj -> more details.
922 917 """
923 918 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
924 919 line = line_info.line
925 920 # We need to make sure that we don't process lines which would be
926 921 # otherwise valid python, such as "x=1 # what?"
927 922 try:
928 923 codeop.compile_command(line)
929 924 except SyntaxError:
930 925 # We should only handle as help stuff which is NOT valid syntax
931 926 if line[0]==ESC_HELP:
932 927 line = line[1:]
933 928 elif line[-1]==ESC_HELP:
934 929 line = line[:-1]
935 930 self.shell.log(line, '#?'+line, line_info.continue_prompt)
936 931 if line:
937 932 #print 'line:<%r>' % line # dbg
938 933 self.shell.magic_pinfo(line)
939 934 else:
940 935 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
941 936 return '' # Empty string is needed here!
942 937 except:
943 938 raise
944 939 # Pass any other exceptions through to the normal handler
945 940 return normal_handler.handle(line_info)
946 941 else:
947 942 raise
948 943 # If the code compiles ok, we should handle it normally
949 944 return normal_handler.handle(line_info)
950 945
951 946
952 947 class EmacsHandler(PrefilterHandler):
953 948
954 949 handler_name = Str('emacs')
955 950 esc_strings = List([])
956 951
957 952 def handle(self, line_info):
958 953 """Handle input lines marked by python-mode."""
959 954
960 955 # Currently, nothing is done. Later more functionality can be added
961 956 # here if needed.
962 957
963 958 # The input cache shouldn't be updated
964 959 return line_info.line
965 960
966 961
967 962 #-----------------------------------------------------------------------------
968 963 # Defaults
969 964 #-----------------------------------------------------------------------------
970 965
971 966
972 967 _default_transformers = [
973 968 AssignSystemTransformer,
974 969 AssignMagicTransformer
975 970 ]
976 971
977 972 _default_checkers = [
978 973 EmacsChecker,
979 974 ShellEscapeChecker,
980 975 IPyAutocallChecker,
981 976 MultiLineMagicChecker,
982 977 EscCharsChecker,
983 978 AssignmentChecker,
984 979 AutoMagicChecker,
985 980 AliasChecker,
986 981 PythonOpsChecker,
987 982 AutocallChecker
988 983 ]
989 984
990 985 _default_handlers = [
991 986 PrefilterHandler,
992 987 AliasHandler,
993 988 ShellEscapeHandler,
994 989 MagicHandler,
995 990 AutoHandler,
996 991 HelpHandler,
997 992 EmacsHandler
998 993 ]
999 994
General Comments 0
You need to be logged in to leave comments. Login now