##// END OF EJS Templates
enabled qtconsole to retrieve history
Satrajit Ghosh -
Show More
@@ -1,2539 +1,2543 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import atexit
24 24 import codeop
25 25 import os
26 26 import re
27 27 import sys
28 28 import tempfile
29 29 import types
30 30 from contextlib import nested
31 31
32 32 from IPython.config.configurable import Configurable
33 33 from IPython.core import debugger, oinspect
34 34 from IPython.core import history as ipcorehist
35 35 from IPython.core import page
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.compilerop import CachingCompiler
42 42 from IPython.core.display_trap import DisplayTrap
43 43 from IPython.core.displayhook import DisplayHook
44 44 from IPython.core.error import TryNext, UsageError
45 45 from IPython.core.extensions import ExtensionManager
46 46 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 47 from IPython.core.history import HistoryManager
48 48 from IPython.core.inputsplitter import IPythonInputSplitter
49 49 from IPython.core.logger import Logger
50 50 from IPython.core.magic import Magic
51 51 from IPython.core.payload import PayloadManager
52 52 from IPython.core.plugin import PluginManager
53 53 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 54 from IPython.external.Itpl import ItplNS
55 55 from IPython.utils import PyColorize
56 56 from IPython.utils import io
57 57 from IPython.utils import pickleshare
58 58 from IPython.utils.doctestreload import doctest_reload
59 59 from IPython.utils.io import ask_yes_no, rprint
60 60 from IPython.utils.ipstruct import Struct
61 61 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 62 from IPython.utils.process import system, getoutput
63 63 from IPython.utils.strdispatch import StrDispatch
64 64 from IPython.utils.syspathcontext import prepended_to_syspath
65 65 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
66 66 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 67 List, Unicode, Instance, Type)
68 68 from IPython.utils.warn import warn, error, fatal
69 69 import IPython.core.hooks
70 70
71 71 #-----------------------------------------------------------------------------
72 72 # Globals
73 73 #-----------------------------------------------------------------------------
74 74
75 75 # compiled regexps for autoindent management
76 76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 77
78 78 #-----------------------------------------------------------------------------
79 79 # Utilities
80 80 #-----------------------------------------------------------------------------
81 81
82 82 # store the builtin raw_input globally, and use this always, in case user code
83 83 # overwrites it (like wx.py.PyShell does)
84 84 raw_input_original = raw_input
85 85
86 86 def softspace(file, newvalue):
87 87 """Copied from code.py, to remove the dependency"""
88 88
89 89 oldvalue = 0
90 90 try:
91 91 oldvalue = file.softspace
92 92 except AttributeError:
93 93 pass
94 94 try:
95 95 file.softspace = newvalue
96 96 except (AttributeError, TypeError):
97 97 # "attribute-less object" or "read-only attributes"
98 98 pass
99 99 return oldvalue
100 100
101 101
102 102 def no_op(*a, **kw): pass
103 103
104 104 class SpaceInInput(Exception): pass
105 105
106 106 class Bunch: pass
107 107
108 108
109 109 def get_default_colors():
110 110 if sys.platform=='darwin':
111 111 return "LightBG"
112 112 elif os.name=='nt':
113 113 return 'Linux'
114 114 else:
115 115 return 'Linux'
116 116
117 117
118 118 class SeparateStr(Str):
119 119 """A Str subclass to validate separate_in, separate_out, etc.
120 120
121 121 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 122 """
123 123
124 124 def validate(self, obj, value):
125 125 if value == '0': value = ''
126 126 value = value.replace('\\n','\n')
127 127 return super(SeparateStr, self).validate(obj, value)
128 128
129 129 class MultipleInstanceError(Exception):
130 130 pass
131 131
132 132
133 133 #-----------------------------------------------------------------------------
134 134 # Main IPython class
135 135 #-----------------------------------------------------------------------------
136 136
137 137 class InteractiveShell(Configurable, Magic):
138 138 """An enhanced, interactive shell for Python."""
139 139
140 140 _instance = None
141 141 autocall = Enum((0,1,2), default_value=1, config=True)
142 142 # TODO: remove all autoindent logic and put into frontends.
143 143 # We can't do this yet because even runlines uses the autoindent.
144 144 autoindent = CBool(True, config=True)
145 145 automagic = CBool(True, config=True)
146 146 cache_size = Int(1000, config=True)
147 147 color_info = CBool(True, config=True)
148 148 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
149 149 default_value=get_default_colors(), config=True)
150 150 debug = CBool(False, config=True)
151 151 deep_reload = CBool(False, config=True)
152 152 displayhook_class = Type(DisplayHook)
153 153 exit_now = CBool(False)
154 154 # Monotonically increasing execution counter
155 155 execution_count = Int(1)
156 156 filename = Str("<ipython console>")
157 157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 158
159 159 # Input splitter, to split entire cells of input into either individual
160 160 # interactive statements or whole blocks.
161 161 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 162 (), {})
163 163 logstart = CBool(False, config=True)
164 164 logfile = Str('', config=True)
165 165 logappend = Str('', config=True)
166 166 object_info_string_level = Enum((0,1,2), default_value=0,
167 167 config=True)
168 168 pdb = CBool(False, config=True)
169 169
170 170 pprint = CBool(True, config=True)
171 171 profile = Str('', config=True)
172 172 prompt_in1 = Str('In [\\#]: ', config=True)
173 173 prompt_in2 = Str(' .\\D.: ', config=True)
174 174 prompt_out = Str('Out[\\#]: ', config=True)
175 175 prompts_pad_left = CBool(True, config=True)
176 176 quiet = CBool(False, config=True)
177 177
178 178 history_length = Int(10000, config=True)
179 179
180 180 # The readline stuff will eventually be moved to the terminal subclass
181 181 # but for now, we can't do that as readline is welded in everywhere.
182 182 readline_use = CBool(True, config=True)
183 183 readline_merge_completions = CBool(True, config=True)
184 184 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
185 185 readline_remove_delims = Str('-/~', config=True)
186 186 readline_parse_and_bind = List([
187 187 'tab: complete',
188 188 '"\C-l": clear-screen',
189 189 'set show-all-if-ambiguous on',
190 190 '"\C-o": tab-insert',
191 191 '"\M-i": " "',
192 192 '"\M-o": "\d\d\d\d"',
193 193 '"\M-I": "\d\d\d\d"',
194 194 '"\C-r": reverse-search-history',
195 195 '"\C-s": forward-search-history',
196 196 '"\C-p": history-search-backward',
197 197 '"\C-n": history-search-forward',
198 198 '"\e[A": history-search-backward',
199 199 '"\e[B": history-search-forward',
200 200 '"\C-k": kill-line',
201 201 '"\C-u": unix-line-discard',
202 202 ], allow_none=False, config=True)
203 203
204 204 # TODO: this part of prompt management should be moved to the frontends.
205 205 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
206 206 separate_in = SeparateStr('\n', config=True)
207 207 separate_out = SeparateStr('', config=True)
208 208 separate_out2 = SeparateStr('', config=True)
209 209 wildcards_case_sensitive = CBool(True, config=True)
210 210 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
211 211 default_value='Context', config=True)
212 212
213 213 # Subcomponents of InteractiveShell
214 214 alias_manager = Instance('IPython.core.alias.AliasManager')
215 215 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
216 216 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
217 217 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
218 218 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
219 219 plugin_manager = Instance('IPython.core.plugin.PluginManager')
220 220 payload_manager = Instance('IPython.core.payload.PayloadManager')
221 221 history_manager = Instance('IPython.core.history.HistoryManager')
222 222
223 223 # Private interface
224 224 _post_execute = set()
225 225
226 226 def __init__(self, config=None, ipython_dir=None,
227 227 user_ns=None, user_global_ns=None,
228 228 custom_exceptions=((), None)):
229 229
230 230 # This is where traits with a config_key argument are updated
231 231 # from the values on config.
232 232 super(InteractiveShell, self).__init__(config=config)
233 233
234 234 # These are relatively independent and stateless
235 235 self.init_ipython_dir(ipython_dir)
236 236 self.init_instance_attrs()
237 237 self.init_environment()
238 238
239 239 # Create namespaces (user_ns, user_global_ns, etc.)
240 240 self.init_create_namespaces(user_ns, user_global_ns)
241 241 # This has to be done after init_create_namespaces because it uses
242 242 # something in self.user_ns, but before init_sys_modules, which
243 243 # is the first thing to modify sys.
244 244 # TODO: When we override sys.stdout and sys.stderr before this class
245 245 # is created, we are saving the overridden ones here. Not sure if this
246 246 # is what we want to do.
247 247 self.save_sys_module_state()
248 248 self.init_sys_modules()
249 249
250 250 self.init_history()
251 251 self.init_encoding()
252 252 self.init_prefilter()
253 253
254 254 Magic.__init__(self, self)
255 255
256 256 self.init_syntax_highlighting()
257 257 self.init_hooks()
258 258 self.init_pushd_popd_magic()
259 259 # self.init_traceback_handlers use to be here, but we moved it below
260 260 # because it and init_io have to come after init_readline.
261 261 self.init_user_ns()
262 262 self.init_logger()
263 263 self.init_alias()
264 264 self.init_builtins()
265 265
266 266 # pre_config_initialization
267 267
268 268 # The next section should contain everything that was in ipmaker.
269 269 self.init_logstart()
270 270
271 271 # The following was in post_config_initialization
272 272 self.init_inspector()
273 273 # init_readline() must come before init_io(), because init_io uses
274 274 # readline related things.
275 275 self.init_readline()
276 276 # init_completer must come after init_readline, because it needs to
277 277 # know whether readline is present or not system-wide to configure the
278 278 # completers, since the completion machinery can now operate
279 279 # independently of readline (e.g. over the network)
280 280 self.init_completer()
281 281 # TODO: init_io() needs to happen before init_traceback handlers
282 282 # because the traceback handlers hardcode the stdout/stderr streams.
283 283 # This logic in in debugger.Pdb and should eventually be changed.
284 284 self.init_io()
285 285 self.init_traceback_handlers(custom_exceptions)
286 286 self.init_prompts()
287 287 self.init_displayhook()
288 288 self.init_reload_doctest()
289 289 self.init_magics()
290 290 self.init_pdb()
291 291 self.init_extension_manager()
292 292 self.init_plugin_manager()
293 293 self.init_payload()
294 294 self.hooks.late_startup_hook()
295 295 atexit.register(self.atexit_operations)
296 296
297 297 # While we're trying to have each part of the code directly access what it
298 298 # needs without keeping redundant references to objects, we have too much
299 299 # legacy code that expects ip.db to exist, so let's make it a property that
300 300 # retrieves the underlying object from our new history manager.
301 301 @property
302 302 def db(self):
303 303 return self.history_manager.shadow_db
304 304
305 305 @classmethod
306 306 def instance(cls, *args, **kwargs):
307 307 """Returns a global InteractiveShell instance."""
308 308 if cls._instance is None:
309 309 inst = cls(*args, **kwargs)
310 310 # Now make sure that the instance will also be returned by
311 311 # the subclasses instance attribute.
312 312 for subclass in cls.mro():
313 313 if issubclass(cls, subclass) and \
314 314 issubclass(subclass, InteractiveShell):
315 315 subclass._instance = inst
316 316 else:
317 317 break
318 318 if isinstance(cls._instance, cls):
319 319 return cls._instance
320 320 else:
321 321 raise MultipleInstanceError(
322 322 'Multiple incompatible subclass instances of '
323 323 'InteractiveShell are being created.'
324 324 )
325 325
326 326 @classmethod
327 327 def initialized(cls):
328 328 return hasattr(cls, "_instance")
329 329
330 330 def get_ipython(self):
331 331 """Return the currently running IPython instance."""
332 332 return self
333 333
334 334 #-------------------------------------------------------------------------
335 335 # Trait changed handlers
336 336 #-------------------------------------------------------------------------
337 337
338 338 def _ipython_dir_changed(self, name, new):
339 339 if not os.path.isdir(new):
340 340 os.makedirs(new, mode = 0777)
341 341
342 342 def set_autoindent(self,value=None):
343 343 """Set the autoindent flag, checking for readline support.
344 344
345 345 If called with no arguments, it acts as a toggle."""
346 346
347 347 if not self.has_readline:
348 348 if os.name == 'posix':
349 349 warn("The auto-indent feature requires the readline library")
350 350 self.autoindent = 0
351 351 return
352 352 if value is None:
353 353 self.autoindent = not self.autoindent
354 354 else:
355 355 self.autoindent = value
356 356
357 357 #-------------------------------------------------------------------------
358 358 # init_* methods called by __init__
359 359 #-------------------------------------------------------------------------
360 360
361 361 def init_ipython_dir(self, ipython_dir):
362 362 if ipython_dir is not None:
363 363 self.ipython_dir = ipython_dir
364 364 self.config.Global.ipython_dir = self.ipython_dir
365 365 return
366 366
367 367 if hasattr(self.config.Global, 'ipython_dir'):
368 368 self.ipython_dir = self.config.Global.ipython_dir
369 369 else:
370 370 self.ipython_dir = get_ipython_dir()
371 371
372 372 # All children can just read this
373 373 self.config.Global.ipython_dir = self.ipython_dir
374 374
375 375 def init_instance_attrs(self):
376 376 self.more = False
377 377
378 378 # command compiler
379 379 self.compile = CachingCompiler()
380 380
381 381 # User input buffers
382 382 # NOTE: these variables are slated for full removal, once we are 100%
383 383 # sure that the new execution logic is solid. We will delte runlines,
384 384 # push_line and these buffers, as all input will be managed by the
385 385 # frontends via an inputsplitter instance.
386 386 self.buffer = []
387 387 self.buffer_raw = []
388 388
389 389 # Make an empty namespace, which extension writers can rely on both
390 390 # existing and NEVER being used by ipython itself. This gives them a
391 391 # convenient location for storing additional information and state
392 392 # their extensions may require, without fear of collisions with other
393 393 # ipython names that may develop later.
394 394 self.meta = Struct()
395 395
396 396 # Object variable to store code object waiting execution. This is
397 397 # used mainly by the multithreaded shells, but it can come in handy in
398 398 # other situations. No need to use a Queue here, since it's a single
399 399 # item which gets cleared once run.
400 400 self.code_to_run = None
401 401
402 402 # Temporary files used for various purposes. Deleted at exit.
403 403 self.tempfiles = []
404 404
405 405 # Keep track of readline usage (later set by init_readline)
406 406 self.has_readline = False
407 407
408 408 # keep track of where we started running (mainly for crash post-mortem)
409 409 # This is not being used anywhere currently.
410 410 self.starting_dir = os.getcwd()
411 411
412 412 # Indentation management
413 413 self.indent_current_nsp = 0
414 414
415 415 def init_environment(self):
416 416 """Any changes we need to make to the user's environment."""
417 417 pass
418 418
419 419 def init_encoding(self):
420 420 # Get system encoding at startup time. Certain terminals (like Emacs
421 421 # under Win32 have it set to None, and we need to have a known valid
422 422 # encoding to use in the raw_input() method
423 423 try:
424 424 self.stdin_encoding = sys.stdin.encoding or 'ascii'
425 425 except AttributeError:
426 426 self.stdin_encoding = 'ascii'
427 427
428 428 def init_syntax_highlighting(self):
429 429 # Python source parser/formatter for syntax highlighting
430 430 pyformat = PyColorize.Parser().format
431 431 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
432 432
433 433 def init_pushd_popd_magic(self):
434 434 # for pushd/popd management
435 435 try:
436 436 self.home_dir = get_home_dir()
437 437 except HomeDirError, msg:
438 438 fatal(msg)
439 439
440 440 self.dir_stack = []
441 441
442 442 def init_logger(self):
443 443 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
444 444 logmode='rotate')
445 445
446 446 def init_logstart(self):
447 447 """Initialize logging in case it was requested at the command line.
448 448 """
449 449 if self.logappend:
450 450 self.magic_logstart(self.logappend + ' append')
451 451 elif self.logfile:
452 452 self.magic_logstart(self.logfile)
453 453 elif self.logstart:
454 454 self.magic_logstart()
455 455
456 456 def init_builtins(self):
457 457 self.builtin_trap = BuiltinTrap(shell=self)
458 458
459 459 def init_inspector(self):
460 460 # Object inspector
461 461 self.inspector = oinspect.Inspector(oinspect.InspectColors,
462 462 PyColorize.ANSICodeColors,
463 463 'NoColor',
464 464 self.object_info_string_level)
465 465
466 466 def init_io(self):
467 467 # This will just use sys.stdout and sys.stderr. If you want to
468 468 # override sys.stdout and sys.stderr themselves, you need to do that
469 469 # *before* instantiating this class, because Term holds onto
470 470 # references to the underlying streams.
471 471 if sys.platform == 'win32' and self.has_readline:
472 472 Term = io.IOTerm(cout=self.readline._outputfile,
473 473 cerr=self.readline._outputfile)
474 474 else:
475 475 Term = io.IOTerm()
476 476 io.Term = Term
477 477
478 478 def init_prompts(self):
479 479 # TODO: This is a pass for now because the prompts are managed inside
480 480 # the DisplayHook. Once there is a separate prompt manager, this
481 481 # will initialize that object and all prompt related information.
482 482 pass
483 483
484 484 def init_displayhook(self):
485 485 # Initialize displayhook, set in/out prompts and printing system
486 486 self.displayhook = self.displayhook_class(
487 487 config=self.config,
488 488 shell=self,
489 489 cache_size=self.cache_size,
490 490 input_sep = self.separate_in,
491 491 output_sep = self.separate_out,
492 492 output_sep2 = self.separate_out2,
493 493 ps1 = self.prompt_in1,
494 494 ps2 = self.prompt_in2,
495 495 ps_out = self.prompt_out,
496 496 pad_left = self.prompts_pad_left
497 497 )
498 498 # This is a context manager that installs/revmoes the displayhook at
499 499 # the appropriate time.
500 500 self.display_trap = DisplayTrap(hook=self.displayhook)
501 501
502 502 def init_reload_doctest(self):
503 503 # Do a proper resetting of doctest, including the necessary displayhook
504 504 # monkeypatching
505 505 try:
506 506 doctest_reload()
507 507 except ImportError:
508 508 warn("doctest module does not exist.")
509 509
510 510 #-------------------------------------------------------------------------
511 511 # Things related to injections into the sys module
512 512 #-------------------------------------------------------------------------
513 513
514 514 def save_sys_module_state(self):
515 515 """Save the state of hooks in the sys module.
516 516
517 517 This has to be called after self.user_ns is created.
518 518 """
519 519 self._orig_sys_module_state = {}
520 520 self._orig_sys_module_state['stdin'] = sys.stdin
521 521 self._orig_sys_module_state['stdout'] = sys.stdout
522 522 self._orig_sys_module_state['stderr'] = sys.stderr
523 523 self._orig_sys_module_state['excepthook'] = sys.excepthook
524 524 try:
525 525 self._orig_sys_modules_main_name = self.user_ns['__name__']
526 526 except KeyError:
527 527 pass
528 528
529 529 def restore_sys_module_state(self):
530 530 """Restore the state of the sys module."""
531 531 try:
532 532 for k, v in self._orig_sys_module_state.iteritems():
533 533 setattr(sys, k, v)
534 534 except AttributeError:
535 535 pass
536 536 # Reset what what done in self.init_sys_modules
537 537 try:
538 538 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
539 539 except (AttributeError, KeyError):
540 540 pass
541 541
542 542 #-------------------------------------------------------------------------
543 543 # Things related to hooks
544 544 #-------------------------------------------------------------------------
545 545
546 546 def init_hooks(self):
547 547 # hooks holds pointers used for user-side customizations
548 548 self.hooks = Struct()
549 549
550 550 self.strdispatchers = {}
551 551
552 552 # Set all default hooks, defined in the IPython.hooks module.
553 553 hooks = IPython.core.hooks
554 554 for hook_name in hooks.__all__:
555 555 # default hooks have priority 100, i.e. low; user hooks should have
556 556 # 0-100 priority
557 557 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
558 558
559 559 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
560 560 """set_hook(name,hook) -> sets an internal IPython hook.
561 561
562 562 IPython exposes some of its internal API as user-modifiable hooks. By
563 563 adding your function to one of these hooks, you can modify IPython's
564 564 behavior to call at runtime your own routines."""
565 565
566 566 # At some point in the future, this should validate the hook before it
567 567 # accepts it. Probably at least check that the hook takes the number
568 568 # of args it's supposed to.
569 569
570 570 f = types.MethodType(hook,self)
571 571
572 572 # check if the hook is for strdispatcher first
573 573 if str_key is not None:
574 574 sdp = self.strdispatchers.get(name, StrDispatch())
575 575 sdp.add_s(str_key, f, priority )
576 576 self.strdispatchers[name] = sdp
577 577 return
578 578 if re_key is not None:
579 579 sdp = self.strdispatchers.get(name, StrDispatch())
580 580 sdp.add_re(re.compile(re_key), f, priority )
581 581 self.strdispatchers[name] = sdp
582 582 return
583 583
584 584 dp = getattr(self.hooks, name, None)
585 585 if name not in IPython.core.hooks.__all__:
586 586 print "Warning! Hook '%s' is not one of %s" % \
587 587 (name, IPython.core.hooks.__all__ )
588 588 if not dp:
589 589 dp = IPython.core.hooks.CommandChainDispatcher()
590 590
591 591 try:
592 592 dp.add(f,priority)
593 593 except AttributeError:
594 594 # it was not commandchain, plain old func - replace
595 595 dp = f
596 596
597 597 setattr(self.hooks,name, dp)
598 598
599 599 def register_post_execute(self, func):
600 600 """Register a function for calling after code execution.
601 601 """
602 602 if not callable(func):
603 603 raise ValueError('argument %s must be callable' % func)
604 604 self._post_execute.add(func)
605 605
606 606 #-------------------------------------------------------------------------
607 607 # Things related to the "main" module
608 608 #-------------------------------------------------------------------------
609 609
610 610 def new_main_mod(self,ns=None):
611 611 """Return a new 'main' module object for user code execution.
612 612 """
613 613 main_mod = self._user_main_module
614 614 init_fakemod_dict(main_mod,ns)
615 615 return main_mod
616 616
617 617 def cache_main_mod(self,ns,fname):
618 618 """Cache a main module's namespace.
619 619
620 620 When scripts are executed via %run, we must keep a reference to the
621 621 namespace of their __main__ module (a FakeModule instance) around so
622 622 that Python doesn't clear it, rendering objects defined therein
623 623 useless.
624 624
625 625 This method keeps said reference in a private dict, keyed by the
626 626 absolute path of the module object (which corresponds to the script
627 627 path). This way, for multiple executions of the same script we only
628 628 keep one copy of the namespace (the last one), thus preventing memory
629 629 leaks from old references while allowing the objects from the last
630 630 execution to be accessible.
631 631
632 632 Note: we can not allow the actual FakeModule instances to be deleted,
633 633 because of how Python tears down modules (it hard-sets all their
634 634 references to None without regard for reference counts). This method
635 635 must therefore make a *copy* of the given namespace, to allow the
636 636 original module's __dict__ to be cleared and reused.
637 637
638 638
639 639 Parameters
640 640 ----------
641 641 ns : a namespace (a dict, typically)
642 642
643 643 fname : str
644 644 Filename associated with the namespace.
645 645
646 646 Examples
647 647 --------
648 648
649 649 In [10]: import IPython
650 650
651 651 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
652 652
653 653 In [12]: IPython.__file__ in _ip._main_ns_cache
654 654 Out[12]: True
655 655 """
656 656 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
657 657
658 658 def clear_main_mod_cache(self):
659 659 """Clear the cache of main modules.
660 660
661 661 Mainly for use by utilities like %reset.
662 662
663 663 Examples
664 664 --------
665 665
666 666 In [15]: import IPython
667 667
668 668 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
669 669
670 670 In [17]: len(_ip._main_ns_cache) > 0
671 671 Out[17]: True
672 672
673 673 In [18]: _ip.clear_main_mod_cache()
674 674
675 675 In [19]: len(_ip._main_ns_cache) == 0
676 676 Out[19]: True
677 677 """
678 678 self._main_ns_cache.clear()
679 679
680 680 #-------------------------------------------------------------------------
681 681 # Things related to debugging
682 682 #-------------------------------------------------------------------------
683 683
684 684 def init_pdb(self):
685 685 # Set calling of pdb on exceptions
686 686 # self.call_pdb is a property
687 687 self.call_pdb = self.pdb
688 688
689 689 def _get_call_pdb(self):
690 690 return self._call_pdb
691 691
692 692 def _set_call_pdb(self,val):
693 693
694 694 if val not in (0,1,False,True):
695 695 raise ValueError,'new call_pdb value must be boolean'
696 696
697 697 # store value in instance
698 698 self._call_pdb = val
699 699
700 700 # notify the actual exception handlers
701 701 self.InteractiveTB.call_pdb = val
702 702
703 703 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
704 704 'Control auto-activation of pdb at exceptions')
705 705
706 706 def debugger(self,force=False):
707 707 """Call the pydb/pdb debugger.
708 708
709 709 Keywords:
710 710
711 711 - force(False): by default, this routine checks the instance call_pdb
712 712 flag and does not actually invoke the debugger if the flag is false.
713 713 The 'force' option forces the debugger to activate even if the flag
714 714 is false.
715 715 """
716 716
717 717 if not (force or self.call_pdb):
718 718 return
719 719
720 720 if not hasattr(sys,'last_traceback'):
721 721 error('No traceback has been produced, nothing to debug.')
722 722 return
723 723
724 724 # use pydb if available
725 725 if debugger.has_pydb:
726 726 from pydb import pm
727 727 else:
728 728 # fallback to our internal debugger
729 729 pm = lambda : self.InteractiveTB.debugger(force=True)
730 730 self.history_saving_wrapper(pm)()
731 731
732 732 #-------------------------------------------------------------------------
733 733 # Things related to IPython's various namespaces
734 734 #-------------------------------------------------------------------------
735 735
736 736 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
737 737 # Create the namespace where the user will operate. user_ns is
738 738 # normally the only one used, and it is passed to the exec calls as
739 739 # the locals argument. But we do carry a user_global_ns namespace
740 740 # given as the exec 'globals' argument, This is useful in embedding
741 741 # situations where the ipython shell opens in a context where the
742 742 # distinction between locals and globals is meaningful. For
743 743 # non-embedded contexts, it is just the same object as the user_ns dict.
744 744
745 745 # FIXME. For some strange reason, __builtins__ is showing up at user
746 746 # level as a dict instead of a module. This is a manual fix, but I
747 747 # should really track down where the problem is coming from. Alex
748 748 # Schmolck reported this problem first.
749 749
750 750 # A useful post by Alex Martelli on this topic:
751 751 # Re: inconsistent value from __builtins__
752 752 # Von: Alex Martelli <aleaxit@yahoo.com>
753 753 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
754 754 # Gruppen: comp.lang.python
755 755
756 756 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
757 757 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
758 758 # > <type 'dict'>
759 759 # > >>> print type(__builtins__)
760 760 # > <type 'module'>
761 761 # > Is this difference in return value intentional?
762 762
763 763 # Well, it's documented that '__builtins__' can be either a dictionary
764 764 # or a module, and it's been that way for a long time. Whether it's
765 765 # intentional (or sensible), I don't know. In any case, the idea is
766 766 # that if you need to access the built-in namespace directly, you
767 767 # should start with "import __builtin__" (note, no 's') which will
768 768 # definitely give you a module. Yeah, it's somewhat confusing:-(.
769 769
770 770 # These routines return properly built dicts as needed by the rest of
771 771 # the code, and can also be used by extension writers to generate
772 772 # properly initialized namespaces.
773 773 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
774 774 user_global_ns)
775 775
776 776 # Assign namespaces
777 777 # This is the namespace where all normal user variables live
778 778 self.user_ns = user_ns
779 779 self.user_global_ns = user_global_ns
780 780
781 781 # An auxiliary namespace that checks what parts of the user_ns were
782 782 # loaded at startup, so we can list later only variables defined in
783 783 # actual interactive use. Since it is always a subset of user_ns, it
784 784 # doesn't need to be separately tracked in the ns_table.
785 785 self.user_ns_hidden = {}
786 786
787 787 # A namespace to keep track of internal data structures to prevent
788 788 # them from cluttering user-visible stuff. Will be updated later
789 789 self.internal_ns = {}
790 790
791 791 # Now that FakeModule produces a real module, we've run into a nasty
792 792 # problem: after script execution (via %run), the module where the user
793 793 # code ran is deleted. Now that this object is a true module (needed
794 794 # so docetst and other tools work correctly), the Python module
795 795 # teardown mechanism runs over it, and sets to None every variable
796 796 # present in that module. Top-level references to objects from the
797 797 # script survive, because the user_ns is updated with them. However,
798 798 # calling functions defined in the script that use other things from
799 799 # the script will fail, because the function's closure had references
800 800 # to the original objects, which are now all None. So we must protect
801 801 # these modules from deletion by keeping a cache.
802 802 #
803 803 # To avoid keeping stale modules around (we only need the one from the
804 804 # last run), we use a dict keyed with the full path to the script, so
805 805 # only the last version of the module is held in the cache. Note,
806 806 # however, that we must cache the module *namespace contents* (their
807 807 # __dict__). Because if we try to cache the actual modules, old ones
808 808 # (uncached) could be destroyed while still holding references (such as
809 809 # those held by GUI objects that tend to be long-lived)>
810 810 #
811 811 # The %reset command will flush this cache. See the cache_main_mod()
812 812 # and clear_main_mod_cache() methods for details on use.
813 813
814 814 # This is the cache used for 'main' namespaces
815 815 self._main_ns_cache = {}
816 816 # And this is the single instance of FakeModule whose __dict__ we keep
817 817 # copying and clearing for reuse on each %run
818 818 self._user_main_module = FakeModule()
819 819
820 820 # A table holding all the namespaces IPython deals with, so that
821 821 # introspection facilities can search easily.
822 822 self.ns_table = {'user':user_ns,
823 823 'user_global':user_global_ns,
824 824 'internal':self.internal_ns,
825 825 'builtin':__builtin__.__dict__
826 826 }
827 827
828 828 # Similarly, track all namespaces where references can be held and that
829 829 # we can safely clear (so it can NOT include builtin). This one can be
830 830 # a simple list. Note that the main execution namespaces, user_ns and
831 831 # user_global_ns, can NOT be listed here, as clearing them blindly
832 832 # causes errors in object __del__ methods. Instead, the reset() method
833 833 # clears them manually and carefully.
834 834 self.ns_refs_table = [ self.user_ns_hidden,
835 835 self.internal_ns, self._main_ns_cache ]
836 836
837 837 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
838 838 """Return a valid local and global user interactive namespaces.
839 839
840 840 This builds a dict with the minimal information needed to operate as a
841 841 valid IPython user namespace, which you can pass to the various
842 842 embedding classes in ipython. The default implementation returns the
843 843 same dict for both the locals and the globals to allow functions to
844 844 refer to variables in the namespace. Customized implementations can
845 845 return different dicts. The locals dictionary can actually be anything
846 846 following the basic mapping protocol of a dict, but the globals dict
847 847 must be a true dict, not even a subclass. It is recommended that any
848 848 custom object for the locals namespace synchronize with the globals
849 849 dict somehow.
850 850
851 851 Raises TypeError if the provided globals namespace is not a true dict.
852 852
853 853 Parameters
854 854 ----------
855 855 user_ns : dict-like, optional
856 856 The current user namespace. The items in this namespace should
857 857 be included in the output. If None, an appropriate blank
858 858 namespace should be created.
859 859 user_global_ns : dict, optional
860 860 The current user global namespace. The items in this namespace
861 861 should be included in the output. If None, an appropriate
862 862 blank namespace should be created.
863 863
864 864 Returns
865 865 -------
866 866 A pair of dictionary-like object to be used as the local namespace
867 867 of the interpreter and a dict to be used as the global namespace.
868 868 """
869 869
870 870
871 871 # We must ensure that __builtin__ (without the final 's') is always
872 872 # available and pointing to the __builtin__ *module*. For more details:
873 873 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
874 874
875 875 if user_ns is None:
876 876 # Set __name__ to __main__ to better match the behavior of the
877 877 # normal interpreter.
878 878 user_ns = {'__name__' :'__main__',
879 879 '__builtin__' : __builtin__,
880 880 '__builtins__' : __builtin__,
881 881 }
882 882 else:
883 883 user_ns.setdefault('__name__','__main__')
884 884 user_ns.setdefault('__builtin__',__builtin__)
885 885 user_ns.setdefault('__builtins__',__builtin__)
886 886
887 887 if user_global_ns is None:
888 888 user_global_ns = user_ns
889 889 if type(user_global_ns) is not dict:
890 890 raise TypeError("user_global_ns must be a true dict; got %r"
891 891 % type(user_global_ns))
892 892
893 893 return user_ns, user_global_ns
894 894
895 895 def init_sys_modules(self):
896 896 # We need to insert into sys.modules something that looks like a
897 897 # module but which accesses the IPython namespace, for shelve and
898 898 # pickle to work interactively. Normally they rely on getting
899 899 # everything out of __main__, but for embedding purposes each IPython
900 900 # instance has its own private namespace, so we can't go shoving
901 901 # everything into __main__.
902 902
903 903 # note, however, that we should only do this for non-embedded
904 904 # ipythons, which really mimic the __main__.__dict__ with their own
905 905 # namespace. Embedded instances, on the other hand, should not do
906 906 # this because they need to manage the user local/global namespaces
907 907 # only, but they live within a 'normal' __main__ (meaning, they
908 908 # shouldn't overtake the execution environment of the script they're
909 909 # embedded in).
910 910
911 911 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
912 912
913 913 try:
914 914 main_name = self.user_ns['__name__']
915 915 except KeyError:
916 916 raise KeyError('user_ns dictionary MUST have a "__name__" key')
917 917 else:
918 918 sys.modules[main_name] = FakeModule(self.user_ns)
919 919
920 920 def init_user_ns(self):
921 921 """Initialize all user-visible namespaces to their minimum defaults.
922 922
923 923 Certain history lists are also initialized here, as they effectively
924 924 act as user namespaces.
925 925
926 926 Notes
927 927 -----
928 928 All data structures here are only filled in, they are NOT reset by this
929 929 method. If they were not empty before, data will simply be added to
930 930 therm.
931 931 """
932 932 # This function works in two parts: first we put a few things in
933 933 # user_ns, and we sync that contents into user_ns_hidden so that these
934 934 # initial variables aren't shown by %who. After the sync, we add the
935 935 # rest of what we *do* want the user to see with %who even on a new
936 936 # session (probably nothing, so theye really only see their own stuff)
937 937
938 938 # The user dict must *always* have a __builtin__ reference to the
939 939 # Python standard __builtin__ namespace, which must be imported.
940 940 # This is so that certain operations in prompt evaluation can be
941 941 # reliably executed with builtins. Note that we can NOT use
942 942 # __builtins__ (note the 's'), because that can either be a dict or a
943 943 # module, and can even mutate at runtime, depending on the context
944 944 # (Python makes no guarantees on it). In contrast, __builtin__ is
945 945 # always a module object, though it must be explicitly imported.
946 946
947 947 # For more details:
948 948 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
949 949 ns = dict(__builtin__ = __builtin__)
950 950
951 951 # Put 'help' in the user namespace
952 952 try:
953 953 from site import _Helper
954 954 ns['help'] = _Helper()
955 955 except ImportError:
956 956 warn('help() not available - check site.py')
957 957
958 958 # make global variables for user access to the histories
959 959 ns['_ih'] = self.history_manager.input_hist_parsed
960 960 ns['_oh'] = self.history_manager.output_hist
961 961 ns['_dh'] = self.history_manager.dir_hist
962 962
963 963 ns['_sh'] = shadowns
964 964
965 965 # user aliases to input and output histories. These shouldn't show up
966 966 # in %who, as they can have very large reprs.
967 967 ns['In'] = self.history_manager.input_hist_parsed
968 968 ns['Out'] = self.history_manager.output_hist
969 969
970 970 # Store myself as the public api!!!
971 971 ns['get_ipython'] = self.get_ipython
972 972
973 973 # Sync what we've added so far to user_ns_hidden so these aren't seen
974 974 # by %who
975 975 self.user_ns_hidden.update(ns)
976 976
977 977 # Anything put into ns now would show up in %who. Think twice before
978 978 # putting anything here, as we really want %who to show the user their
979 979 # stuff, not our variables.
980 980
981 981 # Finally, update the real user's namespace
982 982 self.user_ns.update(ns)
983 983
984 984 def reset(self):
985 985 """Clear all internal namespaces.
986 986
987 987 Note that this is much more aggressive than %reset, since it clears
988 988 fully all namespaces, as well as all input/output lists.
989 989 """
990 990 # Clear histories
991 991 self.history_manager.reset()
992 992
993 993 # Reset counter used to index all histories
994 994 self.execution_count = 0
995 995
996 996 # Restore the user namespaces to minimal usability
997 997 for ns in self.ns_refs_table:
998 998 ns.clear()
999 999
1000 1000 # The main execution namespaces must be cleared very carefully,
1001 1001 # skipping the deletion of the builtin-related keys, because doing so
1002 1002 # would cause errors in many object's __del__ methods.
1003 1003 for ns in [self.user_ns, self.user_global_ns]:
1004 1004 drop_keys = set(ns.keys())
1005 1005 drop_keys.discard('__builtin__')
1006 1006 drop_keys.discard('__builtins__')
1007 1007 for k in drop_keys:
1008 1008 del ns[k]
1009 1009
1010 1010 # Restore the user namespaces to minimal usability
1011 1011 self.init_user_ns()
1012 1012
1013 1013 # Restore the default and user aliases
1014 1014 self.alias_manager.clear_aliases()
1015 1015 self.alias_manager.init_aliases()
1016 1016
1017 1017 def reset_selective(self, regex=None):
1018 1018 """Clear selective variables from internal namespaces based on a
1019 1019 specified regular expression.
1020 1020
1021 1021 Parameters
1022 1022 ----------
1023 1023 regex : string or compiled pattern, optional
1024 1024 A regular expression pattern that will be used in searching
1025 1025 variable names in the users namespaces.
1026 1026 """
1027 1027 if regex is not None:
1028 1028 try:
1029 1029 m = re.compile(regex)
1030 1030 except TypeError:
1031 1031 raise TypeError('regex must be a string or compiled pattern')
1032 1032 # Search for keys in each namespace that match the given regex
1033 1033 # If a match is found, delete the key/value pair.
1034 1034 for ns in self.ns_refs_table:
1035 1035 for var in ns:
1036 1036 if m.search(var):
1037 1037 del ns[var]
1038 1038
1039 1039 def push(self, variables, interactive=True):
1040 1040 """Inject a group of variables into the IPython user namespace.
1041 1041
1042 1042 Parameters
1043 1043 ----------
1044 1044 variables : dict, str or list/tuple of str
1045 1045 The variables to inject into the user's namespace. If a dict, a
1046 1046 simple update is done. If a str, the string is assumed to have
1047 1047 variable names separated by spaces. A list/tuple of str can also
1048 1048 be used to give the variable names. If just the variable names are
1049 1049 give (list/tuple/str) then the variable values looked up in the
1050 1050 callers frame.
1051 1051 interactive : bool
1052 1052 If True (default), the variables will be listed with the ``who``
1053 1053 magic.
1054 1054 """
1055 1055 vdict = None
1056 1056
1057 1057 # We need a dict of name/value pairs to do namespace updates.
1058 1058 if isinstance(variables, dict):
1059 1059 vdict = variables
1060 1060 elif isinstance(variables, (basestring, list, tuple)):
1061 1061 if isinstance(variables, basestring):
1062 1062 vlist = variables.split()
1063 1063 else:
1064 1064 vlist = variables
1065 1065 vdict = {}
1066 1066 cf = sys._getframe(1)
1067 1067 for name in vlist:
1068 1068 try:
1069 1069 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1070 1070 except:
1071 1071 print ('Could not get variable %s from %s' %
1072 1072 (name,cf.f_code.co_name))
1073 1073 else:
1074 1074 raise ValueError('variables must be a dict/str/list/tuple')
1075 1075
1076 1076 # Propagate variables to user namespace
1077 1077 self.user_ns.update(vdict)
1078 1078
1079 1079 # And configure interactive visibility
1080 1080 config_ns = self.user_ns_hidden
1081 1081 if interactive:
1082 1082 for name, val in vdict.iteritems():
1083 1083 config_ns.pop(name, None)
1084 1084 else:
1085 1085 for name,val in vdict.iteritems():
1086 1086 config_ns[name] = val
1087 1087
1088 1088 #-------------------------------------------------------------------------
1089 1089 # Things related to object introspection
1090 1090 #-------------------------------------------------------------------------
1091 1091
1092 1092 def _ofind(self, oname, namespaces=None):
1093 1093 """Find an object in the available namespaces.
1094 1094
1095 1095 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1096 1096
1097 1097 Has special code to detect magic functions.
1098 1098 """
1099 1099 #oname = oname.strip()
1100 1100 #print '1- oname: <%r>' % oname # dbg
1101 1101 try:
1102 1102 oname = oname.strip().encode('ascii')
1103 1103 #print '2- oname: <%r>' % oname # dbg
1104 1104 except UnicodeEncodeError:
1105 1105 print 'Python identifiers can only contain ascii characters.'
1106 1106 return dict(found=False)
1107 1107
1108 1108 alias_ns = None
1109 1109 if namespaces is None:
1110 1110 # Namespaces to search in:
1111 1111 # Put them in a list. The order is important so that we
1112 1112 # find things in the same order that Python finds them.
1113 1113 namespaces = [ ('Interactive', self.user_ns),
1114 1114 ('IPython internal', self.internal_ns),
1115 1115 ('Python builtin', __builtin__.__dict__),
1116 1116 ('Alias', self.alias_manager.alias_table),
1117 1117 ]
1118 1118 alias_ns = self.alias_manager.alias_table
1119 1119
1120 1120 # initialize results to 'null'
1121 1121 found = False; obj = None; ospace = None; ds = None;
1122 1122 ismagic = False; isalias = False; parent = None
1123 1123
1124 1124 # We need to special-case 'print', which as of python2.6 registers as a
1125 1125 # function but should only be treated as one if print_function was
1126 1126 # loaded with a future import. In this case, just bail.
1127 1127 if (oname == 'print' and not (self.compile.compiler_flags &
1128 1128 __future__.CO_FUTURE_PRINT_FUNCTION)):
1129 1129 return {'found':found, 'obj':obj, 'namespace':ospace,
1130 1130 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1131 1131
1132 1132 # Look for the given name by splitting it in parts. If the head is
1133 1133 # found, then we look for all the remaining parts as members, and only
1134 1134 # declare success if we can find them all.
1135 1135 oname_parts = oname.split('.')
1136 1136 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1137 1137 for nsname,ns in namespaces:
1138 1138 try:
1139 1139 obj = ns[oname_head]
1140 1140 except KeyError:
1141 1141 continue
1142 1142 else:
1143 1143 #print 'oname_rest:', oname_rest # dbg
1144 1144 for part in oname_rest:
1145 1145 try:
1146 1146 parent = obj
1147 1147 obj = getattr(obj,part)
1148 1148 except:
1149 1149 # Blanket except b/c some badly implemented objects
1150 1150 # allow __getattr__ to raise exceptions other than
1151 1151 # AttributeError, which then crashes IPython.
1152 1152 break
1153 1153 else:
1154 1154 # If we finish the for loop (no break), we got all members
1155 1155 found = True
1156 1156 ospace = nsname
1157 1157 if ns == alias_ns:
1158 1158 isalias = True
1159 1159 break # namespace loop
1160 1160
1161 1161 # Try to see if it's magic
1162 1162 if not found:
1163 1163 if oname.startswith(ESC_MAGIC):
1164 1164 oname = oname[1:]
1165 1165 obj = getattr(self,'magic_'+oname,None)
1166 1166 if obj is not None:
1167 1167 found = True
1168 1168 ospace = 'IPython internal'
1169 1169 ismagic = True
1170 1170
1171 1171 # Last try: special-case some literals like '', [], {}, etc:
1172 1172 if not found and oname_head in ["''",'""','[]','{}','()']:
1173 1173 obj = eval(oname_head)
1174 1174 found = True
1175 1175 ospace = 'Interactive'
1176 1176
1177 1177 return {'found':found, 'obj':obj, 'namespace':ospace,
1178 1178 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1179 1179
1180 1180 def _ofind_property(self, oname, info):
1181 1181 """Second part of object finding, to look for property details."""
1182 1182 if info.found:
1183 1183 # Get the docstring of the class property if it exists.
1184 1184 path = oname.split('.')
1185 1185 root = '.'.join(path[:-1])
1186 1186 if info.parent is not None:
1187 1187 try:
1188 1188 target = getattr(info.parent, '__class__')
1189 1189 # The object belongs to a class instance.
1190 1190 try:
1191 1191 target = getattr(target, path[-1])
1192 1192 # The class defines the object.
1193 1193 if isinstance(target, property):
1194 1194 oname = root + '.__class__.' + path[-1]
1195 1195 info = Struct(self._ofind(oname))
1196 1196 except AttributeError: pass
1197 1197 except AttributeError: pass
1198 1198
1199 1199 # We return either the new info or the unmodified input if the object
1200 1200 # hadn't been found
1201 1201 return info
1202 1202
1203 1203 def _object_find(self, oname, namespaces=None):
1204 1204 """Find an object and return a struct with info about it."""
1205 1205 inf = Struct(self._ofind(oname, namespaces))
1206 1206 return Struct(self._ofind_property(oname, inf))
1207 1207
1208 1208 def _inspect(self, meth, oname, namespaces=None, **kw):
1209 1209 """Generic interface to the inspector system.
1210 1210
1211 1211 This function is meant to be called by pdef, pdoc & friends."""
1212 1212 info = self._object_find(oname)
1213 1213 if info.found:
1214 1214 pmethod = getattr(self.inspector, meth)
1215 1215 formatter = format_screen if info.ismagic else None
1216 1216 if meth == 'pdoc':
1217 1217 pmethod(info.obj, oname, formatter)
1218 1218 elif meth == 'pinfo':
1219 1219 pmethod(info.obj, oname, formatter, info, **kw)
1220 1220 else:
1221 1221 pmethod(info.obj, oname)
1222 1222 else:
1223 1223 print 'Object `%s` not found.' % oname
1224 1224 return 'not found' # so callers can take other action
1225 1225
1226 1226 def object_inspect(self, oname):
1227 1227 info = self._object_find(oname)
1228 1228 if info.found:
1229 1229 return self.inspector.info(info.obj, oname, info=info)
1230 1230 else:
1231 1231 return oinspect.object_info(name=oname, found=False)
1232 1232
1233 1233 #-------------------------------------------------------------------------
1234 1234 # Things related to history management
1235 1235 #-------------------------------------------------------------------------
1236 1236
1237 1237 def init_history(self):
1238 1238 self.history_manager = HistoryManager(shell=self)
1239 1239
1240 1240 def save_history(self):
1241 1241 """Save input history to a file (via readline library)."""
1242 1242 self.history_manager.save_history()
1243 1243
1244 1244 def reload_history(self):
1245 1245 """Reload the input history from disk file."""
1246 1246 self.history_manager.reload_history()
1247 1247
1248 1248 def history_saving_wrapper(self, func):
1249 1249 """ Wrap func for readline history saving
1250 1250
1251 1251 Convert func into callable that saves & restores
1252 1252 history around the call """
1253 1253
1254 1254 if self.has_readline:
1255 1255 from IPython.utils import rlineimpl as readline
1256 1256 else:
1257 1257 return func
1258 1258
1259 1259 def wrapper():
1260 1260 self.save_history()
1261 1261 try:
1262 1262 func()
1263 1263 finally:
1264 1264 self.reload_history()
1265 1265 return wrapper
1266 1266
1267 def get_history(self, index=None, raw=False, output=True):
1268 return self.history_manager.get_history(index, raw, output)
1269
1270
1267 1271 #-------------------------------------------------------------------------
1268 1272 # Things related to exception handling and tracebacks (not debugging)
1269 1273 #-------------------------------------------------------------------------
1270 1274
1271 1275 def init_traceback_handlers(self, custom_exceptions):
1272 1276 # Syntax error handler.
1273 1277 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1274 1278
1275 1279 # The interactive one is initialized with an offset, meaning we always
1276 1280 # want to remove the topmost item in the traceback, which is our own
1277 1281 # internal code. Valid modes: ['Plain','Context','Verbose']
1278 1282 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1279 1283 color_scheme='NoColor',
1280 1284 tb_offset = 1,
1281 1285 check_cache=self.compile.check_cache)
1282 1286
1283 1287 # The instance will store a pointer to the system-wide exception hook,
1284 1288 # so that runtime code (such as magics) can access it. This is because
1285 1289 # during the read-eval loop, it may get temporarily overwritten.
1286 1290 self.sys_excepthook = sys.excepthook
1287 1291
1288 1292 # and add any custom exception handlers the user may have specified
1289 1293 self.set_custom_exc(*custom_exceptions)
1290 1294
1291 1295 # Set the exception mode
1292 1296 self.InteractiveTB.set_mode(mode=self.xmode)
1293 1297
1294 1298 def set_custom_exc(self, exc_tuple, handler):
1295 1299 """set_custom_exc(exc_tuple,handler)
1296 1300
1297 1301 Set a custom exception handler, which will be called if any of the
1298 1302 exceptions in exc_tuple occur in the mainloop (specifically, in the
1299 1303 run_code() method.
1300 1304
1301 1305 Inputs:
1302 1306
1303 1307 - exc_tuple: a *tuple* of valid exceptions to call the defined
1304 1308 handler for. It is very important that you use a tuple, and NOT A
1305 1309 LIST here, because of the way Python's except statement works. If
1306 1310 you only want to trap a single exception, use a singleton tuple:
1307 1311
1308 1312 exc_tuple == (MyCustomException,)
1309 1313
1310 1314 - handler: this must be defined as a function with the following
1311 1315 basic interface::
1312 1316
1313 1317 def my_handler(self, etype, value, tb, tb_offset=None)
1314 1318 ...
1315 1319 # The return value must be
1316 1320 return structured_traceback
1317 1321
1318 1322 This will be made into an instance method (via types.MethodType)
1319 1323 of IPython itself, and it will be called if any of the exceptions
1320 1324 listed in the exc_tuple are caught. If the handler is None, an
1321 1325 internal basic one is used, which just prints basic info.
1322 1326
1323 1327 WARNING: by putting in your own exception handler into IPython's main
1324 1328 execution loop, you run a very good chance of nasty crashes. This
1325 1329 facility should only be used if you really know what you are doing."""
1326 1330
1327 1331 assert type(exc_tuple)==type(()) , \
1328 1332 "The custom exceptions must be given AS A TUPLE."
1329 1333
1330 1334 def dummy_handler(self,etype,value,tb):
1331 1335 print '*** Simple custom exception handler ***'
1332 1336 print 'Exception type :',etype
1333 1337 print 'Exception value:',value
1334 1338 print 'Traceback :',tb
1335 1339 print 'Source code :','\n'.join(self.buffer)
1336 1340
1337 1341 if handler is None: handler = dummy_handler
1338 1342
1339 1343 self.CustomTB = types.MethodType(handler,self)
1340 1344 self.custom_exceptions = exc_tuple
1341 1345
1342 1346 def excepthook(self, etype, value, tb):
1343 1347 """One more defense for GUI apps that call sys.excepthook.
1344 1348
1345 1349 GUI frameworks like wxPython trap exceptions and call
1346 1350 sys.excepthook themselves. I guess this is a feature that
1347 1351 enables them to keep running after exceptions that would
1348 1352 otherwise kill their mainloop. This is a bother for IPython
1349 1353 which excepts to catch all of the program exceptions with a try:
1350 1354 except: statement.
1351 1355
1352 1356 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1353 1357 any app directly invokes sys.excepthook, it will look to the user like
1354 1358 IPython crashed. In order to work around this, we can disable the
1355 1359 CrashHandler and replace it with this excepthook instead, which prints a
1356 1360 regular traceback using our InteractiveTB. In this fashion, apps which
1357 1361 call sys.excepthook will generate a regular-looking exception from
1358 1362 IPython, and the CrashHandler will only be triggered by real IPython
1359 1363 crashes.
1360 1364
1361 1365 This hook should be used sparingly, only in places which are not likely
1362 1366 to be true IPython errors.
1363 1367 """
1364 1368 self.showtraceback((etype,value,tb),tb_offset=0)
1365 1369
1366 1370 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1367 1371 exception_only=False):
1368 1372 """Display the exception that just occurred.
1369 1373
1370 1374 If nothing is known about the exception, this is the method which
1371 1375 should be used throughout the code for presenting user tracebacks,
1372 1376 rather than directly invoking the InteractiveTB object.
1373 1377
1374 1378 A specific showsyntaxerror() also exists, but this method can take
1375 1379 care of calling it if needed, so unless you are explicitly catching a
1376 1380 SyntaxError exception, don't try to analyze the stack manually and
1377 1381 simply call this method."""
1378 1382
1379 1383 try:
1380 1384 if exc_tuple is None:
1381 1385 etype, value, tb = sys.exc_info()
1382 1386 else:
1383 1387 etype, value, tb = exc_tuple
1384 1388
1385 1389 if etype is None:
1386 1390 if hasattr(sys, 'last_type'):
1387 1391 etype, value, tb = sys.last_type, sys.last_value, \
1388 1392 sys.last_traceback
1389 1393 else:
1390 1394 self.write_err('No traceback available to show.\n')
1391 1395 return
1392 1396
1393 1397 if etype is SyntaxError:
1394 1398 # Though this won't be called by syntax errors in the input
1395 1399 # line, there may be SyntaxError cases whith imported code.
1396 1400 self.showsyntaxerror(filename)
1397 1401 elif etype is UsageError:
1398 1402 print "UsageError:", value
1399 1403 else:
1400 1404 # WARNING: these variables are somewhat deprecated and not
1401 1405 # necessarily safe to use in a threaded environment, but tools
1402 1406 # like pdb depend on their existence, so let's set them. If we
1403 1407 # find problems in the field, we'll need to revisit their use.
1404 1408 sys.last_type = etype
1405 1409 sys.last_value = value
1406 1410 sys.last_traceback = tb
1407 1411
1408 1412 if etype in self.custom_exceptions:
1409 1413 # FIXME: Old custom traceback objects may just return a
1410 1414 # string, in that case we just put it into a list
1411 1415 stb = self.CustomTB(etype, value, tb, tb_offset)
1412 1416 if isinstance(ctb, basestring):
1413 1417 stb = [stb]
1414 1418 else:
1415 1419 if exception_only:
1416 1420 stb = ['An exception has occurred, use %tb to see '
1417 1421 'the full traceback.\n']
1418 1422 stb.extend(self.InteractiveTB.get_exception_only(etype,
1419 1423 value))
1420 1424 else:
1421 1425 stb = self.InteractiveTB.structured_traceback(etype,
1422 1426 value, tb, tb_offset=tb_offset)
1423 1427 # FIXME: the pdb calling should be done by us, not by
1424 1428 # the code computing the traceback.
1425 1429 if self.InteractiveTB.call_pdb:
1426 1430 # pdb mucks up readline, fix it back
1427 1431 self.set_readline_completer()
1428 1432
1429 1433 # Actually show the traceback
1430 1434 self._showtraceback(etype, value, stb)
1431 1435
1432 1436 except KeyboardInterrupt:
1433 1437 self.write_err("\nKeyboardInterrupt\n")
1434 1438
1435 1439 def _showtraceback(self, etype, evalue, stb):
1436 1440 """Actually show a traceback.
1437 1441
1438 1442 Subclasses may override this method to put the traceback on a different
1439 1443 place, like a side channel.
1440 1444 """
1441 1445 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1442 1446
1443 1447 def showsyntaxerror(self, filename=None):
1444 1448 """Display the syntax error that just occurred.
1445 1449
1446 1450 This doesn't display a stack trace because there isn't one.
1447 1451
1448 1452 If a filename is given, it is stuffed in the exception instead
1449 1453 of what was there before (because Python's parser always uses
1450 1454 "<string>" when reading from a string).
1451 1455 """
1452 1456 etype, value, last_traceback = sys.exc_info()
1453 1457
1454 1458 # See note about these variables in showtraceback() above
1455 1459 sys.last_type = etype
1456 1460 sys.last_value = value
1457 1461 sys.last_traceback = last_traceback
1458 1462
1459 1463 if filename and etype is SyntaxError:
1460 1464 # Work hard to stuff the correct filename in the exception
1461 1465 try:
1462 1466 msg, (dummy_filename, lineno, offset, line) = value
1463 1467 except:
1464 1468 # Not the format we expect; leave it alone
1465 1469 pass
1466 1470 else:
1467 1471 # Stuff in the right filename
1468 1472 try:
1469 1473 # Assume SyntaxError is a class exception
1470 1474 value = SyntaxError(msg, (filename, lineno, offset, line))
1471 1475 except:
1472 1476 # If that failed, assume SyntaxError is a string
1473 1477 value = msg, (filename, lineno, offset, line)
1474 1478 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1475 1479 self._showtraceback(etype, value, stb)
1476 1480
1477 1481 #-------------------------------------------------------------------------
1478 1482 # Things related to readline
1479 1483 #-------------------------------------------------------------------------
1480 1484
1481 1485 def init_readline(self):
1482 1486 """Command history completion/saving/reloading."""
1483 1487
1484 1488 if self.readline_use:
1485 1489 import IPython.utils.rlineimpl as readline
1486 1490
1487 1491 self.rl_next_input = None
1488 1492 self.rl_do_indent = False
1489 1493
1490 1494 if not self.readline_use or not readline.have_readline:
1491 1495 self.has_readline = False
1492 1496 self.readline = None
1493 1497 # Set a number of methods that depend on readline to be no-op
1494 1498 self.set_readline_completer = no_op
1495 1499 self.set_custom_completer = no_op
1496 1500 self.set_completer_frame = no_op
1497 1501 warn('Readline services not available or not loaded.')
1498 1502 else:
1499 1503 self.has_readline = True
1500 1504 self.readline = readline
1501 1505 sys.modules['readline'] = readline
1502 1506
1503 1507 # Platform-specific configuration
1504 1508 if os.name == 'nt':
1505 1509 # FIXME - check with Frederick to see if we can harmonize
1506 1510 # naming conventions with pyreadline to avoid this
1507 1511 # platform-dependent check
1508 1512 self.readline_startup_hook = readline.set_pre_input_hook
1509 1513 else:
1510 1514 self.readline_startup_hook = readline.set_startup_hook
1511 1515
1512 1516 # Load user's initrc file (readline config)
1513 1517 # Or if libedit is used, load editrc.
1514 1518 inputrc_name = os.environ.get('INPUTRC')
1515 1519 if inputrc_name is None:
1516 1520 home_dir = get_home_dir()
1517 1521 if home_dir is not None:
1518 1522 inputrc_name = '.inputrc'
1519 1523 if readline.uses_libedit:
1520 1524 inputrc_name = '.editrc'
1521 1525 inputrc_name = os.path.join(home_dir, inputrc_name)
1522 1526 if os.path.isfile(inputrc_name):
1523 1527 try:
1524 1528 readline.read_init_file(inputrc_name)
1525 1529 except:
1526 1530 warn('Problems reading readline initialization file <%s>'
1527 1531 % inputrc_name)
1528 1532
1529 1533 # Configure readline according to user's prefs
1530 1534 # This is only done if GNU readline is being used. If libedit
1531 1535 # is being used (as on Leopard) the readline config is
1532 1536 # not run as the syntax for libedit is different.
1533 1537 if not readline.uses_libedit:
1534 1538 for rlcommand in self.readline_parse_and_bind:
1535 1539 #print "loading rl:",rlcommand # dbg
1536 1540 readline.parse_and_bind(rlcommand)
1537 1541
1538 1542 # Remove some chars from the delimiters list. If we encounter
1539 1543 # unicode chars, discard them.
1540 1544 delims = readline.get_completer_delims().encode("ascii", "ignore")
1541 1545 delims = delims.translate(None, self.readline_remove_delims)
1542 1546 delims = delims.replace(ESC_MAGIC, '')
1543 1547 readline.set_completer_delims(delims)
1544 1548 # otherwise we end up with a monster history after a while:
1545 1549 readline.set_history_length(self.history_length)
1546 1550 try:
1547 1551 #print '*** Reading readline history' # dbg
1548 1552 self.reload_history()
1549 1553 except IOError:
1550 1554 pass # It doesn't exist yet.
1551 1555
1552 1556 # Configure auto-indent for all platforms
1553 1557 self.set_autoindent(self.autoindent)
1554 1558
1555 1559 def set_next_input(self, s):
1556 1560 """ Sets the 'default' input string for the next command line.
1557 1561
1558 1562 Requires readline.
1559 1563
1560 1564 Example:
1561 1565
1562 1566 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1563 1567 [D:\ipython]|2> Hello Word_ # cursor is here
1564 1568 """
1565 1569
1566 1570 self.rl_next_input = s
1567 1571
1568 1572 # Maybe move this to the terminal subclass?
1569 1573 def pre_readline(self):
1570 1574 """readline hook to be used at the start of each line.
1571 1575
1572 1576 Currently it handles auto-indent only."""
1573 1577
1574 1578 if self.rl_do_indent:
1575 1579 self.readline.insert_text(self._indent_current_str())
1576 1580 if self.rl_next_input is not None:
1577 1581 self.readline.insert_text(self.rl_next_input)
1578 1582 self.rl_next_input = None
1579 1583
1580 1584 def _indent_current_str(self):
1581 1585 """return the current level of indentation as a string"""
1582 1586 return self.input_splitter.indent_spaces * ' '
1583 1587
1584 1588 #-------------------------------------------------------------------------
1585 1589 # Things related to text completion
1586 1590 #-------------------------------------------------------------------------
1587 1591
1588 1592 def init_completer(self):
1589 1593 """Initialize the completion machinery.
1590 1594
1591 1595 This creates completion machinery that can be used by client code,
1592 1596 either interactively in-process (typically triggered by the readline
1593 1597 library), programatically (such as in test suites) or out-of-prcess
1594 1598 (typically over the network by remote frontends).
1595 1599 """
1596 1600 from IPython.core.completer import IPCompleter
1597 1601 from IPython.core.completerlib import (module_completer,
1598 1602 magic_run_completer, cd_completer)
1599 1603
1600 1604 self.Completer = IPCompleter(self,
1601 1605 self.user_ns,
1602 1606 self.user_global_ns,
1603 1607 self.readline_omit__names,
1604 1608 self.alias_manager.alias_table,
1605 1609 self.has_readline)
1606 1610
1607 1611 # Add custom completers to the basic ones built into IPCompleter
1608 1612 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1609 1613 self.strdispatchers['complete_command'] = sdisp
1610 1614 self.Completer.custom_completers = sdisp
1611 1615
1612 1616 self.set_hook('complete_command', module_completer, str_key = 'import')
1613 1617 self.set_hook('complete_command', module_completer, str_key = 'from')
1614 1618 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1615 1619 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1616 1620
1617 1621 # Only configure readline if we truly are using readline. IPython can
1618 1622 # do tab-completion over the network, in GUIs, etc, where readline
1619 1623 # itself may be absent
1620 1624 if self.has_readline:
1621 1625 self.set_readline_completer()
1622 1626
1623 1627 def complete(self, text, line=None, cursor_pos=None):
1624 1628 """Return the completed text and a list of completions.
1625 1629
1626 1630 Parameters
1627 1631 ----------
1628 1632
1629 1633 text : string
1630 1634 A string of text to be completed on. It can be given as empty and
1631 1635 instead a line/position pair are given. In this case, the
1632 1636 completer itself will split the line like readline does.
1633 1637
1634 1638 line : string, optional
1635 1639 The complete line that text is part of.
1636 1640
1637 1641 cursor_pos : int, optional
1638 1642 The position of the cursor on the input line.
1639 1643
1640 1644 Returns
1641 1645 -------
1642 1646 text : string
1643 1647 The actual text that was completed.
1644 1648
1645 1649 matches : list
1646 1650 A sorted list with all possible completions.
1647 1651
1648 1652 The optional arguments allow the completion to take more context into
1649 1653 account, and are part of the low-level completion API.
1650 1654
1651 1655 This is a wrapper around the completion mechanism, similar to what
1652 1656 readline does at the command line when the TAB key is hit. By
1653 1657 exposing it as a method, it can be used by other non-readline
1654 1658 environments (such as GUIs) for text completion.
1655 1659
1656 1660 Simple usage example:
1657 1661
1658 1662 In [1]: x = 'hello'
1659 1663
1660 1664 In [2]: _ip.complete('x.l')
1661 1665 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1662 1666 """
1663 1667
1664 1668 # Inject names into __builtin__ so we can complete on the added names.
1665 1669 with self.builtin_trap:
1666 1670 return self.Completer.complete(text, line, cursor_pos)
1667 1671
1668 1672 def set_custom_completer(self, completer, pos=0):
1669 1673 """Adds a new custom completer function.
1670 1674
1671 1675 The position argument (defaults to 0) is the index in the completers
1672 1676 list where you want the completer to be inserted."""
1673 1677
1674 1678 newcomp = types.MethodType(completer,self.Completer)
1675 1679 self.Completer.matchers.insert(pos,newcomp)
1676 1680
1677 1681 def set_readline_completer(self):
1678 1682 """Reset readline's completer to be our own."""
1679 1683 self.readline.set_completer(self.Completer.rlcomplete)
1680 1684
1681 1685 def set_completer_frame(self, frame=None):
1682 1686 """Set the frame of the completer."""
1683 1687 if frame:
1684 1688 self.Completer.namespace = frame.f_locals
1685 1689 self.Completer.global_namespace = frame.f_globals
1686 1690 else:
1687 1691 self.Completer.namespace = self.user_ns
1688 1692 self.Completer.global_namespace = self.user_global_ns
1689 1693
1690 1694 #-------------------------------------------------------------------------
1691 1695 # Things related to magics
1692 1696 #-------------------------------------------------------------------------
1693 1697
1694 1698 def init_magics(self):
1695 1699 # FIXME: Move the color initialization to the DisplayHook, which
1696 1700 # should be split into a prompt manager and displayhook. We probably
1697 1701 # even need a centralize colors management object.
1698 1702 self.magic_colors(self.colors)
1699 1703 # History was moved to a separate module
1700 1704 from . import history
1701 1705 history.init_ipython(self)
1702 1706
1703 1707 def magic(self,arg_s):
1704 1708 """Call a magic function by name.
1705 1709
1706 1710 Input: a string containing the name of the magic function to call and
1707 1711 any additional arguments to be passed to the magic.
1708 1712
1709 1713 magic('name -opt foo bar') is equivalent to typing at the ipython
1710 1714 prompt:
1711 1715
1712 1716 In[1]: %name -opt foo bar
1713 1717
1714 1718 To call a magic without arguments, simply use magic('name').
1715 1719
1716 1720 This provides a proper Python function to call IPython's magics in any
1717 1721 valid Python code you can type at the interpreter, including loops and
1718 1722 compound statements.
1719 1723 """
1720 1724 args = arg_s.split(' ',1)
1721 1725 magic_name = args[0]
1722 1726 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1723 1727
1724 1728 try:
1725 1729 magic_args = args[1]
1726 1730 except IndexError:
1727 1731 magic_args = ''
1728 1732 fn = getattr(self,'magic_'+magic_name,None)
1729 1733 if fn is None:
1730 1734 error("Magic function `%s` not found." % magic_name)
1731 1735 else:
1732 1736 magic_args = self.var_expand(magic_args,1)
1733 1737 with nested(self.builtin_trap,):
1734 1738 result = fn(magic_args)
1735 1739 return result
1736 1740
1737 1741 def define_magic(self, magicname, func):
1738 1742 """Expose own function as magic function for ipython
1739 1743
1740 1744 def foo_impl(self,parameter_s=''):
1741 1745 'My very own magic!. (Use docstrings, IPython reads them).'
1742 1746 print 'Magic function. Passed parameter is between < >:'
1743 1747 print '<%s>' % parameter_s
1744 1748 print 'The self object is:',self
1745 1749
1746 1750 self.define_magic('foo',foo_impl)
1747 1751 """
1748 1752
1749 1753 import new
1750 1754 im = types.MethodType(func,self)
1751 1755 old = getattr(self, "magic_" + magicname, None)
1752 1756 setattr(self, "magic_" + magicname, im)
1753 1757 return old
1754 1758
1755 1759 #-------------------------------------------------------------------------
1756 1760 # Things related to macros
1757 1761 #-------------------------------------------------------------------------
1758 1762
1759 1763 def define_macro(self, name, themacro):
1760 1764 """Define a new macro
1761 1765
1762 1766 Parameters
1763 1767 ----------
1764 1768 name : str
1765 1769 The name of the macro.
1766 1770 themacro : str or Macro
1767 1771 The action to do upon invoking the macro. If a string, a new
1768 1772 Macro object is created by passing the string to it.
1769 1773 """
1770 1774
1771 1775 from IPython.core import macro
1772 1776
1773 1777 if isinstance(themacro, basestring):
1774 1778 themacro = macro.Macro(themacro)
1775 1779 if not isinstance(themacro, macro.Macro):
1776 1780 raise ValueError('A macro must be a string or a Macro instance.')
1777 1781 self.user_ns[name] = themacro
1778 1782
1779 1783 #-------------------------------------------------------------------------
1780 1784 # Things related to the running of system commands
1781 1785 #-------------------------------------------------------------------------
1782 1786
1783 1787 def system(self, cmd):
1784 1788 """Call the given cmd in a subprocess.
1785 1789
1786 1790 Parameters
1787 1791 ----------
1788 1792 cmd : str
1789 1793 Command to execute (can not end in '&', as bacground processes are
1790 1794 not supported.
1791 1795 """
1792 1796 # We do not support backgrounding processes because we either use
1793 1797 # pexpect or pipes to read from. Users can always just call
1794 1798 # os.system() if they really want a background process.
1795 1799 if cmd.endswith('&'):
1796 1800 raise OSError("Background processes not supported.")
1797 1801
1798 1802 return system(self.var_expand(cmd, depth=2))
1799 1803
1800 1804 def getoutput(self, cmd, split=True):
1801 1805 """Get output (possibly including stderr) from a subprocess.
1802 1806
1803 1807 Parameters
1804 1808 ----------
1805 1809 cmd : str
1806 1810 Command to execute (can not end in '&', as background processes are
1807 1811 not supported.
1808 1812 split : bool, optional
1809 1813
1810 1814 If True, split the output into an IPython SList. Otherwise, an
1811 1815 IPython LSString is returned. These are objects similar to normal
1812 1816 lists and strings, with a few convenience attributes for easier
1813 1817 manipulation of line-based output. You can use '?' on them for
1814 1818 details.
1815 1819 """
1816 1820 if cmd.endswith('&'):
1817 1821 raise OSError("Background processes not supported.")
1818 1822 out = getoutput(self.var_expand(cmd, depth=2))
1819 1823 if split:
1820 1824 out = SList(out.splitlines())
1821 1825 else:
1822 1826 out = LSString(out)
1823 1827 return out
1824 1828
1825 1829 #-------------------------------------------------------------------------
1826 1830 # Things related to aliases
1827 1831 #-------------------------------------------------------------------------
1828 1832
1829 1833 def init_alias(self):
1830 1834 self.alias_manager = AliasManager(shell=self, config=self.config)
1831 1835 self.ns_table['alias'] = self.alias_manager.alias_table,
1832 1836
1833 1837 #-------------------------------------------------------------------------
1834 1838 # Things related to extensions and plugins
1835 1839 #-------------------------------------------------------------------------
1836 1840
1837 1841 def init_extension_manager(self):
1838 1842 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1839 1843
1840 1844 def init_plugin_manager(self):
1841 1845 self.plugin_manager = PluginManager(config=self.config)
1842 1846
1843 1847 #-------------------------------------------------------------------------
1844 1848 # Things related to payloads
1845 1849 #-------------------------------------------------------------------------
1846 1850
1847 1851 def init_payload(self):
1848 1852 self.payload_manager = PayloadManager(config=self.config)
1849 1853
1850 1854 #-------------------------------------------------------------------------
1851 1855 # Things related to the prefilter
1852 1856 #-------------------------------------------------------------------------
1853 1857
1854 1858 def init_prefilter(self):
1855 1859 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1856 1860 # Ultimately this will be refactored in the new interpreter code, but
1857 1861 # for now, we should expose the main prefilter method (there's legacy
1858 1862 # code out there that may rely on this).
1859 1863 self.prefilter = self.prefilter_manager.prefilter_lines
1860 1864
1861 1865 def auto_rewrite_input(self, cmd):
1862 1866 """Print to the screen the rewritten form of the user's command.
1863 1867
1864 1868 This shows visual feedback by rewriting input lines that cause
1865 1869 automatic calling to kick in, like::
1866 1870
1867 1871 /f x
1868 1872
1869 1873 into::
1870 1874
1871 1875 ------> f(x)
1872 1876
1873 1877 after the user's input prompt. This helps the user understand that the
1874 1878 input line was transformed automatically by IPython.
1875 1879 """
1876 1880 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1877 1881
1878 1882 try:
1879 1883 # plain ascii works better w/ pyreadline, on some machines, so
1880 1884 # we use it and only print uncolored rewrite if we have unicode
1881 1885 rw = str(rw)
1882 1886 print >> IPython.utils.io.Term.cout, rw
1883 1887 except UnicodeEncodeError:
1884 1888 print "------> " + cmd
1885 1889
1886 1890 #-------------------------------------------------------------------------
1887 1891 # Things related to extracting values/expressions from kernel and user_ns
1888 1892 #-------------------------------------------------------------------------
1889 1893
1890 1894 def _simple_error(self):
1891 1895 etype, value = sys.exc_info()[:2]
1892 1896 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1893 1897
1894 1898 def user_variables(self, names):
1895 1899 """Get a list of variable names from the user's namespace.
1896 1900
1897 1901 Parameters
1898 1902 ----------
1899 1903 names : list of strings
1900 1904 A list of names of variables to be read from the user namespace.
1901 1905
1902 1906 Returns
1903 1907 -------
1904 1908 A dict, keyed by the input names and with the repr() of each value.
1905 1909 """
1906 1910 out = {}
1907 1911 user_ns = self.user_ns
1908 1912 for varname in names:
1909 1913 try:
1910 1914 value = repr(user_ns[varname])
1911 1915 except:
1912 1916 value = self._simple_error()
1913 1917 out[varname] = value
1914 1918 return out
1915 1919
1916 1920 def user_expressions(self, expressions):
1917 1921 """Evaluate a dict of expressions in the user's namespace.
1918 1922
1919 1923 Parameters
1920 1924 ----------
1921 1925 expressions : dict
1922 1926 A dict with string keys and string values. The expression values
1923 1927 should be valid Python expressions, each of which will be evaluated
1924 1928 in the user namespace.
1925 1929
1926 1930 Returns
1927 1931 -------
1928 1932 A dict, keyed like the input expressions dict, with the repr() of each
1929 1933 value.
1930 1934 """
1931 1935 out = {}
1932 1936 user_ns = self.user_ns
1933 1937 global_ns = self.user_global_ns
1934 1938 for key, expr in expressions.iteritems():
1935 1939 try:
1936 1940 value = repr(eval(expr, global_ns, user_ns))
1937 1941 except:
1938 1942 value = self._simple_error()
1939 1943 out[key] = value
1940 1944 return out
1941 1945
1942 1946 #-------------------------------------------------------------------------
1943 1947 # Things related to the running of code
1944 1948 #-------------------------------------------------------------------------
1945 1949
1946 1950 def ex(self, cmd):
1947 1951 """Execute a normal python statement in user namespace."""
1948 1952 with nested(self.builtin_trap,):
1949 1953 exec cmd in self.user_global_ns, self.user_ns
1950 1954
1951 1955 def ev(self, expr):
1952 1956 """Evaluate python expression expr in user namespace.
1953 1957
1954 1958 Returns the result of evaluation
1955 1959 """
1956 1960 with nested(self.builtin_trap,):
1957 1961 return eval(expr, self.user_global_ns, self.user_ns)
1958 1962
1959 1963 def safe_execfile(self, fname, *where, **kw):
1960 1964 """A safe version of the builtin execfile().
1961 1965
1962 1966 This version will never throw an exception, but instead print
1963 1967 helpful error messages to the screen. This only works on pure
1964 1968 Python files with the .py extension.
1965 1969
1966 1970 Parameters
1967 1971 ----------
1968 1972 fname : string
1969 1973 The name of the file to be executed.
1970 1974 where : tuple
1971 1975 One or two namespaces, passed to execfile() as (globals,locals).
1972 1976 If only one is given, it is passed as both.
1973 1977 exit_ignore : bool (False)
1974 1978 If True, then silence SystemExit for non-zero status (it is always
1975 1979 silenced for zero status, as it is so common).
1976 1980 """
1977 1981 kw.setdefault('exit_ignore', False)
1978 1982
1979 1983 fname = os.path.abspath(os.path.expanduser(fname))
1980 1984
1981 1985 # Make sure we have a .py file
1982 1986 if not fname.endswith('.py'):
1983 1987 warn('File must end with .py to be run using execfile: <%s>' % fname)
1984 1988
1985 1989 # Make sure we can open the file
1986 1990 try:
1987 1991 with open(fname) as thefile:
1988 1992 pass
1989 1993 except:
1990 1994 warn('Could not open file <%s> for safe execution.' % fname)
1991 1995 return
1992 1996
1993 1997 # Find things also in current directory. This is needed to mimic the
1994 1998 # behavior of running a script from the system command line, where
1995 1999 # Python inserts the script's directory into sys.path
1996 2000 dname = os.path.dirname(fname)
1997 2001
1998 2002 with prepended_to_syspath(dname):
1999 2003 try:
2000 2004 execfile(fname,*where)
2001 2005 except SystemExit, status:
2002 2006 # If the call was made with 0 or None exit status (sys.exit(0)
2003 2007 # or sys.exit() ), don't bother showing a traceback, as both of
2004 2008 # these are considered normal by the OS:
2005 2009 # > python -c'import sys;sys.exit(0)'; echo $?
2006 2010 # 0
2007 2011 # > python -c'import sys;sys.exit()'; echo $?
2008 2012 # 0
2009 2013 # For other exit status, we show the exception unless
2010 2014 # explicitly silenced, but only in short form.
2011 2015 if status.code not in (0, None) and not kw['exit_ignore']:
2012 2016 self.showtraceback(exception_only=True)
2013 2017 except:
2014 2018 self.showtraceback()
2015 2019
2016 2020 def safe_execfile_ipy(self, fname):
2017 2021 """Like safe_execfile, but for .ipy files with IPython syntax.
2018 2022
2019 2023 Parameters
2020 2024 ----------
2021 2025 fname : str
2022 2026 The name of the file to execute. The filename must have a
2023 2027 .ipy extension.
2024 2028 """
2025 2029 fname = os.path.abspath(os.path.expanduser(fname))
2026 2030
2027 2031 # Make sure we have a .py file
2028 2032 if not fname.endswith('.ipy'):
2029 2033 warn('File must end with .py to be run using execfile: <%s>' % fname)
2030 2034
2031 2035 # Make sure we can open the file
2032 2036 try:
2033 2037 with open(fname) as thefile:
2034 2038 pass
2035 2039 except:
2036 2040 warn('Could not open file <%s> for safe execution.' % fname)
2037 2041 return
2038 2042
2039 2043 # Find things also in current directory. This is needed to mimic the
2040 2044 # behavior of running a script from the system command line, where
2041 2045 # Python inserts the script's directory into sys.path
2042 2046 dname = os.path.dirname(fname)
2043 2047
2044 2048 with prepended_to_syspath(dname):
2045 2049 try:
2046 2050 with open(fname) as thefile:
2047 2051 # self.run_cell currently captures all exceptions
2048 2052 # raised in user code. It would be nice if there were
2049 2053 # versions of runlines, execfile that did raise, so
2050 2054 # we could catch the errors.
2051 2055 self.run_cell(thefile.read())
2052 2056 except:
2053 2057 self.showtraceback()
2054 2058 warn('Unknown failure executing file: <%s>' % fname)
2055 2059
2056 2060 def run_cell(self, cell):
2057 2061 """Run the contents of an entire multiline 'cell' of code.
2058 2062
2059 2063 The cell is split into separate blocks which can be executed
2060 2064 individually. Then, based on how many blocks there are, they are
2061 2065 executed as follows:
2062 2066
2063 2067 - A single block: 'single' mode.
2064 2068
2065 2069 If there's more than one block, it depends:
2066 2070
2067 2071 - if the last one is no more than two lines long, run all but the last
2068 2072 in 'exec' mode and the very last one in 'single' mode. This makes it
2069 2073 easy to type simple expressions at the end to see computed values. -
2070 2074 otherwise (last one is also multiline), run all in 'exec' mode
2071 2075
2072 2076 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2073 2077 results are displayed and output prompts are computed. In 'exec' mode,
2074 2078 no results are displayed unless :func:`print` is called explicitly;
2075 2079 this mode is more akin to running a script.
2076 2080
2077 2081 Parameters
2078 2082 ----------
2079 2083 cell : str
2080 2084 A single or multiline string.
2081 2085 """
2082 2086
2083 2087 # We need to break up the input into executable blocks that can be run
2084 2088 # in 'single' mode, to provide comfortable user behavior.
2085 2089 blocks = self.input_splitter.split_blocks(cell)
2086 2090
2087 2091 if not blocks:
2088 2092 return
2089 2093
2090 2094 # Store the 'ipython' version of the cell as well, since that's what
2091 2095 # needs to go into the translated history and get executed (the
2092 2096 # original cell may contain non-python syntax).
2093 2097 ipy_cell = ''.join(blocks)
2094 2098
2095 2099 # Store raw and processed history
2096 2100 self.history_manager.store_inputs(ipy_cell, cell)
2097 2101
2098 2102 self.logger.log(ipy_cell, cell)
2099 2103 # dbg code!!!
2100 2104 if 0:
2101 2105 def myapp(self, val): # dbg
2102 2106 import traceback as tb
2103 2107 stack = ''.join(tb.format_stack())
2104 2108 print 'Value:', val
2105 2109 print 'Stack:\n', stack
2106 2110 list.append(self, val)
2107 2111
2108 2112 import new
2109 2113 self.history_manager.input_hist_parsed.append = types.MethodType(myapp,
2110 2114 self.history_manager.input_hist_parsed)
2111 2115 # End dbg
2112 2116
2113 2117 # All user code execution must happen with our context managers active
2114 2118 with nested(self.builtin_trap, self.display_trap):
2115 2119
2116 2120 # Single-block input should behave like an interactive prompt
2117 2121 if len(blocks) == 1:
2118 2122 # since we return here, we need to update the execution count
2119 2123 out = self.run_one_block(blocks[0])
2120 2124 self.execution_count += 1
2121 2125 return out
2122 2126
2123 2127 # In multi-block input, if the last block is a simple (one-two
2124 2128 # lines) expression, run it in single mode so it produces output.
2125 2129 # Otherwise just feed the whole thing to run_code. This seems like
2126 2130 # a reasonable usability design.
2127 2131 last = blocks[-1]
2128 2132 last_nlines = len(last.splitlines())
2129 2133
2130 2134 # Note: below, whenever we call run_code, we must sync history
2131 2135 # ourselves, because run_code is NOT meant to manage history at all.
2132 2136 if last_nlines < 2:
2133 2137 # Here we consider the cell split between 'body' and 'last',
2134 2138 # store all history and execute 'body', and if successful, then
2135 2139 # proceed to execute 'last'.
2136 2140
2137 2141 # Get the main body to run as a cell
2138 2142 ipy_body = ''.join(blocks[:-1])
2139 2143 retcode = self.run_source(ipy_body, symbol='exec',
2140 2144 post_execute=False)
2141 2145 if retcode==0:
2142 2146 # And the last expression via runlines so it produces output
2143 2147 self.run_one_block(last)
2144 2148 else:
2145 2149 # Run the whole cell as one entity, storing both raw and
2146 2150 # processed input in history
2147 2151 self.run_source(ipy_cell, symbol='exec')
2148 2152
2149 2153 # Each cell is a *single* input, regardless of how many lines it has
2150 2154 self.execution_count += 1
2151 2155
2152 2156 def run_one_block(self, block):
2153 2157 """Run a single interactive block.
2154 2158
2155 2159 If the block is single-line, dynamic transformations are applied to it
2156 2160 (like automagics, autocall and alias recognition).
2157 2161 """
2158 2162 if len(block.splitlines()) <= 1:
2159 2163 out = self.run_single_line(block)
2160 2164 else:
2161 2165 out = self.run_code(block)
2162 2166 return out
2163 2167
2164 2168 def run_single_line(self, line):
2165 2169 """Run a single-line interactive statement.
2166 2170
2167 2171 This assumes the input has been transformed to IPython syntax by
2168 2172 applying all static transformations (those with an explicit prefix like
2169 2173 % or !), but it will further try to apply the dynamic ones.
2170 2174
2171 2175 It does not update history.
2172 2176 """
2173 2177 tline = self.prefilter_manager.prefilter_line(line)
2174 2178 return self.run_source(tline)
2175 2179
2176 2180 # PENDING REMOVAL: this method is slated for deletion, once our new
2177 2181 # input logic has been 100% moved to frontends and is stable.
2178 2182 def runlines(self, lines, clean=False):
2179 2183 """Run a string of one or more lines of source.
2180 2184
2181 2185 This method is capable of running a string containing multiple source
2182 2186 lines, as if they had been entered at the IPython prompt. Since it
2183 2187 exposes IPython's processing machinery, the given strings can contain
2184 2188 magic calls (%magic), special shell access (!cmd), etc.
2185 2189 """
2186 2190
2187 2191 if isinstance(lines, (list, tuple)):
2188 2192 lines = '\n'.join(lines)
2189 2193
2190 2194 if clean:
2191 2195 lines = self._cleanup_ipy_script(lines)
2192 2196
2193 2197 # We must start with a clean buffer, in case this is run from an
2194 2198 # interactive IPython session (via a magic, for example).
2195 2199 self.reset_buffer()
2196 2200 lines = lines.splitlines()
2197 2201
2198 2202 # Since we will prefilter all lines, store the user's raw input too
2199 2203 # before we apply any transformations
2200 2204 self.buffer_raw[:] = [ l+'\n' for l in lines]
2201 2205
2202 2206 more = False
2203 2207 prefilter_lines = self.prefilter_manager.prefilter_lines
2204 2208 with nested(self.builtin_trap, self.display_trap):
2205 2209 for line in lines:
2206 2210 # skip blank lines so we don't mess up the prompt counter, but
2207 2211 # do NOT skip even a blank line if we are in a code block (more
2208 2212 # is true)
2209 2213
2210 2214 if line or more:
2211 2215 more = self.push_line(prefilter_lines(line, more))
2212 2216 # IPython's run_source returns None if there was an error
2213 2217 # compiling the code. This allows us to stop processing
2214 2218 # right away, so the user gets the error message at the
2215 2219 # right place.
2216 2220 if more is None:
2217 2221 break
2218 2222 # final newline in case the input didn't have it, so that the code
2219 2223 # actually does get executed
2220 2224 if more:
2221 2225 self.push_line('\n')
2222 2226
2223 2227 def run_source(self, source, filename=None,
2224 2228 symbol='single', post_execute=True):
2225 2229 """Compile and run some source in the interpreter.
2226 2230
2227 2231 Arguments are as for compile_command().
2228 2232
2229 2233 One several things can happen:
2230 2234
2231 2235 1) The input is incorrect; compile_command() raised an
2232 2236 exception (SyntaxError or OverflowError). A syntax traceback
2233 2237 will be printed by calling the showsyntaxerror() method.
2234 2238
2235 2239 2) The input is incomplete, and more input is required;
2236 2240 compile_command() returned None. Nothing happens.
2237 2241
2238 2242 3) The input is complete; compile_command() returned a code
2239 2243 object. The code is executed by calling self.run_code() (which
2240 2244 also handles run-time exceptions, except for SystemExit).
2241 2245
2242 2246 The return value is:
2243 2247
2244 2248 - True in case 2
2245 2249
2246 2250 - False in the other cases, unless an exception is raised, where
2247 2251 None is returned instead. This can be used by external callers to
2248 2252 know whether to continue feeding input or not.
2249 2253
2250 2254 The return value can be used to decide whether to use sys.ps1 or
2251 2255 sys.ps2 to prompt the next line."""
2252 2256
2253 2257 # We need to ensure that the source is unicode from here on.
2254 2258 if type(source)==str:
2255 2259 usource = source.decode(self.stdin_encoding)
2256 2260 else:
2257 2261 usource = source
2258 2262
2259 2263 if 0: # dbg
2260 2264 print 'Source:', repr(source) # dbg
2261 2265 print 'USource:', repr(usource) # dbg
2262 2266 print 'type:', type(source) # dbg
2263 2267 print 'encoding', self.stdin_encoding # dbg
2264 2268
2265 2269 try:
2266 2270 code = self.compile(usource, symbol, self.execution_count)
2267 2271 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2268 2272 # Case 1
2269 2273 self.showsyntaxerror(filename)
2270 2274 return None
2271 2275
2272 2276 if code is None:
2273 2277 # Case 2
2274 2278 return True
2275 2279
2276 2280 # Case 3
2277 2281 # We store the code object so that threaded shells and
2278 2282 # custom exception handlers can access all this info if needed.
2279 2283 # The source corresponding to this can be obtained from the
2280 2284 # buffer attribute as '\n'.join(self.buffer).
2281 2285 self.code_to_run = code
2282 2286 # now actually execute the code object
2283 2287 if self.run_code(code, post_execute) == 0:
2284 2288 return False
2285 2289 else:
2286 2290 return None
2287 2291
2288 2292 # For backwards compatibility
2289 2293 runsource = run_source
2290 2294
2291 2295 def run_code(self, code_obj, post_execute=True):
2292 2296 """Execute a code object.
2293 2297
2294 2298 When an exception occurs, self.showtraceback() is called to display a
2295 2299 traceback.
2296 2300
2297 2301 Return value: a flag indicating whether the code to be run completed
2298 2302 successfully:
2299 2303
2300 2304 - 0: successful execution.
2301 2305 - 1: an error occurred.
2302 2306 """
2303 2307
2304 2308 # Set our own excepthook in case the user code tries to call it
2305 2309 # directly, so that the IPython crash handler doesn't get triggered
2306 2310 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2307 2311
2308 2312 # we save the original sys.excepthook in the instance, in case config
2309 2313 # code (such as magics) needs access to it.
2310 2314 self.sys_excepthook = old_excepthook
2311 2315 outflag = 1 # happens in more places, so it's easier as default
2312 2316 try:
2313 2317 try:
2314 2318 self.hooks.pre_run_code_hook()
2315 2319 #rprint('Running code') # dbg
2316 2320 exec code_obj in self.user_global_ns, self.user_ns
2317 2321 finally:
2318 2322 # Reset our crash handler in place
2319 2323 sys.excepthook = old_excepthook
2320 2324 except SystemExit:
2321 2325 self.reset_buffer()
2322 2326 self.showtraceback(exception_only=True)
2323 2327 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2324 2328 except self.custom_exceptions:
2325 2329 etype,value,tb = sys.exc_info()
2326 2330 self.CustomTB(etype,value,tb)
2327 2331 except:
2328 2332 self.showtraceback()
2329 2333 else:
2330 2334 outflag = 0
2331 2335 if softspace(sys.stdout, 0):
2332 2336 print
2333 2337
2334 2338 # Execute any registered post-execution functions. Here, any errors
2335 2339 # are reported only minimally and just on the terminal, because the
2336 2340 # main exception channel may be occupied with a user traceback.
2337 2341 # FIXME: we need to think this mechanism a little more carefully.
2338 2342 if post_execute:
2339 2343 for func in self._post_execute:
2340 2344 try:
2341 2345 func()
2342 2346 except:
2343 2347 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2344 2348 func
2345 2349 print >> io.Term.cout, head
2346 2350 print >> io.Term.cout, self._simple_error()
2347 2351 print >> io.Term.cout, 'Removing from post_execute'
2348 2352 self._post_execute.remove(func)
2349 2353
2350 2354 # Flush out code object which has been run (and source)
2351 2355 self.code_to_run = None
2352 2356 return outflag
2353 2357
2354 2358 # For backwards compatibility
2355 2359 runcode = run_code
2356 2360
2357 2361 # PENDING REMOVAL: this method is slated for deletion, once our new
2358 2362 # input logic has been 100% moved to frontends and is stable.
2359 2363 def push_line(self, line):
2360 2364 """Push a line to the interpreter.
2361 2365
2362 2366 The line should not have a trailing newline; it may have
2363 2367 internal newlines. The line is appended to a buffer and the
2364 2368 interpreter's run_source() method is called with the
2365 2369 concatenated contents of the buffer as source. If this
2366 2370 indicates that the command was executed or invalid, the buffer
2367 2371 is reset; otherwise, the command is incomplete, and the buffer
2368 2372 is left as it was after the line was appended. The return
2369 2373 value is 1 if more input is required, 0 if the line was dealt
2370 2374 with in some way (this is the same as run_source()).
2371 2375 """
2372 2376
2373 2377 # autoindent management should be done here, and not in the
2374 2378 # interactive loop, since that one is only seen by keyboard input. We
2375 2379 # need this done correctly even for code run via runlines (which uses
2376 2380 # push).
2377 2381
2378 2382 #print 'push line: <%s>' % line # dbg
2379 2383 self.buffer.append(line)
2380 2384 full_source = '\n'.join(self.buffer)
2381 2385 more = self.run_source(full_source, self.filename)
2382 2386 if not more:
2383 2387 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2384 2388 full_source)
2385 2389 self.reset_buffer()
2386 2390 self.execution_count += 1
2387 2391 return more
2388 2392
2389 2393 def reset_buffer(self):
2390 2394 """Reset the input buffer."""
2391 2395 self.buffer[:] = []
2392 2396 self.buffer_raw[:] = []
2393 2397 self.input_splitter.reset()
2394 2398
2395 2399 # For backwards compatibility
2396 2400 resetbuffer = reset_buffer
2397 2401
2398 2402 def _is_secondary_block_start(self, s):
2399 2403 if not s.endswith(':'):
2400 2404 return False
2401 2405 if (s.startswith('elif') or
2402 2406 s.startswith('else') or
2403 2407 s.startswith('except') or
2404 2408 s.startswith('finally')):
2405 2409 return True
2406 2410
2407 2411 def _cleanup_ipy_script(self, script):
2408 2412 """Make a script safe for self.runlines()
2409 2413
2410 2414 Currently, IPython is lines based, with blocks being detected by
2411 2415 empty lines. This is a problem for block based scripts that may
2412 2416 not have empty lines after blocks. This script adds those empty
2413 2417 lines to make scripts safe for running in the current line based
2414 2418 IPython.
2415 2419 """
2416 2420 res = []
2417 2421 lines = script.splitlines()
2418 2422 level = 0
2419 2423
2420 2424 for l in lines:
2421 2425 lstripped = l.lstrip()
2422 2426 stripped = l.strip()
2423 2427 if not stripped:
2424 2428 continue
2425 2429 newlevel = len(l) - len(lstripped)
2426 2430 if level > 0 and newlevel == 0 and \
2427 2431 not self._is_secondary_block_start(stripped):
2428 2432 # add empty line
2429 2433 res.append('')
2430 2434 res.append(l)
2431 2435 level = newlevel
2432 2436
2433 2437 return '\n'.join(res) + '\n'
2434 2438
2435 2439 #-------------------------------------------------------------------------
2436 2440 # Things related to GUI support and pylab
2437 2441 #-------------------------------------------------------------------------
2438 2442
2439 2443 def enable_pylab(self, gui=None):
2440 2444 raise NotImplementedError('Implement enable_pylab in a subclass')
2441 2445
2442 2446 #-------------------------------------------------------------------------
2443 2447 # Utilities
2444 2448 #-------------------------------------------------------------------------
2445 2449
2446 2450 def var_expand(self,cmd,depth=0):
2447 2451 """Expand python variables in a string.
2448 2452
2449 2453 The depth argument indicates how many frames above the caller should
2450 2454 be walked to look for the local namespace where to expand variables.
2451 2455
2452 2456 The global namespace for expansion is always the user's interactive
2453 2457 namespace.
2454 2458 """
2455 2459
2456 2460 return str(ItplNS(cmd,
2457 2461 self.user_ns, # globals
2458 2462 # Skip our own frame in searching for locals:
2459 2463 sys._getframe(depth+1).f_locals # locals
2460 2464 ))
2461 2465
2462 2466 def mktempfile(self, data=None, prefix='ipython_edit_'):
2463 2467 """Make a new tempfile and return its filename.
2464 2468
2465 2469 This makes a call to tempfile.mktemp, but it registers the created
2466 2470 filename internally so ipython cleans it up at exit time.
2467 2471
2468 2472 Optional inputs:
2469 2473
2470 2474 - data(None): if data is given, it gets written out to the temp file
2471 2475 immediately, and the file is closed again."""
2472 2476
2473 2477 filename = tempfile.mktemp('.py', prefix)
2474 2478 self.tempfiles.append(filename)
2475 2479
2476 2480 if data:
2477 2481 tmp_file = open(filename,'w')
2478 2482 tmp_file.write(data)
2479 2483 tmp_file.close()
2480 2484 return filename
2481 2485
2482 2486 # TODO: This should be removed when Term is refactored.
2483 2487 def write(self,data):
2484 2488 """Write a string to the default output"""
2485 2489 io.Term.cout.write(data)
2486 2490
2487 2491 # TODO: This should be removed when Term is refactored.
2488 2492 def write_err(self,data):
2489 2493 """Write a string to the default error output"""
2490 2494 io.Term.cerr.write(data)
2491 2495
2492 2496 def ask_yes_no(self,prompt,default=True):
2493 2497 if self.quiet:
2494 2498 return True
2495 2499 return ask_yes_no(prompt,default)
2496 2500
2497 2501 def show_usage(self):
2498 2502 """Show a usage message"""
2499 2503 page.page(IPython.core.usage.interactive_usage)
2500 2504
2501 2505 #-------------------------------------------------------------------------
2502 2506 # Things related to IPython exiting
2503 2507 #-------------------------------------------------------------------------
2504 2508 def atexit_operations(self):
2505 2509 """This will be executed at the time of exit.
2506 2510
2507 2511 Cleanup operations and saving of persistent data that is done
2508 2512 unconditionally by IPython should be performed here.
2509 2513
2510 2514 For things that may depend on startup flags or platform specifics (such
2511 2515 as having readline or not), register a separate atexit function in the
2512 2516 code that has the appropriate information, rather than trying to
2513 2517 clutter
2514 2518 """
2515 2519 # Cleanup all tempfiles left around
2516 2520 for tfile in self.tempfiles:
2517 2521 try:
2518 2522 os.unlink(tfile)
2519 2523 except OSError:
2520 2524 pass
2521 2525
2522 2526
2523 2527 self.save_history()
2524 2528
2525 2529 # Clear all user namespaces to release all references cleanly.
2526 2530 self.reset()
2527 2531
2528 2532 # Run user hooks
2529 2533 self.hooks.shutdown_hook()
2530 2534
2531 2535 def cleanup(self):
2532 2536 self.restore_sys_module_state()
2533 2537
2534 2538
2535 2539 class InteractiveShellABC(object):
2536 2540 """An abstract base class for InteractiveShell."""
2537 2541 __metaclass__ = abc.ABCMeta
2538 2542
2539 2543 InteractiveShellABC.register(InteractiveShell)
@@ -1,465 +1,464 b''
1 1 """ A FrontendWidget that emulates the interface of the console IPython and
2 2 supports the additional functionality provided by the IPython kernel.
3 3
4 4 TODO: Add support for retrieving the system default editor. Requires code
5 5 paths for Windows (use the registry), Mac OS (use LaunchServices), and
6 6 Linux (use the xdg system).
7 7 """
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Imports
11 11 #-----------------------------------------------------------------------------
12 12
13 13 # Standard library imports
14 14 from collections import namedtuple
15 15 import re
16 16 from subprocess import Popen
17 17 from textwrap import dedent
18 18
19 19 # System library imports
20 20 from PyQt4 import QtCore, QtGui
21 21
22 22 # Local imports
23 23 from IPython.core.inputsplitter import IPythonInputSplitter, \
24 24 transform_ipy_prompt
25 25 from IPython.core.usage import default_gui_banner
26 26 from IPython.utils.traitlets import Bool, Str
27 27 from frontend_widget import FrontendWidget
28 28 from styles import (default_light_style_sheet, default_light_syntax_style,
29 29 default_dark_style_sheet, default_dark_syntax_style,
30 30 default_bw_style_sheet, default_bw_syntax_style)
31 31
32 32 #-----------------------------------------------------------------------------
33 33 # Constants
34 34 #-----------------------------------------------------------------------------
35 35
36 36 # Default strings to build and display input and output prompts (and separators
37 37 # in between)
38 38 default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
39 39 default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
40 40 default_input_sep = '\n'
41 41 default_output_sep = ''
42 42 default_output_sep2 = ''
43 43
44 44 # Base path for most payload sources.
45 45 zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell'
46 46
47 47 #-----------------------------------------------------------------------------
48 48 # IPythonWidget class
49 49 #-----------------------------------------------------------------------------
50 50
51 51 class IPythonWidget(FrontendWidget):
52 52 """ A FrontendWidget for an IPython kernel.
53 53 """
54 54
55 55 # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
56 56 # an editor is needed for a file. This overrides 'editor' and 'editor_line'
57 57 # settings.
58 58 custom_edit = Bool(False)
59 59 custom_edit_requested = QtCore.pyqtSignal(object, object)
60 60
61 61 # A command for invoking a system text editor. If the string contains a
62 62 # {filename} format specifier, it will be used. Otherwise, the filename will
63 63 # be appended to the end the command.
64 64 editor = Str('default', config=True)
65 65
66 66 # The editor command to use when a specific line number is requested. The
67 67 # string should contain two format specifiers: {line} and {filename}. If
68 68 # this parameter is not specified, the line number option to the %edit magic
69 69 # will be ignored.
70 70 editor_line = Str(config=True)
71 71
72 72 # A CSS stylesheet. The stylesheet can contain classes for:
73 73 # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
74 74 # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
75 75 # 3. IPython: .error, .in-prompt, .out-prompt, etc
76 76 style_sheet = Str(config=True)
77 77
78 78 # If not empty, use this Pygments style for syntax highlighting. Otherwise,
79 79 # the style sheet is queried for Pygments style information.
80 80 syntax_style = Str(config=True)
81 81
82 82 # Prompts.
83 83 in_prompt = Str(default_in_prompt, config=True)
84 84 out_prompt = Str(default_out_prompt, config=True)
85 85 input_sep = Str(default_input_sep, config=True)
86 86 output_sep = Str(default_output_sep, config=True)
87 87 output_sep2 = Str(default_output_sep2, config=True)
88 88
89 89 # FrontendWidget protected class variables.
90 90 _input_splitter_class = IPythonInputSplitter
91 91
92 92 # IPythonWidget protected class variables.
93 93 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
94 94 _payload_source_edit = zmq_shell_source + '.edit_magic'
95 95 _payload_source_exit = zmq_shell_source + '.ask_exit'
96 96 _payload_source_loadpy = zmq_shell_source + '.magic_loadpy'
97 97 _payload_source_page = 'IPython.zmq.page.page'
98 98
99 99 #---------------------------------------------------------------------------
100 100 # 'object' interface
101 101 #---------------------------------------------------------------------------
102 102
103 103 def __init__(self, *args, **kw):
104 104 super(IPythonWidget, self).__init__(*args, **kw)
105 105
106 106 # IPythonWidget protected variables.
107 107 self._code_to_load = None
108 108 self._payload_handlers = {
109 109 self._payload_source_edit : self._handle_payload_edit,
110 110 self._payload_source_exit : self._handle_payload_exit,
111 111 self._payload_source_page : self._handle_payload_page,
112 112 self._payload_source_loadpy : self._handle_payload_loadpy }
113 113 self._previous_prompt_obj = None
114 114 self._keep_kernel_on_exit = None
115 115
116 116 # Initialize widget styling.
117 117 if self.style_sheet:
118 118 self._style_sheet_changed()
119 119 self._syntax_style_changed()
120 120 else:
121 121 self.set_default_style()
122 122
123 123 #---------------------------------------------------------------------------
124 124 # 'BaseFrontendMixin' abstract interface
125 125 #---------------------------------------------------------------------------
126 126
127 127 def _handle_complete_reply(self, rep):
128 128 """ Reimplemented to support IPython's improved completion machinery.
129 129 """
130 130 cursor = self._get_cursor()
131 131 info = self._request_info.get('complete')
132 132 if info and info.id == rep['parent_header']['msg_id'] and \
133 133 info.pos == cursor.position():
134 134 matches = rep['content']['matches']
135 135 text = rep['content']['matched_text']
136 136 offset = len(text)
137 137
138 138 # Clean up matches with period and path separators if the matched
139 139 # text has not been transformed. This is done by truncating all
140 140 # but the last component and then suitably decreasing the offset
141 141 # between the current cursor position and the start of completion.
142 142 if len(matches) > 1 and matches[0][:offset] == text:
143 143 parts = re.split(r'[./\\]', text)
144 144 sep_count = len(parts) - 1
145 145 if sep_count:
146 146 chop_length = sum(map(len, parts[:sep_count])) + sep_count
147 147 matches = [ match[chop_length:] for match in matches ]
148 148 offset -= chop_length
149 149
150 150 # Move the cursor to the start of the match and complete.
151 151 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
152 152 self._complete_with_items(cursor, matches)
153 153
154 154 def _handle_execute_reply(self, msg):
155 155 """ Reimplemented to support prompt requests.
156 156 """
157 157 info = self._request_info.get('execute')
158 158 if info and info.id == msg['parent_header']['msg_id']:
159 159 if info.kind == 'prompt':
160 160 number = msg['content']['execution_count'] + 1
161 161 self._show_interpreter_prompt(number)
162 162 else:
163 163 super(IPythonWidget, self)._handle_execute_reply(msg)
164 164
165 165 def _handle_history_reply(self, msg):
166 166 """ Implemented to handle history replies, which are only supported by
167 167 the IPython kernel.
168 168 """
169 169 history_dict = msg['content']['history']
170 170 items = [ history_dict[key] for key in sorted(history_dict.keys()) ]
171 171 self._set_history(items)
172 172
173 173 def _handle_pyout(self, msg):
174 174 """ Reimplemented for IPython-style "display hook".
175 175 """
176 176 if not self._hidden and self._is_from_this_session(msg):
177 177 content = msg['content']
178 178 prompt_number = content['execution_count']
179 179 self._append_plain_text(self.output_sep)
180 180 self._append_html(self._make_out_prompt(prompt_number))
181 181 self._append_plain_text(content['data']+self.output_sep2)
182 182
183 183 def _started_channels(self):
184 184 """ Reimplemented to make a history request.
185 185 """
186 186 super(IPythonWidget, self)._started_channels()
187 # FIXME: Disabled until history requests are properly implemented.
188 #self.kernel_manager.xreq_channel.history(raw=True, output=False)
187 self.kernel_manager.xreq_channel.history(raw=True, output=False)
189 188
190 189 #---------------------------------------------------------------------------
191 190 # 'ConsoleWidget' public interface
192 191 #---------------------------------------------------------------------------
193 192
194 193 def copy(self):
195 194 """ Copy the currently selected text to the clipboard, removing prompts
196 195 if possible.
197 196 """
198 197 text = unicode(self._control.textCursor().selection().toPlainText())
199 198 if text:
200 199 lines = map(transform_ipy_prompt, text.splitlines())
201 200 text = '\n'.join(lines)
202 201 QtGui.QApplication.clipboard().setText(text)
203 202
204 203 #---------------------------------------------------------------------------
205 204 # 'FrontendWidget' public interface
206 205 #---------------------------------------------------------------------------
207 206
208 207 def execute_file(self, path, hidden=False):
209 208 """ Reimplemented to use the 'run' magic.
210 209 """
211 210 self.execute('%%run %s' % path, hidden=hidden)
212 211
213 212 #---------------------------------------------------------------------------
214 213 # 'FrontendWidget' protected interface
215 214 #---------------------------------------------------------------------------
216 215
217 216 def _complete(self):
218 217 """ Reimplemented to support IPython's improved completion machinery.
219 218 """
220 219 # We let the kernel split the input line, so we *always* send an empty
221 220 # text field. Readline-based frontends do get a real text field which
222 221 # they can use.
223 222 text = ''
224 223
225 224 # Send the completion request to the kernel
226 225 msg_id = self.kernel_manager.xreq_channel.complete(
227 226 text, # text
228 227 self._get_input_buffer_cursor_line(), # line
229 228 self._get_input_buffer_cursor_column(), # cursor_pos
230 229 self.input_buffer) # block
231 230 pos = self._get_cursor().position()
232 231 info = self._CompletionRequest(msg_id, pos)
233 232 self._request_info['complete'] = info
234 233
235 234 def _get_banner(self):
236 235 """ Reimplemented to return IPython's default banner.
237 236 """
238 237 return default_gui_banner
239 238
240 239 def _process_execute_error(self, msg):
241 240 """ Reimplemented for IPython-style traceback formatting.
242 241 """
243 242 content = msg['content']
244 243 traceback = '\n'.join(content['traceback']) + '\n'
245 244 if False:
246 245 # FIXME: For now, tracebacks come as plain text, so we can't use
247 246 # the html renderer yet. Once we refactor ultratb to produce
248 247 # properly styled tracebacks, this branch should be the default
249 248 traceback = traceback.replace(' ', '&nbsp;')
250 249 traceback = traceback.replace('\n', '<br/>')
251 250
252 251 ename = content['ename']
253 252 ename_styled = '<span class="error">%s</span>' % ename
254 253 traceback = traceback.replace(ename, ename_styled)
255 254
256 255 self._append_html(traceback)
257 256 else:
258 257 # This is the fallback for now, using plain text with ansi escapes
259 258 self._append_plain_text(traceback)
260 259
261 260 def _process_execute_payload(self, item):
262 261 """ Reimplemented to dispatch payloads to handler methods.
263 262 """
264 263 handler = self._payload_handlers.get(item['source'])
265 264 if handler is None:
266 265 # We have no handler for this type of payload, simply ignore it
267 266 return False
268 267 else:
269 268 handler(item)
270 269 return True
271 270
272 271 def _show_interpreter_prompt(self, number=None):
273 272 """ Reimplemented for IPython-style prompts.
274 273 """
275 274 # If a number was not specified, make a prompt number request.
276 275 if number is None:
277 276 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
278 277 info = self._ExecutionRequest(msg_id, 'prompt')
279 278 self._request_info['execute'] = info
280 279 return
281 280
282 281 # Show a new prompt and save information about it so that it can be
283 282 # updated later if the prompt number turns out to be wrong.
284 283 self._prompt_sep = self.input_sep
285 284 self._show_prompt(self._make_in_prompt(number), html=True)
286 285 block = self._control.document().lastBlock()
287 286 length = len(self._prompt)
288 287 self._previous_prompt_obj = self._PromptBlock(block, length, number)
289 288
290 289 # Update continuation prompt to reflect (possibly) new prompt length.
291 290 self._set_continuation_prompt(
292 291 self._make_continuation_prompt(self._prompt), html=True)
293 292
294 293 # Load code from the %loadpy magic, if necessary.
295 294 if self._code_to_load is not None:
296 295 self.input_buffer = dedent(unicode(self._code_to_load).rstrip())
297 296 self._code_to_load = None
298 297
299 298 def _show_interpreter_prompt_for_reply(self, msg):
300 299 """ Reimplemented for IPython-style prompts.
301 300 """
302 301 # Update the old prompt number if necessary.
303 302 content = msg['content']
304 303 previous_prompt_number = content['execution_count']
305 304 if self._previous_prompt_obj and \
306 305 self._previous_prompt_obj.number != previous_prompt_number:
307 306 block = self._previous_prompt_obj.block
308 307
309 308 # Make sure the prompt block has not been erased.
310 309 if block.isValid() and not block.text().isEmpty():
311 310
312 311 # Remove the old prompt and insert a new prompt.
313 312 cursor = QtGui.QTextCursor(block)
314 313 cursor.movePosition(QtGui.QTextCursor.Right,
315 314 QtGui.QTextCursor.KeepAnchor,
316 315 self._previous_prompt_obj.length)
317 316 prompt = self._make_in_prompt(previous_prompt_number)
318 317 self._prompt = self._insert_html_fetching_plain_text(
319 318 cursor, prompt)
320 319
321 320 # When the HTML is inserted, Qt blows away the syntax
322 321 # highlighting for the line, so we need to rehighlight it.
323 322 self._highlighter.rehighlightBlock(cursor.block())
324 323
325 324 self._previous_prompt_obj = None
326 325
327 326 # Show a new prompt with the kernel's estimated prompt number.
328 327 self._show_interpreter_prompt(previous_prompt_number + 1)
329 328
330 329 #---------------------------------------------------------------------------
331 330 # 'IPythonWidget' interface
332 331 #---------------------------------------------------------------------------
333 332
334 333 def set_default_style(self, colors='lightbg'):
335 334 """ Sets the widget style to the class defaults.
336 335
337 336 Parameters:
338 337 -----------
339 338 colors : str, optional (default lightbg)
340 339 Whether to use the default IPython light background or dark
341 340 background or B&W style.
342 341 """
343 342 colors = colors.lower()
344 343 if colors=='lightbg':
345 344 self.style_sheet = default_light_style_sheet
346 345 self.syntax_style = default_light_syntax_style
347 346 elif colors=='linux':
348 347 self.style_sheet = default_dark_style_sheet
349 348 self.syntax_style = default_dark_syntax_style
350 349 elif colors=='nocolor':
351 350 self.style_sheet = default_bw_style_sheet
352 351 self.syntax_style = default_bw_syntax_style
353 352 else:
354 353 raise KeyError("No such color scheme: %s"%colors)
355 354
356 355 #---------------------------------------------------------------------------
357 356 # 'IPythonWidget' protected interface
358 357 #---------------------------------------------------------------------------
359 358
360 359 def _edit(self, filename, line=None):
361 360 """ Opens a Python script for editing.
362 361
363 362 Parameters:
364 363 -----------
365 364 filename : str
366 365 A path to a local system file.
367 366
368 367 line : int, optional
369 368 A line of interest in the file.
370 369 """
371 370 if self.custom_edit:
372 371 self.custom_edit_requested.emit(filename, line)
373 372 elif self.editor == 'default':
374 373 self._append_plain_text('No default editor available.\n')
375 374 else:
376 375 try:
377 376 filename = '"%s"' % filename
378 377 if line and self.editor_line:
379 378 command = self.editor_line.format(filename=filename,
380 379 line=line)
381 380 else:
382 381 try:
383 382 command = self.editor.format()
384 383 except KeyError:
385 384 command = self.editor.format(filename=filename)
386 385 else:
387 386 command += ' ' + filename
388 387 except KeyError:
389 388 self._append_plain_text('Invalid editor command.\n')
390 389 else:
391 390 try:
392 391 Popen(command, shell=True)
393 392 except OSError:
394 393 msg = 'Opening editor with command "%s" failed.\n'
395 394 self._append_plain_text(msg % command)
396 395
397 396 def _make_in_prompt(self, number):
398 397 """ Given a prompt number, returns an HTML In prompt.
399 398 """
400 399 body = self.in_prompt % number
401 400 return '<span class="in-prompt">%s</span>' % body
402 401
403 402 def _make_continuation_prompt(self, prompt):
404 403 """ Given a plain text version of an In prompt, returns an HTML
405 404 continuation prompt.
406 405 """
407 406 end_chars = '...: '
408 407 space_count = len(prompt.lstrip('\n')) - len(end_chars)
409 408 body = '&nbsp;' * space_count + end_chars
410 409 return '<span class="in-prompt">%s</span>' % body
411 410
412 411 def _make_out_prompt(self, number):
413 412 """ Given a prompt number, returns an HTML Out prompt.
414 413 """
415 414 body = self.out_prompt % number
416 415 return '<span class="out-prompt">%s</span>' % body
417 416
418 417 #------ Payload handlers --------------------------------------------------
419 418
420 419 # Payload handlers with a generic interface: each takes the opaque payload
421 420 # dict, unpacks it and calls the underlying functions with the necessary
422 421 # arguments.
423 422
424 423 def _handle_payload_edit(self, item):
425 424 self._edit(item['filename'], item['line_number'])
426 425
427 426 def _handle_payload_exit(self, item):
428 427 self._keep_kernel_on_exit = item['keepkernel']
429 428 self.exit_requested.emit()
430 429
431 430 def _handle_payload_loadpy(self, item):
432 431 # Simple save the text of the .py file for later. The text is written
433 432 # to the buffer when _prompt_started_hook is called.
434 433 self._code_to_load = item['text']
435 434
436 435 def _handle_payload_page(self, item):
437 436 # Since the plain text widget supports only a very small subset of HTML
438 437 # and we have no control over the HTML source, we only page HTML
439 438 # payloads in the rich text widget.
440 439 if item['html'] and self.kind == 'rich':
441 440 self._page(item['html'], html=True)
442 441 else:
443 442 self._page(item['text'], html=False)
444 443
445 444 #------ Trait change handlers ---------------------------------------------
446 445
447 446 def _style_sheet_changed(self):
448 447 """ Set the style sheets of the underlying widgets.
449 448 """
450 449 self.setStyleSheet(self.style_sheet)
451 450 self._control.document().setDefaultStyleSheet(self.style_sheet)
452 451 if self._page_control:
453 452 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
454 453
455 454 bg_color = self._control.palette().background().color()
456 455 self._ansi_processor.set_background_color(bg_color)
457 456
458 457 def _syntax_style_changed(self):
459 458 """ Set the style for the syntax highlighter.
460 459 """
461 460 if self.syntax_style:
462 461 self._highlighter.set_style(self.syntax_style)
463 462 else:
464 463 self._highlighter.set_style_sheet(self.style_sheet)
465 464
General Comments 0
You need to be logged in to leave comments. Login now