##// END OF EJS Templates
Merge branch 'ellisonbg-payload' into trunk
Brian Granger -
r3289:7ac6be05 merge
parent child Browse files
Show More

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

@@ -0,0 +1,122 b''
1 # -*- coding: utf-8 -*-
2 """Top-level display functions for displaying object in different formats.
3
4 Authors:
5
6 * Brian Granger
7 """
8
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2010 The IPython Development Team
11 #
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
15
16 #-----------------------------------------------------------------------------
17 # Imports
18 #-----------------------------------------------------------------------------
19
20 #-----------------------------------------------------------------------------
21 # Main functions
22 #-----------------------------------------------------------------------------
23
24 def display(*objs, **kwargs):
25 """Display a Python object in all frontends.
26
27 By default all representations will be computed and sent to the frontends.
28 Frontends can decide which representation is used and how.
29
30 Parameters
31 ----------
32 objs : tuple of objects
33 The Python objects to display.
34 include : list or tuple, optional
35 A list of format type strings (MIME types) to include in the
36 format data dict. If this is set *only* the format types included
37 in this list will be computed.
38 exclude : list or tuple, optional
39 A list of format type string (MIME types) to exclue in the format
40 data dict. If this is set all format types will be computed,
41 except for those included in this argument.
42 """
43 include = kwargs.get('include')
44 exclude = kwargs.get('exclude')
45
46 from IPython.core.interactiveshell import InteractiveShell
47 inst = InteractiveShell.instance()
48 format = inst.display_formatter.format
49 publish = inst.display_pub.publish
50
51 for obj in objs:
52 format_dict = format(obj, include=include, exclude=exclude)
53 publish('IPython.core.display.display', format_dict)
54
55
56 def display_pretty(*objs):
57 """Display the pretty (default) representation of an object.
58
59 Parameters
60 ----------
61 objs : tuple of objects
62 The Python objects to display.
63 """
64 display(*objs, include=['text/plain'])
65
66
67 def display_html(*objs):
68 """Display the HTML representation of an object.
69
70 Parameters
71 ----------
72 objs : tuple of objects
73 The Python objects to display.
74 """
75 display(*objs, include=['text/plain','text/html'])
76
77
78 def display_svg(*objs):
79 """Display the SVG representation of an object.
80
81 Parameters
82 ----------
83 objs : tuple of objects
84 The Python objects to display.
85 """
86 display(*objs, include=['text/plain','image/svg+xml'])
87
88
89 def display_png(*objs):
90 """Display the PNG representation of an object.
91
92 Parameters
93 ----------
94 objs : tuple of objects
95 The Python objects to display.
96 """
97 display(*objs, include=['text/plain','image/png'])
98
99
100 def display_latex(*objs):
101 """Display the LaTeX representation of an object.
102
103 Parameters
104 ----------
105 objs : tuple of objects
106 The Python objects to display.
107 """
108 display(*objs, include=['text/plain','text/latex'])
109
110
111 def display_json(*objs):
112 """Display the JSON representation of an object.
113
114 Parameters
115 ----------
116 objs : tuple of objects
117 The Python objects to display.
118 """
119 display(*objs, include=['text/plain','application/json'])
120
121
122
@@ -0,0 +1,145 b''
1 """An interface for publishing rich data to frontends.
2
3 There are two components of the display system:
4
5 * Display formatters, which take a Python object and compute the
6 representation of the object in various formats (text, HTML, SVg, etc.).
7 * The display publisher that is used to send the representation data to the
8 various frontends.
9
10 This module defines the logic display publishing. The display publisher uses
11 the ``display_data`` message type that is defined in the IPython messaging
12 spec.
13
14 Authors:
15
16 * Brian Granger
17 """
18
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2010 The IPython Development Team
21 #
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
25
26 #-----------------------------------------------------------------------------
27 # Imports
28 #-----------------------------------------------------------------------------
29
30 from __future__ import print_function
31
32 from IPython.config.configurable import Configurable
33
34 #-----------------------------------------------------------------------------
35 # Main payload class
36 #-----------------------------------------------------------------------------
37
38 class DisplayPublisher(Configurable):
39 """A traited class that publishes display data to frontends.
40
41 Instances of this class are created by the main IPython object and should
42 be accessed there.
43 """
44
45 def _validate_data(self, source, data, metadata=None):
46 """Validate the display data.
47
48 Parameters
49 ----------
50 source : str
51 The fully dotted name of the callable that created the data, like
52 :func:`foo.bar.my_formatter`.
53 data : dict
54 The formata data dictionary.
55 metadata : dict
56 Any metadata for the data.
57 """
58
59 if not isinstance(source, str):
60 raise TypeError('source must be a str, got: %r' % source)
61 if not isinstance(data, dict):
62 raise TypeError('data must be a dict, got: %r' % data)
63 if metadata is not None:
64 if not isinstance(metadata, dict):
65 raise TypeError('metadata must be a dict, got: %r' % data)
66
67 def publish(self, source, data, metadata=None):
68 """Publish data and metadata to all frontends.
69
70 See the ``display_data`` message in the messaging documentation for
71 more details about this message type.
72
73 The following MIME types are currently implemented:
74
75 * text/plain
76 * text/html
77 * text/latex
78 * application/json
79 * image/png
80 * immage/svg+xml
81
82 Parameters
83 ----------
84 source : str
85 A string that give the function or method that created the data,
86 such as 'IPython.core.page'.
87 data : dict
88 A dictionary having keys that are valid MIME types (like
89 'text/plain' or 'image/svg+xml') and values that are the data for
90 that MIME type. The data itself must be a JSON'able data
91 structure. Minimally all data should have the 'text/plain' data,
92 which can be displayed by all frontends. If more than the plain
93 text is given, it is up to the frontend to decide which
94 representation to use.
95 metadata : dict
96 A dictionary for metadata related to the data. This can contain
97 arbitrary key, value pairs that frontends can use to interpret
98 the data.
99 """
100 from IPython.utils import io
101 # The default is to simply write the plain text data using io.Term.
102 if data.has_key('text/plain'):
103 print(data['text/plain'], file=io.Term.cout)
104
105
106 def publish_display_data(self, source, data, metadata=None):
107 """Publish data and metadata to all frontends.
108
109 See the ``display_data`` message in the messaging documentation for
110 more details about this message type.
111
112 The following MIME types are currently implemented:
113
114 * text/plain
115 * text/html
116 * text/latex
117 * application/json
118 * image/png
119 * immage/svg+xml
120
121 Parameters
122 ----------
123 source : str
124 A string that give the function or method that created the data,
125 such as 'IPython.core.page'.
126 data : dict
127 A dictionary having keys that are valid MIME types (like
128 'text/plain' or 'image/svg+xml') and values that are the data for
129 that MIME type. The data itself must be a JSON'able data
130 structure. Minimally all data should have the 'text/plain' data,
131 which can be displayed by all frontends. If more than the plain
132 text is given, it is up to the frontend to decide which
133 representation to use.
134 metadata : dict
135 A dictionary for metadata related to the data. This can contain
136 arbitrary key, value pairs that frontends can use to interpret
137 the data.
138 """
139 from IPython.core.interactiveshell import InteractiveShell
140 InteractiveShell.instance().display_pub.publish(
141 source,
142 data,
143 metadata
144 )
145
@@ -0,0 +1,65 b''
1 """A print function that pretty prints sympy Basic objects.
2
3 Authors:
4 * Brian Granger
5 """
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
12
13 #-----------------------------------------------------------------------------
14 # Imports
15 #-----------------------------------------------------------------------------
16
17 from IPython.lib.latextools import latex_to_png
18
19 from sympy import pretty, latex
20
21 #-----------------------------------------------------------------------------
22 # Definitions of magic functions for use with IPython
23 #-----------------------------------------------------------------------------
24
25 def print_basic_unicode(o, p, cycle):
26 """A function to pretty print sympy Basic objects."""
27 if cycle:
28 return p.text('Basic(...)')
29 out = pretty(o, use_unicode=True)
30 if '\n' in out:
31 p.text(u'\n')
32 p.text(out)
33
34
35 def print_png(o):
36 """A funciton to display sympy expression using LaTex -> PNG."""
37 s = latex(o, mode='inline')
38 # mathtext does not understand certain latex flags, so we try to replace
39 # them with suitable subs.
40 s = s.replace('\\operatorname','')
41 s = s.replace('\\overline', '\\bar')
42 png = latex_to_png(s, encode=True)
43 return png
44
45 _loaded = False
46
47
48 def load_ipython_extension(ip):
49 """Load the extension in IPython."""
50 global _loaded
51 if not _loaded:
52 plaintext_formatter = ip.display_formatter.formatters['text/plain']
53 plaintext_formatter.for_type_by_name(
54 'sympy.core.basic', 'Basic', print_basic_unicode
55 )
56 plaintext_formatter.for_type_by_name(
57 'sympy.matrices.matrices', 'Matrix', print_basic_unicode
58 )
59
60 png_formatter = ip.display_formatter.formatters['image/png']
61 png_formatter.for_type_by_name(
62 'sympy.core.basic', 'Basic', print_png
63 )
64 _loaded = True
65
@@ -0,0 +1,62 b''
1 # -*- coding: utf-8 -*-
2 """Tools for handling LaTeX.
3
4 Authors:
5
6 * Brian Granger
7 """
8 #-----------------------------------------------------------------------------
9 # Copyright (c) 2010, IPython Development Team.
10 #
11 # Distributed under the terms of the Modified BSD License.
12 #
13 # The full license is in the file COPYING.txt, distributed with this software.
14 #-----------------------------------------------------------------------------
15
16 #-----------------------------------------------------------------------------
17 # Imports
18 #-----------------------------------------------------------------------------
19
20 from StringIO import StringIO
21 from base64 import encodestring
22
23 #-----------------------------------------------------------------------------
24 # Tools
25 #-----------------------------------------------------------------------------
26
27
28 def latex_to_png(s, encode=True):
29 """Render a LaTeX string to PNG using matplotlib.mathtext.
30
31 Parameters
32 ----------
33 s : str
34 The raw string containing valid inline LaTeX.
35 encode : bool, optional
36 Should the PNG data bebase64 encoded to make it JSON'able.
37 """
38 from matplotlib import mathtext
39
40 mt = mathtext.MathTextParser('bitmap')
41 f = StringIO()
42 mt.to_png(f, s, fontsize=12)
43 bin_data = f.getvalue()
44 if encode:
45 bin_data = encodestring(bin_data)
46 return bin_data
47
48 _data_uri_template_png = """<img src="data:image/png;base64,%s" alt=%s />"""
49
50 def latex_to_html(s, alt='image'):
51 """Render LaTeX to HTML with embedded PNG data using data URIs.
52
53 Parameters
54 ----------
55 s : str
56 The raw string containing valid inline LateX.
57 alt : str
58 The alt text to use for the HTML.
59 """
60 base64_data = latex_to_png(s, encode=True)
61 return _data_uri_template_png % (base64_data, alt)
62
@@ -1,146 +1,150 b''
1 1 # Get the config being loaded so we can set attributes on it
2 2 c = get_config()
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Global options
6 6 #-----------------------------------------------------------------------------
7 7
8 8 # c.Global.display_banner = True
9 9
10 10 # c.Global.classic = False
11 11
12 12 # c.Global.nosep = True
13 13
14 14 # Set this to determine the detail of what is logged at startup.
15 15 # The default is 30 and possible values are 0,10,20,30,40,50.
16 16 # c.Global.log_level = 20
17 17
18 18 # This should be a list of importable Python modules that have an
19 19 # load_in_ipython(ip) method. This method gets called when the extension
20 20 # is loaded. You can put your extensions anywhere they can be imported
21 21 # but we add the extensions subdir of the ipython directory to sys.path
22 22 # during extension loading, so you can put them there as well.
23 23 # c.Global.extensions = [
24 24 # 'myextension'
25 25 # ]
26 26
27 27 # These lines are run in IPython in the user's namespace after extensions
28 28 # are loaded. They can contain full IPython syntax with magics etc.
29 29 # c.Global.exec_lines = [
30 30 # 'import numpy',
31 31 # 'a = 10; b = 20',
32 32 # '1/0'
33 33 # ]
34 34
35 35 # These files are run in IPython in the user's namespace. Files with a .py
36 36 # extension need to be pure Python. Files with a .ipy extension can have
37 37 # custom IPython syntax (like magics, etc.).
38 38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
39 39 # c.Global.exec_files = [
40 40 # 'mycode.py',
41 41 # 'fancy.ipy'
42 42 # ]
43 43
44 44 #-----------------------------------------------------------------------------
45 45 # InteractiveShell options
46 46 #-----------------------------------------------------------------------------
47 47
48 48 # c.InteractiveShell.autocall = 1
49 49
50 50 # c.TerminalInteractiveShell.autoedit_syntax = False
51 51
52 52 # c.InteractiveShell.autoindent = True
53 53
54 54 # c.InteractiveShell.automagic = False
55 55
56 56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
57 57
58 58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
59 59
60 60 # c.InteractiveShell.cache_size = 1000
61 61
62 62 # c.InteractiveShell.colors = 'LightBG'
63 63
64 64 # c.InteractiveShell.color_info = True
65 65
66 66 # c.TerminalInteractiveShell.confirm_exit = True
67 67
68 68 # c.InteractiveShell.deep_reload = False
69 69
70 70 # c.TerminalInteractiveShell.editor = 'nano'
71 71
72 72 # c.InteractiveShell.logstart = True
73 73
74 74 # c.InteractiveShell.logfile = u'ipython_log.py'
75 75
76 76 # c.InteractiveShell.logappend = u'mylog.py'
77 77
78 78 # c.InteractiveShell.object_info_string_level = 0
79 79
80 80 # c.TerminalInteractiveShell.pager = 'less'
81 81
82 82 # c.InteractiveShell.pdb = False
83 83
84 # c.InteractiveShell.pprint = True
85
86 84 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
87 85 # c.InteractiveShell.prompt_in2 = ' .\D.: '
88 86 # c.InteractiveShell.prompt_out = 'Out[\#]: '
89 87 # c.InteractiveShell.prompts_pad_left = True
90 88
91 89 # c.InteractiveShell.quiet = False
92 90
93 91 # c.InteractiveShell.history_length = 10000
94 92
95 93 # Readline
96 94 # c.InteractiveShell.readline_use = True
97 95
98 96 # c.InteractiveShell.readline_parse_and_bind = [
99 97 # 'tab: complete',
100 98 # '"\C-l": possible-completions',
101 99 # 'set show-all-if-ambiguous on',
102 100 # '"\C-o": tab-insert',
103 101 # '"\M-i": " "',
104 102 # '"\M-o": "\d\d\d\d"',
105 103 # '"\M-I": "\d\d\d\d"',
106 104 # '"\C-r": reverse-search-history',
107 105 # '"\C-s": forward-search-history',
108 106 # '"\C-p": history-search-backward',
109 107 # '"\C-n": history-search-forward',
110 108 # '"\e[A": history-search-backward',
111 109 # '"\e[B": history-search-forward',
112 110 # '"\C-k": kill-line',
113 111 # '"\C-u": unix-line-discard',
114 112 # ]
115 113 # c.InteractiveShell.readline_remove_delims = '-/~'
116 114 # c.InteractiveShell.readline_merge_completions = True
117 115 # c.InteractiveShell.readline_omit__names = 0
118 116
119 117 # c.TerminalInteractiveShell.screen_length = 0
120 118
121 119 # c.InteractiveShell.separate_in = '\n'
122 120 # c.InteractiveShell.separate_out = ''
123 121 # c.InteractiveShell.separate_out2 = ''
124 122
125 123 # c.TerminalInteractiveShell.term_title = False
126 124
127 125 # c.InteractiveShell.wildcards_case_sensitive = True
128 126
129 127 # c.InteractiveShell.xmode = 'Context'
130 128
131 129 #-----------------------------------------------------------------------------
130 # Formatter and display options
131 #-----------------------------------------------------------------------------
132
133 # c.PlainTextFormatter.pprint = True
134
135 #-----------------------------------------------------------------------------
132 136 # PrefilterManager options
133 137 #-----------------------------------------------------------------------------
134 138
135 139 # c.PrefilterManager.multi_line_specials = True
136 140
137 141 #-----------------------------------------------------------------------------
138 142 # AliasManager options
139 143 #-----------------------------------------------------------------------------
140 144
141 145 # Do this to disable all defaults
142 146 # c.AliasManager.default_aliases = []
143 147
144 148 # c.AliasManager.user_aliases = [
145 149 # ('foo', 'echo Hi')
146 150 # ]
@@ -1,21 +1,29 b''
1 1 c = get_config()
2 2
3 3 # This can be used at any point in a config file to load a sub config
4 4 # and merge it into the current one.
5 5 load_subconfig('ipython_config.py')
6 6
7 7 lines = """
8 8 from __future__ import division
9 9 from sympy import *
10 10 x, y, z = symbols('xyz')
11 11 k, m, n = symbols('kmn', integer=True)
12 12 f, g, h = map(Function, 'fgh')
13 13 """
14 14
15 15 # You have to make sure that attributes that are containers already
16 16 # exist before using them. Simple assigning a new list will override
17 17 # all previous values.
18
18 19 if hasattr(c.Global, 'exec_lines'):
19 20 c.Global.exec_lines.append(lines)
20 21 else:
21 22 c.Global.exec_lines = [lines]
23
24 # Load the sympy_printing extension to enable nice printing of sympy expr's.
25 if hasattr(c.Global, 'extensions'):
26 c.Global.extensions.append('sympy_printing')
27 else:
28 c.Global.extensions = ['sympy_printing']
29
@@ -1,304 +1,321 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Displayhook for IPython.
3 3
4 This defines a callable class that IPython uses for `sys.displayhook`.
5
4 6 Authors:
5 7
6 8 * Fernando Perez
7 9 * Brian Granger
10 * Robert Kern
8 11 """
9 12
10 13 #-----------------------------------------------------------------------------
11 14 # Copyright (C) 2008-2010 The IPython Development Team
12 15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
13 16 #
14 17 # Distributed under the terms of the BSD License. The full license is in
15 18 # the file COPYING, distributed as part of this software.
16 19 #-----------------------------------------------------------------------------
17 20
18 21 #-----------------------------------------------------------------------------
19 22 # Imports
20 23 #-----------------------------------------------------------------------------
21 24
22 25 import __builtin__
23 26
24 27 from IPython.config.configurable import Configurable
25 28 from IPython.core import prompts
26 29 import IPython.utils.generics
27 30 import IPython.utils.io
28 31 from IPython.utils.traitlets import Instance, List
29 32 from IPython.utils.warn import warn
30 from IPython.core.formatters import DefaultFormatter
31 33
32 34 #-----------------------------------------------------------------------------
33 35 # Main displayhook class
34 36 #-----------------------------------------------------------------------------
35 37
36 38 # TODO: The DisplayHook class should be split into two classes, one that
37 39 # manages the prompts and their synchronization and another that just does the
38 40 # displayhook logic and calls into the prompt manager.
39 41
40 42 # TODO: Move the various attributes (cache_size, colors, input_sep,
41 43 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
42 44 # attributes of InteractiveShell. They should be on ONE object only and the
43 45 # other objects should ask that one object for their values.
44 46
45 47 class DisplayHook(Configurable):
46 48 """The custom IPython displayhook to replace sys.displayhook.
47 49
48 50 This class does many things, but the basic idea is that it is a callable
49 51 that gets called anytime user code returns a value.
50 52
51 53 Currently this class does more than just the displayhook logic and that
52 54 extra logic should eventually be moved out of here.
53 55 """
54 56
55 57 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
56 58
57 # The default formatter.
58 default_formatter = Instance('IPython.core.formatters.FormatterABC')
59 def _default_formatter_default(self):
60 # FIXME: backwards compatibility for the InteractiveShell.pprint option?
61 return DefaultFormatter(config=self.config)
62
63 # Any additional FormatterABC instances we use.
64 # FIXME: currently unused.
65 extra_formatters = List(config=True)
66
67 # Each call to the In[] prompt raises it by 1, even the first.
68 #prompt_count = Int(0)
69
70 59 def __init__(self, shell=None, cache_size=1000,
71 60 colors='NoColor', input_sep='\n',
72 61 output_sep='\n', output_sep2='',
73 62 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
74 63 config=None):
75 64 super(DisplayHook, self).__init__(shell=shell, config=config)
76 65
77 66 cache_size_min = 3
78 67 if cache_size <= 0:
79 68 self.do_full_cache = 0
80 69 cache_size = 0
81 70 elif cache_size < cache_size_min:
82 71 self.do_full_cache = 0
83 72 cache_size = 0
84 73 warn('caching was disabled (min value for cache size is %s).' %
85 74 cache_size_min,level=3)
86 75 else:
87 76 self.do_full_cache = 1
88 77
89 78 self.cache_size = cache_size
90 79 self.input_sep = input_sep
91 80
92 81 # we need a reference to the user-level namespace
93 82 self.shell = shell
94 83
95 84 # Set input prompt strings and colors
96 85 if cache_size == 0:
97 86 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
98 87 or ps1.find(r'\N') > -1:
99 88 ps1 = '>>> '
100 89 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
101 90 or ps2.find(r'\N') > -1:
102 91 ps2 = '... '
103 92 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
104 93 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
105 94 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
106 95
107 96 self.color_table = prompts.PromptColors
108 97 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
109 98 pad_left=pad_left)
110 99 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
111 100 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
112 101 pad_left=pad_left)
113 102 self.set_colors(colors)
114 103
115 104 # Store the last prompt string each time, we need it for aligning
116 105 # continuation and auto-rewrite prompts
117 106 self.last_prompt = ''
118 107 self.output_sep = output_sep
119 108 self.output_sep2 = output_sep2
120 109 self._,self.__,self.___ = '','',''
121 110
122 111 # these are deliberately global:
123 112 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
124 113 self.shell.user_ns.update(to_user_ns)
125 114
126 115 @property
127 116 def prompt_count(self):
128 117 return self.shell.execution_count
129 118
130 119 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
131 120 if p_str is None:
132 121 if self.do_full_cache:
133 122 return cache_def
134 123 else:
135 124 return no_cache_def
136 125 else:
137 126 return p_str
138 127
139 128 def set_colors(self, colors):
140 129 """Set the active color scheme and configure colors for the three
141 130 prompt subsystems."""
142 131
143 132 # FIXME: This modifying of the global prompts.prompt_specials needs
144 133 # to be fixed. We need to refactor all of the prompts stuff to use
145 134 # proper configuration and traits notifications.
146 135 if colors.lower()=='nocolor':
147 136 prompts.prompt_specials = prompts.prompt_specials_nocolor
148 137 else:
149 138 prompts.prompt_specials = prompts.prompt_specials_color
150 139
151 140 self.color_table.set_active_scheme(colors)
152 141 self.prompt1.set_colors()
153 142 self.prompt2.set_colors()
154 143 self.prompt_out.set_colors()
155 144
156 145 #-------------------------------------------------------------------------
157 146 # Methods used in __call__. Override these methods to modify the behavior
158 147 # of the displayhook.
159 148 #-------------------------------------------------------------------------
160 149
161 150 def check_for_underscore(self):
162 151 """Check if the user has set the '_' variable by hand."""
163 152 # If something injected a '_' variable in __builtin__, delete
164 153 # ipython's automatic one so we don't clobber that. gettext() in
165 154 # particular uses _, so we need to stay away from it.
166 155 if '_' in __builtin__.__dict__:
167 156 try:
168 157 del self.shell.user_ns['_']
169 158 except KeyError:
170 159 pass
171 160
172 161 def quiet(self):
173 162 """Should we silence the display hook because of ';'?"""
174 163 # do not print output if input ends in ';'
175 164 try:
176 165 if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'):
177 166 return True
178 167 except IndexError:
179 168 # some uses of ipshellembed may fail here
180 169 pass
181 170 return False
182 171
183 172 def start_displayhook(self):
184 173 """Start the displayhook, initializing resources."""
185 174 pass
186 175
187 176 def write_output_prompt(self):
188 """Write the output prompt."""
177 """Write the output prompt.
178
179 The default implementation simply writes the prompt to
180 ``io.Term.cout``.
181 """
189 182 # Use write, not print which adds an extra space.
190 183 IPython.utils.io.Term.cout.write(self.output_sep)
191 184 outprompt = str(self.prompt_out)
192 185 if self.do_full_cache:
193 186 IPython.utils.io.Term.cout.write(outprompt)
194 187
195 def compute_result_repr(self, result):
196 """Compute and return the repr of the object to be displayed.
197
198 This method only compute the string form of the repr and should NOT
199 actually print or write that to a stream.
188 def compute_format_data(self, result):
189 """Compute format data of the object to be displayed.
190
191 The format data is a generalization of the :func:`repr` of an object.
192 In the default implementation the format data is a :class:`dict` of
193 key value pair where the keys are valid MIME types and the values
194 are JSON'able data structure containing the raw data for that MIME
195 type. It is up to frontends to determine pick a MIME to to use and
196 display that data in an appropriate manner.
197
198 This method only computes the format data for the object and should
199 NOT actually print or write that to a stream.
200
201 Parameters
202 ----------
203 result : object
204 The Python object passed to the display hook, whose format will be
205 computed.
206
207 Returns
208 -------
209 format_data : dict
210 A :class:`dict` whose keys are valid MIME types and values are
211 JSON'able raw data for that MIME type. It is recommended that
212 all return values of this should always include the "text/plain"
213 MIME type representation of the object.
200 214 """
201 result_repr = self.default_formatter(result)
202 extra_formats = []
203 for f in self.extra_formatters:
204 try:
205 data = f(result)
206 except Exception:
207 # FIXME: log the exception.
208 continue
209 if data is not None:
210 extra_formats.append((f.id, f.format, data))
215 return self.shell.display_formatter.format(result)
211 216
212 return result_repr, extra_formats
217 def write_format_data(self, format_dict):
218 """Write the format data dict to the frontend.
213 219
214 def write_result_repr(self, result_repr, extra_formats):
220 This default version of this method simply writes the plain text
221 representation of the object to ``io.Term.cout``. Subclasses should
222 override this method to send the entire `format_dict` to the
223 frontends.
224
225 Parameters
226 ----------
227 format_dict : dict
228 The format dict for the object passed to `sys.displayhook`.
229 """
215 230 # We want to print because we want to always make sure we have a
216 231 # newline, even if all the prompt separators are ''. This is the
217 232 # standard IPython behavior.
233 result_repr = format_dict['text/plain']
218 234 if '\n' in result_repr:
219 235 # So that multi-line strings line up with the left column of
220 236 # the screen, instead of having the output prompt mess up
221 237 # their first line.
222 238 # We use the ps_out_str template instead of the expanded prompt
223 239 # because the expansion may add ANSI escapes that will interfere
224 240 # with our ability to determine whether or not we should add
225 241 # a newline.
226 242 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
227 243 # But avoid extraneous empty lines.
228 244 result_repr = '\n' + result_repr
229 245
230 246 print >>IPython.utils.io.Term.cout, result_repr
231 247
232 248 def update_user_ns(self, result):
233 249 """Update user_ns with various things like _, __, _1, etc."""
234 250
235 251 # Avoid recursive reference when displaying _oh/Out
236 252 if result is not self.shell.user_ns['_oh']:
237 253 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
238 254 warn('Output cache limit (currently '+
239 255 `self.cache_size`+' entries) hit.\n'
240 256 'Flushing cache and resetting history counter...\n'
241 257 'The only history variables available will be _,__,___ and _1\n'
242 258 'with the current result.')
243 259
244 260 self.flush()
245 261 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
246 262 # we cause buggy behavior for things like gettext).
247 263 if '_' not in __builtin__.__dict__:
248 264 self.___ = self.__
249 265 self.__ = self._
250 266 self._ = result
251 267 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
252 268
253 269 # hackish access to top-level namespace to create _1,_2... dynamically
254 270 to_main = {}
255 271 if self.do_full_cache:
256 272 new_result = '_'+`self.prompt_count`
257 273 to_main[new_result] = result
258 274 self.shell.user_ns.update(to_main)
259 275 self.shell.user_ns['_oh'][self.prompt_count] = result
260 276
261 277 def log_output(self, result):
262 278 """Log the output."""
263 279 if self.shell.logger.log_output:
264 280 self.shell.logger.log_write(repr(result), 'output')
265 281
266 282 def finish_displayhook(self):
267 283 """Finish up all displayhook activities."""
268 284 IPython.utils.io.Term.cout.write(self.output_sep2)
269 285 IPython.utils.io.Term.cout.flush()
270 286
271 287 def __call__(self, result=None):
272 288 """Printing with history cache management.
273 289
274 290 This is invoked everytime the interpreter needs to print, and is
275 291 activated by setting the variable sys.displayhook to it.
276 292 """
277 293 self.check_for_underscore()
278 294 if result is not None and not self.quiet():
279 295 self.start_displayhook()
280 296 self.write_output_prompt()
281 result_repr, extra_formats = self.compute_result_repr(result)
282 self.write_result_repr(result_repr, extra_formats)
297 format_dict = self.compute_format_data(result)
298 self.write_format_data(format_dict)
283 299 self.update_user_ns(result)
284 300 self.log_output(result)
285 301 self.finish_displayhook()
286 302
287 303 def flush(self):
288 304 if not self.do_full_cache:
289 305 raise ValueError,"You shouldn't have reached the cache flush "\
290 306 "if full caching is not enabled!"
291 307 # delete auto-generated vars from global namespace
292 308
293 309 for n in range(1,self.prompt_count + 1):
294 310 key = '_'+`n`
295 311 try:
296 312 del self.shell.user_ns[key]
297 313 except: pass
298 314 self.shell.user_ns['_oh'].clear()
299 315
300 316 if '_' not in __builtin__.__dict__:
301 317 self.shell.user_ns.update({'_':None,'__':None, '___':None})
302 318 import gc
303 gc.collect() # xxx needed?
319 # TODO: Is this really needed?
320 gc.collect()
304 321
This diff has been collapsed as it changes many lines, (531 lines changed) Show them Hide them
@@ -1,169 +1,504 b''
1 1 # -*- coding: utf-8 -*-
2 """Displayhook formatters.
3
4 The DefaultFormatter is always present and may be configured from the
5 ipython_config.py file. For example, to add a pretty-printer for a numpy.dtype
6 object::
7
8 def dtype_pprinter(obj, p, cycle):
9 if cycle:
10 return p.text('dtype(...)')
11 if hasattr(obj, 'fields'):
12 if obj.fields is None:
13 p.text(repr(obj))
14 else:
15 p.begin_group(7, 'dtype([')
16 for i, field in enumerate(obj.descr):
17 if i > 0:
18 p.text(',')
19 p.breakable()
20 p.pretty(field)
21 p.end_group(7, '])')
22
23 c.DefaultFormatter.deferred_pprinters = {
24 ('numpy', 'dtype'): dtype_pprinter,
25 }
26
27 The deferred_pprinters dictionary is the preferred way to configure these
28 pretty-printers. This allows you to define the pretty-printer without needing to
29 import the type itself. The dictionary maps (modulename, typename) pairs to
30 a function.
31
32 See the `IPython.external.pretty` documentation for how to write
33 pretty-printer functions.
2 """Display formatters.
3
4
5 Authors:
6
7 * Robert Kern
8 * Brian Granger
34 9 """
35 10 #-----------------------------------------------------------------------------
36 11 # Copyright (c) 2010, IPython Development Team.
37 12 #
38 13 # Distributed under the terms of the Modified BSD License.
39 14 #
40 15 # The full license is in the file COPYING.txt, distributed with this software.
41 16 #-----------------------------------------------------------------------------
42 17
18 #-----------------------------------------------------------------------------
19 # Imports
20 #-----------------------------------------------------------------------------
21
43 22 # Stdlib imports
44 23 import abc
45 from cStringIO import StringIO
24 # We must use StringIO, as cStringIO doesn't handle unicode properly.
25 from StringIO import StringIO
46 26
47 27 # Our own imports
48 28 from IPython.config.configurable import Configurable
49 29 from IPython.external import pretty
50 30 from IPython.utils.traitlets import Bool, Dict, Int, Str
51 31
52 32
53 33 #-----------------------------------------------------------------------------
54 # Classes and functions
34 # The main DisplayFormatter class
35 #-----------------------------------------------------------------------------
36
37
38 class DisplayFormatter(Configurable):
39
40 # When set to true only the default plain text formatter will be used.
41 plain_text_only = Bool(False, config=True)
42
43 # A dict of formatter whose keys are format types (MIME types) and whose
44 # values are subclasses of BaseFormatter.
45 formatters = Dict(config=True)
46 def _formatters_default(self):
47 """Activate the default formatters."""
48 formatter_classes = [
49 PlainTextFormatter,
50 HTMLFormatter,
51 SVGFormatter,
52 PNGFormatter,
53 LatexFormatter,
54 JSONFormatter
55 ]
56 d = {}
57 for cls in formatter_classes:
58 f = cls(config=self.config)
59 d[f.format_type] = f
60 return d
61
62 def format(self, obj, include=None, exclude=None):
63 """Return a format data dict for an object.
64
65 By default all format types will be computed.
66
67 The following MIME types are currently implemented:
68
69 * text/plain
70 * text/html
71 * text/latex
72 * application/json
73 * image/png
74 * immage/svg+xml
75
76 Parameters
77 ----------
78 obj : object
79 The Python object whose format data will be computed.
80 include : list or tuple, optional
81 A list of format type strings (MIME types) to include in the
82 format data dict. If this is set *only* the format types included
83 in this list will be computed.
84 exclude : list or tuple, optional
85 A list of format type string (MIME types) to exclue in the format
86 data dict. If this is set all format types will be computed,
87 except for those included in this argument.
88
89 Returns
90 -------
91 format_dict : dict
92 A dictionary of key/value pairs, one or each format that was
93 generated for the object. The keys are the format types, which
94 will usually be MIME type strings and the values and JSON'able
95 data structure containing the raw data for the representation in
96 that format.
97 """
98 format_dict = {}
99
100 # If plain text only is active
101 if self.plain_text_only:
102 formatter = self.formatters['text/plain']
103 try:
104 data = formatter(obj)
105 except:
106 # FIXME: log the exception
107 raise
108 if data is not None:
109 format_dict['text/plain'] = data
110 return format_dict
111
112 for format_type, formatter in self.formatters.items():
113 if include is not None:
114 if format_type not in include:
115 continue
116 if exclude is not None:
117 if format_type in exclude:
118 continue
119 try:
120 data = formatter(obj)
121 except:
122 # FIXME: log the exception
123 raise
124 if data is not None:
125 format_dict[format_type] = data
126 return format_dict
127
128 @property
129 def format_types(self):
130 """Return the format types (MIME types) of the active formatters."""
131 return self.formatters.keys()
132
133
134 #-----------------------------------------------------------------------------
135 # Formatters for specific format types (text, html, svg, etc.)
55 136 #-----------------------------------------------------------------------------
56 137
57 class DefaultFormatter(Configurable):
58 """ The default pretty-printer.
138
139 class FormatterABC(object):
140 """ Abstract base class for Formatters.
141
142 A formatter is a callable class that is responsible for computing the
143 raw format data for a particular format type (MIME type). For example,
144 an HTML formatter would have a format type of `text/html` and would return
145 the HTML representation of the object when called.
59 146 """
147 __metaclass__ = abc.ABCMeta
148
149 # The format type of the data returned, usually a MIME type.
150 format_type = 'text/plain'
60 151
61 # The ID of the formatter.
62 id = Str('default')
152 # Is the formatter enabled...
153 enabled = True
63 154
64 # The kind of data returned.
65 # This is often, but not always a MIME type.
66 format = Str('text/plain')
155 @abc.abstractmethod
156 def __call__(self, obj):
157 """Return a JSON'able representation of the object.
158
159 If the object cannot be formatted by this formatter, then return None
160 """
161 try:
162 return repr(obj)
163 except TypeError:
164 return None
165
166
167 class BaseFormatter(Configurable):
168 """A base formatter class that is configurable.
169
170 This formatter should usually be used as the base class of all formatters.
171 It is a traited :class:`Configurable` class and includes an extensible
172 API for users to determine how their objects are formatted. The following
173 logic is used to find a function to format an given object.
174
175 1. The object is introspected to see if it has a method with the name
176 :attr:`print_method`. If is does, that object is passed to that method
177 for formatting.
178 2. If no print method is found, three internal dictionaries are consulted
179 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
180 and :attr:`deferred_printers`.
181
182 Users should use these dictionaries to register functions that will be
183 used to compute the format data for their objects (if those objects don't
184 have the special print methods). The easiest way of using these
185 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
186 methods.
187
188 If no function/callable is found to compute the format data, ``None`` is
189 returned and this format type is not used.
190 """
191
192 format_type = Str('text/plain')
193
194 enabled = Bool(True, config=True)
195
196 print_method = Str('__repr__')
197
198 # The singleton printers.
199 # Maps the IDs of the builtin singleton objects to the format functions.
200 singleton_printers = Dict(config=True)
201 def _singleton_printers_default(self):
202 return {}
203
204 # The type-specific printers.
205 # Map type objects to the format functions.
206 type_printers = Dict(config=True)
207 def _type_printers_default(self):
208 return {}
209
210 # The deferred-import type-specific printers.
211 # Map (modulename, classname) pairs to the format functions.
212 deferred_printers = Dict(config=True)
213 def _deferred_printers_default(self):
214 return {}
215
216 def __call__(self, obj):
217 """Compute the format for an object."""
218 if self.enabled:
219 obj_id = id(obj)
220 try:
221 obj_class = getattr(obj, '__class__', None) or type(obj)
222 if hasattr(obj_class, self.print_method):
223 printer = getattr(obj_class, self.print_method)
224 return printer(obj)
225 try:
226 printer = self.singleton_printers[obj_id]
227 except (TypeError, KeyError):
228 pass
229 else:
230 return printer(obj)
231 for cls in pretty._get_mro(obj_class):
232 if cls in self.type_printers:
233 return self.type_printers[cls](obj)
234 else:
235 printer = self._in_deferred_types(cls)
236 if printer is not None:
237 return printer(obj)
238 return None
239 except Exception:
240 pass
241 else:
242 return None
243
244 def for_type(self, typ, func):
245 """Add a format function for a given type.
246
247 Parameters
248 -----------
249 typ : class
250 The class of the object that will be formatted using `func`.
251 func : callable
252 The callable that will be called to compute the format data. The
253 call signature of this function is simple, it must take the
254 object to be formatted and return the raw data for the given
255 format. Subclasses may use a different call signature for the
256 `func` argument.
257 """
258 oldfunc = self.type_printers.get(typ, None)
259 if func is not None:
260 # To support easy restoration of old printers, we need to ignore
261 # Nones.
262 self.type_printers[typ] = func
263 return oldfunc
264
265 def for_type_by_name(self, type_module, type_name, func):
266 """Add a format function for a type specified by the full dotted
267 module and name of the type, rather than the type of the object.
268
269 Parameters
270 ----------
271 type_module : str
272 The full dotted name of the module the type is defined in, like
273 ``numpy``.
274 type_name : str
275 The name of the type (the class name), like ``dtype``
276 func : callable
277 The callable that will be called to compute the format data. The
278 call signature of this function is simple, it must take the
279 object to be formatted and return the raw data for the given
280 format. Subclasses may use a different call signature for the
281 `func` argument.
282 """
283 key = (type_module, type_name)
284 oldfunc = self.deferred_printers.get(key, None)
285 if func is not None:
286 # To support easy restoration of old printers, we need to ignore
287 # Nones.
288 self.deferred_printers[key] = func
289 return oldfunc
290
291 def _in_deferred_types(self, cls):
292 """
293 Check if the given class is specified in the deferred type registry.
294
295 Returns the printer from the registry if it exists, and None if the
296 class is not in the registry. Successful matches will be moved to the
297 regular type registry for future use.
298 """
299 mod = getattr(cls, '__module__', None)
300 name = getattr(cls, '__name__', None)
301 key = (mod, name)
302 printer = None
303 if key in self.deferred_printers:
304 # Move the printer over to the regular registry.
305 printer = self.deferred_printers.pop(key)
306 self.type_printers[cls] = printer
307 return printer
308
309
310 class PlainTextFormatter(BaseFormatter):
311 """The default pretty-printer.
312
313 This uses :mod:`IPython.external.pretty` to compute the format data of
314 the object. If the object cannot be pretty printed, :func:`repr` is used.
315 See the documentation of :mod:`IPython.external.pretty` for details on
316 how to write pretty printers. Here is a simple example::
317
318 def dtype_pprinter(obj, p, cycle):
319 if cycle:
320 return p.text('dtype(...)')
321 if hasattr(obj, 'fields'):
322 if obj.fields is None:
323 p.text(repr(obj))
324 else:
325 p.begin_group(7, 'dtype([')
326 for i, field in enumerate(obj.descr):
327 if i > 0:
328 p.text(',')
329 p.breakable()
330 p.pretty(field)
331 p.end_group(7, '])')
332 """
333
334 # The format type of data returned.
335 format_type = Str('text/plain')
336
337 # This subclass ignores this attribute as it always need to return
338 # something.
339 enabled = Bool(True, config=False)
340
341 # Look for a __pretty__ methods to use for pretty printing.
342 print_method = Str('__pretty__')
67 343
68 344 # Whether to pretty-print or not.
69 345 pprint = Bool(True, config=True)
70 346
71 347 # Whether to be verbose or not.
72 348 verbose = Bool(False, config=True)
73 349
74 350 # The maximum width.
75 351 max_width = Int(79, config=True)
76 352
77 353 # The newline character.
78 354 newline = Str('\n', config=True)
79 355
80 # The singleton prettyprinters.
81 # Maps the IDs of the builtin singleton objects to the format functions.
82 singleton_pprinters = Dict(config=True)
83 def _singleton_pprinters_default(self):
356 # Use the default pretty printers from IPython.external.pretty.
357 def _singleton_printers_default(self):
84 358 return pretty._singleton_pprinters.copy()
85 359
86 # The type-specific prettyprinters.
87 # Map type objects to the format functions.
88 type_pprinters = Dict(config=True)
89 def _type_pprinters_default(self):
360 def _type_printers_default(self):
90 361 return pretty._type_pprinters.copy()
91 362
92 # The deferred-import type-specific prettyprinters.
93 # Map (modulename, classname) pairs to the format functions.
94 deferred_pprinters = Dict(config=True)
95 def _deferred_pprinters_default(self):
363 def _deferred_printers_default(self):
96 364 return pretty._deferred_type_pprinters.copy()
97 365
98 366 #### FormatterABC interface ####
99 367
100 368 def __call__(self, obj):
101 """ Format the object.
102 """
369 """Compute the pretty representation of the object."""
103 370 if not self.pprint:
104 371 try:
105 372 return repr(obj)
106 373 except TypeError:
107 374 return ''
108 375 else:
376 # This uses use StringIO, as cStringIO doesn't handle unicode.
109 377 stream = StringIO()
110 378 printer = pretty.RepresentationPrinter(stream, self.verbose,
111 379 self.max_width, self.newline,
112 singleton_pprinters=self.singleton_pprinters,
113 type_pprinters=self.type_pprinters,
114 deferred_pprinters=self.deferred_pprinters)
380 singleton_pprinters=self.singleton_printers,
381 type_pprinters=self.type_printers,
382 deferred_pprinters=self.deferred_printers)
115 383 printer.pretty(obj)
116 384 printer.flush()
117 385 return stream.getvalue()
118 386
119 387
120 #### DefaultFormatter interface ####
388 class HTMLFormatter(BaseFormatter):
389 """An HTML formatter.
121 390
122 def for_type(self, typ, func):
123 """
124 Add a pretty printer for a given type.
125 """
126 oldfunc = self.type_pprinters.get(typ, None)
127 if func is not None:
128 # To support easy restoration of old pprinters, we need to ignore
129 # Nones.
130 self.type_pprinters[typ] = func
131 return oldfunc
391 To define the callables that compute the HTML representation of your
392 objects, define a :meth:`__html__` method or use the :meth:`for_type`
393 or :meth:`for_type_by_name` methods to register functions that handle
394 this.
395 """
396 format_type = Str('text/html')
132 397
133 def for_type_by_name(self, type_module, type_name, func):
134 """
135 Add a pretty printer for a type specified by the module and name of
136 a type rather than the type object itself.
137 """
138 key = (type_module, type_name)
139 oldfunc = self.deferred_pprinters.get(key, None)
140 if func is not None:
141 # To support easy restoration of old pprinters, we need to ignore
142 # Nones.
143 self.deferred_pprinters[key] = func
144 return oldfunc
398 print_method = Str('__html__')
145 399
146 400
147 class FormatterABC(object):
148 """ Abstract base class for Formatters.
401 class SVGFormatter(BaseFormatter):
402 """An SVG formatter.
403
404 To define the callables that compute the SVG representation of your
405 objects, define a :meth:`__svg__` method or use the :meth:`for_type`
406 or :meth:`for_type_by_name` methods to register functions that handle
407 this.
149 408 """
150 __metaclass__ = abc.ABCMeta
409 format_type = Str('image/svg+xml')
151 410
152 # The ID of the formatter.
153 id = 'abstract'
411 print_method = Str('__svg__')
154 412
155 # The kind of data returned.
156 format = 'text/plain'
157 413
158 @abc.abstractmethod
159 def __call__(self, obj):
160 """ Return a JSONable representation of the object.
414 class PNGFormatter(BaseFormatter):
415 """A PNG formatter.
161 416
162 If the object cannot be formatted by this formatter, then return None
163 """
164 try:
165 return repr(obj)
166 except TypeError:
167 return None
417 To define the callables that compute the PNG representation of your
418 objects, define a :meth:`__png__` method or use the :meth:`for_type`
419 or :meth:`for_type_by_name` methods to register functions that handle
420 this. The raw data should be the base64 encoded raw png data.
421 """
422 format_type = Str('image/png')
423
424 print_method = Str('__png__')
425
426
427 class LatexFormatter(BaseFormatter):
428 """A LaTeX formatter.
429
430 To define the callables that compute the LaTeX representation of your
431 objects, define a :meth:`__latex__` method or use the :meth:`for_type`
432 or :meth:`for_type_by_name` methods to register functions that handle
433 this.
434 """
435 format_type = Str('text/latex')
436
437 print_method = Str('__latex__')
438
439
440 class JSONFormatter(BaseFormatter):
441 """A JSON string formatter.
442
443 To define the callables that compute the JSON string representation of
444 your objects, define a :meth:`__json__` method or use the :meth:`for_type`
445 or :meth:`for_type_by_name` methods to register functions that handle
446 this.
447 """
448 format_type = Str('application/json')
449
450 print_method = Str('__json__')
451
452
453 FormatterABC.register(BaseFormatter)
454 FormatterABC.register(PlainTextFormatter)
455 FormatterABC.register(HTMLFormatter)
456 FormatterABC.register(SVGFormatter)
457 FormatterABC.register(PNGFormatter)
458 FormatterABC.register(LatexFormatter)
459 FormatterABC.register(JSONFormatter)
460
461
462 def format_display_data(obj, include=None, exclude=None):
463 """Return a format data dict for an object.
464
465 By default all format types will be computed.
466
467 The following MIME types are currently implemented:
468
469 * text/plain
470 * text/html
471 * text/latex
472 * application/json
473 * image/png
474 * immage/svg+xml
475
476 Parameters
477 ----------
478 obj : object
479 The Python object whose format data will be computed.
480
481 Returns
482 -------
483 format_dict : dict
484 A dictionary of key/value pairs, one or each format that was
485 generated for the object. The keys are the format types, which
486 will usually be MIME type strings and the values and JSON'able
487 data structure containing the raw data for the representation in
488 that format.
489 include : list or tuple, optional
490 A list of format type strings (MIME types) to include in the
491 format data dict. If this is set *only* the format types included
492 in this list will be computed.
493 exclude : list or tuple, optional
494 A list of format type string (MIME types) to exclue in the format
495 data dict. If this is set all format types will be computed,
496 except for those included in this argument.
497 """
498 from IPython.core.interactiveshell import InteractiveShell
168 499
169 FormatterABC.register(DefaultFormatter)
500 InteractiveShell.instance().display_formatter.format(
501 obj,
502 include,
503 exclude
504 )
@@ -1,263 +1,236 b''
1 1 """hooks for IPython.
2 2
3 3 In Python, it is possible to overwrite any method of any object if you really
4 4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 5 be overwritten by users for customization purposes. This module defines the
6 6 default versions of all such hooks, which get used by IPython if not
7 7 overridden by the user.
8 8
9 9 hooks are simple functions, but they should be declared with 'self' as their
10 10 first argument, because when activated they are registered into IPython as
11 11 instance methods. The self argument will be the IPython running instance
12 12 itself, so hooks have full access to the entire IPython object.
13 13
14 14 If you wish to define a new hook and activate it, you need to put the
15 15 necessary code into a python file which can be either imported or execfile()'d
16 16 from within your ipythonrc configuration.
17 17
18 18 For example, suppose that you have a module called 'myiphooks' in your
19 19 PYTHONPATH, which contains the following definition:
20 20
21 21 import os
22 22 from IPython.core import ipapi
23 23 ip = ipapi.get()
24 24
25 25 def calljed(self,filename, linenum):
26 26 "My editor hook calls the jed editor directly."
27 27 print "Calling my own editor, jed ..."
28 28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 29 raise TryNext()
30 30
31 31 ip.set_hook('editor', calljed)
32 32
33 33 You can then enable the functionality by doing 'import myiphooks'
34 34 somewhere in your configuration files or ipython command line.
35 35 """
36 36
37 37 #*****************************************************************************
38 38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 39 #
40 40 # Distributed under the terms of the BSD License. The full license is in
41 41 # the file COPYING, distributed as part of this software.
42 42 #*****************************************************************************
43 43
44 44 import os, bisect
45 45 import sys
46 46
47 47 from IPython.core.error import TryNext
48 48 import IPython.utils.io
49 49
50 50 # List here all the default hooks. For now it's just the editor functions
51 51 # but over time we'll move here all the public API for user-accessible things.
52 52
53 53 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
54 54 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
55 55 'generate_prompt', 'show_in_pager','pre_prompt_hook',
56 56 'pre_run_code_hook', 'clipboard_get']
57 57
58 58 def editor(self,filename, linenum=None):
59 59 """Open the default editor at the given filename and linenumber.
60 60
61 61 This is IPython's default editor hook, you can use it as an example to
62 62 write your own modified one. To set your own editor function as the
63 63 new editor hook, call ip.set_hook('editor',yourfunc)."""
64 64
65 65 # IPython configures a default editor at startup by reading $EDITOR from
66 66 # the environment, and falling back on vi (unix) or notepad (win32).
67 67 editor = self.editor
68 68
69 69 # marker for at which line to open the file (for existing objects)
70 70 if linenum is None or editor=='notepad':
71 71 linemark = ''
72 72 else:
73 73 linemark = '+%d' % int(linenum)
74 74
75 75 # Enclose in quotes if necessary and legal
76 76 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
77 77 editor = '"%s"' % editor
78 78
79 79 # Call the actual editor
80 80 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
81 81 raise TryNext()
82 82
83 83 import tempfile
84 84 def fix_error_editor(self,filename,linenum,column,msg):
85 85 """Open the editor at the given filename, linenumber, column and
86 86 show an error message. This is used for correcting syntax errors.
87 87 The current implementation only has special support for the VIM editor,
88 88 and falls back on the 'editor' hook if VIM is not used.
89 89
90 90 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
91 91 """
92 92 def vim_quickfix_file():
93 93 t = tempfile.NamedTemporaryFile()
94 94 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
95 95 t.flush()
96 96 return t
97 97 if os.path.basename(self.editor) != 'vim':
98 98 self.hooks.editor(filename,linenum)
99 99 return
100 100 t = vim_quickfix_file()
101 101 try:
102 102 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
103 103 raise TryNext()
104 104 finally:
105 105 t.close()
106 106
107 107
108 108 def synchronize_with_editor(self, filename, linenum, column):
109 109 pass
110 110
111 111
112 112 class CommandChainDispatcher:
113 113 """ Dispatch calls to a chain of commands until some func can handle it
114 114
115 115 Usage: instantiate, execute "add" to add commands (with optional
116 116 priority), execute normally via f() calling mechanism.
117 117
118 118 """
119 119 def __init__(self,commands=None):
120 120 if commands is None:
121 121 self.chain = []
122 122 else:
123 123 self.chain = commands
124 124
125 125
126 126 def __call__(self,*args, **kw):
127 127 """ Command chain is called just like normal func.
128 128
129 129 This will call all funcs in chain with the same args as were given to this
130 130 function, and return the result of first func that didn't raise
131 131 TryNext """
132 132
133 133 for prio,cmd in self.chain:
134 134 #print "prio",prio,"cmd",cmd #dbg
135 135 try:
136 136 return cmd(*args, **kw)
137 137 except TryNext, exc:
138 138 if exc.args or exc.kwargs:
139 139 args = exc.args
140 140 kw = exc.kwargs
141 141 # if no function will accept it, raise TryNext up to the caller
142 142 raise TryNext
143 143
144 144 def __str__(self):
145 145 return str(self.chain)
146 146
147 147 def add(self, func, priority=0):
148 148 """ Add a func to the cmd chain with given priority """
149 149 bisect.insort(self.chain,(priority,func))
150 150
151 151 def __iter__(self):
152 152 """ Return all objects in chain.
153 153
154 154 Handy if the objects are not callable.
155 155 """
156 156 return iter(self.chain)
157 157
158 158
159 def result_display(self,arg):
160 """ Default display hook.
161
162 Called for displaying the result to the user.
163 """
164
165 if self.pprint:
166 try:
167 out = pformat(arg)
168 except:
169 # Work around possible bugs in pformat
170 out = repr(arg)
171 if '\n' in out:
172 # So that multi-line strings line up with the left column of
173 # the screen, instead of having the output prompt mess up
174 # their first line.
175 IPython.utils.io.Term.cout.write('\n')
176 print >>IPython.utils.io.Term.cout, out
177 else:
178 # By default, the interactive prompt uses repr() to display results,
179 # so we should honor this. Users who'd rather use a different
180 # mechanism can easily override this hook.
181 print >>IPython.utils.io.Term.cout, repr(arg)
182 # the default display hook doesn't manipulate the value to put in history
183 return None
184
185
186 159 def input_prefilter(self,line):
187 160 """ Default input prefilter
188 161
189 162 This returns the line as unchanged, so that the interpreter
190 163 knows that nothing was done and proceeds with "classic" prefiltering
191 164 (%magics, !shell commands etc.).
192 165
193 166 Note that leading whitespace is not passed to this hook. Prefilter
194 167 can't alter indentation.
195 168
196 169 """
197 170 #print "attempt to rewrite",line #dbg
198 171 return line
199 172
200 173
201 174 def shutdown_hook(self):
202 175 """ default shutdown hook
203 176
204 177 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
205 178 """
206 179
207 180 #print "default shutdown hook ok" # dbg
208 181 return
209 182
210 183
211 184 def late_startup_hook(self):
212 185 """ Executed after ipython has been constructed and configured
213 186
214 187 """
215 188 #print "default startup hook ok" # dbg
216 189
217 190
218 191 def generate_prompt(self, is_continuation):
219 192 """ calculate and return a string with the prompt to display """
220 193 if is_continuation:
221 194 return str(self.displayhook.prompt2)
222 195 return str(self.displayhook.prompt1)
223 196
224 197
225 198 def show_in_pager(self,s):
226 199 """ Run a string through pager """
227 200 # raising TryNext here will use the default paging functionality
228 201 raise TryNext
229 202
230 203
231 204 def pre_prompt_hook(self):
232 205 """ Run before displaying the next prompt
233 206
234 207 Use this e.g. to display output from asynchronous operations (in order
235 208 to not mess up text entry)
236 209 """
237 210
238 211 return None
239 212
240 213
241 214 def pre_run_code_hook(self):
242 215 """ Executed before running the (prefiltered) code in IPython """
243 216 return None
244 217
245 218
246 219 def clipboard_get(self):
247 220 """ Get text from the clipboard.
248 221 """
249 222 from IPython.lib.clipboard import (
250 223 osx_clipboard_get, tkinter_clipboard_get,
251 224 win32_clipboard_get
252 225 )
253 226 if sys.platform == 'win32':
254 227 chain = [win32_clipboard_get, tkinter_clipboard_get]
255 228 elif sys.platform == 'darwin':
256 229 chain = [osx_clipboard_get, tkinter_clipboard_get]
257 230 else:
258 231 chain = [tkinter_clipboard_get]
259 232 dispatcher = CommandChainDispatcher()
260 233 for func in chain:
261 234 dispatcher.add(func)
262 235 text = dispatcher()
263 236 return text
@@ -1,2543 +1,2555 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 from IPython.core.displaypub import DisplayPublisher
44 45 from IPython.core.error import TryNext, UsageError
45 46 from IPython.core.extensions import ExtensionManager
46 47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 from IPython.core.formatters import DisplayFormatter
47 49 from IPython.core.history import HistoryManager
48 50 from IPython.core.inputsplitter import IPythonInputSplitter
49 51 from IPython.core.logger import Logger
50 52 from IPython.core.magic import Magic
51 53 from IPython.core.payload import PayloadManager
52 54 from IPython.core.plugin import PluginManager
53 55 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 56 from IPython.external.Itpl import ItplNS
55 57 from IPython.utils import PyColorize
56 58 from IPython.utils import io
57 59 from IPython.utils import pickleshare
58 60 from IPython.utils.doctestreload import doctest_reload
59 61 from IPython.utils.io import ask_yes_no, rprint
60 62 from IPython.utils.ipstruct import Struct
61 63 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 64 from IPython.utils.process import system, getoutput
63 65 from IPython.utils.strdispatch import StrDispatch
64 66 from IPython.utils.syspathcontext import prepended_to_syspath
65 67 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
66 68 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 69 List, Unicode, Instance, Type)
68 70 from IPython.utils.warn import warn, error, fatal
69 71 import IPython.core.hooks
70 72
71 73 #-----------------------------------------------------------------------------
72 74 # Globals
73 75 #-----------------------------------------------------------------------------
74 76
75 77 # compiled regexps for autoindent management
76 78 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 79
78 80 #-----------------------------------------------------------------------------
79 81 # Utilities
80 82 #-----------------------------------------------------------------------------
81 83
82 84 # store the builtin raw_input globally, and use this always, in case user code
83 85 # overwrites it (like wx.py.PyShell does)
84 86 raw_input_original = raw_input
85 87
86 88 def softspace(file, newvalue):
87 89 """Copied from code.py, to remove the dependency"""
88 90
89 91 oldvalue = 0
90 92 try:
91 93 oldvalue = file.softspace
92 94 except AttributeError:
93 95 pass
94 96 try:
95 97 file.softspace = newvalue
96 98 except (AttributeError, TypeError):
97 99 # "attribute-less object" or "read-only attributes"
98 100 pass
99 101 return oldvalue
100 102
101 103
102 104 def no_op(*a, **kw): pass
103 105
104 106 class SpaceInInput(Exception): pass
105 107
106 108 class Bunch: pass
107 109
108 110
109 111 def get_default_colors():
110 112 if sys.platform=='darwin':
111 113 return "LightBG"
112 114 elif os.name=='nt':
113 115 return 'Linux'
114 116 else:
115 117 return 'Linux'
116 118
117 119
118 120 class SeparateStr(Str):
119 121 """A Str subclass to validate separate_in, separate_out, etc.
120 122
121 123 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 124 """
123 125
124 126 def validate(self, obj, value):
125 127 if value == '0': value = ''
126 128 value = value.replace('\\n','\n')
127 129 return super(SeparateStr, self).validate(obj, value)
128 130
129 131 class MultipleInstanceError(Exception):
130 132 pass
131 133
132 134
133 135 #-----------------------------------------------------------------------------
134 136 # Main IPython class
135 137 #-----------------------------------------------------------------------------
136 138
137 139 class InteractiveShell(Configurable, Magic):
138 140 """An enhanced, interactive shell for Python."""
139 141
140 142 _instance = None
141 143 autocall = Enum((0,1,2), default_value=1, config=True)
142 144 # TODO: remove all autoindent logic and put into frontends.
143 145 # We can't do this yet because even runlines uses the autoindent.
144 146 autoindent = CBool(True, config=True)
145 147 automagic = CBool(True, config=True)
146 148 cache_size = Int(1000, config=True)
147 149 color_info = CBool(True, config=True)
148 150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
149 151 default_value=get_default_colors(), config=True)
150 152 debug = CBool(False, config=True)
151 153 deep_reload = CBool(False, config=True)
154 display_formatter = Instance(DisplayFormatter)
152 155 displayhook_class = Type(DisplayHook)
156 display_pub_class = Type(DisplayPublisher)
157
153 158 exit_now = CBool(False)
154 159 # Monotonically increasing execution counter
155 160 execution_count = Int(1)
156 161 filename = Str("<ipython console>")
157 162 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 163
159 164 # Input splitter, to split entire cells of input into either individual
160 165 # interactive statements or whole blocks.
161 166 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 167 (), {})
163 168 logstart = CBool(False, config=True)
164 169 logfile = Str('', config=True)
165 170 logappend = Str('', config=True)
166 171 object_info_string_level = Enum((0,1,2), default_value=0,
167 172 config=True)
168 173 pdb = CBool(False, config=True)
169 174
170 pprint = CBool(True, config=True)
171 175 profile = Str('', config=True)
172 176 prompt_in1 = Str('In [\\#]: ', config=True)
173 177 prompt_in2 = Str(' .\\D.: ', config=True)
174 178 prompt_out = Str('Out[\\#]: ', config=True)
175 179 prompts_pad_left = CBool(True, config=True)
176 180 quiet = CBool(False, config=True)
177 181
178 182 history_length = Int(10000, config=True)
179 183
180 184 # The readline stuff will eventually be moved to the terminal subclass
181 185 # but for now, we can't do that as readline is welded in everywhere.
182 186 readline_use = CBool(True, config=True)
183 187 readline_merge_completions = CBool(True, config=True)
184 188 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
185 189 readline_remove_delims = Str('-/~', config=True)
186 190 readline_parse_and_bind = List([
187 191 'tab: complete',
188 192 '"\C-l": clear-screen',
189 193 'set show-all-if-ambiguous on',
190 194 '"\C-o": tab-insert',
191 195 '"\M-i": " "',
192 196 '"\M-o": "\d\d\d\d"',
193 197 '"\M-I": "\d\d\d\d"',
194 198 '"\C-r": reverse-search-history',
195 199 '"\C-s": forward-search-history',
196 200 '"\C-p": history-search-backward',
197 201 '"\C-n": history-search-forward',
198 202 '"\e[A": history-search-backward',
199 203 '"\e[B": history-search-forward',
200 204 '"\C-k": kill-line',
201 205 '"\C-u": unix-line-discard',
202 206 ], allow_none=False, config=True)
203 207
204 208 # TODO: this part of prompt management should be moved to the frontends.
205 209 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
206 210 separate_in = SeparateStr('\n', config=True)
207 211 separate_out = SeparateStr('', config=True)
208 212 separate_out2 = SeparateStr('', config=True)
209 213 wildcards_case_sensitive = CBool(True, config=True)
210 214 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
211 215 default_value='Context', config=True)
212 216
213 217 # Subcomponents of InteractiveShell
214 218 alias_manager = Instance('IPython.core.alias.AliasManager')
215 219 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
216 220 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
217 221 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
218 222 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
219 223 plugin_manager = Instance('IPython.core.plugin.PluginManager')
220 224 payload_manager = Instance('IPython.core.payload.PayloadManager')
221 225 history_manager = Instance('IPython.core.history.HistoryManager')
222 226
223 227 # Private interface
224 228 _post_execute = set()
225 229
226 230 def __init__(self, config=None, ipython_dir=None,
227 231 user_ns=None, user_global_ns=None,
228 232 custom_exceptions=((), None)):
229 233
230 234 # This is where traits with a config_key argument are updated
231 235 # from the values on config.
232 236 super(InteractiveShell, self).__init__(config=config)
233 237
234 238 # These are relatively independent and stateless
235 239 self.init_ipython_dir(ipython_dir)
236 240 self.init_instance_attrs()
237 241 self.init_environment()
238 242
239 243 # Create namespaces (user_ns, user_global_ns, etc.)
240 244 self.init_create_namespaces(user_ns, user_global_ns)
241 245 # This has to be done after init_create_namespaces because it uses
242 246 # something in self.user_ns, but before init_sys_modules, which
243 247 # is the first thing to modify sys.
244 248 # TODO: When we override sys.stdout and sys.stderr before this class
245 249 # is created, we are saving the overridden ones here. Not sure if this
246 250 # is what we want to do.
247 251 self.save_sys_module_state()
248 252 self.init_sys_modules()
249 253
250 254 self.init_history()
251 255 self.init_encoding()
252 256 self.init_prefilter()
253 257
254 258 Magic.__init__(self, self)
255 259
256 260 self.init_syntax_highlighting()
257 261 self.init_hooks()
258 262 self.init_pushd_popd_magic()
259 263 # self.init_traceback_handlers use to be here, but we moved it below
260 264 # because it and init_io have to come after init_readline.
261 265 self.init_user_ns()
262 266 self.init_logger()
263 267 self.init_alias()
264 268 self.init_builtins()
265 269
266 270 # pre_config_initialization
267 271
268 272 # The next section should contain everything that was in ipmaker.
269 273 self.init_logstart()
270 274
271 275 # The following was in post_config_initialization
272 276 self.init_inspector()
273 277 # init_readline() must come before init_io(), because init_io uses
274 278 # readline related things.
275 279 self.init_readline()
276 280 # init_completer must come after init_readline, because it needs to
277 281 # know whether readline is present or not system-wide to configure the
278 282 # completers, since the completion machinery can now operate
279 283 # independently of readline (e.g. over the network)
280 284 self.init_completer()
281 285 # TODO: init_io() needs to happen before init_traceback handlers
282 286 # because the traceback handlers hardcode the stdout/stderr streams.
283 287 # This logic in in debugger.Pdb and should eventually be changed.
284 288 self.init_io()
285 289 self.init_traceback_handlers(custom_exceptions)
286 290 self.init_prompts()
291 self.init_display_formatter()
292 self.init_display_pub()
287 293 self.init_displayhook()
288 294 self.init_reload_doctest()
289 295 self.init_magics()
290 296 self.init_pdb()
291 297 self.init_extension_manager()
292 298 self.init_plugin_manager()
293 299 self.init_payload()
294 300 self.hooks.late_startup_hook()
295 301 atexit.register(self.atexit_operations)
296 302
297 303 # While we're trying to have each part of the code directly access what it
298 304 # needs without keeping redundant references to objects, we have too much
299 305 # legacy code that expects ip.db to exist, so let's make it a property that
300 306 # retrieves the underlying object from our new history manager.
301 307 @property
302 308 def db(self):
303 309 return self.history_manager.shadow_db
304 310
305 311 @classmethod
306 312 def instance(cls, *args, **kwargs):
307 313 """Returns a global InteractiveShell instance."""
308 314 if cls._instance is None:
309 315 inst = cls(*args, **kwargs)
310 316 # Now make sure that the instance will also be returned by
311 317 # the subclasses instance attribute.
312 318 for subclass in cls.mro():
313 319 if issubclass(cls, subclass) and \
314 320 issubclass(subclass, InteractiveShell):
315 321 subclass._instance = inst
316 322 else:
317 323 break
318 324 if isinstance(cls._instance, cls):
319 325 return cls._instance
320 326 else:
321 327 raise MultipleInstanceError(
322 328 'Multiple incompatible subclass instances of '
323 329 'InteractiveShell are being created.'
324 330 )
325 331
326 332 @classmethod
327 333 def initialized(cls):
328 334 return hasattr(cls, "_instance")
329 335
330 336 def get_ipython(self):
331 337 """Return the currently running IPython instance."""
332 338 return self
333 339
334 340 #-------------------------------------------------------------------------
335 341 # Trait changed handlers
336 342 #-------------------------------------------------------------------------
337 343
338 344 def _ipython_dir_changed(self, name, new):
339 345 if not os.path.isdir(new):
340 346 os.makedirs(new, mode = 0777)
341 347
342 348 def set_autoindent(self,value=None):
343 349 """Set the autoindent flag, checking for readline support.
344 350
345 351 If called with no arguments, it acts as a toggle."""
346 352
347 353 if not self.has_readline:
348 354 if os.name == 'posix':
349 355 warn("The auto-indent feature requires the readline library")
350 356 self.autoindent = 0
351 357 return
352 358 if value is None:
353 359 self.autoindent = not self.autoindent
354 360 else:
355 361 self.autoindent = value
356 362
357 363 #-------------------------------------------------------------------------
358 364 # init_* methods called by __init__
359 365 #-------------------------------------------------------------------------
360 366
361 367 def init_ipython_dir(self, ipython_dir):
362 368 if ipython_dir is not None:
363 369 self.ipython_dir = ipython_dir
364 370 self.config.Global.ipython_dir = self.ipython_dir
365 371 return
366 372
367 373 if hasattr(self.config.Global, 'ipython_dir'):
368 374 self.ipython_dir = self.config.Global.ipython_dir
369 375 else:
370 376 self.ipython_dir = get_ipython_dir()
371 377
372 378 # All children can just read this
373 379 self.config.Global.ipython_dir = self.ipython_dir
374 380
375 381 def init_instance_attrs(self):
376 382 self.more = False
377 383
378 384 # command compiler
379 385 self.compile = CachingCompiler()
380 386
381 387 # User input buffers
382 388 # NOTE: these variables are slated for full removal, once we are 100%
383 389 # sure that the new execution logic is solid. We will delte runlines,
384 390 # push_line and these buffers, as all input will be managed by the
385 391 # frontends via an inputsplitter instance.
386 392 self.buffer = []
387 393 self.buffer_raw = []
388 394
389 395 # Make an empty namespace, which extension writers can rely on both
390 396 # existing and NEVER being used by ipython itself. This gives them a
391 397 # convenient location for storing additional information and state
392 398 # their extensions may require, without fear of collisions with other
393 399 # ipython names that may develop later.
394 400 self.meta = Struct()
395 401
396 402 # Object variable to store code object waiting execution. This is
397 403 # used mainly by the multithreaded shells, but it can come in handy in
398 404 # other situations. No need to use a Queue here, since it's a single
399 405 # item which gets cleared once run.
400 406 self.code_to_run = None
401 407
402 408 # Temporary files used for various purposes. Deleted at exit.
403 409 self.tempfiles = []
404 410
405 411 # Keep track of readline usage (later set by init_readline)
406 412 self.has_readline = False
407 413
408 414 # keep track of where we started running (mainly for crash post-mortem)
409 415 # This is not being used anywhere currently.
410 416 self.starting_dir = os.getcwd()
411 417
412 418 # Indentation management
413 419 self.indent_current_nsp = 0
414 420
415 421 def init_environment(self):
416 422 """Any changes we need to make to the user's environment."""
417 423 pass
418 424
419 425 def init_encoding(self):
420 426 # Get system encoding at startup time. Certain terminals (like Emacs
421 427 # under Win32 have it set to None, and we need to have a known valid
422 428 # encoding to use in the raw_input() method
423 429 try:
424 430 self.stdin_encoding = sys.stdin.encoding or 'ascii'
425 431 except AttributeError:
426 432 self.stdin_encoding = 'ascii'
427 433
428 434 def init_syntax_highlighting(self):
429 435 # Python source parser/formatter for syntax highlighting
430 436 pyformat = PyColorize.Parser().format
431 437 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
432 438
433 439 def init_pushd_popd_magic(self):
434 440 # for pushd/popd management
435 441 try:
436 442 self.home_dir = get_home_dir()
437 443 except HomeDirError, msg:
438 444 fatal(msg)
439 445
440 446 self.dir_stack = []
441 447
442 448 def init_logger(self):
443 449 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
444 450 logmode='rotate')
445 451
446 452 def init_logstart(self):
447 453 """Initialize logging in case it was requested at the command line.
448 454 """
449 455 if self.logappend:
450 456 self.magic_logstart(self.logappend + ' append')
451 457 elif self.logfile:
452 458 self.magic_logstart(self.logfile)
453 459 elif self.logstart:
454 460 self.magic_logstart()
455 461
456 462 def init_builtins(self):
457 463 self.builtin_trap = BuiltinTrap(shell=self)
458 464
459 465 def init_inspector(self):
460 466 # Object inspector
461 467 self.inspector = oinspect.Inspector(oinspect.InspectColors,
462 468 PyColorize.ANSICodeColors,
463 469 'NoColor',
464 470 self.object_info_string_level)
465 471
466 472 def init_io(self):
467 473 # This will just use sys.stdout and sys.stderr. If you want to
468 474 # override sys.stdout and sys.stderr themselves, you need to do that
469 475 # *before* instantiating this class, because Term holds onto
470 476 # references to the underlying streams.
471 477 if sys.platform == 'win32' and self.has_readline:
472 478 Term = io.IOTerm(cout=self.readline._outputfile,
473 479 cerr=self.readline._outputfile)
474 480 else:
475 481 Term = io.IOTerm()
476 482 io.Term = Term
477 483
478 484 def init_prompts(self):
479 485 # TODO: This is a pass for now because the prompts are managed inside
480 486 # the DisplayHook. Once there is a separate prompt manager, this
481 487 # will initialize that object and all prompt related information.
482 488 pass
483 489
490 def init_display_formatter(self):
491 self.display_formatter = DisplayFormatter(config=self.config)
492
493 def init_display_pub(self):
494 self.display_pub = self.display_pub_class(config=self.config)
495
484 496 def init_displayhook(self):
485 497 # Initialize displayhook, set in/out prompts and printing system
486 498 self.displayhook = self.displayhook_class(
487 499 config=self.config,
488 500 shell=self,
489 501 cache_size=self.cache_size,
490 502 input_sep = self.separate_in,
491 503 output_sep = self.separate_out,
492 504 output_sep2 = self.separate_out2,
493 505 ps1 = self.prompt_in1,
494 506 ps2 = self.prompt_in2,
495 507 ps_out = self.prompt_out,
496 508 pad_left = self.prompts_pad_left
497 509 )
498 510 # This is a context manager that installs/revmoes the displayhook at
499 511 # the appropriate time.
500 512 self.display_trap = DisplayTrap(hook=self.displayhook)
501 513
502 514 def init_reload_doctest(self):
503 515 # Do a proper resetting of doctest, including the necessary displayhook
504 516 # monkeypatching
505 517 try:
506 518 doctest_reload()
507 519 except ImportError:
508 520 warn("doctest module does not exist.")
509 521
510 522 #-------------------------------------------------------------------------
511 523 # Things related to injections into the sys module
512 524 #-------------------------------------------------------------------------
513 525
514 526 def save_sys_module_state(self):
515 527 """Save the state of hooks in the sys module.
516 528
517 529 This has to be called after self.user_ns is created.
518 530 """
519 531 self._orig_sys_module_state = {}
520 532 self._orig_sys_module_state['stdin'] = sys.stdin
521 533 self._orig_sys_module_state['stdout'] = sys.stdout
522 534 self._orig_sys_module_state['stderr'] = sys.stderr
523 535 self._orig_sys_module_state['excepthook'] = sys.excepthook
524 536 try:
525 537 self._orig_sys_modules_main_name = self.user_ns['__name__']
526 538 except KeyError:
527 539 pass
528 540
529 541 def restore_sys_module_state(self):
530 542 """Restore the state of the sys module."""
531 543 try:
532 544 for k, v in self._orig_sys_module_state.iteritems():
533 545 setattr(sys, k, v)
534 546 except AttributeError:
535 547 pass
536 548 # Reset what what done in self.init_sys_modules
537 549 try:
538 550 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
539 551 except (AttributeError, KeyError):
540 552 pass
541 553
542 554 #-------------------------------------------------------------------------
543 555 # Things related to hooks
544 556 #-------------------------------------------------------------------------
545 557
546 558 def init_hooks(self):
547 559 # hooks holds pointers used for user-side customizations
548 560 self.hooks = Struct()
549 561
550 562 self.strdispatchers = {}
551 563
552 564 # Set all default hooks, defined in the IPython.hooks module.
553 565 hooks = IPython.core.hooks
554 566 for hook_name in hooks.__all__:
555 567 # default hooks have priority 100, i.e. low; user hooks should have
556 568 # 0-100 priority
557 569 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
558 570
559 571 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
560 572 """set_hook(name,hook) -> sets an internal IPython hook.
561 573
562 574 IPython exposes some of its internal API as user-modifiable hooks. By
563 575 adding your function to one of these hooks, you can modify IPython's
564 576 behavior to call at runtime your own routines."""
565 577
566 578 # At some point in the future, this should validate the hook before it
567 579 # accepts it. Probably at least check that the hook takes the number
568 580 # of args it's supposed to.
569 581
570 582 f = types.MethodType(hook,self)
571 583
572 584 # check if the hook is for strdispatcher first
573 585 if str_key is not None:
574 586 sdp = self.strdispatchers.get(name, StrDispatch())
575 587 sdp.add_s(str_key, f, priority )
576 588 self.strdispatchers[name] = sdp
577 589 return
578 590 if re_key is not None:
579 591 sdp = self.strdispatchers.get(name, StrDispatch())
580 592 sdp.add_re(re.compile(re_key), f, priority )
581 593 self.strdispatchers[name] = sdp
582 594 return
583 595
584 596 dp = getattr(self.hooks, name, None)
585 597 if name not in IPython.core.hooks.__all__:
586 598 print "Warning! Hook '%s' is not one of %s" % \
587 599 (name, IPython.core.hooks.__all__ )
588 600 if not dp:
589 601 dp = IPython.core.hooks.CommandChainDispatcher()
590 602
591 603 try:
592 604 dp.add(f,priority)
593 605 except AttributeError:
594 606 # it was not commandchain, plain old func - replace
595 607 dp = f
596 608
597 609 setattr(self.hooks,name, dp)
598 610
599 611 def register_post_execute(self, func):
600 612 """Register a function for calling after code execution.
601 613 """
602 614 if not callable(func):
603 615 raise ValueError('argument %s must be callable' % func)
604 616 self._post_execute.add(func)
605 617
606 618 #-------------------------------------------------------------------------
607 619 # Things related to the "main" module
608 620 #-------------------------------------------------------------------------
609 621
610 622 def new_main_mod(self,ns=None):
611 623 """Return a new 'main' module object for user code execution.
612 624 """
613 625 main_mod = self._user_main_module
614 626 init_fakemod_dict(main_mod,ns)
615 627 return main_mod
616 628
617 629 def cache_main_mod(self,ns,fname):
618 630 """Cache a main module's namespace.
619 631
620 632 When scripts are executed via %run, we must keep a reference to the
621 633 namespace of their __main__ module (a FakeModule instance) around so
622 634 that Python doesn't clear it, rendering objects defined therein
623 635 useless.
624 636
625 637 This method keeps said reference in a private dict, keyed by the
626 638 absolute path of the module object (which corresponds to the script
627 639 path). This way, for multiple executions of the same script we only
628 640 keep one copy of the namespace (the last one), thus preventing memory
629 641 leaks from old references while allowing the objects from the last
630 642 execution to be accessible.
631 643
632 644 Note: we can not allow the actual FakeModule instances to be deleted,
633 645 because of how Python tears down modules (it hard-sets all their
634 646 references to None without regard for reference counts). This method
635 647 must therefore make a *copy* of the given namespace, to allow the
636 648 original module's __dict__ to be cleared and reused.
637 649
638 650
639 651 Parameters
640 652 ----------
641 653 ns : a namespace (a dict, typically)
642 654
643 655 fname : str
644 656 Filename associated with the namespace.
645 657
646 658 Examples
647 659 --------
648 660
649 661 In [10]: import IPython
650 662
651 663 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
652 664
653 665 In [12]: IPython.__file__ in _ip._main_ns_cache
654 666 Out[12]: True
655 667 """
656 668 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
657 669
658 670 def clear_main_mod_cache(self):
659 671 """Clear the cache of main modules.
660 672
661 673 Mainly for use by utilities like %reset.
662 674
663 675 Examples
664 676 --------
665 677
666 678 In [15]: import IPython
667 679
668 680 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
669 681
670 682 In [17]: len(_ip._main_ns_cache) > 0
671 683 Out[17]: True
672 684
673 685 In [18]: _ip.clear_main_mod_cache()
674 686
675 687 In [19]: len(_ip._main_ns_cache) == 0
676 688 Out[19]: True
677 689 """
678 690 self._main_ns_cache.clear()
679 691
680 692 #-------------------------------------------------------------------------
681 693 # Things related to debugging
682 694 #-------------------------------------------------------------------------
683 695
684 696 def init_pdb(self):
685 697 # Set calling of pdb on exceptions
686 698 # self.call_pdb is a property
687 699 self.call_pdb = self.pdb
688 700
689 701 def _get_call_pdb(self):
690 702 return self._call_pdb
691 703
692 704 def _set_call_pdb(self,val):
693 705
694 706 if val not in (0,1,False,True):
695 707 raise ValueError,'new call_pdb value must be boolean'
696 708
697 709 # store value in instance
698 710 self._call_pdb = val
699 711
700 712 # notify the actual exception handlers
701 713 self.InteractiveTB.call_pdb = val
702 714
703 715 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
704 716 'Control auto-activation of pdb at exceptions')
705 717
706 718 def debugger(self,force=False):
707 719 """Call the pydb/pdb debugger.
708 720
709 721 Keywords:
710 722
711 723 - force(False): by default, this routine checks the instance call_pdb
712 724 flag and does not actually invoke the debugger if the flag is false.
713 725 The 'force' option forces the debugger to activate even if the flag
714 726 is false.
715 727 """
716 728
717 729 if not (force or self.call_pdb):
718 730 return
719 731
720 732 if not hasattr(sys,'last_traceback'):
721 733 error('No traceback has been produced, nothing to debug.')
722 734 return
723 735
724 736 # use pydb if available
725 737 if debugger.has_pydb:
726 738 from pydb import pm
727 739 else:
728 740 # fallback to our internal debugger
729 741 pm = lambda : self.InteractiveTB.debugger(force=True)
730 742 self.history_saving_wrapper(pm)()
731 743
732 744 #-------------------------------------------------------------------------
733 745 # Things related to IPython's various namespaces
734 746 #-------------------------------------------------------------------------
735 747
736 748 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
737 749 # Create the namespace where the user will operate. user_ns is
738 750 # normally the only one used, and it is passed to the exec calls as
739 751 # the locals argument. But we do carry a user_global_ns namespace
740 752 # given as the exec 'globals' argument, This is useful in embedding
741 753 # situations where the ipython shell opens in a context where the
742 754 # distinction between locals and globals is meaningful. For
743 755 # non-embedded contexts, it is just the same object as the user_ns dict.
744 756
745 757 # FIXME. For some strange reason, __builtins__ is showing up at user
746 758 # level as a dict instead of a module. This is a manual fix, but I
747 759 # should really track down where the problem is coming from. Alex
748 760 # Schmolck reported this problem first.
749 761
750 762 # A useful post by Alex Martelli on this topic:
751 763 # Re: inconsistent value from __builtins__
752 764 # Von: Alex Martelli <aleaxit@yahoo.com>
753 765 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
754 766 # Gruppen: comp.lang.python
755 767
756 768 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
757 769 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
758 770 # > <type 'dict'>
759 771 # > >>> print type(__builtins__)
760 772 # > <type 'module'>
761 773 # > Is this difference in return value intentional?
762 774
763 775 # Well, it's documented that '__builtins__' can be either a dictionary
764 776 # or a module, and it's been that way for a long time. Whether it's
765 777 # intentional (or sensible), I don't know. In any case, the idea is
766 778 # that if you need to access the built-in namespace directly, you
767 779 # should start with "import __builtin__" (note, no 's') which will
768 780 # definitely give you a module. Yeah, it's somewhat confusing:-(.
769 781
770 782 # These routines return properly built dicts as needed by the rest of
771 783 # the code, and can also be used by extension writers to generate
772 784 # properly initialized namespaces.
773 785 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
774 786 user_global_ns)
775 787
776 788 # Assign namespaces
777 789 # This is the namespace where all normal user variables live
778 790 self.user_ns = user_ns
779 791 self.user_global_ns = user_global_ns
780 792
781 793 # An auxiliary namespace that checks what parts of the user_ns were
782 794 # loaded at startup, so we can list later only variables defined in
783 795 # actual interactive use. Since it is always a subset of user_ns, it
784 796 # doesn't need to be separately tracked in the ns_table.
785 797 self.user_ns_hidden = {}
786 798
787 799 # A namespace to keep track of internal data structures to prevent
788 800 # them from cluttering user-visible stuff. Will be updated later
789 801 self.internal_ns = {}
790 802
791 803 # Now that FakeModule produces a real module, we've run into a nasty
792 804 # problem: after script execution (via %run), the module where the user
793 805 # code ran is deleted. Now that this object is a true module (needed
794 806 # so docetst and other tools work correctly), the Python module
795 807 # teardown mechanism runs over it, and sets to None every variable
796 808 # present in that module. Top-level references to objects from the
797 809 # script survive, because the user_ns is updated with them. However,
798 810 # calling functions defined in the script that use other things from
799 811 # the script will fail, because the function's closure had references
800 812 # to the original objects, which are now all None. So we must protect
801 813 # these modules from deletion by keeping a cache.
802 814 #
803 815 # To avoid keeping stale modules around (we only need the one from the
804 816 # last run), we use a dict keyed with the full path to the script, so
805 817 # only the last version of the module is held in the cache. Note,
806 818 # however, that we must cache the module *namespace contents* (their
807 819 # __dict__). Because if we try to cache the actual modules, old ones
808 820 # (uncached) could be destroyed while still holding references (such as
809 821 # those held by GUI objects that tend to be long-lived)>
810 822 #
811 823 # The %reset command will flush this cache. See the cache_main_mod()
812 824 # and clear_main_mod_cache() methods for details on use.
813 825
814 826 # This is the cache used for 'main' namespaces
815 827 self._main_ns_cache = {}
816 828 # And this is the single instance of FakeModule whose __dict__ we keep
817 829 # copying and clearing for reuse on each %run
818 830 self._user_main_module = FakeModule()
819 831
820 832 # A table holding all the namespaces IPython deals with, so that
821 833 # introspection facilities can search easily.
822 834 self.ns_table = {'user':user_ns,
823 835 'user_global':user_global_ns,
824 836 'internal':self.internal_ns,
825 837 'builtin':__builtin__.__dict__
826 838 }
827 839
828 840 # Similarly, track all namespaces where references can be held and that
829 841 # we can safely clear (so it can NOT include builtin). This one can be
830 842 # a simple list. Note that the main execution namespaces, user_ns and
831 843 # user_global_ns, can NOT be listed here, as clearing them blindly
832 844 # causes errors in object __del__ methods. Instead, the reset() method
833 845 # clears them manually and carefully.
834 846 self.ns_refs_table = [ self.user_ns_hidden,
835 847 self.internal_ns, self._main_ns_cache ]
836 848
837 849 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
838 850 """Return a valid local and global user interactive namespaces.
839 851
840 852 This builds a dict with the minimal information needed to operate as a
841 853 valid IPython user namespace, which you can pass to the various
842 854 embedding classes in ipython. The default implementation returns the
843 855 same dict for both the locals and the globals to allow functions to
844 856 refer to variables in the namespace. Customized implementations can
845 857 return different dicts. The locals dictionary can actually be anything
846 858 following the basic mapping protocol of a dict, but the globals dict
847 859 must be a true dict, not even a subclass. It is recommended that any
848 860 custom object for the locals namespace synchronize with the globals
849 861 dict somehow.
850 862
851 863 Raises TypeError if the provided globals namespace is not a true dict.
852 864
853 865 Parameters
854 866 ----------
855 867 user_ns : dict-like, optional
856 868 The current user namespace. The items in this namespace should
857 869 be included in the output. If None, an appropriate blank
858 870 namespace should be created.
859 871 user_global_ns : dict, optional
860 872 The current user global namespace. The items in this namespace
861 873 should be included in the output. If None, an appropriate
862 874 blank namespace should be created.
863 875
864 876 Returns
865 877 -------
866 878 A pair of dictionary-like object to be used as the local namespace
867 879 of the interpreter and a dict to be used as the global namespace.
868 880 """
869 881
870 882
871 883 # We must ensure that __builtin__ (without the final 's') is always
872 884 # available and pointing to the __builtin__ *module*. For more details:
873 885 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
874 886
875 887 if user_ns is None:
876 888 # Set __name__ to __main__ to better match the behavior of the
877 889 # normal interpreter.
878 890 user_ns = {'__name__' :'__main__',
879 891 '__builtin__' : __builtin__,
880 892 '__builtins__' : __builtin__,
881 893 }
882 894 else:
883 895 user_ns.setdefault('__name__','__main__')
884 896 user_ns.setdefault('__builtin__',__builtin__)
885 897 user_ns.setdefault('__builtins__',__builtin__)
886 898
887 899 if user_global_ns is None:
888 900 user_global_ns = user_ns
889 901 if type(user_global_ns) is not dict:
890 902 raise TypeError("user_global_ns must be a true dict; got %r"
891 903 % type(user_global_ns))
892 904
893 905 return user_ns, user_global_ns
894 906
895 907 def init_sys_modules(self):
896 908 # We need to insert into sys.modules something that looks like a
897 909 # module but which accesses the IPython namespace, for shelve and
898 910 # pickle to work interactively. Normally they rely on getting
899 911 # everything out of __main__, but for embedding purposes each IPython
900 912 # instance has its own private namespace, so we can't go shoving
901 913 # everything into __main__.
902 914
903 915 # note, however, that we should only do this for non-embedded
904 916 # ipythons, which really mimic the __main__.__dict__ with their own
905 917 # namespace. Embedded instances, on the other hand, should not do
906 918 # this because they need to manage the user local/global namespaces
907 919 # only, but they live within a 'normal' __main__ (meaning, they
908 920 # shouldn't overtake the execution environment of the script they're
909 921 # embedded in).
910 922
911 923 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
912 924
913 925 try:
914 926 main_name = self.user_ns['__name__']
915 927 except KeyError:
916 928 raise KeyError('user_ns dictionary MUST have a "__name__" key')
917 929 else:
918 930 sys.modules[main_name] = FakeModule(self.user_ns)
919 931
920 932 def init_user_ns(self):
921 933 """Initialize all user-visible namespaces to their minimum defaults.
922 934
923 935 Certain history lists are also initialized here, as they effectively
924 936 act as user namespaces.
925 937
926 938 Notes
927 939 -----
928 940 All data structures here are only filled in, they are NOT reset by this
929 941 method. If they were not empty before, data will simply be added to
930 942 therm.
931 943 """
932 944 # This function works in two parts: first we put a few things in
933 945 # user_ns, and we sync that contents into user_ns_hidden so that these
934 946 # initial variables aren't shown by %who. After the sync, we add the
935 947 # rest of what we *do* want the user to see with %who even on a new
936 948 # session (probably nothing, so theye really only see their own stuff)
937 949
938 950 # The user dict must *always* have a __builtin__ reference to the
939 951 # Python standard __builtin__ namespace, which must be imported.
940 952 # This is so that certain operations in prompt evaluation can be
941 953 # reliably executed with builtins. Note that we can NOT use
942 954 # __builtins__ (note the 's'), because that can either be a dict or a
943 955 # module, and can even mutate at runtime, depending on the context
944 956 # (Python makes no guarantees on it). In contrast, __builtin__ is
945 957 # always a module object, though it must be explicitly imported.
946 958
947 959 # For more details:
948 960 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
949 961 ns = dict(__builtin__ = __builtin__)
950 962
951 963 # Put 'help' in the user namespace
952 964 try:
953 965 from site import _Helper
954 966 ns['help'] = _Helper()
955 967 except ImportError:
956 968 warn('help() not available - check site.py')
957 969
958 970 # make global variables for user access to the histories
959 971 ns['_ih'] = self.history_manager.input_hist_parsed
960 972 ns['_oh'] = self.history_manager.output_hist
961 973 ns['_dh'] = self.history_manager.dir_hist
962 974
963 975 ns['_sh'] = shadowns
964 976
965 977 # user aliases to input and output histories. These shouldn't show up
966 978 # in %who, as they can have very large reprs.
967 979 ns['In'] = self.history_manager.input_hist_parsed
968 980 ns['Out'] = self.history_manager.output_hist
969 981
970 982 # Store myself as the public api!!!
971 983 ns['get_ipython'] = self.get_ipython
972 984
973 985 # Sync what we've added so far to user_ns_hidden so these aren't seen
974 986 # by %who
975 987 self.user_ns_hidden.update(ns)
976 988
977 989 # Anything put into ns now would show up in %who. Think twice before
978 990 # putting anything here, as we really want %who to show the user their
979 991 # stuff, not our variables.
980 992
981 993 # Finally, update the real user's namespace
982 994 self.user_ns.update(ns)
983 995
984 996 def reset(self):
985 997 """Clear all internal namespaces.
986 998
987 999 Note that this is much more aggressive than %reset, since it clears
988 1000 fully all namespaces, as well as all input/output lists.
989 1001 """
990 1002 # Clear histories
991 1003 self.history_manager.reset()
992 1004
993 1005 # Reset counter used to index all histories
994 1006 self.execution_count = 0
995 1007
996 1008 # Restore the user namespaces to minimal usability
997 1009 for ns in self.ns_refs_table:
998 1010 ns.clear()
999 1011
1000 1012 # The main execution namespaces must be cleared very carefully,
1001 1013 # skipping the deletion of the builtin-related keys, because doing so
1002 1014 # would cause errors in many object's __del__ methods.
1003 1015 for ns in [self.user_ns, self.user_global_ns]:
1004 1016 drop_keys = set(ns.keys())
1005 1017 drop_keys.discard('__builtin__')
1006 1018 drop_keys.discard('__builtins__')
1007 1019 for k in drop_keys:
1008 1020 del ns[k]
1009 1021
1010 1022 # Restore the user namespaces to minimal usability
1011 1023 self.init_user_ns()
1012 1024
1013 1025 # Restore the default and user aliases
1014 1026 self.alias_manager.clear_aliases()
1015 1027 self.alias_manager.init_aliases()
1016 1028
1017 1029 def reset_selective(self, regex=None):
1018 1030 """Clear selective variables from internal namespaces based on a
1019 1031 specified regular expression.
1020 1032
1021 1033 Parameters
1022 1034 ----------
1023 1035 regex : string or compiled pattern, optional
1024 1036 A regular expression pattern that will be used in searching
1025 1037 variable names in the users namespaces.
1026 1038 """
1027 1039 if regex is not None:
1028 1040 try:
1029 1041 m = re.compile(regex)
1030 1042 except TypeError:
1031 1043 raise TypeError('regex must be a string or compiled pattern')
1032 1044 # Search for keys in each namespace that match the given regex
1033 1045 # If a match is found, delete the key/value pair.
1034 1046 for ns in self.ns_refs_table:
1035 1047 for var in ns:
1036 1048 if m.search(var):
1037 1049 del ns[var]
1038 1050
1039 1051 def push(self, variables, interactive=True):
1040 1052 """Inject a group of variables into the IPython user namespace.
1041 1053
1042 1054 Parameters
1043 1055 ----------
1044 1056 variables : dict, str or list/tuple of str
1045 1057 The variables to inject into the user's namespace. If a dict, a
1046 1058 simple update is done. If a str, the string is assumed to have
1047 1059 variable names separated by spaces. A list/tuple of str can also
1048 1060 be used to give the variable names. If just the variable names are
1049 1061 give (list/tuple/str) then the variable values looked up in the
1050 1062 callers frame.
1051 1063 interactive : bool
1052 1064 If True (default), the variables will be listed with the ``who``
1053 1065 magic.
1054 1066 """
1055 1067 vdict = None
1056 1068
1057 1069 # We need a dict of name/value pairs to do namespace updates.
1058 1070 if isinstance(variables, dict):
1059 1071 vdict = variables
1060 1072 elif isinstance(variables, (basestring, list, tuple)):
1061 1073 if isinstance(variables, basestring):
1062 1074 vlist = variables.split()
1063 1075 else:
1064 1076 vlist = variables
1065 1077 vdict = {}
1066 1078 cf = sys._getframe(1)
1067 1079 for name in vlist:
1068 1080 try:
1069 1081 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1070 1082 except:
1071 1083 print ('Could not get variable %s from %s' %
1072 1084 (name,cf.f_code.co_name))
1073 1085 else:
1074 1086 raise ValueError('variables must be a dict/str/list/tuple')
1075 1087
1076 1088 # Propagate variables to user namespace
1077 1089 self.user_ns.update(vdict)
1078 1090
1079 1091 # And configure interactive visibility
1080 1092 config_ns = self.user_ns_hidden
1081 1093 if interactive:
1082 1094 for name, val in vdict.iteritems():
1083 1095 config_ns.pop(name, None)
1084 1096 else:
1085 1097 for name,val in vdict.iteritems():
1086 1098 config_ns[name] = val
1087 1099
1088 1100 #-------------------------------------------------------------------------
1089 1101 # Things related to object introspection
1090 1102 #-------------------------------------------------------------------------
1091 1103
1092 1104 def _ofind(self, oname, namespaces=None):
1093 1105 """Find an object in the available namespaces.
1094 1106
1095 1107 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1096 1108
1097 1109 Has special code to detect magic functions.
1098 1110 """
1099 1111 #oname = oname.strip()
1100 1112 #print '1- oname: <%r>' % oname # dbg
1101 1113 try:
1102 1114 oname = oname.strip().encode('ascii')
1103 1115 #print '2- oname: <%r>' % oname # dbg
1104 1116 except UnicodeEncodeError:
1105 1117 print 'Python identifiers can only contain ascii characters.'
1106 1118 return dict(found=False)
1107 1119
1108 1120 alias_ns = None
1109 1121 if namespaces is None:
1110 1122 # Namespaces to search in:
1111 1123 # Put them in a list. The order is important so that we
1112 1124 # find things in the same order that Python finds them.
1113 1125 namespaces = [ ('Interactive', self.user_ns),
1114 1126 ('IPython internal', self.internal_ns),
1115 1127 ('Python builtin', __builtin__.__dict__),
1116 1128 ('Alias', self.alias_manager.alias_table),
1117 1129 ]
1118 1130 alias_ns = self.alias_manager.alias_table
1119 1131
1120 1132 # initialize results to 'null'
1121 1133 found = False; obj = None; ospace = None; ds = None;
1122 1134 ismagic = False; isalias = False; parent = None
1123 1135
1124 1136 # We need to special-case 'print', which as of python2.6 registers as a
1125 1137 # function but should only be treated as one if print_function was
1126 1138 # loaded with a future import. In this case, just bail.
1127 1139 if (oname == 'print' and not (self.compile.compiler_flags &
1128 1140 __future__.CO_FUTURE_PRINT_FUNCTION)):
1129 1141 return {'found':found, 'obj':obj, 'namespace':ospace,
1130 1142 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1131 1143
1132 1144 # Look for the given name by splitting it in parts. If the head is
1133 1145 # found, then we look for all the remaining parts as members, and only
1134 1146 # declare success if we can find them all.
1135 1147 oname_parts = oname.split('.')
1136 1148 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1137 1149 for nsname,ns in namespaces:
1138 1150 try:
1139 1151 obj = ns[oname_head]
1140 1152 except KeyError:
1141 1153 continue
1142 1154 else:
1143 1155 #print 'oname_rest:', oname_rest # dbg
1144 1156 for part in oname_rest:
1145 1157 try:
1146 1158 parent = obj
1147 1159 obj = getattr(obj,part)
1148 1160 except:
1149 1161 # Blanket except b/c some badly implemented objects
1150 1162 # allow __getattr__ to raise exceptions other than
1151 1163 # AttributeError, which then crashes IPython.
1152 1164 break
1153 1165 else:
1154 1166 # If we finish the for loop (no break), we got all members
1155 1167 found = True
1156 1168 ospace = nsname
1157 1169 if ns == alias_ns:
1158 1170 isalias = True
1159 1171 break # namespace loop
1160 1172
1161 1173 # Try to see if it's magic
1162 1174 if not found:
1163 1175 if oname.startswith(ESC_MAGIC):
1164 1176 oname = oname[1:]
1165 1177 obj = getattr(self,'magic_'+oname,None)
1166 1178 if obj is not None:
1167 1179 found = True
1168 1180 ospace = 'IPython internal'
1169 1181 ismagic = True
1170 1182
1171 1183 # Last try: special-case some literals like '', [], {}, etc:
1172 1184 if not found and oname_head in ["''",'""','[]','{}','()']:
1173 1185 obj = eval(oname_head)
1174 1186 found = True
1175 1187 ospace = 'Interactive'
1176 1188
1177 1189 return {'found':found, 'obj':obj, 'namespace':ospace,
1178 1190 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1179 1191
1180 1192 def _ofind_property(self, oname, info):
1181 1193 """Second part of object finding, to look for property details."""
1182 1194 if info.found:
1183 1195 # Get the docstring of the class property if it exists.
1184 1196 path = oname.split('.')
1185 1197 root = '.'.join(path[:-1])
1186 1198 if info.parent is not None:
1187 1199 try:
1188 1200 target = getattr(info.parent, '__class__')
1189 1201 # The object belongs to a class instance.
1190 1202 try:
1191 1203 target = getattr(target, path[-1])
1192 1204 # The class defines the object.
1193 1205 if isinstance(target, property):
1194 1206 oname = root + '.__class__.' + path[-1]
1195 1207 info = Struct(self._ofind(oname))
1196 1208 except AttributeError: pass
1197 1209 except AttributeError: pass
1198 1210
1199 1211 # We return either the new info or the unmodified input if the object
1200 1212 # hadn't been found
1201 1213 return info
1202 1214
1203 1215 def _object_find(self, oname, namespaces=None):
1204 1216 """Find an object and return a struct with info about it."""
1205 1217 inf = Struct(self._ofind(oname, namespaces))
1206 1218 return Struct(self._ofind_property(oname, inf))
1207 1219
1208 1220 def _inspect(self, meth, oname, namespaces=None, **kw):
1209 1221 """Generic interface to the inspector system.
1210 1222
1211 1223 This function is meant to be called by pdef, pdoc & friends."""
1212 1224 info = self._object_find(oname)
1213 1225 if info.found:
1214 1226 pmethod = getattr(self.inspector, meth)
1215 1227 formatter = format_screen if info.ismagic else None
1216 1228 if meth == 'pdoc':
1217 1229 pmethod(info.obj, oname, formatter)
1218 1230 elif meth == 'pinfo':
1219 1231 pmethod(info.obj, oname, formatter, info, **kw)
1220 1232 else:
1221 1233 pmethod(info.obj, oname)
1222 1234 else:
1223 1235 print 'Object `%s` not found.' % oname
1224 1236 return 'not found' # so callers can take other action
1225 1237
1226 1238 def object_inspect(self, oname):
1227 1239 info = self._object_find(oname)
1228 1240 if info.found:
1229 1241 return self.inspector.info(info.obj, oname, info=info)
1230 1242 else:
1231 1243 return oinspect.object_info(name=oname, found=False)
1232 1244
1233 1245 #-------------------------------------------------------------------------
1234 1246 # Things related to history management
1235 1247 #-------------------------------------------------------------------------
1236 1248
1237 1249 def init_history(self):
1238 1250 """Sets up the command history, and starts regular autosaves."""
1239 1251 self.history_manager = HistoryManager(shell=self)
1240 1252
1241 1253 def save_history(self):
1242 1254 """Save input history to a file (via readline library)."""
1243 1255 self.history_manager.save_history()
1244 1256
1245 1257 def reload_history(self):
1246 1258 """Reload the input history from disk file."""
1247 1259 self.history_manager.reload_history()
1248 1260
1249 1261 def history_saving_wrapper(self, func):
1250 1262 """ Wrap func for readline history saving
1251 1263
1252 1264 Convert func into callable that saves & restores
1253 1265 history around the call """
1254 1266
1255 1267 if self.has_readline:
1256 1268 from IPython.utils import rlineimpl as readline
1257 1269 else:
1258 1270 return func
1259 1271
1260 1272 def wrapper():
1261 1273 self.save_history()
1262 1274 try:
1263 1275 func()
1264 1276 finally:
1265 1277 self.reload_history()
1266 1278 return wrapper
1267 1279
1268 1280 def get_history(self, index=None, raw=False, output=True):
1269 1281 return self.history_manager.get_history(index, raw, output)
1270 1282
1271 1283
1272 1284 #-------------------------------------------------------------------------
1273 1285 # Things related to exception handling and tracebacks (not debugging)
1274 1286 #-------------------------------------------------------------------------
1275 1287
1276 1288 def init_traceback_handlers(self, custom_exceptions):
1277 1289 # Syntax error handler.
1278 1290 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1279 1291
1280 1292 # The interactive one is initialized with an offset, meaning we always
1281 1293 # want to remove the topmost item in the traceback, which is our own
1282 1294 # internal code. Valid modes: ['Plain','Context','Verbose']
1283 1295 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1284 1296 color_scheme='NoColor',
1285 1297 tb_offset = 1,
1286 1298 check_cache=self.compile.check_cache)
1287 1299
1288 1300 # The instance will store a pointer to the system-wide exception hook,
1289 1301 # so that runtime code (such as magics) can access it. This is because
1290 1302 # during the read-eval loop, it may get temporarily overwritten.
1291 1303 self.sys_excepthook = sys.excepthook
1292 1304
1293 1305 # and add any custom exception handlers the user may have specified
1294 1306 self.set_custom_exc(*custom_exceptions)
1295 1307
1296 1308 # Set the exception mode
1297 1309 self.InteractiveTB.set_mode(mode=self.xmode)
1298 1310
1299 1311 def set_custom_exc(self, exc_tuple, handler):
1300 1312 """set_custom_exc(exc_tuple,handler)
1301 1313
1302 1314 Set a custom exception handler, which will be called if any of the
1303 1315 exceptions in exc_tuple occur in the mainloop (specifically, in the
1304 1316 run_code() method.
1305 1317
1306 1318 Inputs:
1307 1319
1308 1320 - exc_tuple: a *tuple* of valid exceptions to call the defined
1309 1321 handler for. It is very important that you use a tuple, and NOT A
1310 1322 LIST here, because of the way Python's except statement works. If
1311 1323 you only want to trap a single exception, use a singleton tuple:
1312 1324
1313 1325 exc_tuple == (MyCustomException,)
1314 1326
1315 1327 - handler: this must be defined as a function with the following
1316 1328 basic interface::
1317 1329
1318 1330 def my_handler(self, etype, value, tb, tb_offset=None)
1319 1331 ...
1320 1332 # The return value must be
1321 1333 return structured_traceback
1322 1334
1323 1335 This will be made into an instance method (via types.MethodType)
1324 1336 of IPython itself, and it will be called if any of the exceptions
1325 1337 listed in the exc_tuple are caught. If the handler is None, an
1326 1338 internal basic one is used, which just prints basic info.
1327 1339
1328 1340 WARNING: by putting in your own exception handler into IPython's main
1329 1341 execution loop, you run a very good chance of nasty crashes. This
1330 1342 facility should only be used if you really know what you are doing."""
1331 1343
1332 1344 assert type(exc_tuple)==type(()) , \
1333 1345 "The custom exceptions must be given AS A TUPLE."
1334 1346
1335 1347 def dummy_handler(self,etype,value,tb):
1336 1348 print '*** Simple custom exception handler ***'
1337 1349 print 'Exception type :',etype
1338 1350 print 'Exception value:',value
1339 1351 print 'Traceback :',tb
1340 1352 print 'Source code :','\n'.join(self.buffer)
1341 1353
1342 1354 if handler is None: handler = dummy_handler
1343 1355
1344 1356 self.CustomTB = types.MethodType(handler,self)
1345 1357 self.custom_exceptions = exc_tuple
1346 1358
1347 1359 def excepthook(self, etype, value, tb):
1348 1360 """One more defense for GUI apps that call sys.excepthook.
1349 1361
1350 1362 GUI frameworks like wxPython trap exceptions and call
1351 1363 sys.excepthook themselves. I guess this is a feature that
1352 1364 enables them to keep running after exceptions that would
1353 1365 otherwise kill their mainloop. This is a bother for IPython
1354 1366 which excepts to catch all of the program exceptions with a try:
1355 1367 except: statement.
1356 1368
1357 1369 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1358 1370 any app directly invokes sys.excepthook, it will look to the user like
1359 1371 IPython crashed. In order to work around this, we can disable the
1360 1372 CrashHandler and replace it with this excepthook instead, which prints a
1361 1373 regular traceback using our InteractiveTB. In this fashion, apps which
1362 1374 call sys.excepthook will generate a regular-looking exception from
1363 1375 IPython, and the CrashHandler will only be triggered by real IPython
1364 1376 crashes.
1365 1377
1366 1378 This hook should be used sparingly, only in places which are not likely
1367 1379 to be true IPython errors.
1368 1380 """
1369 1381 self.showtraceback((etype,value,tb),tb_offset=0)
1370 1382
1371 1383 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1372 1384 exception_only=False):
1373 1385 """Display the exception that just occurred.
1374 1386
1375 1387 If nothing is known about the exception, this is the method which
1376 1388 should be used throughout the code for presenting user tracebacks,
1377 1389 rather than directly invoking the InteractiveTB object.
1378 1390
1379 1391 A specific showsyntaxerror() also exists, but this method can take
1380 1392 care of calling it if needed, so unless you are explicitly catching a
1381 1393 SyntaxError exception, don't try to analyze the stack manually and
1382 1394 simply call this method."""
1383 1395
1384 1396 try:
1385 1397 if exc_tuple is None:
1386 1398 etype, value, tb = sys.exc_info()
1387 1399 else:
1388 1400 etype, value, tb = exc_tuple
1389 1401
1390 1402 if etype is None:
1391 1403 if hasattr(sys, 'last_type'):
1392 1404 etype, value, tb = sys.last_type, sys.last_value, \
1393 1405 sys.last_traceback
1394 1406 else:
1395 1407 self.write_err('No traceback available to show.\n')
1396 1408 return
1397 1409
1398 1410 if etype is SyntaxError:
1399 1411 # Though this won't be called by syntax errors in the input
1400 1412 # line, there may be SyntaxError cases whith imported code.
1401 1413 self.showsyntaxerror(filename)
1402 1414 elif etype is UsageError:
1403 1415 print "UsageError:", value
1404 1416 else:
1405 1417 # WARNING: these variables are somewhat deprecated and not
1406 1418 # necessarily safe to use in a threaded environment, but tools
1407 1419 # like pdb depend on their existence, so let's set them. If we
1408 1420 # find problems in the field, we'll need to revisit their use.
1409 1421 sys.last_type = etype
1410 1422 sys.last_value = value
1411 1423 sys.last_traceback = tb
1412 1424
1413 1425 if etype in self.custom_exceptions:
1414 1426 # FIXME: Old custom traceback objects may just return a
1415 1427 # string, in that case we just put it into a list
1416 1428 stb = self.CustomTB(etype, value, tb, tb_offset)
1417 1429 if isinstance(ctb, basestring):
1418 1430 stb = [stb]
1419 1431 else:
1420 1432 if exception_only:
1421 1433 stb = ['An exception has occurred, use %tb to see '
1422 1434 'the full traceback.\n']
1423 1435 stb.extend(self.InteractiveTB.get_exception_only(etype,
1424 1436 value))
1425 1437 else:
1426 1438 stb = self.InteractiveTB.structured_traceback(etype,
1427 1439 value, tb, tb_offset=tb_offset)
1428 1440 # FIXME: the pdb calling should be done by us, not by
1429 1441 # the code computing the traceback.
1430 1442 if self.InteractiveTB.call_pdb:
1431 1443 # pdb mucks up readline, fix it back
1432 1444 self.set_readline_completer()
1433 1445
1434 1446 # Actually show the traceback
1435 1447 self._showtraceback(etype, value, stb)
1436 1448
1437 1449 except KeyboardInterrupt:
1438 1450 self.write_err("\nKeyboardInterrupt\n")
1439 1451
1440 1452 def _showtraceback(self, etype, evalue, stb):
1441 1453 """Actually show a traceback.
1442 1454
1443 1455 Subclasses may override this method to put the traceback on a different
1444 1456 place, like a side channel.
1445 1457 """
1446 1458 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1447 1459
1448 1460 def showsyntaxerror(self, filename=None):
1449 1461 """Display the syntax error that just occurred.
1450 1462
1451 1463 This doesn't display a stack trace because there isn't one.
1452 1464
1453 1465 If a filename is given, it is stuffed in the exception instead
1454 1466 of what was there before (because Python's parser always uses
1455 1467 "<string>" when reading from a string).
1456 1468 """
1457 1469 etype, value, last_traceback = sys.exc_info()
1458 1470
1459 1471 # See note about these variables in showtraceback() above
1460 1472 sys.last_type = etype
1461 1473 sys.last_value = value
1462 1474 sys.last_traceback = last_traceback
1463 1475
1464 1476 if filename and etype is SyntaxError:
1465 1477 # Work hard to stuff the correct filename in the exception
1466 1478 try:
1467 1479 msg, (dummy_filename, lineno, offset, line) = value
1468 1480 except:
1469 1481 # Not the format we expect; leave it alone
1470 1482 pass
1471 1483 else:
1472 1484 # Stuff in the right filename
1473 1485 try:
1474 1486 # Assume SyntaxError is a class exception
1475 1487 value = SyntaxError(msg, (filename, lineno, offset, line))
1476 1488 except:
1477 1489 # If that failed, assume SyntaxError is a string
1478 1490 value = msg, (filename, lineno, offset, line)
1479 1491 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1480 1492 self._showtraceback(etype, value, stb)
1481 1493
1482 1494 #-------------------------------------------------------------------------
1483 1495 # Things related to readline
1484 1496 #-------------------------------------------------------------------------
1485 1497
1486 1498 def init_readline(self):
1487 1499 """Command history completion/saving/reloading."""
1488 1500
1489 1501 if self.readline_use:
1490 1502 import IPython.utils.rlineimpl as readline
1491 1503
1492 1504 self.rl_next_input = None
1493 1505 self.rl_do_indent = False
1494 1506
1495 1507 if not self.readline_use or not readline.have_readline:
1496 1508 self.has_readline = False
1497 1509 self.readline = None
1498 1510 # Set a number of methods that depend on readline to be no-op
1499 1511 self.set_readline_completer = no_op
1500 1512 self.set_custom_completer = no_op
1501 1513 self.set_completer_frame = no_op
1502 1514 warn('Readline services not available or not loaded.')
1503 1515 else:
1504 1516 self.has_readline = True
1505 1517 self.readline = readline
1506 1518 sys.modules['readline'] = readline
1507 1519
1508 1520 # Platform-specific configuration
1509 1521 if os.name == 'nt':
1510 1522 # FIXME - check with Frederick to see if we can harmonize
1511 1523 # naming conventions with pyreadline to avoid this
1512 1524 # platform-dependent check
1513 1525 self.readline_startup_hook = readline.set_pre_input_hook
1514 1526 else:
1515 1527 self.readline_startup_hook = readline.set_startup_hook
1516 1528
1517 1529 # Load user's initrc file (readline config)
1518 1530 # Or if libedit is used, load editrc.
1519 1531 inputrc_name = os.environ.get('INPUTRC')
1520 1532 if inputrc_name is None:
1521 1533 home_dir = get_home_dir()
1522 1534 if home_dir is not None:
1523 1535 inputrc_name = '.inputrc'
1524 1536 if readline.uses_libedit:
1525 1537 inputrc_name = '.editrc'
1526 1538 inputrc_name = os.path.join(home_dir, inputrc_name)
1527 1539 if os.path.isfile(inputrc_name):
1528 1540 try:
1529 1541 readline.read_init_file(inputrc_name)
1530 1542 except:
1531 1543 warn('Problems reading readline initialization file <%s>'
1532 1544 % inputrc_name)
1533 1545
1534 1546 # Configure readline according to user's prefs
1535 1547 # This is only done if GNU readline is being used. If libedit
1536 1548 # is being used (as on Leopard) the readline config is
1537 1549 # not run as the syntax for libedit is different.
1538 1550 if not readline.uses_libedit:
1539 1551 for rlcommand in self.readline_parse_and_bind:
1540 1552 #print "loading rl:",rlcommand # dbg
1541 1553 readline.parse_and_bind(rlcommand)
1542 1554
1543 1555 # Remove some chars from the delimiters list. If we encounter
1544 1556 # unicode chars, discard them.
1545 1557 delims = readline.get_completer_delims().encode("ascii", "ignore")
1546 1558 delims = delims.translate(None, self.readline_remove_delims)
1547 1559 delims = delims.replace(ESC_MAGIC, '')
1548 1560 readline.set_completer_delims(delims)
1549 1561 # otherwise we end up with a monster history after a while:
1550 1562 readline.set_history_length(self.history_length)
1551 1563 try:
1552 1564 #print '*** Reading readline history' # dbg
1553 1565 self.reload_history()
1554 1566 except IOError:
1555 1567 pass # It doesn't exist yet.
1556 1568
1557 1569 # Configure auto-indent for all platforms
1558 1570 self.set_autoindent(self.autoindent)
1559 1571
1560 1572 def set_next_input(self, s):
1561 1573 """ Sets the 'default' input string for the next command line.
1562 1574
1563 1575 Requires readline.
1564 1576
1565 1577 Example:
1566 1578
1567 1579 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1568 1580 [D:\ipython]|2> Hello Word_ # cursor is here
1569 1581 """
1570 1582
1571 1583 self.rl_next_input = s
1572 1584
1573 1585 # Maybe move this to the terminal subclass?
1574 1586 def pre_readline(self):
1575 1587 """readline hook to be used at the start of each line.
1576 1588
1577 1589 Currently it handles auto-indent only."""
1578 1590
1579 1591 if self.rl_do_indent:
1580 1592 self.readline.insert_text(self._indent_current_str())
1581 1593 if self.rl_next_input is not None:
1582 1594 self.readline.insert_text(self.rl_next_input)
1583 1595 self.rl_next_input = None
1584 1596
1585 1597 def _indent_current_str(self):
1586 1598 """return the current level of indentation as a string"""
1587 1599 return self.input_splitter.indent_spaces * ' '
1588 1600
1589 1601 #-------------------------------------------------------------------------
1590 1602 # Things related to text completion
1591 1603 #-------------------------------------------------------------------------
1592 1604
1593 1605 def init_completer(self):
1594 1606 """Initialize the completion machinery.
1595 1607
1596 1608 This creates completion machinery that can be used by client code,
1597 1609 either interactively in-process (typically triggered by the readline
1598 1610 library), programatically (such as in test suites) or out-of-prcess
1599 1611 (typically over the network by remote frontends).
1600 1612 """
1601 1613 from IPython.core.completer import IPCompleter
1602 1614 from IPython.core.completerlib import (module_completer,
1603 1615 magic_run_completer, cd_completer)
1604 1616
1605 1617 self.Completer = IPCompleter(self,
1606 1618 self.user_ns,
1607 1619 self.user_global_ns,
1608 1620 self.readline_omit__names,
1609 1621 self.alias_manager.alias_table,
1610 1622 self.has_readline)
1611 1623
1612 1624 # Add custom completers to the basic ones built into IPCompleter
1613 1625 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1614 1626 self.strdispatchers['complete_command'] = sdisp
1615 1627 self.Completer.custom_completers = sdisp
1616 1628
1617 1629 self.set_hook('complete_command', module_completer, str_key = 'import')
1618 1630 self.set_hook('complete_command', module_completer, str_key = 'from')
1619 1631 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1620 1632 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1621 1633
1622 1634 # Only configure readline if we truly are using readline. IPython can
1623 1635 # do tab-completion over the network, in GUIs, etc, where readline
1624 1636 # itself may be absent
1625 1637 if self.has_readline:
1626 1638 self.set_readline_completer()
1627 1639
1628 1640 def complete(self, text, line=None, cursor_pos=None):
1629 1641 """Return the completed text and a list of completions.
1630 1642
1631 1643 Parameters
1632 1644 ----------
1633 1645
1634 1646 text : string
1635 1647 A string of text to be completed on. It can be given as empty and
1636 1648 instead a line/position pair are given. In this case, the
1637 1649 completer itself will split the line like readline does.
1638 1650
1639 1651 line : string, optional
1640 1652 The complete line that text is part of.
1641 1653
1642 1654 cursor_pos : int, optional
1643 1655 The position of the cursor on the input line.
1644 1656
1645 1657 Returns
1646 1658 -------
1647 1659 text : string
1648 1660 The actual text that was completed.
1649 1661
1650 1662 matches : list
1651 1663 A sorted list with all possible completions.
1652 1664
1653 1665 The optional arguments allow the completion to take more context into
1654 1666 account, and are part of the low-level completion API.
1655 1667
1656 1668 This is a wrapper around the completion mechanism, similar to what
1657 1669 readline does at the command line when the TAB key is hit. By
1658 1670 exposing it as a method, it can be used by other non-readline
1659 1671 environments (such as GUIs) for text completion.
1660 1672
1661 1673 Simple usage example:
1662 1674
1663 1675 In [1]: x = 'hello'
1664 1676
1665 1677 In [2]: _ip.complete('x.l')
1666 1678 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1667 1679 """
1668 1680
1669 1681 # Inject names into __builtin__ so we can complete on the added names.
1670 1682 with self.builtin_trap:
1671 1683 return self.Completer.complete(text, line, cursor_pos)
1672 1684
1673 1685 def set_custom_completer(self, completer, pos=0):
1674 1686 """Adds a new custom completer function.
1675 1687
1676 1688 The position argument (defaults to 0) is the index in the completers
1677 1689 list where you want the completer to be inserted."""
1678 1690
1679 1691 newcomp = types.MethodType(completer,self.Completer)
1680 1692 self.Completer.matchers.insert(pos,newcomp)
1681 1693
1682 1694 def set_readline_completer(self):
1683 1695 """Reset readline's completer to be our own."""
1684 1696 self.readline.set_completer(self.Completer.rlcomplete)
1685 1697
1686 1698 def set_completer_frame(self, frame=None):
1687 1699 """Set the frame of the completer."""
1688 1700 if frame:
1689 1701 self.Completer.namespace = frame.f_locals
1690 1702 self.Completer.global_namespace = frame.f_globals
1691 1703 else:
1692 1704 self.Completer.namespace = self.user_ns
1693 1705 self.Completer.global_namespace = self.user_global_ns
1694 1706
1695 1707 #-------------------------------------------------------------------------
1696 1708 # Things related to magics
1697 1709 #-------------------------------------------------------------------------
1698 1710
1699 1711 def init_magics(self):
1700 1712 # FIXME: Move the color initialization to the DisplayHook, which
1701 1713 # should be split into a prompt manager and displayhook. We probably
1702 1714 # even need a centralize colors management object.
1703 1715 self.magic_colors(self.colors)
1704 1716 # History was moved to a separate module
1705 1717 from . import history
1706 1718 history.init_ipython(self)
1707 1719
1708 1720 def magic(self,arg_s):
1709 1721 """Call a magic function by name.
1710 1722
1711 1723 Input: a string containing the name of the magic function to call and
1712 1724 any additional arguments to be passed to the magic.
1713 1725
1714 1726 magic('name -opt foo bar') is equivalent to typing at the ipython
1715 1727 prompt:
1716 1728
1717 1729 In[1]: %name -opt foo bar
1718 1730
1719 1731 To call a magic without arguments, simply use magic('name').
1720 1732
1721 1733 This provides a proper Python function to call IPython's magics in any
1722 1734 valid Python code you can type at the interpreter, including loops and
1723 1735 compound statements.
1724 1736 """
1725 1737 args = arg_s.split(' ',1)
1726 1738 magic_name = args[0]
1727 1739 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1728 1740
1729 1741 try:
1730 1742 magic_args = args[1]
1731 1743 except IndexError:
1732 1744 magic_args = ''
1733 1745 fn = getattr(self,'magic_'+magic_name,None)
1734 1746 if fn is None:
1735 1747 error("Magic function `%s` not found." % magic_name)
1736 1748 else:
1737 1749 magic_args = self.var_expand(magic_args,1)
1738 1750 with nested(self.builtin_trap,):
1739 1751 result = fn(magic_args)
1740 1752 return result
1741 1753
1742 1754 def define_magic(self, magicname, func):
1743 1755 """Expose own function as magic function for ipython
1744 1756
1745 1757 def foo_impl(self,parameter_s=''):
1746 1758 'My very own magic!. (Use docstrings, IPython reads them).'
1747 1759 print 'Magic function. Passed parameter is between < >:'
1748 1760 print '<%s>' % parameter_s
1749 1761 print 'The self object is:',self
1750 1762
1751 1763 self.define_magic('foo',foo_impl)
1752 1764 """
1753 1765
1754 1766 import new
1755 1767 im = types.MethodType(func,self)
1756 1768 old = getattr(self, "magic_" + magicname, None)
1757 1769 setattr(self, "magic_" + magicname, im)
1758 1770 return old
1759 1771
1760 1772 #-------------------------------------------------------------------------
1761 1773 # Things related to macros
1762 1774 #-------------------------------------------------------------------------
1763 1775
1764 1776 def define_macro(self, name, themacro):
1765 1777 """Define a new macro
1766 1778
1767 1779 Parameters
1768 1780 ----------
1769 1781 name : str
1770 1782 The name of the macro.
1771 1783 themacro : str or Macro
1772 1784 The action to do upon invoking the macro. If a string, a new
1773 1785 Macro object is created by passing the string to it.
1774 1786 """
1775 1787
1776 1788 from IPython.core import macro
1777 1789
1778 1790 if isinstance(themacro, basestring):
1779 1791 themacro = macro.Macro(themacro)
1780 1792 if not isinstance(themacro, macro.Macro):
1781 1793 raise ValueError('A macro must be a string or a Macro instance.')
1782 1794 self.user_ns[name] = themacro
1783 1795
1784 1796 #-------------------------------------------------------------------------
1785 1797 # Things related to the running of system commands
1786 1798 #-------------------------------------------------------------------------
1787 1799
1788 1800 def system(self, cmd):
1789 1801 """Call the given cmd in a subprocess.
1790 1802
1791 1803 Parameters
1792 1804 ----------
1793 1805 cmd : str
1794 1806 Command to execute (can not end in '&', as bacground processes are
1795 1807 not supported.
1796 1808 """
1797 1809 # We do not support backgrounding processes because we either use
1798 1810 # pexpect or pipes to read from. Users can always just call
1799 1811 # os.system() if they really want a background process.
1800 1812 if cmd.endswith('&'):
1801 1813 raise OSError("Background processes not supported.")
1802 1814
1803 1815 return system(self.var_expand(cmd, depth=2))
1804 1816
1805 1817 def getoutput(self, cmd, split=True):
1806 1818 """Get output (possibly including stderr) from a subprocess.
1807 1819
1808 1820 Parameters
1809 1821 ----------
1810 1822 cmd : str
1811 1823 Command to execute (can not end in '&', as background processes are
1812 1824 not supported.
1813 1825 split : bool, optional
1814 1826
1815 1827 If True, split the output into an IPython SList. Otherwise, an
1816 1828 IPython LSString is returned. These are objects similar to normal
1817 1829 lists and strings, with a few convenience attributes for easier
1818 1830 manipulation of line-based output. You can use '?' on them for
1819 1831 details.
1820 1832 """
1821 1833 if cmd.endswith('&'):
1822 1834 raise OSError("Background processes not supported.")
1823 1835 out = getoutput(self.var_expand(cmd, depth=2))
1824 1836 if split:
1825 1837 out = SList(out.splitlines())
1826 1838 else:
1827 1839 out = LSString(out)
1828 1840 return out
1829 1841
1830 1842 #-------------------------------------------------------------------------
1831 1843 # Things related to aliases
1832 1844 #-------------------------------------------------------------------------
1833 1845
1834 1846 def init_alias(self):
1835 1847 self.alias_manager = AliasManager(shell=self, config=self.config)
1836 1848 self.ns_table['alias'] = self.alias_manager.alias_table,
1837 1849
1838 1850 #-------------------------------------------------------------------------
1839 1851 # Things related to extensions and plugins
1840 1852 #-------------------------------------------------------------------------
1841 1853
1842 1854 def init_extension_manager(self):
1843 1855 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1844 1856
1845 1857 def init_plugin_manager(self):
1846 1858 self.plugin_manager = PluginManager(config=self.config)
1847 1859
1848 1860 #-------------------------------------------------------------------------
1849 1861 # Things related to payloads
1850 1862 #-------------------------------------------------------------------------
1851 1863
1852 1864 def init_payload(self):
1853 1865 self.payload_manager = PayloadManager(config=self.config)
1854 1866
1855 1867 #-------------------------------------------------------------------------
1856 1868 # Things related to the prefilter
1857 1869 #-------------------------------------------------------------------------
1858 1870
1859 1871 def init_prefilter(self):
1860 1872 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1861 1873 # Ultimately this will be refactored in the new interpreter code, but
1862 1874 # for now, we should expose the main prefilter method (there's legacy
1863 1875 # code out there that may rely on this).
1864 1876 self.prefilter = self.prefilter_manager.prefilter_lines
1865 1877
1866 1878 def auto_rewrite_input(self, cmd):
1867 1879 """Print to the screen the rewritten form of the user's command.
1868 1880
1869 1881 This shows visual feedback by rewriting input lines that cause
1870 1882 automatic calling to kick in, like::
1871 1883
1872 1884 /f x
1873 1885
1874 1886 into::
1875 1887
1876 1888 ------> f(x)
1877 1889
1878 1890 after the user's input prompt. This helps the user understand that the
1879 1891 input line was transformed automatically by IPython.
1880 1892 """
1881 1893 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1882 1894
1883 1895 try:
1884 1896 # plain ascii works better w/ pyreadline, on some machines, so
1885 1897 # we use it and only print uncolored rewrite if we have unicode
1886 1898 rw = str(rw)
1887 1899 print >> IPython.utils.io.Term.cout, rw
1888 1900 except UnicodeEncodeError:
1889 1901 print "------> " + cmd
1890 1902
1891 1903 #-------------------------------------------------------------------------
1892 1904 # Things related to extracting values/expressions from kernel and user_ns
1893 1905 #-------------------------------------------------------------------------
1894 1906
1895 1907 def _simple_error(self):
1896 1908 etype, value = sys.exc_info()[:2]
1897 1909 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1898 1910
1899 1911 def user_variables(self, names):
1900 1912 """Get a list of variable names from the user's namespace.
1901 1913
1902 1914 Parameters
1903 1915 ----------
1904 1916 names : list of strings
1905 1917 A list of names of variables to be read from the user namespace.
1906 1918
1907 1919 Returns
1908 1920 -------
1909 1921 A dict, keyed by the input names and with the repr() of each value.
1910 1922 """
1911 1923 out = {}
1912 1924 user_ns = self.user_ns
1913 1925 for varname in names:
1914 1926 try:
1915 1927 value = repr(user_ns[varname])
1916 1928 except:
1917 1929 value = self._simple_error()
1918 1930 out[varname] = value
1919 1931 return out
1920 1932
1921 1933 def user_expressions(self, expressions):
1922 1934 """Evaluate a dict of expressions in the user's namespace.
1923 1935
1924 1936 Parameters
1925 1937 ----------
1926 1938 expressions : dict
1927 1939 A dict with string keys and string values. The expression values
1928 1940 should be valid Python expressions, each of which will be evaluated
1929 1941 in the user namespace.
1930 1942
1931 1943 Returns
1932 1944 -------
1933 1945 A dict, keyed like the input expressions dict, with the repr() of each
1934 1946 value.
1935 1947 """
1936 1948 out = {}
1937 1949 user_ns = self.user_ns
1938 1950 global_ns = self.user_global_ns
1939 1951 for key, expr in expressions.iteritems():
1940 1952 try:
1941 1953 value = repr(eval(expr, global_ns, user_ns))
1942 1954 except:
1943 1955 value = self._simple_error()
1944 1956 out[key] = value
1945 1957 return out
1946 1958
1947 1959 #-------------------------------------------------------------------------
1948 1960 # Things related to the running of code
1949 1961 #-------------------------------------------------------------------------
1950 1962
1951 1963 def ex(self, cmd):
1952 1964 """Execute a normal python statement in user namespace."""
1953 1965 with nested(self.builtin_trap,):
1954 1966 exec cmd in self.user_global_ns, self.user_ns
1955 1967
1956 1968 def ev(self, expr):
1957 1969 """Evaluate python expression expr in user namespace.
1958 1970
1959 1971 Returns the result of evaluation
1960 1972 """
1961 1973 with nested(self.builtin_trap,):
1962 1974 return eval(expr, self.user_global_ns, self.user_ns)
1963 1975
1964 1976 def safe_execfile(self, fname, *where, **kw):
1965 1977 """A safe version of the builtin execfile().
1966 1978
1967 1979 This version will never throw an exception, but instead print
1968 1980 helpful error messages to the screen. This only works on pure
1969 1981 Python files with the .py extension.
1970 1982
1971 1983 Parameters
1972 1984 ----------
1973 1985 fname : string
1974 1986 The name of the file to be executed.
1975 1987 where : tuple
1976 1988 One or two namespaces, passed to execfile() as (globals,locals).
1977 1989 If only one is given, it is passed as both.
1978 1990 exit_ignore : bool (False)
1979 1991 If True, then silence SystemExit for non-zero status (it is always
1980 1992 silenced for zero status, as it is so common).
1981 1993 """
1982 1994 kw.setdefault('exit_ignore', False)
1983 1995
1984 1996 fname = os.path.abspath(os.path.expanduser(fname))
1985 1997
1986 1998 # Make sure we have a .py file
1987 1999 if not fname.endswith('.py'):
1988 2000 warn('File must end with .py to be run using execfile: <%s>' % fname)
1989 2001
1990 2002 # Make sure we can open the file
1991 2003 try:
1992 2004 with open(fname) as thefile:
1993 2005 pass
1994 2006 except:
1995 2007 warn('Could not open file <%s> for safe execution.' % fname)
1996 2008 return
1997 2009
1998 2010 # Find things also in current directory. This is needed to mimic the
1999 2011 # behavior of running a script from the system command line, where
2000 2012 # Python inserts the script's directory into sys.path
2001 2013 dname = os.path.dirname(fname)
2002 2014
2003 2015 with prepended_to_syspath(dname):
2004 2016 try:
2005 2017 execfile(fname,*where)
2006 2018 except SystemExit, status:
2007 2019 # If the call was made with 0 or None exit status (sys.exit(0)
2008 2020 # or sys.exit() ), don't bother showing a traceback, as both of
2009 2021 # these are considered normal by the OS:
2010 2022 # > python -c'import sys;sys.exit(0)'; echo $?
2011 2023 # 0
2012 2024 # > python -c'import sys;sys.exit()'; echo $?
2013 2025 # 0
2014 2026 # For other exit status, we show the exception unless
2015 2027 # explicitly silenced, but only in short form.
2016 2028 if status.code not in (0, None) and not kw['exit_ignore']:
2017 2029 self.showtraceback(exception_only=True)
2018 2030 except:
2019 2031 self.showtraceback()
2020 2032
2021 2033 def safe_execfile_ipy(self, fname):
2022 2034 """Like safe_execfile, but for .ipy files with IPython syntax.
2023 2035
2024 2036 Parameters
2025 2037 ----------
2026 2038 fname : str
2027 2039 The name of the file to execute. The filename must have a
2028 2040 .ipy extension.
2029 2041 """
2030 2042 fname = os.path.abspath(os.path.expanduser(fname))
2031 2043
2032 2044 # Make sure we have a .py file
2033 2045 if not fname.endswith('.ipy'):
2034 2046 warn('File must end with .py to be run using execfile: <%s>' % fname)
2035 2047
2036 2048 # Make sure we can open the file
2037 2049 try:
2038 2050 with open(fname) as thefile:
2039 2051 pass
2040 2052 except:
2041 2053 warn('Could not open file <%s> for safe execution.' % fname)
2042 2054 return
2043 2055
2044 2056 # Find things also in current directory. This is needed to mimic the
2045 2057 # behavior of running a script from the system command line, where
2046 2058 # Python inserts the script's directory into sys.path
2047 2059 dname = os.path.dirname(fname)
2048 2060
2049 2061 with prepended_to_syspath(dname):
2050 2062 try:
2051 2063 with open(fname) as thefile:
2052 2064 # self.run_cell currently captures all exceptions
2053 2065 # raised in user code. It would be nice if there were
2054 2066 # versions of runlines, execfile that did raise, so
2055 2067 # we could catch the errors.
2056 2068 self.run_cell(thefile.read())
2057 2069 except:
2058 2070 self.showtraceback()
2059 2071 warn('Unknown failure executing file: <%s>' % fname)
2060 2072
2061 2073 def run_cell(self, cell):
2062 2074 """Run the contents of an entire multiline 'cell' of code.
2063 2075
2064 2076 The cell is split into separate blocks which can be executed
2065 2077 individually. Then, based on how many blocks there are, they are
2066 2078 executed as follows:
2067 2079
2068 2080 - A single block: 'single' mode.
2069 2081
2070 2082 If there's more than one block, it depends:
2071 2083
2072 2084 - if the last one is no more than two lines long, run all but the last
2073 2085 in 'exec' mode and the very last one in 'single' mode. This makes it
2074 2086 easy to type simple expressions at the end to see computed values. -
2075 2087 otherwise (last one is also multiline), run all in 'exec' mode
2076 2088
2077 2089 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2078 2090 results are displayed and output prompts are computed. In 'exec' mode,
2079 2091 no results are displayed unless :func:`print` is called explicitly;
2080 2092 this mode is more akin to running a script.
2081 2093
2082 2094 Parameters
2083 2095 ----------
2084 2096 cell : str
2085 2097 A single or multiline string.
2086 2098 """
2087 2099
2088 2100 # We need to break up the input into executable blocks that can be run
2089 2101 # in 'single' mode, to provide comfortable user behavior.
2090 2102 blocks = self.input_splitter.split_blocks(cell)
2091 2103
2092 2104 if not blocks:
2093 2105 return
2094 2106
2095 2107 # Store the 'ipython' version of the cell as well, since that's what
2096 2108 # needs to go into the translated history and get executed (the
2097 2109 # original cell may contain non-python syntax).
2098 2110 ipy_cell = ''.join(blocks)
2099 2111
2100 2112 # Store raw and processed history
2101 2113 self.history_manager.store_inputs(ipy_cell, cell)
2102 2114
2103 2115 self.logger.log(ipy_cell, cell)
2104 2116 # dbg code!!!
2105 2117 if 0:
2106 2118 def myapp(self, val): # dbg
2107 2119 import traceback as tb
2108 2120 stack = ''.join(tb.format_stack())
2109 2121 print 'Value:', val
2110 2122 print 'Stack:\n', stack
2111 2123 list.append(self, val)
2112 2124
2113 2125 import new
2114 2126 self.history_manager.input_hist_parsed.append = types.MethodType(myapp,
2115 2127 self.history_manager.input_hist_parsed)
2116 2128 # End dbg
2117 2129
2118 2130 # All user code execution must happen with our context managers active
2119 2131 with nested(self.builtin_trap, self.display_trap):
2120 2132
2121 2133 # Single-block input should behave like an interactive prompt
2122 2134 if len(blocks) == 1:
2123 2135 # since we return here, we need to update the execution count
2124 2136 out = self.run_one_block(blocks[0])
2125 2137 self.execution_count += 1
2126 2138 return out
2127 2139
2128 2140 # In multi-block input, if the last block is a simple (one-two
2129 2141 # lines) expression, run it in single mode so it produces output.
2130 2142 # Otherwise just feed the whole thing to run_code. This seems like
2131 2143 # a reasonable usability design.
2132 2144 last = blocks[-1]
2133 2145 last_nlines = len(last.splitlines())
2134 2146
2135 2147 # Note: below, whenever we call run_code, we must sync history
2136 2148 # ourselves, because run_code is NOT meant to manage history at all.
2137 2149 if last_nlines < 2:
2138 2150 # Here we consider the cell split between 'body' and 'last',
2139 2151 # store all history and execute 'body', and if successful, then
2140 2152 # proceed to execute 'last'.
2141 2153
2142 2154 # Get the main body to run as a cell
2143 2155 ipy_body = ''.join(blocks[:-1])
2144 2156 retcode = self.run_source(ipy_body, symbol='exec',
2145 2157 post_execute=False)
2146 2158 if retcode==0:
2147 2159 # And the last expression via runlines so it produces output
2148 2160 self.run_one_block(last)
2149 2161 else:
2150 2162 # Run the whole cell as one entity, storing both raw and
2151 2163 # processed input in history
2152 2164 self.run_source(ipy_cell, symbol='exec')
2153 2165
2154 2166 # Each cell is a *single* input, regardless of how many lines it has
2155 2167 self.execution_count += 1
2156 2168
2157 2169 def run_one_block(self, block):
2158 2170 """Run a single interactive block.
2159 2171
2160 2172 If the block is single-line, dynamic transformations are applied to it
2161 2173 (like automagics, autocall and alias recognition).
2162 2174 """
2163 2175 if len(block.splitlines()) <= 1:
2164 2176 out = self.run_single_line(block)
2165 2177 else:
2166 2178 out = self.run_code(block)
2167 2179 return out
2168 2180
2169 2181 def run_single_line(self, line):
2170 2182 """Run a single-line interactive statement.
2171 2183
2172 2184 This assumes the input has been transformed to IPython syntax by
2173 2185 applying all static transformations (those with an explicit prefix like
2174 2186 % or !), but it will further try to apply the dynamic ones.
2175 2187
2176 2188 It does not update history.
2177 2189 """
2178 2190 tline = self.prefilter_manager.prefilter_line(line)
2179 2191 return self.run_source(tline)
2180 2192
2181 2193 # PENDING REMOVAL: this method is slated for deletion, once our new
2182 2194 # input logic has been 100% moved to frontends and is stable.
2183 2195 def runlines(self, lines, clean=False):
2184 2196 """Run a string of one or more lines of source.
2185 2197
2186 2198 This method is capable of running a string containing multiple source
2187 2199 lines, as if they had been entered at the IPython prompt. Since it
2188 2200 exposes IPython's processing machinery, the given strings can contain
2189 2201 magic calls (%magic), special shell access (!cmd), etc.
2190 2202 """
2191 2203
2192 2204 if isinstance(lines, (list, tuple)):
2193 2205 lines = '\n'.join(lines)
2194 2206
2195 2207 if clean:
2196 2208 lines = self._cleanup_ipy_script(lines)
2197 2209
2198 2210 # We must start with a clean buffer, in case this is run from an
2199 2211 # interactive IPython session (via a magic, for example).
2200 2212 self.reset_buffer()
2201 2213 lines = lines.splitlines()
2202 2214
2203 2215 # Since we will prefilter all lines, store the user's raw input too
2204 2216 # before we apply any transformations
2205 2217 self.buffer_raw[:] = [ l+'\n' for l in lines]
2206 2218
2207 2219 more = False
2208 2220 prefilter_lines = self.prefilter_manager.prefilter_lines
2209 2221 with nested(self.builtin_trap, self.display_trap):
2210 2222 for line in lines:
2211 2223 # skip blank lines so we don't mess up the prompt counter, but
2212 2224 # do NOT skip even a blank line if we are in a code block (more
2213 2225 # is true)
2214 2226
2215 2227 if line or more:
2216 2228 more = self.push_line(prefilter_lines(line, more))
2217 2229 # IPython's run_source returns None if there was an error
2218 2230 # compiling the code. This allows us to stop processing
2219 2231 # right away, so the user gets the error message at the
2220 2232 # right place.
2221 2233 if more is None:
2222 2234 break
2223 2235 # final newline in case the input didn't have it, so that the code
2224 2236 # actually does get executed
2225 2237 if more:
2226 2238 self.push_line('\n')
2227 2239
2228 2240 def run_source(self, source, filename=None,
2229 2241 symbol='single', post_execute=True):
2230 2242 """Compile and run some source in the interpreter.
2231 2243
2232 2244 Arguments are as for compile_command().
2233 2245
2234 2246 One several things can happen:
2235 2247
2236 2248 1) The input is incorrect; compile_command() raised an
2237 2249 exception (SyntaxError or OverflowError). A syntax traceback
2238 2250 will be printed by calling the showsyntaxerror() method.
2239 2251
2240 2252 2) The input is incomplete, and more input is required;
2241 2253 compile_command() returned None. Nothing happens.
2242 2254
2243 2255 3) The input is complete; compile_command() returned a code
2244 2256 object. The code is executed by calling self.run_code() (which
2245 2257 also handles run-time exceptions, except for SystemExit).
2246 2258
2247 2259 The return value is:
2248 2260
2249 2261 - True in case 2
2250 2262
2251 2263 - False in the other cases, unless an exception is raised, where
2252 2264 None is returned instead. This can be used by external callers to
2253 2265 know whether to continue feeding input or not.
2254 2266
2255 2267 The return value can be used to decide whether to use sys.ps1 or
2256 2268 sys.ps2 to prompt the next line."""
2257 2269
2258 2270 # We need to ensure that the source is unicode from here on.
2259 2271 if type(source)==str:
2260 2272 usource = source.decode(self.stdin_encoding)
2261 2273 else:
2262 2274 usource = source
2263 2275
2264 2276 if 0: # dbg
2265 2277 print 'Source:', repr(source) # dbg
2266 2278 print 'USource:', repr(usource) # dbg
2267 2279 print 'type:', type(source) # dbg
2268 2280 print 'encoding', self.stdin_encoding # dbg
2269 2281
2270 2282 try:
2271 2283 code = self.compile(usource, symbol, self.execution_count)
2272 2284 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2273 2285 # Case 1
2274 2286 self.showsyntaxerror(filename)
2275 2287 return None
2276 2288
2277 2289 if code is None:
2278 2290 # Case 2
2279 2291 return True
2280 2292
2281 2293 # Case 3
2282 2294 # We store the code object so that threaded shells and
2283 2295 # custom exception handlers can access all this info if needed.
2284 2296 # The source corresponding to this can be obtained from the
2285 2297 # buffer attribute as '\n'.join(self.buffer).
2286 2298 self.code_to_run = code
2287 2299 # now actually execute the code object
2288 2300 if self.run_code(code, post_execute) == 0:
2289 2301 return False
2290 2302 else:
2291 2303 return None
2292 2304
2293 2305 # For backwards compatibility
2294 2306 runsource = run_source
2295 2307
2296 2308 def run_code(self, code_obj, post_execute=True):
2297 2309 """Execute a code object.
2298 2310
2299 2311 When an exception occurs, self.showtraceback() is called to display a
2300 2312 traceback.
2301 2313
2302 2314 Return value: a flag indicating whether the code to be run completed
2303 2315 successfully:
2304 2316
2305 2317 - 0: successful execution.
2306 2318 - 1: an error occurred.
2307 2319 """
2308 2320
2309 2321 # Set our own excepthook in case the user code tries to call it
2310 2322 # directly, so that the IPython crash handler doesn't get triggered
2311 2323 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2312 2324
2313 2325 # we save the original sys.excepthook in the instance, in case config
2314 2326 # code (such as magics) needs access to it.
2315 2327 self.sys_excepthook = old_excepthook
2316 2328 outflag = 1 # happens in more places, so it's easier as default
2317 2329 try:
2318 2330 try:
2319 2331 self.hooks.pre_run_code_hook()
2320 2332 #rprint('Running code') # dbg
2321 2333 exec code_obj in self.user_global_ns, self.user_ns
2322 2334 finally:
2323 2335 # Reset our crash handler in place
2324 2336 sys.excepthook = old_excepthook
2325 2337 except SystemExit:
2326 2338 self.reset_buffer()
2327 2339 self.showtraceback(exception_only=True)
2328 2340 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2329 2341 except self.custom_exceptions:
2330 2342 etype,value,tb = sys.exc_info()
2331 2343 self.CustomTB(etype,value,tb)
2332 2344 except:
2333 2345 self.showtraceback()
2334 2346 else:
2335 2347 outflag = 0
2336 2348 if softspace(sys.stdout, 0):
2337 2349 print
2338 2350
2339 2351 # Execute any registered post-execution functions. Here, any errors
2340 2352 # are reported only minimally and just on the terminal, because the
2341 2353 # main exception channel may be occupied with a user traceback.
2342 2354 # FIXME: we need to think this mechanism a little more carefully.
2343 2355 if post_execute:
2344 2356 for func in self._post_execute:
2345 2357 try:
2346 2358 func()
2347 2359 except:
2348 2360 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2349 2361 func
2350 2362 print >> io.Term.cout, head
2351 2363 print >> io.Term.cout, self._simple_error()
2352 2364 print >> io.Term.cout, 'Removing from post_execute'
2353 2365 self._post_execute.remove(func)
2354 2366
2355 2367 # Flush out code object which has been run (and source)
2356 2368 self.code_to_run = None
2357 2369 return outflag
2358 2370
2359 2371 # For backwards compatibility
2360 2372 runcode = run_code
2361 2373
2362 2374 # PENDING REMOVAL: this method is slated for deletion, once our new
2363 2375 # input logic has been 100% moved to frontends and is stable.
2364 2376 def push_line(self, line):
2365 2377 """Push a line to the interpreter.
2366 2378
2367 2379 The line should not have a trailing newline; it may have
2368 2380 internal newlines. The line is appended to a buffer and the
2369 2381 interpreter's run_source() method is called with the
2370 2382 concatenated contents of the buffer as source. If this
2371 2383 indicates that the command was executed or invalid, the buffer
2372 2384 is reset; otherwise, the command is incomplete, and the buffer
2373 2385 is left as it was after the line was appended. The return
2374 2386 value is 1 if more input is required, 0 if the line was dealt
2375 2387 with in some way (this is the same as run_source()).
2376 2388 """
2377 2389
2378 2390 # autoindent management should be done here, and not in the
2379 2391 # interactive loop, since that one is only seen by keyboard input. We
2380 2392 # need this done correctly even for code run via runlines (which uses
2381 2393 # push).
2382 2394
2383 2395 #print 'push line: <%s>' % line # dbg
2384 2396 self.buffer.append(line)
2385 2397 full_source = '\n'.join(self.buffer)
2386 2398 more = self.run_source(full_source, self.filename)
2387 2399 if not more:
2388 2400 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2389 2401 full_source)
2390 2402 self.reset_buffer()
2391 2403 self.execution_count += 1
2392 2404 return more
2393 2405
2394 2406 def reset_buffer(self):
2395 2407 """Reset the input buffer."""
2396 2408 self.buffer[:] = []
2397 2409 self.buffer_raw[:] = []
2398 2410 self.input_splitter.reset()
2399 2411
2400 2412 # For backwards compatibility
2401 2413 resetbuffer = reset_buffer
2402 2414
2403 2415 def _is_secondary_block_start(self, s):
2404 2416 if not s.endswith(':'):
2405 2417 return False
2406 2418 if (s.startswith('elif') or
2407 2419 s.startswith('else') or
2408 2420 s.startswith('except') or
2409 2421 s.startswith('finally')):
2410 2422 return True
2411 2423
2412 2424 def _cleanup_ipy_script(self, script):
2413 2425 """Make a script safe for self.runlines()
2414 2426
2415 2427 Currently, IPython is lines based, with blocks being detected by
2416 2428 empty lines. This is a problem for block based scripts that may
2417 2429 not have empty lines after blocks. This script adds those empty
2418 2430 lines to make scripts safe for running in the current line based
2419 2431 IPython.
2420 2432 """
2421 2433 res = []
2422 2434 lines = script.splitlines()
2423 2435 level = 0
2424 2436
2425 2437 for l in lines:
2426 2438 lstripped = l.lstrip()
2427 2439 stripped = l.strip()
2428 2440 if not stripped:
2429 2441 continue
2430 2442 newlevel = len(l) - len(lstripped)
2431 2443 if level > 0 and newlevel == 0 and \
2432 2444 not self._is_secondary_block_start(stripped):
2433 2445 # add empty line
2434 2446 res.append('')
2435 2447 res.append(l)
2436 2448 level = newlevel
2437 2449
2438 2450 return '\n'.join(res) + '\n'
2439 2451
2440 2452 #-------------------------------------------------------------------------
2441 2453 # Things related to GUI support and pylab
2442 2454 #-------------------------------------------------------------------------
2443 2455
2444 2456 def enable_pylab(self, gui=None):
2445 2457 raise NotImplementedError('Implement enable_pylab in a subclass')
2446 2458
2447 2459 #-------------------------------------------------------------------------
2448 2460 # Utilities
2449 2461 #-------------------------------------------------------------------------
2450 2462
2451 2463 def var_expand(self,cmd,depth=0):
2452 2464 """Expand python variables in a string.
2453 2465
2454 2466 The depth argument indicates how many frames above the caller should
2455 2467 be walked to look for the local namespace where to expand variables.
2456 2468
2457 2469 The global namespace for expansion is always the user's interactive
2458 2470 namespace.
2459 2471 """
2460 2472
2461 2473 return str(ItplNS(cmd,
2462 2474 self.user_ns, # globals
2463 2475 # Skip our own frame in searching for locals:
2464 2476 sys._getframe(depth+1).f_locals # locals
2465 2477 ))
2466 2478
2467 2479 def mktempfile(self, data=None, prefix='ipython_edit_'):
2468 2480 """Make a new tempfile and return its filename.
2469 2481
2470 2482 This makes a call to tempfile.mktemp, but it registers the created
2471 2483 filename internally so ipython cleans it up at exit time.
2472 2484
2473 2485 Optional inputs:
2474 2486
2475 2487 - data(None): if data is given, it gets written out to the temp file
2476 2488 immediately, and the file is closed again."""
2477 2489
2478 2490 filename = tempfile.mktemp('.py', prefix)
2479 2491 self.tempfiles.append(filename)
2480 2492
2481 2493 if data:
2482 2494 tmp_file = open(filename,'w')
2483 2495 tmp_file.write(data)
2484 2496 tmp_file.close()
2485 2497 return filename
2486 2498
2487 2499 # TODO: This should be removed when Term is refactored.
2488 2500 def write(self,data):
2489 2501 """Write a string to the default output"""
2490 2502 io.Term.cout.write(data)
2491 2503
2492 2504 # TODO: This should be removed when Term is refactored.
2493 2505 def write_err(self,data):
2494 2506 """Write a string to the default error output"""
2495 2507 io.Term.cerr.write(data)
2496 2508
2497 2509 def ask_yes_no(self,prompt,default=True):
2498 2510 if self.quiet:
2499 2511 return True
2500 2512 return ask_yes_no(prompt,default)
2501 2513
2502 2514 def show_usage(self):
2503 2515 """Show a usage message"""
2504 2516 page.page(IPython.core.usage.interactive_usage)
2505 2517
2506 2518 #-------------------------------------------------------------------------
2507 2519 # Things related to IPython exiting
2508 2520 #-------------------------------------------------------------------------
2509 2521 def atexit_operations(self):
2510 2522 """This will be executed at the time of exit.
2511 2523
2512 2524 Cleanup operations and saving of persistent data that is done
2513 2525 unconditionally by IPython should be performed here.
2514 2526
2515 2527 For things that may depend on startup flags or platform specifics (such
2516 2528 as having readline or not), register a separate atexit function in the
2517 2529 code that has the appropriate information, rather than trying to
2518 2530 clutter
2519 2531 """
2520 2532 # Cleanup all tempfiles left around
2521 2533 for tfile in self.tempfiles:
2522 2534 try:
2523 2535 os.unlink(tfile)
2524 2536 except OSError:
2525 2537 pass
2526 2538
2527 2539 self.save_history()
2528 2540
2529 2541 # Clear all user namespaces to release all references cleanly.
2530 2542 self.reset()
2531 2543
2532 2544 # Run user hooks
2533 2545 self.hooks.shutdown_hook()
2534 2546
2535 2547 def cleanup(self):
2536 2548 self.restore_sys_module_state()
2537 2549
2538 2550
2539 2551 class InteractiveShellABC(object):
2540 2552 """An abstract base class for InteractiveShell."""
2541 2553 __metaclass__ = abc.ABCMeta
2542 2554
2543 2555 InteractiveShellABC.register(InteractiveShell)
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,478 +1,507 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Usage information for the main IPython applications.
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2008-2010 The IPython Development Team
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 #
8 8 # Distributed under the terms of the BSD License. The full license is in
9 9 # the file COPYING, distributed as part of this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 import sys
13 13 from IPython.core import release
14 14
15 15 cl_usage = """\
16 16 ipython [options] [files]
17 17
18 18 IPython: an enhanced interactive Python shell.
19 19
20 20 A Python shell with automatic history (input and output), dynamic object
21 21 introspection, easier configuration, command completion, access to the
22 22 system shell and more. IPython can also be embedded in running programs.
23 23
24 24 If invoked with no options, it executes all the files listed in sequence
25 25 and exits, use -i to enter interactive mode after running the files. Files
26 26 ending in .py will be treated as normal Python, but files ending in .ipy
27 27 can contain special IPython syntax (magic commands, shell expansions, etc.)
28 28
29 29 Please note that some of the configuration options are not available at the
30 30 command line, simply because they are not practical here. Look into your
31 31 ipython_config.py configuration file for details on those.
32 32
33 33 This file typically installed in the $HOME/.ipython directory. For Windows
34 34 users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most
35 35 instances.
36 36
37 37 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
38 38 you can change its default location by setting any path you want in this
39 39 environment variable.
40 40
41 41 For more information, see the manual available in HTML and PDF in your
42 42 installation, or online at http://ipython.scipy.org.
43 43 """
44 44
45 45 interactive_usage = """
46 46 IPython -- An enhanced Interactive Python
47 47 =========================================
48 48
49 49 IPython offers a combination of convenient shell features, special commands
50 50 and a history mechanism for both input (command history) and output (results
51 51 caching, similar to Mathematica). It is intended to be a fully compatible
52 52 replacement for the standard Python interpreter, while offering vastly
53 53 improved functionality and flexibility.
54 54
55 55 At your system command line, type 'ipython -help' to see the command line
56 56 options available. This document only describes interactive features.
57 57
58 58 Warning: IPython relies on the existence of a global variable called __IP which
59 59 controls the shell itself. If you redefine __IP to anything, bizarre behavior
60 60 will quickly occur.
61 61
62 62 MAIN FEATURES
63 63
64 64 * Access to the standard Python help. As of Python 2.1, a help system is
65 65 available with access to object docstrings and the Python manuals. Simply
66 66 type 'help' (no quotes) to access it.
67 67
68 68 * Magic commands: type %magic for information on the magic subsystem.
69 69
70 70 * System command aliases, via the %alias command or the ipythonrc config file.
71 71
72 72 * Dynamic object information:
73 73
74 74 Typing ?word or word? prints detailed information about an object. If
75 75 certain strings in the object are too long (docstrings, code, etc.) they get
76 76 snipped in the center for brevity.
77 77
78 78 Typing ??word or word?? gives access to the full information without
79 79 snipping long strings. Long strings are sent to the screen through the less
80 80 pager if longer than the screen, printed otherwise.
81 81
82 82 The ?/?? system gives access to the full source code for any object (if
83 83 available), shows function prototypes and other useful information.
84 84
85 85 If you just want to see an object's docstring, type '%pdoc object' (without
86 86 quotes, and without % if you have automagic on).
87 87
88 88 Both %pdoc and ?/?? give you access to documentation even on things which are
89 89 not explicitely defined. Try for example typing {}.get? or after import os,
90 90 type os.path.abspath??. The magic functions %pdef, %source and %file operate
91 91 similarly.
92 92
93 93 * Completion in the local namespace, by typing TAB at the prompt.
94 94
95 95 At any time, hitting tab will complete any available python commands or
96 96 variable names, and show you a list of the possible completions if there's
97 97 no unambiguous one. It will also complete filenames in the current directory.
98 98
99 99 This feature requires the readline and rlcomplete modules, so it won't work
100 100 if your Python lacks readline support (such as under Windows).
101 101
102 102 * Search previous command history in two ways (also requires readline):
103 103
104 104 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
105 105 search through only the history items that match what you've typed so
106 106 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
107 107 normal arrow keys.
108 108
109 109 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
110 110 your history for lines that match what you've typed so far, completing as
111 111 much as it can.
112 112
113 113 * Persistent command history across sessions (readline required).
114 114
115 115 * Logging of input with the ability to save and restore a working session.
116 116
117 117 * System escape with !. Typing !ls will run 'ls' in the current directory.
118 118
119 119 * The reload command does a 'deep' reload of a module: changes made to the
120 120 module since you imported will actually be available without having to exit.
121 121
122 122 * Verbose and colored exception traceback printouts. See the magic xmode and
123 123 xcolor functions for details (just type %magic).
124 124
125 125 * Input caching system:
126 126
127 127 IPython offers numbered prompts (In/Out) with input and output caching. All
128 128 input is saved and can be retrieved as variables (besides the usual arrow
129 129 key recall).
130 130
131 131 The following GLOBAL variables always exist (so don't overwrite them!):
132 132 _i: stores previous input.
133 133 _ii: next previous.
134 134 _iii: next-next previous.
135 135 _ih : a list of all input _ih[n] is the input from line n.
136 136
137 137 Additionally, global variables named _i<n> are dynamically created (<n>
138 138 being the prompt counter), such that _i<n> == _ih[<n>]
139 139
140 140 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
141 141
142 142 You can create macros which contain multiple input lines from this history,
143 143 for later re-execution, with the %macro function.
144 144
145 145 The history function %hist allows you to see any part of your input history
146 146 by printing a range of the _i variables. Note that inputs which contain
147 147 magic functions (%) appear in the history with a prepended comment. This is
148 148 because they aren't really valid Python code, so you can't exec them.
149 149
150 150 * Output caching system:
151 151
152 152 For output that is returned from actions, a system similar to the input
153 153 cache exists but using _ instead of _i. Only actions that produce a result
154 154 (NOT assignments, for example) are cached. If you are familiar with
155 155 Mathematica, IPython's _ variables behave exactly like Mathematica's %
156 156 variables.
157 157
158 158 The following GLOBAL variables always exist (so don't overwrite them!):
159 159 _ (one underscore): previous output.
160 160 __ (two underscores): next previous.
161 161 ___ (three underscores): next-next previous.
162 162
163 163 Global variables named _<n> are dynamically created (<n> being the prompt
164 164 counter), such that the result of output <n> is always available as _<n>.
165 165
166 166 Finally, a global dictionary named _oh exists with entries for all lines
167 167 which generated output.
168 168
169 169 * Directory history:
170 170
171 171 Your history of visited directories is kept in the global list _dh, and the
172 172 magic %cd command can be used to go to any entry in that list.
173 173
174 174 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
175 175
176 176 1. Auto-parentheses
177 177 Callable objects (i.e. functions, methods, etc) can be invoked like
178 178 this (notice the commas between the arguments):
179 179 >>> callable_ob arg1, arg2, arg3
180 180 and the input will be translated to this:
181 181 --> callable_ob(arg1, arg2, arg3)
182 182 You can force auto-parentheses by using '/' as the first character
183 183 of a line. For example:
184 184 >>> /globals # becomes 'globals()'
185 185 Note that the '/' MUST be the first character on the line! This
186 186 won't work:
187 187 >>> print /globals # syntax error
188 188
189 189 In most cases the automatic algorithm should work, so you should
190 190 rarely need to explicitly invoke /. One notable exception is if you
191 191 are trying to call a function with a list of tuples as arguments (the
192 192 parenthesis will confuse IPython):
193 193 In [1]: zip (1,2,3),(4,5,6) # won't work
194 194 but this will work:
195 195 In [2]: /zip (1,2,3),(4,5,6)
196 196 ------> zip ((1,2,3),(4,5,6))
197 197 Out[2]= [(1, 4), (2, 5), (3, 6)]
198 198
199 199 IPython tells you that it has altered your command line by
200 200 displaying the new command line preceded by -->. e.g.:
201 201 In [18]: callable list
202 202 -------> callable (list)
203 203
204 204 2. Auto-Quoting
205 205 You can force auto-quoting of a function's arguments by using ',' as
206 206 the first character of a line. For example:
207 207 >>> ,my_function /home/me # becomes my_function("/home/me")
208 208
209 209 If you use ';' instead, the whole argument is quoted as a single
210 210 string (while ',' splits on whitespace):
211 211 >>> ,my_function a b c # becomes my_function("a","b","c")
212 212 >>> ;my_function a b c # becomes my_function("a b c")
213 213
214 214 Note that the ',' MUST be the first character on the line! This
215 215 won't work:
216 216 >>> x = ,my_function /home/me # syntax error
217 217 """
218 218
219 219 interactive_usage_min = """\
220 220 An enhanced console for Python.
221 221 Some of its features are:
222 222 - Readline support if the readline library is present.
223 223 - Tab completion in the local namespace.
224 224 - Logging of input, see command-line options.
225 225 - System shell escape via ! , eg !ls.
226 226 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
227 227 - Keeps track of locally defined variables via %who, %whos.
228 228 - Show object information with a ? eg ?x or x? (use ?? for more info).
229 229 """
230 230
231 231 quick_reference = r"""
232 232 IPython -- An enhanced Interactive Python - Quick Reference Card
233 233 ================================================================
234 234
235 235 obj?, obj?? : Get help, or more help for object (also works as
236 236 ?obj, ??obj).
237 237 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
238 238 %magic : Information about IPython's 'magic' % functions.
239 239
240 240 Magic functions are prefixed by %, and typically take their arguments without
241 241 parentheses, quotes or even commas for convenience.
242 242
243 243 Example magic function calls:
244 244
245 245 %alias d ls -F : 'd' is now an alias for 'ls -F'
246 246 alias d ls -F : Works if 'alias' not a python name
247 247 alist = %alias : Get list of aliases to 'alist'
248 248 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
249 249 %cd?? : See help AND source for magic %cd
250 250
251 251 System commands:
252 252
253 253 !cp a.txt b/ : System command escape, calls os.system()
254 254 cp a.txt b/ : after %rehashx, most system commands work without !
255 255 cp ${f}.txt $bar : Variable expansion in magics and system commands
256 256 files = !ls /usr : Capture sytem command output
257 257 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
258 258
259 259 History:
260 260
261 261 _i, _ii, _iii : Previous, next previous, next next previous input
262 262 _i4, _ih[2:5] : Input history line 4, lines 2-4
263 263 exec _i81 : Execute input history line #81 again
264 264 %rep 81 : Edit input history line #81
265 265 _, __, ___ : previous, next previous, next next previous output
266 266 _dh : Directory history
267 267 _oh : Output history
268 268 %hist : Command history. '%hist -g foo' search history for 'foo'
269 269
270 270 Autocall:
271 271
272 272 f 1,2 : f(1,2)
273 273 /f 1,2 : f(1,2) (forced autoparen)
274 274 ,f 1 2 : f("1","2")
275 275 ;f 1 2 : f("1 2")
276 276
277 277 Remember: TAB completion works in many contexts, not just file names
278 278 or python names.
279 279
280 280 The following magic functions are currently available:
281 281
282 282 """
283 283
284 284 gui_reference = """\
285 285 ===============================
286 286 The graphical IPython console
287 287 ===============================
288 288
289 289 This console is designed to emulate the look, feel and workflow of a terminal
290 290 environment, while adding a number of enhancements that are simply not possible
291 291 in a real terminal, such as inline syntax highlighting, true multiline editing,
292 292 inline graphics and much more.
293 293
294 294 This quick reference document contains the basic information you'll need to
295 295 know to make the most efficient use of it. For the various command line
296 296 options available at startup, type ``--help`` at the command line.
297 297
298 298
299 299 Multiline editing
300 300 =================
301 301
302 302 The graphical console is capable of true multiline editing, but it also tries
303 303 to behave intuitively like a terminal when possible. If you are used to
304 304 IPyhton's old terminal behavior, you should find the transition painless, and
305 305 once you learn a few basic keybindings it will be a much more efficient
306 306 environment.
307 307
308 308 For single expressions or indented blocks, the console behaves almost like the
309 309 terminal IPython: single expressions are immediately evaluated, and indented
310 310 blocks are evaluated once a single blank line is entered::
311 311
312 312 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
313 313 Hello IPython!
314 314
315 315 In [2]: for i in range(10):
316 316 ...: print i,
317 317 ...:
318 318 0 1 2 3 4 5 6 7 8 9
319 319
320 320 If you want to enter more than one expression in a single input block
321 321 (something not possible in the terminal), you can use ``Control-Enter`` at the
322 322 end of your first line instead of ``Enter``. At that point the console goes
323 323 into 'cell mode' and even if your inputs are not indented, it will continue
324 324 accepting arbitrarily many lines until either you enter an extra blank line or
325 325 you hit ``Shift-Enter`` (the key binding that forces execution). When a
326 326 multiline cell is entered, IPython analyzes it and executes its code producing
327 327 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
328 328 cell is executed as if it was a script. An example should clarify this::
329 329
330 330 In [3]: x=1 # Hit C-Enter here
331 331 ...: y=2 # from now on, regular Enter is sufficient
332 332 ...: z=3
333 333 ...: x**2 # This does *not* produce an Out[] value
334 334 ...: x+y+z # Only the last expression does
335 335 ...:
336 336 Out[3]: 6
337 337
338 338 The behavior where an extra blank line forces execution is only active if you
339 339 are actually typing at the keyboard each line, and is meant to make it mimic
340 340 the IPython terminal behavior. If you paste a long chunk of input (for example
341 341 a long script copied form an editor or web browser), it can contain arbitrarily
342 342 many intermediate blank lines and they won't cause any problems. As always,
343 343 you can then make it execute by appending a blank line *at the end* or hitting
344 344 ``Shift-Enter`` anywhere within the cell.
345 345
346 346 With the up arrow key, you can retrieve previous blocks of input that contain
347 347 multiple lines. You can move inside of a multiline cell like you would in any
348 348 text editor. When you want it executed, the simplest thing to do is to hit the
349 349 force execution key, ``Shift-Enter`` (though you can also navigate to the end
350 350 and append a blank line by using ``Enter`` twice).
351 351
352 352 If you've edited a multiline cell and accidentally navigate out of it with the
353 353 up or down arrow keys, IPython will clear the cell and replace it with the
354 354 contents of the one above or below that you navigated to. If this was an
355 355 accident and you want to retrieve the cell you were editing, use the Undo
356 356 keybinding, ``Control-z``.
357 357
358 358
359 359 Key bindings
360 360 ============
361 361
362 362 The IPython console supports most of the basic Emacs line-oriented keybindings,
363 363 in addition to some of its own.
364 364
365 365 The keybinding prefixes mean:
366 366
367 367 - ``C``: Control
368 368 - ``S``: Shift
369 369 - ``M``: Meta (typically the Alt key)
370 370
371 371 The keybindings themselves are:
372 372
373 373 - ``Enter``: insert new line (may cause execution, see above).
374 374 - ``C-Enter``: force new line, *never* causes execution.
375 375 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
376 376 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
377 377 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
378 378 - ``C-v``: paste text from clipboard.
379 379 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
380 380 - ``C-S-z``: redo.
381 381 - ``C-o``: move to 'other' area, between pager and terminal.
382 382 - ``C-l``: clear terminal.
383 383 - ``C-a``: go to beginning of line.
384 384 - ``C-e``: go to end of line.
385 385 - ``C-k``: kill from cursor to the end of the line.
386 386 - ``C-y``: yank (paste)
387 387 - ``C-p``: previous line (like up arrow)
388 388 - ``C-n``: next line (like down arrow)
389 389 - ``C-f``: forward (like right arrow)
390 390 - ``C-b``: back (like left arrow)
391 391 - ``C-d``: delete next character.
392 392 - ``M-<``: move to the beginning of the input region.
393 393 - ``M->``: move to the end of the input region.
394 394 - ``M-d``: delete next word.
395 395 - ``M-Backspace``: delete previous word.
396 396 - ``C-.``: force a kernel restart (a confirmation dialog appears).
397 397 - ``C-+``: increase font size.
398 398 - ``C--``: decrease font size.
399 399
400 400 The IPython pager
401 401 =================
402 402
403 403 IPython will show long blocks of text from many sources using a builtin pager.
404 404 You can control where this pager appears with the ``--paging`` command-line
405 405 flag:
406 406
407 407 - default: it is overlaid on top of the main terminal. You must quit the pager
408 408 to get back to the terminal (similar to how a pager such as ``less`` or
409 409 ``more`` works).
410 410
411 411 - vertical: the console is made double-tall, and the pager appears on the
412 412 bottom area when needed. You can view its contents while using the terminal.
413 413
414 414 - horizontal: the console is made double-wide, and the pager appears on the
415 415 right area when needed. You can view its contents while using the terminal.
416 416
417 417 If you use the vertical or horizontal paging modes, you can navigate between
418 418 terminal and pager as follows:
419 419
420 420 - Tab key: goes from pager to terminal (but not the other way around).
421 421 - Control-o: goes from one to another always.
422 422 - Mouse: click on either.
423 423
424 424 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
425 425 focus on the pager area).
426 426
427 427
428 428 Running subprocesses
429 429 ====================
430 430
431 431 The graphical IPython console uses the ``pexpect`` module to run subprocesses
432 432 when you type ``!command``. This has a number of advantages (true asynchronous
433 433 output from subprocesses as well as very robust termination of rogue
434 434 subprocesses with ``Control-C``), as well as some limitations. The main
435 435 limitation is that you can *not* interact back with the subprocess, so anything
436 436 that invokes a pager or expects you to type input into it will block and hang
437 437 (you can kill it with ``Control-C``).
438 438
439 439 We have provided as magics ``%less`` to page files (aliased to ``%more``),
440 440 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
441 441 most common commands you'd want to call in your subshell and that would cause
442 442 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
443 443
444 Display
445 =======
446
447 The IPython console can now display objects in a variety of formats, including
448 HTML, PNG and SVG. This is accomplished using the display functions in
449 ``IPython.core.display``::
450
451 In [4]: from IPython.core.display import display, display_html
452
453 In [5]: from IPython.core.display import display_png, display_svg
454
455 Python objects can simply be passed to these functions and the appropriate
456 representations will be displayed in the console as long as the objects know
457 how to compute those representations. The easiest way of teaching objects how
458 to format themselves in various representations is to define special methods
459 such as: ``__html``, ``__svg__`` and ``__png__``. IPython's display formatters
460 can also be given custom formatter functions for various types::
461
462 In [6]: ip = get_ipython()
463
464 In [7]: html_formatter = ip.display_formatter.formatters['text/html']
465
466 In [8]: html_formatter.for_type(Foo, foo_to_html)
467
468 For further details, see ``IPython.core.formatters``.
444 469
445 470 Inline matplotlib graphics
446 471 ==========================
447 472
448 473 The IPython console is capable of displaying matplotlib figures inline, in SVG
449 474 format. If started with the ``--pylab inline`` flag, then all figures are
450 475 rendered inline automatically. If started with ``--pylab`` or ``--pylab <your
451 backend>``, then a GUI backend will be used, but the ``pastefig()`` function is
452 added to the global and ``plt`` namespaces. You can paste any figure that is
453 currently open in a window with this function; type ``pastefig?`` for
454 additional details."""
476 backend>``, then a GUI backend will be used, but IPython's ``display()`` and
477 ``getfigs()`` functions can be used to view plots inline::
478
479 In [9]: display(*getfigs()) # display all figures inline
480
481 In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline
482 """
483
455 484
456 485 quick_guide = """\
457 486 ? -> Introduction and overview of IPython's features.
458 487 %quickref -> Quick reference.
459 488 help -> Python's own help system.
460 489 object? -> Details about 'object', use 'object??' for extra details.
461 490 """
462 491
463 492 gui_note = """\
464 493 %guiref -> A brief reference about the graphical user interface.
465 494 """
466 495
467 496 default_banner_parts = [
468 497 'Python %s\n' % (sys.version.split('\n')[0],),
469 498 'Type "copyright", "credits" or "license" for more information.\n\n',
470 499 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
471 500 quick_guide
472 501 ]
473 502
474 503 default_gui_banner_parts = default_banner_parts + [gui_note]
475 504
476 505 default_banner = ''.join(default_banner_parts)
477 506
478 507 default_gui_banner = ''.join(default_gui_banner_parts)
@@ -1,598 +1,598 b''
1 1 from __future__ import print_function
2 2
3 3 # Standard library imports
4 4 from collections import namedtuple
5 5 import sys
6 6 import time
7 7
8 8 # System library imports
9 9 from pygments.lexers import PythonLexer
10 10 from PyQt4 import QtCore, QtGui
11 11
12 12 # Local imports
13 13 from IPython.core.inputsplitter import InputSplitter, transform_classic_prompt
14 14 from IPython.core.oinspect import call_tip
15 15 from IPython.frontend.qt.base_frontend_mixin import BaseFrontendMixin
16 16 from IPython.utils.traitlets import Bool
17 17 from bracket_matcher import BracketMatcher
18 18 from call_tip_widget import CallTipWidget
19 19 from completion_lexer import CompletionLexer
20 20 from history_console_widget import HistoryConsoleWidget
21 21 from pygments_highlighter import PygmentsHighlighter
22 22
23 23
24 24 class FrontendHighlighter(PygmentsHighlighter):
25 25 """ A PygmentsHighlighter that can be turned on and off and that ignores
26 26 prompts.
27 27 """
28 28
29 29 def __init__(self, frontend):
30 30 super(FrontendHighlighter, self).__init__(frontend._control.document())
31 31 self._current_offset = 0
32 32 self._frontend = frontend
33 33 self.highlighting_on = False
34 34
35 35 def highlightBlock(self, qstring):
36 36 """ Highlight a block of text. Reimplemented to highlight selectively.
37 37 """
38 38 if not self.highlighting_on:
39 39 return
40 40
41 41 # The input to this function is unicode string that may contain
42 42 # paragraph break characters, non-breaking spaces, etc. Here we acquire
43 43 # the string as plain text so we can compare it.
44 44 current_block = self.currentBlock()
45 45 string = self._frontend._get_block_plain_text(current_block)
46 46
47 47 # Decide whether to check for the regular or continuation prompt.
48 48 if current_block.contains(self._frontend._prompt_pos):
49 49 prompt = self._frontend._prompt
50 50 else:
51 51 prompt = self._frontend._continuation_prompt
52 52
53 53 # Don't highlight the part of the string that contains the prompt.
54 54 if string.startswith(prompt):
55 55 self._current_offset = len(prompt)
56 56 qstring.remove(0, len(prompt))
57 57 else:
58 58 self._current_offset = 0
59 59
60 60 PygmentsHighlighter.highlightBlock(self, qstring)
61 61
62 62 def rehighlightBlock(self, block):
63 63 """ Reimplemented to temporarily enable highlighting if disabled.
64 64 """
65 65 old = self.highlighting_on
66 66 self.highlighting_on = True
67 67 super(FrontendHighlighter, self).rehighlightBlock(block)
68 68 self.highlighting_on = old
69 69
70 70 def setFormat(self, start, count, format):
71 71 """ Reimplemented to highlight selectively.
72 72 """
73 73 start += self._current_offset
74 74 PygmentsHighlighter.setFormat(self, start, count, format)
75 75
76 76
77 77 class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin):
78 78 """ A Qt frontend for a generic Python kernel.
79 79 """
80 80
81 81 # An option and corresponding signal for overriding the default kernel
82 82 # interrupt behavior.
83 83 custom_interrupt = Bool(False)
84 84 custom_interrupt_requested = QtCore.pyqtSignal()
85 85
86 86 # An option and corresponding signals for overriding the default kernel
87 87 # restart behavior.
88 88 custom_restart = Bool(False)
89 89 custom_restart_kernel_died = QtCore.pyqtSignal(float)
90 90 custom_restart_requested = QtCore.pyqtSignal()
91 91
92 92 # Emitted when an 'execute_reply' has been received from the kernel and
93 93 # processed by the FrontendWidget.
94 94 executed = QtCore.pyqtSignal(object)
95 95
96 96 # Emitted when an exit request has been received from the kernel.
97 97 exit_requested = QtCore.pyqtSignal()
98 98
99 99 # Protected class variables.
100 100 _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos'])
101 101 _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos'])
102 102 _ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind'])
103 103 _input_splitter_class = InputSplitter
104 104 _local_kernel = False
105 105
106 106 #---------------------------------------------------------------------------
107 107 # 'object' interface
108 108 #---------------------------------------------------------------------------
109 109
110 110 def __init__(self, *args, **kw):
111 111 super(FrontendWidget, self).__init__(*args, **kw)
112 112
113 113 # FrontendWidget protected variables.
114 114 self._bracket_matcher = BracketMatcher(self._control)
115 115 self._call_tip_widget = CallTipWidget(self._control)
116 116 self._completion_lexer = CompletionLexer(PythonLexer())
117 117 self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None)
118 118 self._hidden = False
119 119 self._highlighter = FrontendHighlighter(self)
120 120 self._input_splitter = self._input_splitter_class(input_mode='cell')
121 121 self._kernel_manager = None
122 122 self._request_info = {}
123 123
124 124 # Configure the ConsoleWidget.
125 125 self.tab_width = 4
126 126 self._set_continuation_prompt('... ')
127 127
128 128 # Configure the CallTipWidget.
129 129 self._call_tip_widget.setFont(self.font)
130 130 self.font_changed.connect(self._call_tip_widget.setFont)
131 131
132 132 # Configure actions.
133 133 action = self._copy_raw_action
134 134 key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C
135 135 action.setEnabled(False)
136 136 action.setShortcut(QtGui.QKeySequence(key))
137 137 action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
138 138 action.triggered.connect(self.copy_raw)
139 139 self.copy_available.connect(action.setEnabled)
140 140 self.addAction(action)
141 141
142 142 # Connect signal handlers.
143 143 document = self._control.document()
144 144 document.contentsChange.connect(self._document_contents_change)
145 145
146 146 # set flag for whether we are connected via localhost
147 147 self._local_kernel = kw.get('local_kernel', FrontendWidget._local_kernel)
148 148
149 149 #---------------------------------------------------------------------------
150 150 # 'ConsoleWidget' public interface
151 151 #---------------------------------------------------------------------------
152 152
153 153 def copy(self):
154 154 """ Copy the currently selected text to the clipboard, removing prompts.
155 155 """
156 156 text = unicode(self._control.textCursor().selection().toPlainText())
157 157 if text:
158 158 lines = map(transform_classic_prompt, text.splitlines())
159 159 text = '\n'.join(lines)
160 160 QtGui.QApplication.clipboard().setText(text)
161 161
162 162 #---------------------------------------------------------------------------
163 163 # 'ConsoleWidget' abstract interface
164 164 #---------------------------------------------------------------------------
165 165
166 166 def _is_complete(self, source, interactive):
167 167 """ Returns whether 'source' can be completely processed and a new
168 168 prompt created. When triggered by an Enter/Return key press,
169 169 'interactive' is True; otherwise, it is False.
170 170 """
171 171 complete = self._input_splitter.push(source)
172 172 if interactive:
173 173 complete = not self._input_splitter.push_accepts_more()
174 174 return complete
175 175
176 176 def _execute(self, source, hidden):
177 177 """ Execute 'source'. If 'hidden', do not show any output.
178 178
179 179 See parent class :meth:`execute` docstring for full details.
180 180 """
181 181 msg_id = self.kernel_manager.xreq_channel.execute(source, hidden)
182 182 self._request_info['execute'] = self._ExecutionRequest(msg_id, 'user')
183 183 self._hidden = hidden
184 184
185 185 def _prompt_started_hook(self):
186 186 """ Called immediately after a new prompt is displayed.
187 187 """
188 188 if not self._reading:
189 189 self._highlighter.highlighting_on = True
190 190
191 191 def _prompt_finished_hook(self):
192 192 """ Called immediately after a prompt is finished, i.e. when some input
193 193 will be processed and a new prompt displayed.
194 194 """
195 195 if not self._reading:
196 196 self._highlighter.highlighting_on = False
197 197
198 198 def _tab_pressed(self):
199 199 """ Called when the tab key is pressed. Returns whether to continue
200 200 processing the event.
201 201 """
202 202 # Perform tab completion if:
203 203 # 1) The cursor is in the input buffer.
204 204 # 2) There is a non-whitespace character before the cursor.
205 205 text = self._get_input_buffer_cursor_line()
206 206 if text is None:
207 207 return False
208 208 complete = bool(text[:self._get_input_buffer_cursor_column()].strip())
209 209 if complete:
210 210 self._complete()
211 211 return not complete
212 212
213 213 #---------------------------------------------------------------------------
214 214 # 'ConsoleWidget' protected interface
215 215 #---------------------------------------------------------------------------
216 216
217 217 def _context_menu_make(self, pos):
218 218 """ Reimplemented to add an action for raw copy.
219 219 """
220 220 menu = super(FrontendWidget, self)._context_menu_make(pos)
221 221 for before_action in menu.actions():
222 222 if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \
223 223 QtGui.QKeySequence.ExactMatch:
224 224 menu.insertAction(before_action, self._copy_raw_action)
225 225 break
226 226 return menu
227 227
228 228 def _event_filter_console_keypress(self, event):
229 229 """ Reimplemented for execution interruption and smart backspace.
230 230 """
231 231 key = event.key()
232 232 if self._control_key_down(event.modifiers(), include_command=False):
233 233
234 234 if key == QtCore.Qt.Key_C and self._executing:
235 235 self.interrupt_kernel()
236 236 return True
237 237
238 238 elif key == QtCore.Qt.Key_Period:
239 239 message = 'Are you sure you want to restart the kernel?'
240 240 self.restart_kernel(message, now=False)
241 241 return True
242 242
243 243 elif not event.modifiers() & QtCore.Qt.AltModifier:
244 244
245 245 # Smart backspace: remove four characters in one backspace if:
246 246 # 1) everything left of the cursor is whitespace
247 247 # 2) the four characters immediately left of the cursor are spaces
248 248 if key == QtCore.Qt.Key_Backspace:
249 249 col = self._get_input_buffer_cursor_column()
250 250 cursor = self._control.textCursor()
251 251 if col > 3 and not cursor.hasSelection():
252 252 text = self._get_input_buffer_cursor_line()[:col]
253 253 if text.endswith(' ') and not text.strip():
254 254 cursor.movePosition(QtGui.QTextCursor.Left,
255 255 QtGui.QTextCursor.KeepAnchor, 4)
256 256 cursor.removeSelectedText()
257 257 return True
258 258
259 259 return super(FrontendWidget, self)._event_filter_console_keypress(event)
260 260
261 261 def _insert_continuation_prompt(self, cursor):
262 262 """ Reimplemented for auto-indentation.
263 263 """
264 264 super(FrontendWidget, self)._insert_continuation_prompt(cursor)
265 265 cursor.insertText(' ' * self._input_splitter.indent_spaces)
266 266
267 267 #---------------------------------------------------------------------------
268 268 # 'BaseFrontendMixin' abstract interface
269 269 #---------------------------------------------------------------------------
270 270
271 271 def _handle_complete_reply(self, rep):
272 272 """ Handle replies for tab completion.
273 273 """
274 274 cursor = self._get_cursor()
275 275 info = self._request_info.get('complete')
276 276 if info and info.id == rep['parent_header']['msg_id'] and \
277 277 info.pos == cursor.position():
278 278 text = '.'.join(self._get_context())
279 279 cursor.movePosition(QtGui.QTextCursor.Left, n=len(text))
280 280 self._complete_with_items(cursor, rep['content']['matches'])
281 281
282 282 def _handle_execute_reply(self, msg):
283 283 """ Handles replies for code execution.
284 284 """
285 285 info = self._request_info.get('execute')
286 286 if info and info.id == msg['parent_header']['msg_id'] and \
287 287 info.kind == 'user' and not self._hidden:
288 288 # Make sure that all output from the SUB channel has been processed
289 289 # before writing a new prompt.
290 290 self.kernel_manager.sub_channel.flush()
291 291
292 292 # Reset the ANSI style information to prevent bad text in stdout
293 293 # from messing up our colors. We're not a true terminal so we're
294 294 # allowed to do this.
295 295 if self.ansi_codes:
296 296 self._ansi_processor.reset_sgr()
297 297
298 298 content = msg['content']
299 299 status = content['status']
300 300 if status == 'ok':
301 301 self._process_execute_ok(msg)
302 302 elif status == 'error':
303 303 self._process_execute_error(msg)
304 304 elif status == 'abort':
305 305 self._process_execute_abort(msg)
306 306
307 307 self._show_interpreter_prompt_for_reply(msg)
308 308 self.executed.emit(msg)
309 309
310 310 def _handle_input_request(self, msg):
311 311 """ Handle requests for raw_input.
312 312 """
313 313 if self._hidden:
314 314 raise RuntimeError('Request for raw input during hidden execution.')
315 315
316 316 # Make sure that all output from the SUB channel has been processed
317 317 # before entering readline mode.
318 318 self.kernel_manager.sub_channel.flush()
319 319
320 320 def callback(line):
321 321 self.kernel_manager.rep_channel.input(line)
322 322 self._readline(msg['content']['prompt'], callback=callback)
323 323
324 324 def _handle_kernel_died(self, since_last_heartbeat):
325 325 """ Handle the kernel's death by asking if the user wants to restart.
326 326 """
327 327 if self.custom_restart:
328 328 self.custom_restart_kernel_died.emit(since_last_heartbeat)
329 329 else:
330 330 message = 'The kernel heartbeat has been inactive for %.2f ' \
331 331 'seconds. Do you want to restart the kernel? You may ' \
332 332 'first want to check the network connection.' % \
333 333 since_last_heartbeat
334 334 self.restart_kernel(message, now=True)
335 335
336 336 def _handle_object_info_reply(self, rep):
337 337 """ Handle replies for call tips.
338 338 """
339 339 cursor = self._get_cursor()
340 340 info = self._request_info.get('call_tip')
341 341 if info and info.id == rep['parent_header']['msg_id'] and \
342 342 info.pos == cursor.position():
343 343 # Get the information for a call tip. For now we format the call
344 344 # line as string, later we can pass False to format_call and
345 345 # syntax-highlight it ourselves for nicer formatting in the
346 346 # calltip.
347 347 call_info, doc = call_tip(rep['content'], format_call=True)
348 348 if call_info or doc:
349 349 self._call_tip_widget.show_call_info(call_info, doc)
350 350
351 351 def _handle_pyout(self, msg):
352 352 """ Handle display hook output.
353 353 """
354 354 if not self._hidden and self._is_from_this_session(msg):
355 self._append_plain_text(msg['content']['data'] + '\n')
355 self._append_plain_text(msg['content']['data']['text/plain'] + '\n')
356 356
357 357 def _handle_stream(self, msg):
358 358 """ Handle stdout, stderr, and stdin.
359 359 """
360 360 if not self._hidden and self._is_from_this_session(msg):
361 361 # Most consoles treat tabs as being 8 space characters. Convert tabs
362 362 # to spaces so that output looks as expected regardless of this
363 363 # widget's tab width.
364 364 text = msg['content']['data'].expandtabs(8)
365 365
366 366 self._append_plain_text(text)
367 367 self._control.moveCursor(QtGui.QTextCursor.End)
368 368
369 369 def _handle_shutdown_reply(self, msg):
370 370 """ Handle shutdown signal, only if from other console.
371 371 """
372 372 if not self._hidden and not self._is_from_this_session(msg):
373 373 if self._local_kernel:
374 374 if not msg['content']['restart']:
375 375 sys.exit(0)
376 376 else:
377 377 # we just got notified of a restart!
378 378 time.sleep(0.25) # wait 1/4 sec to reset
379 379 # lest the request for a new prompt
380 380 # goes to the old kernel
381 381 self.reset()
382 382 else: # remote kernel, prompt on Kernel shutdown/reset
383 383 title = self.window().windowTitle()
384 384 if not msg['content']['restart']:
385 385 reply = QtGui.QMessageBox.question(self, title,
386 386 "Kernel has been shutdown permanently. Close the Console?",
387 387 QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
388 388 if reply == QtGui.QMessageBox.Yes:
389 389 sys.exit(0)
390 390 else:
391 391 reply = QtGui.QMessageBox.question(self, title,
392 392 "Kernel has been reset. Clear the Console?",
393 393 QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
394 394 if reply == QtGui.QMessageBox.Yes:
395 395 time.sleep(0.25) # wait 1/4 sec to reset
396 396 # lest the request for a new prompt
397 397 # goes to the old kernel
398 398 self.reset()
399 399
400 400 def _started_channels(self):
401 401 """ Called when the KernelManager channels have started listening or
402 402 when the frontend is assigned an already listening KernelManager.
403 403 """
404 404 self.reset()
405 405
406 406 #---------------------------------------------------------------------------
407 407 # 'FrontendWidget' public interface
408 408 #---------------------------------------------------------------------------
409 409
410 410 def copy_raw(self):
411 411 """ Copy the currently selected text to the clipboard without attempting
412 412 to remove prompts or otherwise alter the text.
413 413 """
414 414 self._control.copy()
415 415
416 416 def execute_file(self, path, hidden=False):
417 417 """ Attempts to execute file with 'path'. If 'hidden', no output is
418 418 shown.
419 419 """
420 420 self.execute('execfile("%s")' % path, hidden=hidden)
421 421
422 422 def interrupt_kernel(self):
423 423 """ Attempts to interrupt the running kernel.
424 424 """
425 425 if self.custom_interrupt:
426 426 self.custom_interrupt_requested.emit()
427 427 elif self.kernel_manager.has_kernel:
428 428 self.kernel_manager.interrupt_kernel()
429 429 else:
430 430 self._append_plain_text('Kernel process is either remote or '
431 431 'unspecified. Cannot interrupt.\n')
432 432
433 433 def reset(self):
434 434 """ Resets the widget to its initial state. Similar to ``clear``, but
435 435 also re-writes the banner and aborts execution if necessary.
436 436 """
437 437 if self._executing:
438 438 self._executing = False
439 439 self._request_info['execute'] = None
440 440 self._reading = False
441 441 self._highlighter.highlighting_on = False
442 442
443 443 self._control.clear()
444 444 self._append_plain_text(self._get_banner())
445 445 self._show_interpreter_prompt()
446 446
447 447 def restart_kernel(self, message, now=False):
448 448 """ Attempts to restart the running kernel.
449 449 """
450 450 # FIXME: now should be configurable via a checkbox in the dialog. Right
451 451 # now at least the heartbeat path sets it to True and the manual restart
452 452 # to False. But those should just be the pre-selected states of a
453 453 # checkbox that the user could override if so desired. But I don't know
454 454 # enough Qt to go implementing the checkbox now.
455 455
456 456 if self.custom_restart:
457 457 self.custom_restart_requested.emit()
458 458
459 459 elif self.kernel_manager.has_kernel:
460 460 # Pause the heart beat channel to prevent further warnings.
461 461 self.kernel_manager.hb_channel.pause()
462 462
463 463 # Prompt the user to restart the kernel. Un-pause the heartbeat if
464 464 # they decline. (If they accept, the heartbeat will be un-paused
465 465 # automatically when the kernel is restarted.)
466 466 buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
467 467 result = QtGui.QMessageBox.question(self, 'Restart kernel?',
468 468 message, buttons)
469 469 if result == QtGui.QMessageBox.Yes:
470 470 try:
471 471 self.kernel_manager.restart_kernel(now=now)
472 472 except RuntimeError:
473 473 self._append_plain_text('Kernel started externally. '
474 474 'Cannot restart.\n')
475 475 else:
476 476 self.reset()
477 477 else:
478 478 self.kernel_manager.hb_channel.unpause()
479 479
480 480 else:
481 481 self._append_plain_text('Kernel process is either remote or '
482 482 'unspecified. Cannot restart.\n')
483 483
484 484 #---------------------------------------------------------------------------
485 485 # 'FrontendWidget' protected interface
486 486 #---------------------------------------------------------------------------
487 487
488 488 def _call_tip(self):
489 489 """ Shows a call tip, if appropriate, at the current cursor location.
490 490 """
491 491 # Decide if it makes sense to show a call tip
492 492 cursor = self._get_cursor()
493 493 cursor.movePosition(QtGui.QTextCursor.Left)
494 494 if cursor.document().characterAt(cursor.position()).toAscii() != '(':
495 495 return False
496 496 context = self._get_context(cursor)
497 497 if not context:
498 498 return False
499 499
500 500 # Send the metadata request to the kernel
501 501 name = '.'.join(context)
502 502 msg_id = self.kernel_manager.xreq_channel.object_info(name)
503 503 pos = self._get_cursor().position()
504 504 self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos)
505 505 return True
506 506
507 507 def _complete(self):
508 508 """ Performs completion at the current cursor location.
509 509 """
510 510 context = self._get_context()
511 511 if context:
512 512 # Send the completion request to the kernel
513 513 msg_id = self.kernel_manager.xreq_channel.complete(
514 514 '.'.join(context), # text
515 515 self._get_input_buffer_cursor_line(), # line
516 516 self._get_input_buffer_cursor_column(), # cursor_pos
517 517 self.input_buffer) # block
518 518 pos = self._get_cursor().position()
519 519 info = self._CompletionRequest(msg_id, pos)
520 520 self._request_info['complete'] = info
521 521
522 522 def _get_banner(self):
523 523 """ Gets a banner to display at the beginning of a session.
524 524 """
525 525 banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \
526 526 '"license" for more information.'
527 527 return banner % (sys.version, sys.platform)
528 528
529 529 def _get_context(self, cursor=None):
530 530 """ Gets the context for the specified cursor (or the current cursor
531 531 if none is specified).
532 532 """
533 533 if cursor is None:
534 534 cursor = self._get_cursor()
535 535 cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
536 536 QtGui.QTextCursor.KeepAnchor)
537 537 text = unicode(cursor.selection().toPlainText())
538 538 return self._completion_lexer.get_context(text)
539 539
540 540 def _process_execute_abort(self, msg):
541 541 """ Process a reply for an aborted execution request.
542 542 """
543 543 self._append_plain_text("ERROR: execution aborted\n")
544 544
545 545 def _process_execute_error(self, msg):
546 546 """ Process a reply for an execution request that resulted in an error.
547 547 """
548 548 content = msg['content']
549 549 # If a SystemExit is passed along, this means exit() was called - also
550 550 # all the ipython %exit magic syntax of '-k' to be used to keep
551 551 # the kernel running
552 552 if content['ename']=='SystemExit':
553 553 keepkernel = content['evalue']=='-k' or content['evalue']=='True'
554 554 self._keep_kernel_on_exit = keepkernel
555 555 self.exit_requested.emit()
556 556 else:
557 557 traceback = ''.join(content['traceback'])
558 558 self._append_plain_text(traceback)
559 559
560 560 def _process_execute_ok(self, msg):
561 561 """ Process a reply for a successful execution equest.
562 562 """
563 563 payload = msg['content']['payload']
564 564 for item in payload:
565 565 if not self._process_execute_payload(item):
566 566 warning = 'Warning: received unknown payload of type %s'
567 567 print(warning % repr(item['source']))
568 568
569 569 def _process_execute_payload(self, item):
570 570 """ Process a single payload item from the list of payload items in an
571 571 execution reply. Returns whether the payload was handled.
572 572 """
573 573 # The basic FrontendWidget doesn't handle payloads, as they are a
574 574 # mechanism for going beyond the standard Python interpreter model.
575 575 return False
576 576
577 577 def _show_interpreter_prompt(self):
578 578 """ Shows a prompt for the interpreter.
579 579 """
580 580 self._show_prompt('>>> ')
581 581
582 582 def _show_interpreter_prompt_for_reply(self, msg):
583 583 """ Shows a prompt for the interpreter given an 'execute_reply' message.
584 584 """
585 585 self._show_interpreter_prompt()
586 586
587 587 #------ Signal handlers ----------------------------------------------------
588 588
589 589 def _document_contents_change(self, position, removed, added):
590 590 """ Called whenever the document's content changes. Display a call tip
591 591 if appropriate.
592 592 """
593 593 # Calculate where the cursor should be *after* the change:
594 594 position += added
595 595
596 596 document = self._control.document()
597 597 if position == self._get_cursor().position():
598 598 self._call_tip()
@@ -1,467 +1,497 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 input_history_dict = {}
171 171 for key,val in history_dict.items():
172 172 input_history_dict[int(key)] = val
173 173 items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ]
174 174 self._set_history(items)
175 175
176 176 def _handle_pyout(self, msg):
177 177 """ Reimplemented for IPython-style "display hook".
178 178 """
179 179 if not self._hidden and self._is_from_this_session(msg):
180 180 content = msg['content']
181 181 prompt_number = content['execution_count']
182 self._append_plain_text(self.output_sep)
183 self._append_html(self._make_out_prompt(prompt_number))
184 self._append_plain_text(content['data']+self.output_sep2)
182 data = content['data']
183 if data.has_key('text/html'):
184 self._append_plain_text(self.output_sep)
185 self._append_html(self._make_out_prompt(prompt_number))
186 html = data['text/html']
187 self._append_plain_text('\n')
188 self._append_html(html + self.output_sep2)
189 elif data.has_key('text/plain'):
190 self._append_plain_text(self.output_sep)
191 self._append_html(self._make_out_prompt(prompt_number))
192 text = data['text/plain']
193 self._append_plain_text(text + self.output_sep2)
194
195 def _handle_display_data(self, msg):
196 """ The base handler for the ``display_data`` message.
197 """
198 # For now, we don't display data from other frontends, but we
199 # eventually will as this allows all frontends to monitor the display
200 # data. But we need to figure out how to handle this in the GUI.
201 if not self._hidden and self._is_from_this_session(msg):
202 source = msg['content']['source']
203 data = msg['content']['data']
204 metadata = msg['content']['metadata']
205 # In the regular IPythonWidget, we simply print the plain text
206 # representation.
207 if data.has_key('text/html'):
208 html = data['text/html']
209 self._append_html(html)
210 elif data.has_key('text/plain'):
211 text = data['text/plain']
212 self._append_plain_text(text)
213 # This newline seems to be needed for text and html output.
214 self._append_plain_text(u'\n')
185 215
186 216 def _started_channels(self):
187 217 """ Reimplemented to make a history request.
188 218 """
189 219 super(IPythonWidget, self)._started_channels()
190 220 self.kernel_manager.xreq_channel.history(raw=True, output=False)
191 221
192 222 #---------------------------------------------------------------------------
193 223 # 'ConsoleWidget' public interface
194 224 #---------------------------------------------------------------------------
195 225
196 226 def copy(self):
197 227 """ Copy the currently selected text to the clipboard, removing prompts
198 228 if possible.
199 229 """
200 230 text = unicode(self._control.textCursor().selection().toPlainText())
201 231 if text:
202 232 lines = map(transform_ipy_prompt, text.splitlines())
203 233 text = '\n'.join(lines)
204 234 QtGui.QApplication.clipboard().setText(text)
205 235
206 236 #---------------------------------------------------------------------------
207 237 # 'FrontendWidget' public interface
208 238 #---------------------------------------------------------------------------
209 239
210 240 def execute_file(self, path, hidden=False):
211 241 """ Reimplemented to use the 'run' magic.
212 242 """
213 243 self.execute('%%run %s' % path, hidden=hidden)
214 244
215 245 #---------------------------------------------------------------------------
216 246 # 'FrontendWidget' protected interface
217 247 #---------------------------------------------------------------------------
218 248
219 249 def _complete(self):
220 250 """ Reimplemented to support IPython's improved completion machinery.
221 251 """
222 252 # We let the kernel split the input line, so we *always* send an empty
223 253 # text field. Readline-based frontends do get a real text field which
224 254 # they can use.
225 255 text = ''
226 256
227 257 # Send the completion request to the kernel
228 258 msg_id = self.kernel_manager.xreq_channel.complete(
229 259 text, # text
230 260 self._get_input_buffer_cursor_line(), # line
231 261 self._get_input_buffer_cursor_column(), # cursor_pos
232 262 self.input_buffer) # block
233 263 pos = self._get_cursor().position()
234 264 info = self._CompletionRequest(msg_id, pos)
235 265 self._request_info['complete'] = info
236 266
237 267 def _get_banner(self):
238 268 """ Reimplemented to return IPython's default banner.
239 269 """
240 270 return default_gui_banner
241 271
242 272 def _process_execute_error(self, msg):
243 273 """ Reimplemented for IPython-style traceback formatting.
244 274 """
245 275 content = msg['content']
246 276 traceback = '\n'.join(content['traceback']) + '\n'
247 277 if False:
248 278 # FIXME: For now, tracebacks come as plain text, so we can't use
249 279 # the html renderer yet. Once we refactor ultratb to produce
250 280 # properly styled tracebacks, this branch should be the default
251 281 traceback = traceback.replace(' ', '&nbsp;')
252 282 traceback = traceback.replace('\n', '<br/>')
253 283
254 284 ename = content['ename']
255 285 ename_styled = '<span class="error">%s</span>' % ename
256 286 traceback = traceback.replace(ename, ename_styled)
257 287
258 288 self._append_html(traceback)
259 289 else:
260 290 # This is the fallback for now, using plain text with ansi escapes
261 291 self._append_plain_text(traceback)
262 292
263 293 def _process_execute_payload(self, item):
264 294 """ Reimplemented to dispatch payloads to handler methods.
265 295 """
266 296 handler = self._payload_handlers.get(item['source'])
267 297 if handler is None:
268 298 # We have no handler for this type of payload, simply ignore it
269 299 return False
270 300 else:
271 301 handler(item)
272 302 return True
273 303
274 304 def _show_interpreter_prompt(self, number=None):
275 305 """ Reimplemented for IPython-style prompts.
276 306 """
277 307 # If a number was not specified, make a prompt number request.
278 308 if number is None:
279 309 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
280 310 info = self._ExecutionRequest(msg_id, 'prompt')
281 311 self._request_info['execute'] = info
282 312 return
283 313
284 314 # Show a new prompt and save information about it so that it can be
285 315 # updated later if the prompt number turns out to be wrong.
286 316 self._prompt_sep = self.input_sep
287 317 self._show_prompt(self._make_in_prompt(number), html=True)
288 318 block = self._control.document().lastBlock()
289 319 length = len(self._prompt)
290 320 self._previous_prompt_obj = self._PromptBlock(block, length, number)
291 321
292 322 # Update continuation prompt to reflect (possibly) new prompt length.
293 323 self._set_continuation_prompt(
294 324 self._make_continuation_prompt(self._prompt), html=True)
295 325
296 326 # Load code from the %loadpy magic, if necessary.
297 327 if self._code_to_load is not None:
298 328 self.input_buffer = dedent(unicode(self._code_to_load).rstrip())
299 329 self._code_to_load = None
300 330
301 331 def _show_interpreter_prompt_for_reply(self, msg):
302 332 """ Reimplemented for IPython-style prompts.
303 333 """
304 334 # Update the old prompt number if necessary.
305 335 content = msg['content']
306 336 previous_prompt_number = content['execution_count']
307 337 if self._previous_prompt_obj and \
308 338 self._previous_prompt_obj.number != previous_prompt_number:
309 339 block = self._previous_prompt_obj.block
310 340
311 341 # Make sure the prompt block has not been erased.
312 342 if block.isValid() and not block.text().isEmpty():
313 343
314 344 # Remove the old prompt and insert a new prompt.
315 345 cursor = QtGui.QTextCursor(block)
316 346 cursor.movePosition(QtGui.QTextCursor.Right,
317 347 QtGui.QTextCursor.KeepAnchor,
318 348 self._previous_prompt_obj.length)
319 349 prompt = self._make_in_prompt(previous_prompt_number)
320 350 self._prompt = self._insert_html_fetching_plain_text(
321 351 cursor, prompt)
322 352
323 353 # When the HTML is inserted, Qt blows away the syntax
324 354 # highlighting for the line, so we need to rehighlight it.
325 355 self._highlighter.rehighlightBlock(cursor.block())
326 356
327 357 self._previous_prompt_obj = None
328 358
329 359 # Show a new prompt with the kernel's estimated prompt number.
330 360 self._show_interpreter_prompt(previous_prompt_number + 1)
331 361
332 362 #---------------------------------------------------------------------------
333 363 # 'IPythonWidget' interface
334 364 #---------------------------------------------------------------------------
335 365
336 366 def set_default_style(self, colors='lightbg'):
337 367 """ Sets the widget style to the class defaults.
338 368
339 369 Parameters:
340 370 -----------
341 371 colors : str, optional (default lightbg)
342 372 Whether to use the default IPython light background or dark
343 373 background or B&W style.
344 374 """
345 375 colors = colors.lower()
346 376 if colors=='lightbg':
347 377 self.style_sheet = default_light_style_sheet
348 378 self.syntax_style = default_light_syntax_style
349 379 elif colors=='linux':
350 380 self.style_sheet = default_dark_style_sheet
351 381 self.syntax_style = default_dark_syntax_style
352 382 elif colors=='nocolor':
353 383 self.style_sheet = default_bw_style_sheet
354 384 self.syntax_style = default_bw_syntax_style
355 385 else:
356 386 raise KeyError("No such color scheme: %s"%colors)
357 387
358 388 #---------------------------------------------------------------------------
359 389 # 'IPythonWidget' protected interface
360 390 #---------------------------------------------------------------------------
361 391
362 392 def _edit(self, filename, line=None):
363 393 """ Opens a Python script for editing.
364 394
365 395 Parameters:
366 396 -----------
367 397 filename : str
368 398 A path to a local system file.
369 399
370 400 line : int, optional
371 401 A line of interest in the file.
372 402 """
373 403 if self.custom_edit:
374 404 self.custom_edit_requested.emit(filename, line)
375 405 elif self.editor == 'default':
376 406 self._append_plain_text('No default editor available.\n')
377 407 else:
378 408 try:
379 409 filename = '"%s"' % filename
380 410 if line and self.editor_line:
381 411 command = self.editor_line.format(filename=filename,
382 412 line=line)
383 413 else:
384 414 try:
385 415 command = self.editor.format()
386 416 except KeyError:
387 417 command = self.editor.format(filename=filename)
388 418 else:
389 419 command += ' ' + filename
390 420 except KeyError:
391 421 self._append_plain_text('Invalid editor command.\n')
392 422 else:
393 423 try:
394 424 Popen(command, shell=True)
395 425 except OSError:
396 426 msg = 'Opening editor with command "%s" failed.\n'
397 427 self._append_plain_text(msg % command)
398 428
399 429 def _make_in_prompt(self, number):
400 430 """ Given a prompt number, returns an HTML In prompt.
401 431 """
402 432 body = self.in_prompt % number
403 433 return '<span class="in-prompt">%s</span>' % body
404 434
405 435 def _make_continuation_prompt(self, prompt):
406 436 """ Given a plain text version of an In prompt, returns an HTML
407 437 continuation prompt.
408 438 """
409 439 end_chars = '...: '
410 440 space_count = len(prompt.lstrip('\n')) - len(end_chars)
411 441 body = '&nbsp;' * space_count + end_chars
412 442 return '<span class="in-prompt">%s</span>' % body
413 443
414 444 def _make_out_prompt(self, number):
415 445 """ Given a prompt number, returns an HTML Out prompt.
416 446 """
417 447 body = self.out_prompt % number
418 448 return '<span class="out-prompt">%s</span>' % body
419 449
420 450 #------ Payload handlers --------------------------------------------------
421 451
422 452 # Payload handlers with a generic interface: each takes the opaque payload
423 453 # dict, unpacks it and calls the underlying functions with the necessary
424 454 # arguments.
425 455
426 456 def _handle_payload_edit(self, item):
427 457 self._edit(item['filename'], item['line_number'])
428 458
429 459 def _handle_payload_exit(self, item):
430 460 self._keep_kernel_on_exit = item['keepkernel']
431 461 self.exit_requested.emit()
432 462
433 463 def _handle_payload_loadpy(self, item):
434 464 # Simple save the text of the .py file for later. The text is written
435 465 # to the buffer when _prompt_started_hook is called.
436 466 self._code_to_load = item['text']
437 467
438 468 def _handle_payload_page(self, item):
439 469 # Since the plain text widget supports only a very small subset of HTML
440 470 # and we have no control over the HTML source, we only page HTML
441 471 # payloads in the rich text widget.
442 472 if item['html'] and self.kind == 'rich':
443 473 self._page(item['html'], html=True)
444 474 else:
445 475 self._page(item['text'], html=False)
446 476
447 #------ Trait change handlers ---------------------------------------------
477 #------ Trait change handlers --------------------------------------------
448 478
449 479 def _style_sheet_changed(self):
450 480 """ Set the style sheets of the underlying widgets.
451 481 """
452 482 self.setStyleSheet(self.style_sheet)
453 483 self._control.document().setDefaultStyleSheet(self.style_sheet)
454 484 if self._page_control:
455 485 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
456 486
457 487 bg_color = self._control.palette().background().color()
458 488 self._ansi_processor.set_background_color(bg_color)
459 489
460 490 def _syntax_style_changed(self):
461 491 """ Set the style for the syntax highlighter.
462 492 """
463 493 if self.syntax_style:
464 494 self._highlighter.set_style(self.syntax_style)
465 495 else:
466 496 self._highlighter.set_style_sheet(self.style_sheet)
467
497
@@ -1,195 +1,271 b''
1 1 # System library imports
2 2 import os
3 3 import re
4 from base64 import decodestring
4 5 from PyQt4 import QtCore, QtGui
5 6
6 7 # Local imports
7 8 from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image
8 9 from ipython_widget import IPythonWidget
9 10
10 11
11 12 class RichIPythonWidget(IPythonWidget):
12 13 """ An IPythonWidget that supports rich text, including lists, images, and
13 14 tables. Note that raw performance will be reduced compared to the plain
14 15 text version.
15 16 """
16 17
17 18 # RichIPythonWidget protected class variables.
18 19 _payload_source_plot = 'IPython.zmq.pylab.backend_payload.add_plot_payload'
19 20 _svg_text_format_property = 1
20 21
21 22 #---------------------------------------------------------------------------
22 23 # 'object' interface
23 24 #---------------------------------------------------------------------------
24 25
25 26 def __init__(self, *args, **kw):
26 27 """ Create a RichIPythonWidget.
27 28 """
28 29 kw['kind'] = 'rich'
29 30 super(RichIPythonWidget, self).__init__(*args, **kw)
30 31 # Dictionary for resolving Qt names to images when
31 32 # generating XHTML output
32 33 self._name_to_svg = {}
33 34
34 35 #---------------------------------------------------------------------------
35 36 # 'ConsoleWidget' protected interface
36 37 #---------------------------------------------------------------------------
37 38
38 39 def _context_menu_make(self, pos):
39 40 """ Reimplemented to return a custom context menu for images.
40 41 """
41 42 format = self._control.cursorForPosition(pos).charFormat()
42 43 name = format.stringProperty(QtGui.QTextFormat.ImageName)
43 44 if name.isEmpty():
44 45 menu = super(RichIPythonWidget, self)._context_menu_make(pos)
45 46 else:
46 47 menu = QtGui.QMenu()
47 48
48 49 menu.addAction('Copy Image', lambda: self._copy_image(name))
49 50 menu.addAction('Save Image As...', lambda: self._save_image(name))
50 51 menu.addSeparator()
51 52
52 53 svg = format.stringProperty(self._svg_text_format_property)
53 54 if not svg.isEmpty():
54 55 menu.addSeparator()
55 56 menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg))
56 57 menu.addAction('Save SVG As...',
57 58 lambda: save_svg(svg, self._control))
58 59 return menu
59
60
61 #---------------------------------------------------------------------------
62 # 'BaseFrontendMixin' abstract interface
63 #---------------------------------------------------------------------------
64
65 def _handle_pyout(self, msg):
66 """ Overridden to handle rich data types, like SVG.
67 """
68 if not self._hidden and self._is_from_this_session(msg):
69 content = msg['content']
70 prompt_number = content['execution_count']
71 data = content['data']
72 if data.has_key('image/svg+xml'):
73 self._append_plain_text(self.output_sep)
74 self._append_html(self._make_out_prompt(prompt_number))
75 # TODO: try/except this call.
76 self._append_svg(data['image/svg+xml'])
77 self._append_html(self.output_sep2)
78 elif data.has_key('image/png'):
79 self._append_plain_text(self.output_sep)
80 self._append_html(self._make_out_prompt(prompt_number))
81 # This helps the output to look nice.
82 self._append_plain_text('\n')
83 # TODO: try/except these calls
84 png = decodestring(data['image/png'])
85 self._append_png(png)
86 self._append_html(self.output_sep2)
87 else:
88 # Default back to the plain text representation.
89 return super(RichIPythonWidget, self)._handle_pyout(msg)
90
91 def _handle_display_data(self, msg):
92 """ Overridden to handle rich data types, like SVG.
93 """
94 if not self._hidden and self._is_from_this_session(msg):
95 source = msg['content']['source']
96 data = msg['content']['data']
97 metadata = msg['content']['metadata']
98 # Try to use the svg or html representations.
99 # FIXME: Is this the right ordering of things to try?
100 if data.has_key('image/svg+xml'):
101 svg = data['image/svg+xml']
102 # TODO: try/except this call.
103 self._append_svg(svg)
104 elif data.has_key('image/png'):
105 # TODO: try/except these calls
106 # PNG data is base64 encoded as it passes over the network
107 # in a JSON structure so we decode it.
108 png = decodestring(data['image/png'])
109 self._append_png(png)
110 else:
111 # Default back to the plain text representation.
112 return super(RichIPythonWidget, self)._handle_display_data(msg)
113
60 114 #---------------------------------------------------------------------------
61 115 # 'FrontendWidget' protected interface
62 116 #---------------------------------------------------------------------------
63 117
64 118 def _process_execute_payload(self, item):
65 119 """ Reimplemented to handle matplotlib plot payloads.
66 120 """
121 # TODO: remove this as all plot data is coming back through the
122 # display_data message type.
67 123 if item['source'] == self._payload_source_plot:
68 124 if item['format'] == 'svg':
69 125 svg = item['data']
70 try:
71 image = svg_to_image(svg)
72 except ValueError:
73 self._append_plain_text('Received invalid plot data.')
74 else:
75 format = self._add_image(image)
76 self._name_to_svg[str(format.name())] = svg
77 format.setProperty(self._svg_text_format_property, svg)
78 cursor = self._get_end_cursor()
79 cursor.insertBlock()
80 cursor.insertImage(format)
81 cursor.insertBlock()
126 self._append_svg(svg)
82 127 return True
83 128 else:
84 129 # Add other plot formats here!
85 130 return False
86 131 else:
87 132 return super(RichIPythonWidget, self)._process_execute_payload(item)
88 133
89 134 #---------------------------------------------------------------------------
90 135 # 'RichIPythonWidget' protected interface
91 136 #---------------------------------------------------------------------------
92 137
138 def _append_svg(self, svg):
139 """ Append raw svg data to the widget.
140 """
141 try:
142 image = svg_to_image(svg)
143 except ValueError:
144 self._append_plain_text('Received invalid plot data.')
145 else:
146 format = self._add_image(image)
147 self._name_to_svg[str(format.name())] = svg
148 format.setProperty(self._svg_text_format_property, svg)
149 cursor = self._get_end_cursor()
150 cursor.insertBlock()
151 cursor.insertImage(format)
152 cursor.insertBlock()
153
154 def _append_png(self, png):
155 """ Append raw svg data to the widget.
156 """
157 try:
158 image = QtGui.QImage()
159 image.loadFromData(png, 'PNG')
160 except ValueError:
161 self._append_plain_text('Received invalid plot data.')
162 else:
163 format = self._add_image(image)
164 cursor = self._get_end_cursor()
165 cursor.insertBlock()
166 cursor.insertImage(format)
167 cursor.insertBlock()
168
93 169 def _add_image(self, image):
94 170 """ Adds the specified QImage to the document and returns a
95 171 QTextImageFormat that references it.
96 172 """
97 173 document = self._control.document()
98 174 name = QtCore.QString.number(image.cacheKey())
99 175 document.addResource(QtGui.QTextDocument.ImageResource,
100 176 QtCore.QUrl(name), image)
101 177 format = QtGui.QTextImageFormat()
102 178 format.setName(name)
103 179 return format
104 180
105 181 def _copy_image(self, name):
106 182 """ Copies the ImageResource with 'name' to the clipboard.
107 183 """
108 184 image = self._get_image(name)
109 185 QtGui.QApplication.clipboard().setImage(image)
110 186
111 187 def _get_image(self, name):
112 188 """ Returns the QImage stored as the ImageResource with 'name'.
113 189 """
114 190 document = self._control.document()
115 191 variant = document.resource(QtGui.QTextDocument.ImageResource,
116 192 QtCore.QUrl(name))
117 193 return variant.toPyObject()
118 194
119 195 def _save_image(self, name, format='PNG'):
120 196 """ Shows a save dialog for the ImageResource with 'name'.
121 197 """
122 198 dialog = QtGui.QFileDialog(self._control, 'Save Image')
123 199 dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
124 200 dialog.setDefaultSuffix(format.lower())
125 201 dialog.setNameFilter('%s file (*.%s)' % (format, format.lower()))
126 202 if dialog.exec_():
127 203 filename = dialog.selectedFiles()[0]
128 204 image = self._get_image(name)
129 205 image.save(filename, format)
130 206
131 207 def image_tag(self, match, path = None, format = "png"):
132 208 """ Return (X)HTML mark-up for the image-tag given by match.
133 209
134 210 Parameters
135 211 ----------
136 212 match : re.SRE_Match
137 213 A match to an HTML image tag as exported by Qt, with
138 214 match.group("Name") containing the matched image ID.
139 215
140 216 path : string|None, optional [default None]
141 217 If not None, specifies a path to which supporting files
142 218 may be written (e.g., for linked images).
143 219 If None, all images are to be included inline.
144 220
145 221 format : "png"|"svg", optional [default "png"]
146 222 Format for returned or referenced images.
147 223
148 224 Subclasses supporting image display should override this
149 225 method.
150 226 """
151 227
152 228 if(format == "png"):
153 229 try:
154 230 image = self._get_image(match.group("name"))
155 231 except KeyError:
156 232 return "<b>Couldn't find image %s</b>" % match.group("name")
157 233
158 234 if(path is not None):
159 235 if not os.path.exists(path):
160 236 os.mkdir(path)
161 237 relpath = os.path.basename(path)
162 238 if(image.save("%s/qt_img%s.png" % (path,match.group("name")),
163 239 "PNG")):
164 240 return '<img src="%s/qt_img%s.png">' % (relpath,
165 241 match.group("name"))
166 242 else:
167 243 return "<b>Couldn't save image!</b>"
168 244 else:
169 245 ba = QtCore.QByteArray()
170 246 buffer_ = QtCore.QBuffer(ba)
171 247 buffer_.open(QtCore.QIODevice.WriteOnly)
172 248 image.save(buffer_, "PNG")
173 249 buffer_.close()
174 250 return '<img src="data:image/png;base64,\n%s\n" />' % (
175 251 re.sub(r'(.{60})',r'\1\n',str(ba.toBase64())))
176 252
177 253 elif(format == "svg"):
178 254 try:
179 255 svg = str(self._name_to_svg[match.group("name")])
180 256 except KeyError:
181 257 return "<b>Couldn't find image %s</b>" % match.group("name")
182 258
183 259 # Not currently checking path, because it's tricky to find a
184 260 # cross-browser way to embed external SVG images (e.g., via
185 261 # object or embed tags).
186 262
187 263 # Chop stand-alone header from matplotlib SVG
188 264 offset = svg.find("<svg")
189 265 assert(offset > -1)
190 266
191 267 return svg[offset:]
192 268
193 269 else:
194 270 return '<b>Unrecognized image format</b>'
195
271
@@ -1,240 +1,242 b''
1 1 """ Defines a KernelManager that provides signals and slots.
2 2 """
3 3
4 4 # System library imports.
5 5 from PyQt4 import QtCore
6 6
7 7 # IPython imports.
8 8 from IPython.utils.traitlets import Type
9 9 from IPython.zmq.kernelmanager import KernelManager, SubSocketChannel, \
10 10 XReqSocketChannel, RepSocketChannel, HBSocketChannel
11 11 from util import MetaQObjectHasTraits, SuperQObject
12 12
13 13
14 14 class SocketChannelQObject(SuperQObject):
15 15
16 16 # Emitted when the channel is started.
17 17 started = QtCore.pyqtSignal()
18 18
19 19 # Emitted when the channel is stopped.
20 20 stopped = QtCore.pyqtSignal()
21 21
22 22 #---------------------------------------------------------------------------
23 23 # 'ZmqSocketChannel' interface
24 24 #---------------------------------------------------------------------------
25 25
26 26 def start(self):
27 27 """ Reimplemented to emit signal.
28 28 """
29 29 super(SocketChannelQObject, self).start()
30 30 self.started.emit()
31 31
32 32 def stop(self):
33 33 """ Reimplemented to emit signal.
34 34 """
35 35 super(SocketChannelQObject, self).stop()
36 36 self.stopped.emit()
37 37
38 38
39 39 class QtXReqSocketChannel(SocketChannelQObject, XReqSocketChannel):
40 40
41 41 # Emitted when any message is received.
42 42 message_received = QtCore.pyqtSignal(object)
43 43
44 44 # Emitted when a reply has been received for the corresponding request
45 45 # type.
46 46 execute_reply = QtCore.pyqtSignal(object)
47 47 complete_reply = QtCore.pyqtSignal(object)
48 48 object_info_reply = QtCore.pyqtSignal(object)
49 49
50 50 # Emitted when the first reply comes back.
51 51 first_reply = QtCore.pyqtSignal()
52 52
53 53 # Used by the first_reply signal logic to determine if a reply is the
54 54 # first.
55 55 _handlers_called = False
56 56
57 57 #---------------------------------------------------------------------------
58 58 # 'XReqSocketChannel' interface
59 59 #---------------------------------------------------------------------------
60 60
61 61 def call_handlers(self, msg):
62 62 """ Reimplemented to emit signals instead of making callbacks.
63 63 """
64 64 # Emit the generic signal.
65 65 self.message_received.emit(msg)
66 66
67 67 # Emit signals for specialized message types.
68 68 msg_type = msg['msg_type']
69 69 signal = getattr(self, msg_type, None)
70 70 if signal:
71 71 signal.emit(msg)
72 72
73 73 if not self._handlers_called:
74 74 self.first_reply.emit()
75 75 self._handlers_called = True
76 76
77 77 #---------------------------------------------------------------------------
78 78 # 'QtXReqSocketChannel' interface
79 79 #---------------------------------------------------------------------------
80 80
81 81 def reset_first_reply(self):
82 82 """ Reset the first_reply signal to fire again on the next reply.
83 83 """
84 84 self._handlers_called = False
85 85
86 86
87 87 class QtSubSocketChannel(SocketChannelQObject, SubSocketChannel):
88 88
89 89 # Emitted when any message is received.
90 90 message_received = QtCore.pyqtSignal(object)
91 91
92 92 # Emitted when a message of type 'stream' is received.
93 93 stream_received = QtCore.pyqtSignal(object)
94 94
95 95 # Emitted when a message of type 'pyin' is received.
96 96 pyin_received = QtCore.pyqtSignal(object)
97 97
98 98 # Emitted when a message of type 'pyout' is received.
99 99 pyout_received = QtCore.pyqtSignal(object)
100 100
101 101 # Emitted when a message of type 'pyerr' is received.
102 102 pyerr_received = QtCore.pyqtSignal(object)
103 103
104 # Emitted when a message of type 'display_data' is received
105 display_data_received = QtCore.pyqtSignal(object)
106
104 107 # Emitted when a crash report message is received from the kernel's
105 108 # last-resort sys.excepthook.
106 109 crash_received = QtCore.pyqtSignal(object)
107 110
108 111 # Emitted when a shutdown is noticed.
109 112 shutdown_reply_received = QtCore.pyqtSignal(object)
110 113
111 114 #---------------------------------------------------------------------------
112 115 # 'SubSocketChannel' interface
113 116 #---------------------------------------------------------------------------
114 117
115 118 def call_handlers(self, msg):
116 119 """ Reimplemented to emit signals instead of making callbacks.
117 120 """
118 121 # Emit the generic signal.
119 122 self.message_received.emit(msg)
120
121 123 # Emit signals for specialized message types.
122 124 msg_type = msg['msg_type']
123 125 signal = getattr(self, msg_type + '_received', None)
124 126 if signal:
125 127 signal.emit(msg)
126 128 elif msg_type in ('stdout', 'stderr'):
127 129 self.stream_received.emit(msg)
128 130
129 131 def flush(self):
130 132 """ Reimplemented to ensure that signals are dispatched immediately.
131 133 """
132 134 super(QtSubSocketChannel, self).flush()
133 135 QtCore.QCoreApplication.instance().processEvents()
134 136
135 137
136 138 class QtRepSocketChannel(SocketChannelQObject, RepSocketChannel):
137 139
138 140 # Emitted when any message is received.
139 141 message_received = QtCore.pyqtSignal(object)
140 142
141 143 # Emitted when an input request is received.
142 144 input_requested = QtCore.pyqtSignal(object)
143 145
144 146 #---------------------------------------------------------------------------
145 147 # 'RepSocketChannel' interface
146 148 #---------------------------------------------------------------------------
147 149
148 150 def call_handlers(self, msg):
149 151 """ Reimplemented to emit signals instead of making callbacks.
150 152 """
151 153 # Emit the generic signal.
152 154 self.message_received.emit(msg)
153 155
154 156 # Emit signals for specialized message types.
155 157 msg_type = msg['msg_type']
156 158 if msg_type == 'input_request':
157 159 self.input_requested.emit(msg)
158 160
159 161
160 162 class QtHBSocketChannel(SocketChannelQObject, HBSocketChannel):
161 163
162 164 # Emitted when the kernel has died.
163 165 kernel_died = QtCore.pyqtSignal(object)
164 166
165 167 #---------------------------------------------------------------------------
166 168 # 'HBSocketChannel' interface
167 169 #---------------------------------------------------------------------------
168 170
169 171 def call_handlers(self, since_last_heartbeat):
170 172 """ Reimplemented to emit signals instead of making callbacks.
171 173 """
172 174 # Emit the generic signal.
173 175 self.kernel_died.emit(since_last_heartbeat)
174 176
175 177
176 178 class QtKernelManager(KernelManager, SuperQObject):
177 179 """ A KernelManager that provides signals and slots.
178 180 """
179 181
180 182 __metaclass__ = MetaQObjectHasTraits
181 183
182 184 # Emitted when the kernel manager has started listening.
183 185 started_channels = QtCore.pyqtSignal()
184 186
185 187 # Emitted when the kernel manager has stopped listening.
186 188 stopped_channels = QtCore.pyqtSignal()
187 189
188 190 # Use Qt-specific channel classes that emit signals.
189 191 sub_channel_class = Type(QtSubSocketChannel)
190 192 xreq_channel_class = Type(QtXReqSocketChannel)
191 193 rep_channel_class = Type(QtRepSocketChannel)
192 194 hb_channel_class = Type(QtHBSocketChannel)
193 195
194 196 #---------------------------------------------------------------------------
195 197 # 'KernelManager' interface
196 198 #---------------------------------------------------------------------------
197 199
198 200 #------ Kernel process management ------------------------------------------
199 201
200 202 def start_kernel(self, *args, **kw):
201 203 """ Reimplemented for proper heartbeat management.
202 204 """
203 205 if self._xreq_channel is not None:
204 206 self._xreq_channel.reset_first_reply()
205 207 super(QtKernelManager, self).start_kernel(*args, **kw)
206 208
207 209 #------ Channel management -------------------------------------------------
208 210
209 211 def start_channels(self, *args, **kw):
210 212 """ Reimplemented to emit signal.
211 213 """
212 214 super(QtKernelManager, self).start_channels(*args, **kw)
213 215 self.started_channels.emit()
214 216
215 217 def stop_channels(self):
216 218 """ Reimplemented to emit signal.
217 219 """
218 220 super(QtKernelManager, self).stop_channels()
219 221 self.stopped_channels.emit()
220 222
221 223 @property
222 224 def xreq_channel(self):
223 225 """ Reimplemented for proper heartbeat management.
224 226 """
225 227 if self._xreq_channel is None:
226 228 self._xreq_channel = super(QtKernelManager, self).xreq_channel
227 229 self._xreq_channel.first_reply.connect(self._first_reply)
228 230 return self._xreq_channel
229 231
230 232 #---------------------------------------------------------------------------
231 233 # Protected interface
232 234 #---------------------------------------------------------------------------
233 235
234 236 def _first_reply(self):
235 237 """ Unpauses the heartbeat channel when the first reply is received on
236 238 the execute channel. Note that this will *not* start the heartbeat
237 239 channel if it is not already running!
238 240 """
239 241 if self._hb_channel is not None:
240 242 self._hb_channel.unpause()
@@ -1,664 +1,664 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The :class:`~IPython.core.application.Application` object for the command
5 5 line :command:`ipython` program.
6 6
7 7 Authors
8 8 -------
9 9
10 10 * Brian Granger
11 11 * Fernando Perez
12 12 """
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Copyright (C) 2008-2010 The IPython Development Team
16 16 #
17 17 # Distributed under the terms of the BSD License. The full license is in
18 18 # the file COPYING, distributed as part of this software.
19 19 #-----------------------------------------------------------------------------
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 24
25 25 from __future__ import absolute_import
26 26
27 27 import logging
28 28 import os
29 29 import sys
30 30
31 31 from IPython.core import release
32 32 from IPython.core.crashhandler import CrashHandler
33 33 from IPython.core.application import Application, BaseAppConfigLoader
34 34 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
35 35 from IPython.config.loader import (
36 36 Config,
37 37 PyFileConfigLoader
38 38 )
39 39 from IPython.lib import inputhook
40 40 from IPython.utils.path import filefind, get_ipython_dir
41 41 from IPython.core import usage
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # Globals, utilities and helpers
45 45 #-----------------------------------------------------------------------------
46 46
47 47 #: The default config file name for this application.
48 48 default_config_file_name = u'ipython_config.py'
49 49
50 50
51 51 class IPAppConfigLoader(BaseAppConfigLoader):
52 52
53 53 def _add_arguments(self):
54 54 super(IPAppConfigLoader, self)._add_arguments()
55 55 paa = self.parser.add_argument
56 56 paa('-p',
57 57 '--profile', dest='Global.profile', type=unicode,
58 58 help=
59 59 """The string name of the ipython profile to be used. Assume that your
60 60 config file is ipython_config-<name>.py (looks in current dir first,
61 61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
62 62 config files for different tasks, especially if include your basic one
63 63 in your more specialized ones. You can keep a basic
64 64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
65 65 include this one and load extra things for particular tasks.""",
66 66 metavar='Global.profile')
67 67 paa('--config-file',
68 68 dest='Global.config_file', type=unicode,
69 69 help=
70 70 """Set the config file name to override default. Normally IPython
71 71 loads ipython_config.py (from current directory) or
72 72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
73 73 fails, IPython starts with a bare bones configuration (no modules
74 74 loaded at all).""",
75 75 metavar='Global.config_file')
76 76 paa('--autocall',
77 77 dest='InteractiveShell.autocall', type=int,
78 78 help=
79 79 """Make IPython automatically call any callable object even if you
80 80 didn't type explicit parentheses. For example, 'str 43' becomes
81 81 'str(43)' automatically. The value can be '0' to disable the feature,
82 82 '1' for 'smart' autocall, where it is not applied if there are no more
83 83 arguments on the line, and '2' for 'full' autocall, where all callable
84 84 objects are automatically called (even if no arguments are present).
85 85 The default is '1'.""",
86 86 metavar='InteractiveShell.autocall')
87 87 paa('--autoindent',
88 88 action='store_true', dest='InteractiveShell.autoindent',
89 89 help='Turn on autoindenting.')
90 90 paa('--no-autoindent',
91 91 action='store_false', dest='InteractiveShell.autoindent',
92 92 help='Turn off autoindenting.')
93 93 paa('--automagic',
94 94 action='store_true', dest='InteractiveShell.automagic',
95 95 help=
96 96 """Turn on the auto calling of magic commands. Type %%magic at the
97 97 IPython prompt for more information.""")
98 98 paa('--no-automagic',
99 99 action='store_false', dest='InteractiveShell.automagic',
100 100 help='Turn off the auto calling of magic commands.')
101 101 paa('--autoedit-syntax',
102 102 action='store_true', dest='TerminalInteractiveShell.autoedit_syntax',
103 103 help='Turn on auto editing of files with syntax errors.')
104 104 paa('--no-autoedit-syntax',
105 105 action='store_false', dest='TerminalInteractiveShell.autoedit_syntax',
106 106 help='Turn off auto editing of files with syntax errors.')
107 107 paa('--banner',
108 108 action='store_true', dest='Global.display_banner',
109 109 help='Display a banner upon starting IPython.')
110 110 paa('--no-banner',
111 111 action='store_false', dest='Global.display_banner',
112 112 help="Don't display a banner upon starting IPython.")
113 113 paa('--cache-size',
114 114 type=int, dest='InteractiveShell.cache_size',
115 115 help=
116 116 """Set the size of the output cache. The default is 1000, you can
117 117 change it permanently in your config file. Setting it to 0 completely
118 118 disables the caching system, and the minimum value accepted is 20 (if
119 119 you provide a value less than 20, it is reset to 0 and a warning is
120 120 issued). This limit is defined because otherwise you'll spend more
121 121 time re-flushing a too small cache than working""",
122 122 metavar='InteractiveShell.cache_size')
123 123 paa('--classic',
124 124 action='store_true', dest='Global.classic',
125 125 help="Gives IPython a similar feel to the classic Python prompt.")
126 126 paa('--colors',
127 127 type=str, dest='InteractiveShell.colors',
128 128 help="Set the color scheme (NoColor, Linux, and LightBG).",
129 129 metavar='InteractiveShell.colors')
130 130 paa('--color-info',
131 131 action='store_true', dest='InteractiveShell.color_info',
132 132 help=
133 133 """IPython can display information about objects via a set of func-
134 134 tions, and optionally can use colors for this, syntax highlighting
135 135 source code and various other elements. However, because this
136 136 information is passed through a pager (like 'less') and many pagers get
137 137 confused with color codes, this option is off by default. You can test
138 138 it and turn it on permanently in your ipython_config.py file if it
139 139 works for you. Test it and turn it on permanently if it works with
140 140 your system. The magic function %%color_info allows you to toggle this
141 141 inter- actively for testing.""")
142 142 paa('--no-color-info',
143 143 action='store_false', dest='InteractiveShell.color_info',
144 144 help="Disable using colors for info related things.")
145 145 paa('--confirm-exit',
146 146 action='store_true', dest='TerminalInteractiveShell.confirm_exit',
147 147 help=
148 148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 150 '%%Exit', you can force a direct exit without any confirmation.""")
151 151 paa('--no-confirm-exit',
152 152 action='store_false', dest='TerminalInteractiveShell.confirm_exit',
153 153 help="Don't prompt the user when exiting.")
154 154 paa('--deep-reload',
155 155 action='store_true', dest='InteractiveShell.deep_reload',
156 156 help=
157 157 """Enable deep (recursive) reloading by default. IPython can use the
158 158 deep_reload module which reloads changes in modules recursively (it
159 159 replaces the reload() function, so you don't need to change anything to
160 160 use it). deep_reload() forces a full reload of modules whose code may
161 161 have changed, which the default reload() function does not. When
162 162 deep_reload is off, IPython will use the normal reload(), but
163 163 deep_reload will still be available as dreload(). This fea- ture is off
164 164 by default [which means that you have both normal reload() and
165 165 dreload()].""")
166 166 paa('--no-deep-reload',
167 167 action='store_false', dest='InteractiveShell.deep_reload',
168 168 help="Disable deep (recursive) reloading by default.")
169 169 paa('--editor',
170 170 type=str, dest='TerminalInteractiveShell.editor',
171 171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 172 metavar='TerminalInteractiveShell.editor')
173 173 paa('--log','-l',
174 174 action='store_true', dest='InteractiveShell.logstart',
175 175 help="Start logging to the default log file (./ipython_log.py).")
176 176 paa('--logfile','-lf',
177 177 type=unicode, dest='InteractiveShell.logfile',
178 178 help="Start logging to logfile with this name.",
179 179 metavar='InteractiveShell.logfile')
180 180 paa('--log-append','-la',
181 181 type=unicode, dest='InteractiveShell.logappend',
182 182 help="Start logging to the given file in append mode.",
183 183 metavar='InteractiveShell.logfile')
184 184 paa('--pdb',
185 185 action='store_true', dest='InteractiveShell.pdb',
186 186 help="Enable auto calling the pdb debugger after every exception.")
187 187 paa('--no-pdb',
188 188 action='store_false', dest='InteractiveShell.pdb',
189 189 help="Disable auto calling the pdb debugger after every exception.")
190 190 paa('--pprint',
191 action='store_true', dest='InteractiveShell.pprint',
191 action='store_true', dest='PlainTextFormatter.pprint',
192 192 help="Enable auto pretty printing of results.")
193 193 paa('--no-pprint',
194 action='store_false', dest='InteractiveShell.pprint',
194 action='store_false', dest='PlainTextFormatter.pprint',
195 195 help="Disable auto auto pretty printing of results.")
196 196 paa('--prompt-in1','-pi1',
197 197 type=str, dest='InteractiveShell.prompt_in1',
198 198 help=
199 199 """Set the main input prompt ('In [\#]: '). Note that if you are using
200 200 numbered prompts, the number is represented with a '\#' in the string.
201 201 Don't forget to quote strings with spaces embedded in them. Most
202 202 bash-like escapes can be used to customize IPython's prompts, as well
203 203 as a few additional ones which are IPython-spe- cific. All valid
204 204 prompt escapes are described in detail in the Customization section of
205 205 the IPython manual.""",
206 206 metavar='InteractiveShell.prompt_in1')
207 207 paa('--prompt-in2','-pi2',
208 208 type=str, dest='InteractiveShell.prompt_in2',
209 209 help=
210 210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
211 211 option, but used for the continuation prompts. The special sequence
212 212 '\D' is similar to '\#', but with all digits replaced by dots (so you
213 213 can have your continuation prompt aligned with your input prompt).
214 214 Default: ' .\D.: ' (note three spaces at the start for alignment with
215 215 'In [\#]')""",
216 216 metavar='InteractiveShell.prompt_in2')
217 217 paa('--prompt-out','-po',
218 218 type=str, dest='InteractiveShell.prompt_out',
219 219 help="Set the output prompt ('Out[\#]:')",
220 220 metavar='InteractiveShell.prompt_out')
221 221 paa('--quick',
222 222 action='store_true', dest='Global.quick',
223 223 help="Enable quick startup with no config files.")
224 224 paa('--readline',
225 225 action='store_true', dest='InteractiveShell.readline_use',
226 226 help="Enable readline for command line usage.")
227 227 paa('--no-readline',
228 228 action='store_false', dest='InteractiveShell.readline_use',
229 229 help="Disable readline for command line usage.")
230 230 paa('--screen-length','-sl',
231 231 type=int, dest='TerminalInteractiveShell.screen_length',
232 232 help=
233 233 """Number of lines of your screen, used to control printing of very
234 234 long strings. Strings longer than this number of lines will be sent
235 235 through a pager instead of directly printed. The default value for
236 236 this is 0, which means IPython will auto-detect your screen size every
237 237 time it needs to print certain potentially long strings (this doesn't
238 238 change the behavior of the 'print' keyword, it's only triggered
239 239 internally). If for some reason this isn't working well (it needs
240 240 curses support), specify it yourself. Otherwise don't change the
241 241 default.""",
242 242 metavar='TerminalInteractiveShell.screen_length')
243 243 paa('--separate-in','-si',
244 244 type=str, dest='InteractiveShell.separate_in',
245 245 help="Separator before input prompts. Default '\\n'.",
246 246 metavar='InteractiveShell.separate_in')
247 247 paa('--separate-out','-so',
248 248 type=str, dest='InteractiveShell.separate_out',
249 249 help="Separator before output prompts. Default 0 (nothing).",
250 250 metavar='InteractiveShell.separate_out')
251 251 paa('--separate-out2','-so2',
252 252 type=str, dest='InteractiveShell.separate_out2',
253 253 help="Separator after output prompts. Default 0 (nonight).",
254 254 metavar='InteractiveShell.separate_out2')
255 255 paa('--no-sep',
256 256 action='store_true', dest='Global.nosep',
257 257 help="Eliminate all spacing between prompts.")
258 258 paa('--term-title',
259 259 action='store_true', dest='TerminalInteractiveShell.term_title',
260 260 help="Enable auto setting the terminal title.")
261 261 paa('--no-term-title',
262 262 action='store_false', dest='TerminalInteractiveShell.term_title',
263 263 help="Disable auto setting the terminal title.")
264 264 paa('--xmode',
265 265 type=str, dest='InteractiveShell.xmode',
266 266 help=
267 267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
268 268 similar to python's normal traceback printing. Context: prints 5 lines
269 269 of context source code around each line in the traceback. Verbose:
270 270 similar to Context, but additionally prints the variables currently
271 271 visible where the exception happened (shortening their strings if too
272 272 long). This can potentially be very slow, if you happen to have a huge
273 273 data structure whose string representation is complex to compute.
274 274 Your computer may appear to freeze for a while with cpu usage at 100%%.
275 275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
276 276 it more than once).
277 277 """,
278 278 metavar='InteractiveShell.xmode')
279 279 paa('--ext',
280 280 type=str, dest='Global.extra_extension',
281 281 help="The dotted module name of an IPython extension to load.",
282 282 metavar='Global.extra_extension')
283 283 paa('-c',
284 284 type=str, dest='Global.code_to_run',
285 285 help="Execute the given command string.",
286 286 metavar='Global.code_to_run')
287 287 paa('-i',
288 288 action='store_true', dest='Global.force_interact',
289 289 help=
290 290 "If running code from the command line, become interactive afterwards.")
291 291
292 292 # Options to start with GUI control enabled from the beginning
293 293 paa('--gui',
294 294 type=str, dest='Global.gui',
295 295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
296 296 metavar='gui-mode')
297 297 paa('--pylab','-pylab',
298 298 type=str, dest='Global.pylab',
299 299 nargs='?', const='auto', metavar='gui-mode',
300 300 help="Pre-load matplotlib and numpy for interactive use. "+
301 301 "If no value is given, the gui backend is matplotlib's, else use "+
302 302 "one of: ['tk', 'qt', 'wx', 'gtk'].")
303 303
304 304 # Legacy GUI options. Leave them in for backwards compatibility, but the
305 305 # 'thread' names are really a misnomer now.
306 306 paa('--wthread', '-wthread',
307 307 action='store_true', dest='Global.wthread',
308 308 help=
309 309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
310 310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
311 311 action='store_true', dest='Global.q4thread',
312 312 help=
313 313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
314 314 (DEPRECATED, use --gui qt)""")
315 315 paa('--gthread', '-gthread',
316 316 action='store_true', dest='Global.gthread',
317 317 help=
318 318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
319 319
320 320
321 321 #-----------------------------------------------------------------------------
322 322 # Crash handler for this application
323 323 #-----------------------------------------------------------------------------
324 324
325 325 _message_template = """\
326 326 Oops, $self.app_name crashed. We do our best to make it stable, but...
327 327
328 328 A crash report was automatically generated with the following information:
329 329 - A verbatim copy of the crash traceback.
330 330 - A copy of your input history during this session.
331 331 - Data on your current $self.app_name configuration.
332 332
333 333 It was left in the file named:
334 334 \t'$self.crash_report_fname'
335 335 If you can email this file to the developers, the information in it will help
336 336 them in understanding and correcting the problem.
337 337
338 338 You can mail it to: $self.contact_name at $self.contact_email
339 339 with the subject '$self.app_name Crash Report'.
340 340
341 341 If you want to do it now, the following command will work (under Unix):
342 342 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
343 343
344 344 To ensure accurate tracking of this issue, please file a report about it at:
345 345 $self.bug_tracker
346 346 """
347 347
348 348 class IPAppCrashHandler(CrashHandler):
349 349 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
350 350
351 351 message_template = _message_template
352 352
353 353 def __init__(self, app):
354 354 contact_name = release.authors['Fernando'][0]
355 355 contact_email = release.authors['Fernando'][1]
356 356 bug_tracker = 'http://github.com/ipython/ipython/issues'
357 357 super(IPAppCrashHandler,self).__init__(
358 358 app, contact_name, contact_email, bug_tracker
359 359 )
360 360
361 361 def make_report(self,traceback):
362 362 """Return a string containing a crash report."""
363 363
364 364 sec_sep = self.section_sep
365 365 # Start with parent report
366 366 report = [super(IPAppCrashHandler, self).make_report(traceback)]
367 367 # Add interactive-specific info we may have
368 368 rpt_add = report.append
369 369 try:
370 370 rpt_add(sec_sep+"History of session input:")
371 371 for line in self.app.shell.user_ns['_ih']:
372 372 rpt_add(line)
373 373 rpt_add('\n*** Last line of input (may not be in above history):\n')
374 374 rpt_add(self.app.shell._last_input_line+'\n')
375 375 except:
376 376 pass
377 377
378 378 return ''.join(report)
379 379
380 380
381 381 #-----------------------------------------------------------------------------
382 382 # Main classes and functions
383 383 #-----------------------------------------------------------------------------
384 384
385 385 class IPythonApp(Application):
386 386 name = u'ipython'
387 387 #: argparse formats better the 'usage' than the 'description' field
388 388 description = None
389 389 usage = usage.cl_usage
390 390 command_line_loader = IPAppConfigLoader
391 391 default_config_file_name = default_config_file_name
392 392 crash_handler_class = IPAppCrashHandler
393 393
394 394 def create_default_config(self):
395 395 super(IPythonApp, self).create_default_config()
396 396 # Eliminate multiple lookups
397 397 Global = self.default_config.Global
398 398
399 399 # Set all default values
400 400 Global.display_banner = True
401 401
402 402 # If the -c flag is given or a file is given to run at the cmd line
403 403 # like "ipython foo.py", normally we exit without starting the main
404 404 # loop. The force_interact config variable allows a user to override
405 405 # this and interact. It is also set by the -i cmd line flag, just
406 406 # like Python.
407 407 Global.force_interact = False
408 408
409 409 # By default always interact by starting the IPython mainloop.
410 410 Global.interact = True
411 411
412 412 # No GUI integration by default
413 413 Global.gui = False
414 414 # Pylab off by default
415 415 Global.pylab = False
416 416
417 417 # Deprecated versions of gui support that used threading, we support
418 418 # them just for bacwards compatibility as an alternate spelling for
419 419 # '--gui X'
420 420 Global.qthread = False
421 421 Global.q4thread = False
422 422 Global.wthread = False
423 423 Global.gthread = False
424 424
425 425 def load_file_config(self):
426 426 if hasattr(self.command_line_config.Global, 'quick'):
427 427 if self.command_line_config.Global.quick:
428 428 self.file_config = Config()
429 429 return
430 430 super(IPythonApp, self).load_file_config()
431 431
432 432 def post_load_file_config(self):
433 433 if hasattr(self.command_line_config.Global, 'extra_extension'):
434 434 if not hasattr(self.file_config.Global, 'extensions'):
435 435 self.file_config.Global.extensions = []
436 436 self.file_config.Global.extensions.append(
437 437 self.command_line_config.Global.extra_extension)
438 438 del self.command_line_config.Global.extra_extension
439 439
440 440 def pre_construct(self):
441 441 config = self.master_config
442 442
443 443 if hasattr(config.Global, 'classic'):
444 444 if config.Global.classic:
445 445 config.InteractiveShell.cache_size = 0
446 config.InteractiveShell.pprint = 0
446 config.PlainTextFormatter.pprint = 0
447 447 config.InteractiveShell.prompt_in1 = '>>> '
448 448 config.InteractiveShell.prompt_in2 = '... '
449 449 config.InteractiveShell.prompt_out = ''
450 450 config.InteractiveShell.separate_in = \
451 451 config.InteractiveShell.separate_out = \
452 452 config.InteractiveShell.separate_out2 = ''
453 453 config.InteractiveShell.colors = 'NoColor'
454 454 config.InteractiveShell.xmode = 'Plain'
455 455
456 456 if hasattr(config.Global, 'nosep'):
457 457 if config.Global.nosep:
458 458 config.InteractiveShell.separate_in = \
459 459 config.InteractiveShell.separate_out = \
460 460 config.InteractiveShell.separate_out2 = ''
461 461
462 462 # if there is code of files to run from the cmd line, don't interact
463 463 # unless the -i flag (Global.force_interact) is true.
464 464 code_to_run = config.Global.get('code_to_run','')
465 465 file_to_run = False
466 466 if self.extra_args and self.extra_args[0]:
467 467 file_to_run = True
468 468 if file_to_run or code_to_run:
469 469 if not config.Global.force_interact:
470 470 config.Global.interact = False
471 471
472 472 def construct(self):
473 473 # I am a little hesitant to put these into InteractiveShell itself.
474 474 # But that might be the place for them
475 475 sys.path.insert(0, '')
476 476
477 477 # Create an InteractiveShell instance.
478 478 self.shell = TerminalInteractiveShell.instance(config=self.master_config)
479 479
480 480 def post_construct(self):
481 481 """Do actions after construct, but before starting the app."""
482 482 config = self.master_config
483 483
484 484 # shell.display_banner should always be False for the terminal
485 485 # based app, because we call shell.show_banner() by hand below
486 486 # so the banner shows *before* all extension loading stuff.
487 487 self.shell.display_banner = False
488 488 if config.Global.display_banner and \
489 489 config.Global.interact:
490 490 self.shell.show_banner()
491 491
492 492 # Make sure there is a space below the banner.
493 493 if self.log_level <= logging.INFO: print
494 494
495 495 # Now a variety of things that happen after the banner is printed.
496 496 self._enable_gui_pylab()
497 497 self._load_extensions()
498 498 self._run_exec_lines()
499 499 self._run_exec_files()
500 500 self._run_cmd_line_code()
501 501
502 502 def _enable_gui_pylab(self):
503 503 """Enable GUI event loop integration, taking pylab into account."""
504 504 Global = self.master_config.Global
505 505
506 506 # Select which gui to use
507 507 if Global.gui:
508 508 gui = Global.gui
509 509 # The following are deprecated, but there's likely to be a lot of use
510 510 # of this form out there, so we might as well support it for now. But
511 511 # the --gui option above takes precedence.
512 512 elif Global.wthread:
513 513 gui = inputhook.GUI_WX
514 514 elif Global.qthread:
515 515 gui = inputhook.GUI_QT
516 516 elif Global.gthread:
517 517 gui = inputhook.GUI_GTK
518 518 else:
519 519 gui = None
520 520
521 521 # Using --pylab will also require gui activation, though which toolkit
522 522 # to use may be chosen automatically based on mpl configuration.
523 523 if Global.pylab:
524 524 activate = self.shell.enable_pylab
525 525 if Global.pylab == 'auto':
526 526 gui = None
527 527 else:
528 528 gui = Global.pylab
529 529 else:
530 530 # Enable only GUI integration, no pylab
531 531 activate = inputhook.enable_gui
532 532
533 533 if gui or Global.pylab:
534 534 try:
535 535 self.log.info("Enabling GUI event loop integration, "
536 536 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
537 537 activate(gui)
538 538 except:
539 539 self.log.warn("Error in enabling GUI event loop integration:")
540 540 self.shell.showtraceback()
541 541
542 542 def _load_extensions(self):
543 543 """Load all IPython extensions in Global.extensions.
544 544
545 545 This uses the :meth:`ExtensionManager.load_extensions` to load all
546 546 the extensions listed in ``self.master_config.Global.extensions``.
547 547 """
548 548 try:
549 549 if hasattr(self.master_config.Global, 'extensions'):
550 550 self.log.debug("Loading IPython extensions...")
551 551 extensions = self.master_config.Global.extensions
552 552 for ext in extensions:
553 553 try:
554 554 self.log.info("Loading IPython extension: %s" % ext)
555 555 self.shell.extension_manager.load_extension(ext)
556 556 except:
557 557 self.log.warn("Error in loading extension: %s" % ext)
558 558 self.shell.showtraceback()
559 559 except:
560 560 self.log.warn("Unknown error in loading extensions:")
561 561 self.shell.showtraceback()
562 562
563 563 def _run_exec_lines(self):
564 564 """Run lines of code in Global.exec_lines in the user's namespace."""
565 565 try:
566 566 if hasattr(self.master_config.Global, 'exec_lines'):
567 567 self.log.debug("Running code from Global.exec_lines...")
568 568 exec_lines = self.master_config.Global.exec_lines
569 569 for line in exec_lines:
570 570 try:
571 571 self.log.info("Running code in user namespace: %s" %
572 572 line)
573 573 self.shell.run_cell(line)
574 574 except:
575 575 self.log.warn("Error in executing line in user "
576 576 "namespace: %s" % line)
577 577 self.shell.showtraceback()
578 578 except:
579 579 self.log.warn("Unknown error in handling Global.exec_lines:")
580 580 self.shell.showtraceback()
581 581
582 582 def _exec_file(self, fname):
583 583 full_filename = filefind(fname, [u'.', self.ipython_dir])
584 584 if os.path.isfile(full_filename):
585 585 if full_filename.endswith(u'.py'):
586 586 self.log.info("Running file in user namespace: %s" %
587 587 full_filename)
588 588 # Ensure that __file__ is always defined to match Python behavior
589 589 self.shell.user_ns['__file__'] = fname
590 590 try:
591 591 self.shell.safe_execfile(full_filename, self.shell.user_ns)
592 592 finally:
593 593 del self.shell.user_ns['__file__']
594 594 elif full_filename.endswith('.ipy'):
595 595 self.log.info("Running file in user namespace: %s" %
596 596 full_filename)
597 597 self.shell.safe_execfile_ipy(full_filename)
598 598 else:
599 599 self.log.warn("File does not have a .py or .ipy extension: <%s>"
600 600 % full_filename)
601 601 def _run_exec_files(self):
602 602 try:
603 603 if hasattr(self.master_config.Global, 'exec_files'):
604 604 self.log.debug("Running files in Global.exec_files...")
605 605 exec_files = self.master_config.Global.exec_files
606 606 for fname in exec_files:
607 607 self._exec_file(fname)
608 608 except:
609 609 self.log.warn("Unknown error in handling Global.exec_files:")
610 610 self.shell.showtraceback()
611 611
612 612 def _run_cmd_line_code(self):
613 613 if hasattr(self.master_config.Global, 'code_to_run'):
614 614 line = self.master_config.Global.code_to_run
615 615 try:
616 616 self.log.info("Running code given at command line (-c): %s" %
617 617 line)
618 618 self.shell.run_cell(line)
619 619 except:
620 620 self.log.warn("Error in executing line in user namespace: %s" %
621 621 line)
622 622 self.shell.showtraceback()
623 623 return
624 624 # Like Python itself, ignore the second if the first of these is present
625 625 try:
626 626 fname = self.extra_args[0]
627 627 except:
628 628 pass
629 629 else:
630 630 try:
631 631 self._exec_file(fname)
632 632 except:
633 633 self.log.warn("Error in executing file in user namespace: %s" %
634 634 fname)
635 635 self.shell.showtraceback()
636 636
637 637 def start_app(self):
638 638 if self.master_config.Global.interact:
639 639 self.log.debug("Starting IPython's mainloop...")
640 640 self.shell.mainloop()
641 641 else:
642 642 self.log.debug("IPython not interactive, start_app is no-op...")
643 643
644 644
645 645 def load_default_config(ipython_dir=None):
646 646 """Load the default config file from the default ipython_dir.
647 647
648 648 This is useful for embedded shells.
649 649 """
650 650 if ipython_dir is None:
651 651 ipython_dir = get_ipython_dir()
652 652 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
653 653 config = cl.load_config()
654 654 return config
655 655
656 656
657 657 def launch_new_instance():
658 658 """Create and run a full blown IPython instance"""
659 659 app = IPythonApp()
660 660 app.start()
661 661
662 662
663 663 if __name__ == '__main__':
664 664 launch_new_instance()
@@ -1,110 +1,110 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3
4 4 """This module contains blocking clients for the controller interfaces.
5 5
6 6 Unlike the clients in `asyncclient.py`, the clients in this module are fully
7 7 blocking. This means that methods on the clients return the actual results
8 8 rather than a deferred to the result. Also, we manage the Twisted reactor
9 9 for you. This is done by running the reactor in a thread.
10 10
11 11 The main classes in this module are:
12 12
13 13 * MultiEngineClient
14 14 * TaskClient
15 15 * Task
16 16 * CompositeError
17 17 """
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Copyright (C) 2008-2009 The IPython Development Team
21 21 #
22 22 # Distributed under the terms of the BSD License. The full license is in
23 23 # the file COPYING, distributed as part of this software.
24 24 #-----------------------------------------------------------------------------
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Warnings control
28 28 #-----------------------------------------------------------------------------
29 29
30 30 import warnings
31 31
32 32 # Twisted generates annoying warnings with Python 2.6, as will do other code
33 33 # that imports 'sets' as of today
34 34 warnings.filterwarnings('ignore', 'the sets module is deprecated',
35 35 DeprecationWarning )
36 36
37 37 # This one also comes from Twisted
38 38 warnings.filterwarnings('ignore', 'the sha module is deprecated',
39 39 DeprecationWarning)
40 40
41 41 #-----------------------------------------------------------------------------
42 42 # Imports
43 43 #-----------------------------------------------------------------------------
44 44
45 45 import sys
46 46
47 47 import twisted
48 48 from twisted.internet import reactor
49 49 from twisted.python import log
50 50
51 51 from IPython.kernel.clientconnector import ClientConnector, Cluster
52 52 from IPython.kernel.twistedutil import ReactorInThread
53 53 from IPython.kernel.twistedutil import blockingCallFromThread
54 54
55 55 # These enable various things
56 56 from IPython.kernel import codeutil
57 57
58 58 # Other things that the user will need
59 59 from IPython.kernel.task import MapTask, StringTask
60 60 from IPython.kernel.error import CompositeError
61 61
62 62 #-------------------------------------------------------------------------------
63 63 # Code
64 64 #-------------------------------------------------------------------------------
65 65
66 66 # PotentialZombieWarning is deprecated from Twisted 10.0.0 and above and
67 67 # using the filter on > 10.0.0 creates a warning itself.
68 68 if twisted.version.major < 10:
69 69 from twisted.internet.error import PotentialZombieWarning
70 70 warnings.simplefilter('ignore', PotentialZombieWarning)
71 71
72 72 _client_tub = ClientConnector()
73 73
74 74 get_multiengine_client = _client_tub.get_multiengine_client
75 75 get_task_client = _client_tub.get_task_client
76 76 MultiEngineClient = get_multiengine_client
77 77 TaskClient = get_task_client
78 78
79 79 # This isn't great. I should probably set this up in the ReactorInThread
80 80 # class below. But, it does work for now.
81 81 log.startLogging(sys.stdout, setStdout=0)
82 82
83 83 def _result_list_printer(obj, p, cycle):
84 84 if cycle:
85 85 return p.text('ResultList(...)')
86 86 return p.text(repr(obj))
87 87
88 88 # ResultList is a list subclass and will use the default pretty printer.
89 89 # This overrides that to use the __repr__ of ResultList.
90 90 ip = get_ipython()
91 ip.displayhook.default_formatter.for_type_by_name(
91 ip.display_formatter.formatters['text/plain'].for_type_by_name(
92 92 'IPython.kernel.multiengineclient', 'ResultList', _result_list_printer
93 93 )
94 94
95 95 # Now we start the reactor in a thread
96 96 rit = ReactorInThread()
97 97 rit.setDaemon(True)
98 98 rit.start()
99 99
100 100
101 101 __all__ = [
102 102 'MapTask',
103 103 'StringTask',
104 104 'MultiEngineClient',
105 105 'TaskClient',
106 106 'CompositeError',
107 107 'get_task_client',
108 108 'get_multiengine_client',
109 109 'Cluster'
110 110 ]
@@ -1,208 +1,280 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Pylab (matplotlib) support utilities.
3 3
4 4 Authors
5 5 -------
6 6
7 7 * Fernando Perez.
8 8 * Brian Granger
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2009 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 from cStringIO import StringIO
23
22 24 from IPython.utils.decorators import flag_calls
23 25
24 26 # If user specifies a GUI, that dictates the backend, otherwise we read the
25 27 # user's mpl default from the mpl rc structure
26 28 backends = {'tk': 'TkAgg',
27 29 'gtk': 'GTKAgg',
28 30 'wx': 'WXAgg',
29 31 'qt': 'Qt4Agg', # qt3 not supported
30 32 'qt4': 'Qt4Agg',
31 33 'inline' : 'module://IPython.zmq.pylab.backend_inline'}
32 34
33 35 #-----------------------------------------------------------------------------
34 # Main classes and functions
36 # Matplotlib utilities
37 #-----------------------------------------------------------------------------
38
39
40 def getfigs(*fig_nums):
41 """Get a list of matplotlib figures by figure numbers.
42
43 If no arguments are given, all available figures are returned. If the
44 argument list contains references to invalid figures, a warning is printed
45 but the function continues pasting further figures.
46
47 Parameters
48 ----------
49 figs : tuple
50 A tuple of ints giving the figure numbers of the figures to return.
51 """
52 from matplotlib._pylab_helpers import Gcf
53 if not fig_nums:
54 fig_managers = Gcf.get_all_fig_managers()
55 return [fm.canvas.figure for fm in fig_managers]
56 else:
57 figs = []
58 for num in fig_nums:
59 f = Gcf.figs.get(num)
60 if f is None:
61 print('Warning: figure %s not available.' % num)
62 figs.append(f.canvas.figure)
63 return figs
64
65
66 def figsize(sizex, sizey):
67 """Set the default figure size to be [sizex, sizey].
68
69 This is just an easy to remember, convenience wrapper that sets::
70
71 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
72 """
73 import matplotlib
74 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
75
76
77 def figure_to_svg(fig):
78 """Convert a figure to svg for inline display."""
79 fc = fig.get_facecolor()
80 ec = fig.get_edgecolor()
81 fig.set_facecolor('white')
82 fig.set_edgecolor('white')
83 try:
84 string_io = StringIO()
85 fig.canvas.print_figure(string_io, format='svg')
86 svg = string_io.getvalue()
87 finally:
88 fig.set_facecolor(fc)
89 fig.set_edgecolor(ec)
90 return svg
91
92
93 # We need a little factory function here to create the closure where
94 # safe_execfile can live.
95 def mpl_runner(safe_execfile):
96 """Factory to return a matplotlib-enabled runner for %run.
97
98 Parameters
99 ----------
100 safe_execfile : function
101 This must be a function with the same interface as the
102 :meth:`safe_execfile` method of IPython.
103
104 Returns
105 -------
106 A function suitable for use as the ``runner`` argument of the %run magic
107 function.
108 """
109
110 def mpl_execfile(fname,*where,**kw):
111 """matplotlib-aware wrapper around safe_execfile.
112
113 Its interface is identical to that of the :func:`execfile` builtin.
114
115 This is ultimately a call to execfile(), but wrapped in safeties to
116 properly handle interactive rendering."""
117
118 import matplotlib
119 import matplotlib.pylab as pylab
120
121 #print '*** Matplotlib runner ***' # dbg
122 # turn off rendering until end of script
123 is_interactive = matplotlib.rcParams['interactive']
124 matplotlib.interactive(False)
125 safe_execfile(fname,*where,**kw)
126 matplotlib.interactive(is_interactive)
127 # make rendering call now, if the user tried to do it
128 if pylab.draw_if_interactive.called:
129 pylab.draw()
130 pylab.draw_if_interactive.called = False
131
132 return mpl_execfile
133
134
135 #-----------------------------------------------------------------------------
136 # Code for initializing matplotlib and importing pylab
35 137 #-----------------------------------------------------------------------------
36 138
37 139
38 140 def find_gui_and_backend(gui=None):
39 141 """Given a gui string return the gui and mpl backend.
40 142
41 143 Parameters
42 144 ----------
43 145 gui : str
44 146 Can be one of ('tk','gtk','wx','qt','qt4','inline').
45 147
46 148 Returns
47 149 -------
48 150 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
49 151 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline').
50 152 """
51 153
52 154 import matplotlib
53 155
54 156 if gui:
55 157 # select backend based on requested gui
56 158 backend = backends[gui]
57 159 else:
58 160 backend = matplotlib.rcParams['backend']
59 161 # In this case, we need to find what the appropriate gui selection call
60 162 # should be for IPython, so we can activate inputhook accordingly
61 163 g2b = backends # maps gui names to mpl backend names
62 164 b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict
63 165 gui = b2g.get(backend, None)
64 166 return gui, backend
65 167
66 168
67 169 def activate_matplotlib(backend):
68 170 """Activate the given backend and set interactive to True."""
69 171
70 172 import matplotlib
71 173 if backend.startswith('module://'):
72 174 # Work around bug in matplotlib: matplotlib.use converts the
73 175 # backend_id to lowercase even if a module name is specified!
74 176 matplotlib.rcParams['backend'] = backend
75 177 else:
76 178 matplotlib.use(backend)
77 179 matplotlib.interactive(True)
78 180
79 181 # This must be imported last in the matplotlib series, after
80 182 # backend/interactivity choices have been made
81 183 import matplotlib.pylab as pylab
82 184
83 185 # XXX For now leave this commented out, but depending on discussions with
84 186 # mpl-dev, we may be able to allow interactive switching...
85 187 #import matplotlib.pyplot
86 188 #matplotlib.pyplot.switch_backend(backend)
87 189
88 190 pylab.show._needmain = False
89 191 # We need to detect at runtime whether show() is called by the user.
90 192 # For this, we wrap it into a decorator which adds a 'called' flag.
91 193 pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
92 194
93 195
94 196 def import_pylab(user_ns, backend, import_all=True, shell=None):
95 197 """Import the standard pylab symbols into user_ns."""
96 198
97 199 # Import numpy as np/pyplot as plt are conventions we're trying to
98 200 # somewhat standardize on. Making them available to users by default
99 201 # will greatly help this.
100 202 s = ("import numpy\n"
101 203 "import matplotlib\n"
102 204 "from matplotlib import pylab, mlab, pyplot\n"
103 205 "np = numpy\n"
104 206 "plt = pyplot\n"
105 207 )
106 208 exec s in user_ns
107 209
108 210 if shell is not None:
109 211 exec s in shell.user_ns_hidden
110 212 # If using our svg payload backend, register the post-execution
111 213 # function that will pick up the results for display. This can only be
112 214 # done with access to the real shell object.
113 215 if backend == backends['inline']:
114 from IPython.zmq.pylab.backend_inline import flush_svg, figsize
216 from IPython.zmq.pylab.backend_inline import flush_svg
115 217 from matplotlib import pyplot
116 218 shell.register_post_execute(flush_svg)
117 219 # The typical default figure size is too large for inline use. We
118 220 # might make this a user-configurable parameter later.
119 221 figsize(6.0, 4.0)
120 222 # Add 'figsize' to pyplot and to the user's namespace
121 223 user_ns['figsize'] = pyplot.figsize = figsize
122 224 shell.user_ns_hidden['figsize'] = figsize
123 else:
124 from IPython.zmq.pylab.backend_inline import pastefig
125 from matplotlib import pyplot
126 # Add 'paste' to pyplot and to the user's namespace
127 user_ns['pastefig'] = pyplot.pastefig = pastefig
225
226 # The old pastefig function has been replaced by display
227 # Always add this svg formatter so display works.
228 from IPython.zmq.pylab.backend_inline import figure_to_svg
229 from IPython.core.display import display, display_svg
230 svg_formatter = shell.display_formatter.formatters['image/svg+xml']
231 svg_formatter.for_type_by_name(
232 'matplotlib.figure','Figure',figure_to_svg
233 )
234 # Add display and display_png to the user's namespace
235 user_ns['display'] = display
236 shell.user_ns_hidden['display'] = display
237 user_ns['display_svg'] = display_svg
238 shell.user_ns_hidden['display_svg'] = display_svg
239 user_ns['getfigs'] = getfigs
240 shell.user_ns_hidden['getfigs'] = getfigs
128 241
129 242 if import_all:
130 243 s = ("from matplotlib.pylab import *\n"
131 244 "from numpy import *\n")
132 245 exec s in user_ns
133 246 if shell is not None:
134 247 exec s in shell.user_ns_hidden
135 248
136 249
137 250 def pylab_activate(user_ns, gui=None, import_all=True):
138 251 """Activate pylab mode in the user's namespace.
139 252
140 253 Loads and initializes numpy, matplotlib and friends for interactive use.
141 254
142 255 Parameters
143 256 ----------
144 257 user_ns : dict
145 258 Namespace where the imports will occur.
146 259
147 260 gui : optional, string
148 261 A valid gui name following the conventions of the %gui magic.
149 262
150 263 import_all : optional, boolean
151 264 If true, an 'import *' is done from numpy and pylab.
152 265
153 266 Returns
154 267 -------
155 268 The actual gui used (if not given as input, it was obtained from matplotlib
156 269 itself, and will be needed next to configure IPython's gui integration.
157 270 """
158 271 gui, backend = find_gui_and_backend(gui)
159 272 activate_matplotlib(backend)
160 273 import_pylab(user_ns, backend)
161 274
162 275 print """
163 276 Welcome to pylab, a matplotlib-based Python environment [backend: %s].
164 277 For more information, type 'help(pylab)'.""" % backend
165 278
166 279 return gui
167 280
168 # We need a little factory function here to create the closure where
169 # safe_execfile can live.
170 def mpl_runner(safe_execfile):
171 """Factory to return a matplotlib-enabled runner for %run.
172
173 Parameters
174 ----------
175 safe_execfile : function
176 This must be a function with the same interface as the
177 :meth:`safe_execfile` method of IPython.
178
179 Returns
180 -------
181 A function suitable for use as the ``runner`` argument of the %run magic
182 function.
183 """
184
185 def mpl_execfile(fname,*where,**kw):
186 """matplotlib-aware wrapper around safe_execfile.
187
188 Its interface is identical to that of the :func:`execfile` builtin.
189
190 This is ultimately a call to execfile(), but wrapped in safeties to
191 properly handle interactive rendering."""
192
193 import matplotlib
194 import matplotlib.pylab as pylab
195
196 #print '*** Matplotlib runner ***' # dbg
197 # turn off rendering until end of script
198 is_interactive = matplotlib.rcParams['interactive']
199 matplotlib.interactive(False)
200 safe_execfile(fname,*where,**kw)
201 matplotlib.interactive(is_interactive)
202 # make rendering call now, if the user tried to do it
203 if pylab.draw_if_interactive.called:
204 pylab.draw()
205 pylab.draw_if_interactive.called = False
206
207 return mpl_execfile
208
@@ -1,58 +1,49 b''
1 1 # encoding: utf-8
2 2 """Generic functions for extending IPython.
3 3
4 4 See http://cheeseshop.python.org/pypi/simplegeneric.
5
6 Here is an example from IPython.utils.text::
7
8 def print_lsstring(arg):
9 "Prettier (non-repr-like) and more informative printer for LSString"
10 print "LSString (.p, .n, .l, .s available). Value:"
11 print arg
12
13 print_lsstring = result_display.when_type(LSString)(print_lsstring)
14 5 """
15 6
16 7 #-----------------------------------------------------------------------------
17 8 # Copyright (C) 2008-2009 The IPython Development Team
18 9 #
19 10 # Distributed under the terms of the BSD License. The full license is in
20 11 # the file COPYING, distributed as part of this software.
21 12 #-----------------------------------------------------------------------------
22 13
23 14 #-----------------------------------------------------------------------------
24 15 # Imports
25 16 #-----------------------------------------------------------------------------
26 17
27 18 from IPython.core.error import TryNext
28 19 from IPython.external.simplegeneric import generic
29 20
30 21 #-----------------------------------------------------------------------------
31 22 # Imports
32 23 #-----------------------------------------------------------------------------
33 24
34 25
35 26 @generic
36 27 def inspect_object(obj):
37 28 """Called when you do obj?"""
38 29 raise TryNext
39 30
40 31
41 32 @generic
42 33 def complete_object(obj, prev_completions):
43 34 """Custom completer dispatching for python objects.
44 35
45 36 Parameters
46 37 ----------
47 38 obj : object
48 39 The object to complete.
49 40 prev_completions : list
50 41 List of attributes discovered so far.
51 42
52 43 This should return the list of attributes in obj. If you only wish to
53 44 add to the attributes already discovered normally, return
54 45 own_attrs + prev_completions.
55 46 """
56 47 raise TryNext
57 48
58 49
@@ -1,398 +1,396 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """A dict subclass that supports attribute style access.
4 4
5 5 Authors:
6 6
7 7 * Fernando Perez (original)
8 8 * Brian Granger (refactoring to a dict subclass)
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2008-2009 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 from IPython.utils.data import list2dict2
23 23
24 24 __all__ = ['Struct']
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Code
28 28 #-----------------------------------------------------------------------------
29 29
30 30
31 31 class Struct(dict):
32 32 """A dict subclass with attribute style access.
33 33
34 34 This dict subclass has a a few extra features:
35 35
36 36 * Attribute style access.
37 37 * Protection of class members (like keys, items) when using attribute
38 38 style access.
39 39 * The ability to restrict assignment to only existing keys.
40 40 * Intelligent merging.
41 41 * Overloaded operators.
42 42 """
43 43 _allownew = True
44 44 def __init__(self, *args, **kw):
45 45 """Initialize with a dictionary, another Struct, or data.
46 46
47 47 Parameters
48 48 ----------
49 49 args : dict, Struct
50 50 Initialize with one dict or Struct
51 51 kw : dict
52 52 Initialize with key, value pairs.
53 53
54 54 Examples
55 55 --------
56 56
57 57 >>> s = Struct(a=10,b=30)
58 58 >>> s.a
59 59 10
60 60 >>> s.b
61 61 30
62 62 >>> s2 = Struct(s,c=30)
63 63 >>> s2.keys()
64 64 ['a', 'c', 'b']
65 65 """
66 66 object.__setattr__(self, '_allownew', True)
67 67 dict.__init__(self, *args, **kw)
68 68
69 69 def __setitem__(self, key, value):
70 70 """Set an item with check for allownew.
71 71
72 72 Examples
73 73 --------
74 74
75 75 >>> s = Struct()
76 76 >>> s['a'] = 10
77 77 >>> s.allow_new_attr(False)
78 78 >>> s['a'] = 10
79 79 >>> s['a']
80 80 10
81 81 >>> try:
82 82 ... s['b'] = 20
83 83 ... except KeyError:
84 84 ... print 'this is not allowed'
85 85 ...
86 86 this is not allowed
87 87 """
88 88 if not self._allownew and not self.has_key(key):
89 89 raise KeyError(
90 90 "can't create new attribute %s when allow_new_attr(False)" % key)
91 91 dict.__setitem__(self, key, value)
92 92
93 93 def __setattr__(self, key, value):
94 94 """Set an attr with protection of class members.
95 95
96 96 This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to
97 97 :exc:`AttributeError`.
98 98
99 99 Examples
100 100 --------
101 101
102 102 >>> s = Struct()
103 103 >>> s.a = 10
104 104 >>> s.a
105 105 10
106 106 >>> try:
107 107 ... s.get = 10
108 108 ... except AttributeError:
109 109 ... print "you can't set a class member"
110 110 ...
111 111 you can't set a class member
112 112 """
113 113 # If key is an str it might be a class member or instance var
114 114 if isinstance(key, str):
115 115 # I can't simply call hasattr here because it calls getattr, which
116 116 # calls self.__getattr__, which returns True for keys in
117 117 # self._data. But I only want keys in the class and in
118 118 # self.__dict__
119 119 if key in self.__dict__ or hasattr(Struct, key):
120 120 raise AttributeError(
121 121 'attr %s is a protected member of class Struct.' % key
122 122 )
123 123 try:
124 124 self.__setitem__(key, value)
125 125 except KeyError, e:
126 126 raise AttributeError(e)
127 127
128 128 def __getattr__(self, key):
129 129 """Get an attr by calling :meth:`dict.__getitem__`.
130 130
131 131 Like :meth:`__setattr__`, this method converts :exc:`KeyError` to
132 132 :exc:`AttributeError`.
133 133
134 134 Examples
135 135 --------
136 136
137 137 >>> s = Struct(a=10)
138 138 >>> s.a
139 139 10
140 140 >>> type(s.get)
141 141 <type 'builtin_function_or_method'>
142 142 >>> try:
143 143 ... s.b
144 144 ... except AttributeError:
145 145 ... print "I don't have that key"
146 146 ...
147 147 I don't have that key
148 148 """
149 149 try:
150 150 result = self[key]
151 151 except KeyError:
152 152 raise AttributeError(key)
153 153 else:
154 154 return result
155 155
156 156 def __iadd__(self, other):
157 157 """s += s2 is a shorthand for s.merge(s2).
158 158
159 159 Examples
160 160 --------
161 161
162 162 >>> s = Struct(a=10,b=30)
163 163 >>> s2 = Struct(a=20,c=40)
164 164 >>> s += s2
165 165 >>> s
166 166 {'a': 10, 'c': 40, 'b': 30}
167 167 """
168 168 self.merge(other)
169 169 return self
170 170
171 171 def __add__(self,other):
172 172 """s + s2 -> New Struct made from s.merge(s2).
173 173
174 174 Examples
175 175 --------
176 176
177 177 >>> s1 = Struct(a=10,b=30)
178 178 >>> s2 = Struct(a=20,c=40)
179 179 >>> s = s1 + s2
180 180 >>> s
181 181 {'a': 10, 'c': 40, 'b': 30}
182 182 """
183 183 sout = self.copy()
184 184 sout.merge(other)
185 185 return sout
186 186
187 187 def __sub__(self,other):
188 188 """s1 - s2 -> remove keys in s2 from s1.
189 189
190 190 Examples
191 191 --------
192 192
193 193 >>> s1 = Struct(a=10,b=30)
194 194 >>> s2 = Struct(a=40)
195 195 >>> s = s1 - s2
196 196 >>> s
197 197 {'b': 30}
198 198 """
199 199 sout = self.copy()
200 200 sout -= other
201 201 return sout
202 202
203 203 def __isub__(self,other):
204 204 """Inplace remove keys from self that are in other.
205 205
206 206 Examples
207 207 --------
208 208
209 209 >>> s1 = Struct(a=10,b=30)
210 210 >>> s2 = Struct(a=40)
211 211 >>> s1 -= s2
212 212 >>> s1
213 213 {'b': 30}
214 214 """
215 215 for k in other.keys():
216 216 if self.has_key(k):
217 217 del self[k]
218 218 return self
219 219
220 220 def __dict_invert(self, data):
221 221 """Helper function for merge.
222 222
223 223 Takes a dictionary whose values are lists and returns a dict with
224 224 the elements of each list as keys and the original keys as values.
225 225 """
226 226 outdict = {}
227 227 for k,lst in data.items():
228 228 if isinstance(lst, str):
229 229 lst = lst.split()
230 230 for entry in lst:
231 231 outdict[entry] = k
232 232 return outdict
233 233
234 234 def dict(self):
235 235 return self
236 236
237 237 def copy(self):
238 238 """Return a copy as a Struct.
239 239
240 240 Examples
241 241 --------
242 242
243 243 >>> s = Struct(a=10,b=30)
244 244 >>> s2 = s.copy()
245 245 >>> s2
246 246 {'a': 10, 'b': 30}
247 247 >>> type(s2).__name__
248 248 'Struct'
249 249 """
250 250 return Struct(dict.copy(self))
251 251
252 252 def hasattr(self, key):
253 253 """hasattr function available as a method.
254 254
255 255 Implemented like has_key.
256 256
257 257 Examples
258 258 --------
259 259
260 260 >>> s = Struct(a=10)
261 261 >>> s.hasattr('a')
262 262 True
263 263 >>> s.hasattr('b')
264 264 False
265 265 >>> s.hasattr('get')
266 266 False
267 267 """
268 268 return self.has_key(key)
269 269
270 270 def allow_new_attr(self, allow = True):
271 271 """Set whether new attributes can be created in this Struct.
272 272
273 273 This can be used to catch typos by verifying that the attribute user
274 274 tries to change already exists in this Struct.
275 275 """
276 276 object.__setattr__(self, '_allownew', allow)
277 277
278 278 def merge(self, __loc_data__=None, __conflict_solve=None, **kw):
279 279 """Merge two Structs with customizable conflict resolution.
280 280
281 281 This is similar to :meth:`update`, but much more flexible. First, a
282 282 dict is made from data+key=value pairs. When merging this dict with
283 283 the Struct S, the optional dictionary 'conflict' is used to decide
284 284 what to do.
285 285
286 286 If conflict is not given, the default behavior is to preserve any keys
287 287 with their current value (the opposite of the :meth:`update` method's
288 288 behavior).
289 289
290 290 Parameters
291 291 ----------
292 292 __loc_data : dict, Struct
293 293 The data to merge into self
294 294 __conflict_solve : dict
295 295 The conflict policy dict. The keys are binary functions used to
296 296 resolve the conflict and the values are lists of strings naming
297 297 the keys the conflict resolution function applies to. Instead of
298 298 a list of strings a space separated string can be used, like
299 299 'a b c'.
300 300 kw : dict
301 301 Additional key, value pairs to merge in
302 302
303 303 Notes
304 304 -----
305 305
306 306 The `__conflict_solve` dict is a dictionary of binary functions which will be used to
307 307 solve key conflicts. Here is an example::
308 308
309 309 __conflict_solve = dict(
310 310 func1=['a','b','c'],
311 311 func2=['d','e']
312 312 )
313 313
314 314 In this case, the function :func:`func1` will be used to resolve
315 315 keys 'a', 'b' and 'c' and the function :func:`func2` will be used for
316 316 keys 'd' and 'e'. This could also be written as::
317 317
318 318 __conflict_solve = dict(func1='a b c',func2='d e')
319 319
320 320 These functions will be called for each key they apply to with the
321 321 form::
322 322
323 323 func1(self['a'], other['a'])
324 324
325 325 The return value is used as the final merged value.
326 326
327 327 As a convenience, merge() provides five (the most commonly needed)
328 328 pre-defined policies: preserve, update, add, add_flip and add_s. The
329 329 easiest explanation is their implementation::
330 330
331 331 preserve = lambda old,new: old
332 332 update = lambda old,new: new
333 333 add = lambda old,new: old + new
334 334 add_flip = lambda old,new: new + old # note change of order!
335 335 add_s = lambda old,new: old + ' ' + new # only for str!
336 336
337 337 You can use those four words (as strings) as keys instead
338 338 of defining them as functions, and the merge method will substitute
339 339 the appropriate functions for you.
340 340
341 341 For more complicated conflict resolution policies, you still need to
342 342 construct your own functions.
343 343
344 344 Examples
345 345 --------
346 346
347 347 This show the default policy:
348 348
349 349 >>> s = Struct(a=10,b=30)
350 350 >>> s2 = Struct(a=20,c=40)
351 351 >>> s.merge(s2)
352 352 >>> s
353 353 {'a': 10, 'c': 40, 'b': 30}
354 354
355 355 Now, show how to specify a conflict dict:
356 356
357 357 >>> s = Struct(a=10,b=30)
358 358 >>> s2 = Struct(a=20,b=40)
359 359 >>> conflict = {'update':'a','add':'b'}
360 360 >>> s.merge(s2,conflict)
361 361 >>> s
362 362 {'a': 20, 'b': 70}
363 363 """
364 364
365 365 data_dict = dict(__loc_data__,**kw)
366 366
367 367 # policies for conflict resolution: two argument functions which return
368 368 # the value that will go in the new struct
369 369 preserve = lambda old,new: old
370 370 update = lambda old,new: new
371 371 add = lambda old,new: old + new
372 372 add_flip = lambda old,new: new + old # note change of order!
373 373 add_s = lambda old,new: old + ' ' + new
374 374
375 375 # default policy is to keep current keys when there's a conflict
376 376 conflict_solve = list2dict2(self.keys(), default = preserve)
377 377
378 378 # the conflict_solve dictionary is given by the user 'inverted': we
379 379 # need a name-function mapping, it comes as a function -> names
380 380 # dict. Make a local copy (b/c we'll make changes), replace user
381 381 # strings for the three builtin policies and invert it.
382 382 if __conflict_solve:
383 383 inv_conflict_solve_user = __conflict_solve.copy()
384 384 for name, func in [('preserve',preserve), ('update',update),
385 385 ('add',add), ('add_flip',add_flip),
386 386 ('add_s',add_s)]:
387 387 if name in inv_conflict_solve_user.keys():
388 388 inv_conflict_solve_user[func] = inv_conflict_solve_user[name]
389 389 del inv_conflict_solve_user[name]
390 390 conflict_solve.update(self.__dict_invert(inv_conflict_solve_user))
391 #print 'merge. conflict_solve: '; pprint(conflict_solve) # dbg
392 #print '*'*50,'in merger. conflict_solver:'; pprint(conflict_solve)
393 391 for key in data_dict:
394 392 if key not in self:
395 393 self[key] = data_dict[key]
396 394 else:
397 395 self[key] = conflict_solve[key](self[key],data_dict[key])
398 396
@@ -1,629 +1,632 b''
1 1 #!/usr/bin/env python
2 2 """A simple interactive kernel that talks to a frontend over 0MQ.
3 3
4 4 Things to do:
5 5
6 6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 7 call set_parent on all the PUB objects with the message about to be executed.
8 8 * Implement random port and security key logic.
9 9 * Implement control messages.
10 10 * Implement event loop and poll version.
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Standard library imports.
19 19 import __builtin__
20 20 import atexit
21 21 import sys
22 22 import time
23 23 import traceback
24 24
25 25 # System library imports.
26 26 import zmq
27 27
28 28 # Local imports.
29 29 from IPython.config.configurable import Configurable
30 30 from IPython.utils import io
31 31 from IPython.utils.jsonutil import json_clean
32 32 from IPython.lib import pylabtools
33 33 from IPython.utils.traitlets import Instance, Float
34 34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
35 35 start_kernel)
36 36 from iostream import OutStream
37 37 from session import Session, Message
38 38 from zmqshell import ZMQInteractiveShell
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Main kernel class
42 42 #-----------------------------------------------------------------------------
43 43
44 44 class Kernel(Configurable):
45 45
46 46 #---------------------------------------------------------------------------
47 47 # Kernel interface
48 48 #---------------------------------------------------------------------------
49 49
50 50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
51 51 session = Instance(Session)
52 52 reply_socket = Instance('zmq.Socket')
53 53 pub_socket = Instance('zmq.Socket')
54 54 req_socket = Instance('zmq.Socket')
55 55
56 56 # Private interface
57 57
58 58 # Time to sleep after flushing the stdout/err buffers in each execute
59 59 # cycle. While this introduces a hard limit on the minimal latency of the
60 60 # execute cycle, it helps prevent output synchronization problems for
61 61 # clients.
62 62 # Units are in seconds. The minimum zmq latency on local host is probably
63 63 # ~150 microseconds, set this to 500us for now. We may need to increase it
64 64 # a little if it's not enough after more interactive testing.
65 65 _execute_sleep = Float(0.0005, config=True)
66 66
67 67 # Frequency of the kernel's event loop.
68 68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
69 69 # adapt to milliseconds.
70 70 _poll_interval = Float(0.05, config=True)
71 71
72 72 # If the shutdown was requested over the network, we leave here the
73 73 # necessary reply message so it can be sent by our registered atexit
74 74 # handler. This ensures that the reply is only sent to clients truly at
75 75 # the end of our shutdown process (which happens after the underlying
76 76 # IPython shell's own shutdown).
77 77 _shutdown_message = None
78 78
79 79 # This is a dict of port number that the kernel is listening on. It is set
80 80 # by record_ports and used by connect_request.
81 81 _recorded_ports = None
82 82
83 83 def __init__(self, **kwargs):
84 84 super(Kernel, self).__init__(**kwargs)
85 85
86 86 # Before we even start up the shell, register *first* our exit handlers
87 87 # so they come before the shell's
88 88 atexit.register(self._at_shutdown)
89 89
90 90 # Initialize the InteractiveShell subclass
91 91 self.shell = ZMQInteractiveShell.instance()
92 92 self.shell.displayhook.session = self.session
93 93 self.shell.displayhook.pub_socket = self.pub_socket
94 self.shell.display_pub.session = self.session
95 self.shell.display_pub.pub_socket = self.pub_socket
94 96
95 97 # TMP - hack while developing
96 98 self.shell._reply_content = None
97 99
98 100 # Build dict of handlers for message types
99 101 msg_types = [ 'execute_request', 'complete_request',
100 102 'object_info_request', 'history_request',
101 103 'connect_request', 'shutdown_request']
102 104 self.handlers = {}
103 105 for msg_type in msg_types:
104 106 self.handlers[msg_type] = getattr(self, msg_type)
105 107
106 108 def do_one_iteration(self):
107 109 """Do one iteration of the kernel's evaluation loop.
108 110 """
109 111 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
110 112 if msg is None:
111 113 return
112 114
113 115 # This assert will raise in versions of zeromq 2.0.7 and lesser.
114 116 # We now require 2.0.8 or above, so we can uncomment for safety.
115 117 # print(ident,msg, file=sys.__stdout__)
116 118 assert ident is not None, "Missing message part."
117 119
118 120 # Print some info about this message and leave a '--->' marker, so it's
119 121 # easier to trace visually the message chain when debugging. Each
120 122 # handler prints its message at the end.
121 123 # Eventually we'll move these from stdout to a logger.
122 124 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
123 125 io.raw_print(' Content: ', msg['content'],
124 126 '\n --->\n ', sep='', end='')
125 127
126 128 # Find and call actual handler for message
127 129 handler = self.handlers.get(msg['msg_type'], None)
128 130 if handler is None:
129 131 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
130 132 else:
131 133 handler(ident, msg)
132 134
133 135 # Check whether we should exit, in case the incoming message set the
134 136 # exit flag on
135 137 if self.shell.exit_now:
136 138 io.raw_print('\nExiting IPython kernel...')
137 139 # We do a normal, clean exit, which allows any actions registered
138 140 # via atexit (such as history saving) to take place.
139 141 sys.exit(0)
140 142
141 143
142 144 def start(self):
143 145 """ Start the kernel main loop.
144 146 """
145 147 while True:
146 148 time.sleep(self._poll_interval)
147 149 self.do_one_iteration()
148 150
149 151 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
150 152 """Record the ports that this kernel is using.
151 153
152 154 The creator of the Kernel instance must call this methods if they
153 155 want the :meth:`connect_request` method to return the port numbers.
154 156 """
155 157 self._recorded_ports = {
156 158 'xrep_port' : xrep_port,
157 159 'pub_port' : pub_port,
158 160 'req_port' : req_port,
159 161 'hb_port' : hb_port
160 162 }
161 163
162 164 #---------------------------------------------------------------------------
163 165 # Kernel request handlers
164 166 #---------------------------------------------------------------------------
165 167
166 168 def _publish_pyin(self, code, parent):
167 169 """Publish the code request on the pyin stream."""
168 170
169 171 pyin_msg = self.session.send(self.pub_socket, u'pyin',{u'code':code}, parent=parent)
170 172
171 173 def execute_request(self, ident, parent):
172 174
173 175 status_msg = self.session.send(self.pub_socket,
174 176 u'status',
175 177 {u'execution_state':u'busy'},
176 178 parent=parent
177 179 )
178 180
179 181 try:
180 182 content = parent[u'content']
181 183 code = content[u'code']
182 184 silent = content[u'silent']
183 185 except:
184 186 io.raw_print_err("Got bad msg: ")
185 187 io.raw_print_err(Message(parent))
186 188 return
187 189
188 190 shell = self.shell # we'll need this a lot here
189 191
190 192 # Replace raw_input. Note that is not sufficient to replace
191 193 # raw_input in the user namespace.
192 194 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
193 195 __builtin__.raw_input = raw_input
194 196
195 197 # Set the parent message of the display hook and out streams.
196 198 shell.displayhook.set_parent(parent)
199 shell.display_pub.set_parent(parent)
197 200 sys.stdout.set_parent(parent)
198 201 sys.stderr.set_parent(parent)
199 202
200 203 # Re-broadcast our input for the benefit of listening clients, and
201 204 # start computing output
202 205 if not silent:
203 206 self._publish_pyin(code, parent)
204 207
205 208 reply_content = {}
206 209 try:
207 210 if silent:
208 211 # run_code uses 'exec' mode, so no displayhook will fire, and it
209 212 # doesn't call logging or history manipulations. Print
210 213 # statements in that code will obviously still execute.
211 214 shell.run_code(code)
212 215 else:
213 216 # FIXME: the shell calls the exception handler itself.
214 217 shell._reply_content = None
215 218 shell.run_cell(code)
216 219 except:
217 220 status = u'error'
218 221 # FIXME: this code right now isn't being used yet by default,
219 222 # because the runlines() call above directly fires off exception
220 223 # reporting. This code, therefore, is only active in the scenario
221 224 # where runlines itself has an unhandled exception. We need to
222 225 # uniformize this, for all exception construction to come from a
223 226 # single location in the codbase.
224 227 etype, evalue, tb = sys.exc_info()
225 228 tb_list = traceback.format_exception(etype, evalue, tb)
226 229 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
227 230 else:
228 231 status = u'ok'
229 232
230 233 reply_content[u'status'] = status
231 234
232 235 # Return the execution counter so clients can display prompts
233 236 reply_content['execution_count'] = shell.execution_count -1
234 237
235 238 # FIXME - fish exception info out of shell, possibly left there by
236 239 # runlines. We'll need to clean up this logic later.
237 240 if shell._reply_content is not None:
238 241 reply_content.update(shell._reply_content)
239 242
240 243 # At this point, we can tell whether the main code execution succeeded
241 244 # or not. If it did, we proceed to evaluate user_variables/expressions
242 245 if reply_content['status'] == 'ok':
243 246 reply_content[u'user_variables'] = \
244 247 shell.user_variables(content[u'user_variables'])
245 248 reply_content[u'user_expressions'] = \
246 249 shell.user_expressions(content[u'user_expressions'])
247 250 else:
248 251 # If there was an error, don't even try to compute variables or
249 252 # expressions
250 253 reply_content[u'user_variables'] = {}
251 254 reply_content[u'user_expressions'] = {}
252 255
253 256 # Payloads should be retrieved regardless of outcome, so we can both
254 257 # recover partial output (that could have been generated early in a
255 258 # block, before an error) and clear the payload system always.
256 259 reply_content[u'payload'] = shell.payload_manager.read_payload()
257 260 # Be agressive about clearing the payload because we don't want
258 261 # it to sit in memory until the next execute_request comes in.
259 262 shell.payload_manager.clear_payload()
260 263
261 264 # Send the reply.
262 265 reply_msg = self.session.send(self.reply_socket, u'execute_reply', reply_content, parent, ident=ident)
263 266 io.raw_print(reply_msg)
264 267
265 268 # Flush output before sending the reply.
266 269 sys.stdout.flush()
267 270 sys.stderr.flush()
268 271 # FIXME: on rare occasions, the flush doesn't seem to make it to the
269 272 # clients... This seems to mitigate the problem, but we definitely need
270 273 # to better understand what's going on.
271 274 if self._execute_sleep:
272 275 time.sleep(self._execute_sleep)
273 276
274 277 if reply_msg['content']['status'] == u'error':
275 278 self._abort_queue()
276 279
277 280 status_msg = self.session.send(self.pub_socket,
278 281 u'status',
279 282 {u'execution_state':u'idle'},
280 283 parent=parent
281 284 )
282 285
283 286 def complete_request(self, ident, parent):
284 287 txt, matches = self._complete(parent)
285 288 matches = {'matches' : matches,
286 289 'matched_text' : txt,
287 290 'status' : 'ok'}
288 291 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
289 292 matches, parent, ident)
290 293 io.raw_print(completion_msg)
291 294
292 295 def object_info_request(self, ident, parent):
293 296 object_info = self.shell.object_inspect(parent['content']['oname'])
294 297 # Before we send this object over, we scrub it for JSON usage
295 298 oinfo = json_clean(object_info)
296 299 msg = self.session.send(self.reply_socket, 'object_info_reply',
297 300 oinfo, parent, ident)
298 301 io.raw_print(msg)
299 302
300 303 def history_request(self, ident, parent):
301 304 output = parent['content']['output']
302 305 index = parent['content']['index']
303 306 raw = parent['content']['raw']
304 307 hist = self.shell.get_history(index=index, raw=raw, output=output)
305 308 content = {'history' : hist}
306 309 msg = self.session.send(self.reply_socket, 'history_reply',
307 310 content, parent, ident)
308 311 io.raw_print(msg)
309 312
310 313 def connect_request(self, ident, parent):
311 314 if self._recorded_ports is not None:
312 315 content = self._recorded_ports.copy()
313 316 else:
314 317 content = {}
315 318 msg = self.session.send(self.reply_socket, 'connect_reply',
316 319 content, parent, ident)
317 320 io.raw_print(msg)
318 321
319 322 def shutdown_request(self, ident, parent):
320 323 self.shell.exit_now = True
321 324 self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent)
322 325 sys.exit(0)
323 326
324 327 #---------------------------------------------------------------------------
325 328 # Protected interface
326 329 #---------------------------------------------------------------------------
327 330
328 331 def _abort_queue(self):
329 332 while True:
330 333 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
331 334 if msg is None:
332 335 break
333 336 else:
334 337 assert ident is not None, \
335 338 "Unexpected missing message part."
336 339 io.raw_print("Aborting:\n", Message(msg))
337 340 msg_type = msg['msg_type']
338 341 reply_type = msg_type.split('_')[0] + '_reply'
339 342 reply_msg = self.session.send(self.reply_socket, reply_type,
340 343 {'status' : 'aborted'}, msg, ident=ident)
341 344 io.raw_print(reply_msg)
342 345 # We need to wait a bit for requests to come in. This can probably
343 346 # be set shorter for true asynchronous clients.
344 347 time.sleep(0.1)
345 348
346 349 def _raw_input(self, prompt, ident, parent):
347 350 # Flush output before making the request.
348 351 sys.stderr.flush()
349 352 sys.stdout.flush()
350 353
351 354 # Send the input request.
352 355 content = dict(prompt=prompt)
353 356 msg = self.session.send(self.req_socket, u'input_request', content, parent)
354 357
355 358 # Await a response.
356 359 ident, reply = self.session.recv(self.req_socket, 0)
357 360 try:
358 361 value = reply['content']['value']
359 362 except:
360 363 io.raw_print_err("Got bad raw_input reply: ")
361 364 io.raw_print_err(Message(parent))
362 365 value = ''
363 366 return value
364 367
365 368 def _complete(self, msg):
366 369 c = msg['content']
367 370 try:
368 371 cpos = int(c['cursor_pos'])
369 372 except:
370 373 # If we don't get something that we can convert to an integer, at
371 374 # least attempt the completion guessing the cursor is at the end of
372 375 # the text, if there's any, and otherwise of the line
373 376 cpos = len(c['text'])
374 377 if cpos==0:
375 378 cpos = len(c['line'])
376 379 return self.shell.complete(c['text'], c['line'], cpos)
377 380
378 381 def _object_info(self, context):
379 382 symbol, leftover = self._symbol_from_context(context)
380 383 if symbol is not None and not leftover:
381 384 doc = getattr(symbol, '__doc__', '')
382 385 else:
383 386 doc = ''
384 387 object_info = dict(docstring = doc)
385 388 return object_info
386 389
387 390 def _symbol_from_context(self, context):
388 391 if not context:
389 392 return None, context
390 393
391 394 base_symbol_string = context[0]
392 395 symbol = self.shell.user_ns.get(base_symbol_string, None)
393 396 if symbol is None:
394 397 symbol = __builtin__.__dict__.get(base_symbol_string, None)
395 398 if symbol is None:
396 399 return None, context
397 400
398 401 context = context[1:]
399 402 for i, name in enumerate(context):
400 403 new_symbol = getattr(symbol, name, None)
401 404 if new_symbol is None:
402 405 return symbol, context[i:]
403 406 else:
404 407 symbol = new_symbol
405 408
406 409 return symbol, []
407 410
408 411 def _at_shutdown(self):
409 412 """Actions taken at shutdown by the kernel, called by python's atexit.
410 413 """
411 414 # io.rprint("Kernel at_shutdown") # dbg
412 415 if self._shutdown_message is not None:
413 416 self.session.send(self.reply_socket, self._shutdown_message)
414 417 self.session.send(self.pub_socket, self._shutdown_message)
415 418 io.raw_print(self._shutdown_message)
416 419 # A very short sleep to give zmq time to flush its message buffers
417 420 # before Python truly shuts down.
418 421 time.sleep(0.01)
419 422
420 423
421 424 class QtKernel(Kernel):
422 425 """A Kernel subclass with Qt support."""
423 426
424 427 def start(self):
425 428 """Start a kernel with QtPy4 event loop integration."""
426 429
427 430 from PyQt4 import QtCore
428 431 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
429 432
430 433 self.app = get_app_qt4([" "])
431 434 self.app.setQuitOnLastWindowClosed(False)
432 435 self.timer = QtCore.QTimer()
433 436 self.timer.timeout.connect(self.do_one_iteration)
434 437 # Units for the timer are in milliseconds
435 438 self.timer.start(1000*self._poll_interval)
436 439 start_event_loop_qt4(self.app)
437 440
438 441
439 442 class WxKernel(Kernel):
440 443 """A Kernel subclass with Wx support."""
441 444
442 445 def start(self):
443 446 """Start a kernel with wx event loop support."""
444 447
445 448 import wx
446 449 from IPython.lib.guisupport import start_event_loop_wx
447 450
448 451 doi = self.do_one_iteration
449 452 # Wx uses milliseconds
450 453 poll_interval = int(1000*self._poll_interval)
451 454
452 455 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
453 456 # We make the Frame hidden when we create it in the main app below.
454 457 class TimerFrame(wx.Frame):
455 458 def __init__(self, func):
456 459 wx.Frame.__init__(self, None, -1)
457 460 self.timer = wx.Timer(self)
458 461 # Units for the timer are in milliseconds
459 462 self.timer.Start(poll_interval)
460 463 self.Bind(wx.EVT_TIMER, self.on_timer)
461 464 self.func = func
462 465
463 466 def on_timer(self, event):
464 467 self.func()
465 468
466 469 # We need a custom wx.App to create our Frame subclass that has the
467 470 # wx.Timer to drive the ZMQ event loop.
468 471 class IPWxApp(wx.App):
469 472 def OnInit(self):
470 473 self.frame = TimerFrame(doi)
471 474 self.frame.Show(False)
472 475 return True
473 476
474 477 # The redirect=False here makes sure that wx doesn't replace
475 478 # sys.stdout/stderr with its own classes.
476 479 self.app = IPWxApp(redirect=False)
477 480 start_event_loop_wx(self.app)
478 481
479 482
480 483 class TkKernel(Kernel):
481 484 """A Kernel subclass with Tk support."""
482 485
483 486 def start(self):
484 487 """Start a Tk enabled event loop."""
485 488
486 489 import Tkinter
487 490 doi = self.do_one_iteration
488 491 # Tk uses milliseconds
489 492 poll_interval = int(1000*self._poll_interval)
490 493 # For Tkinter, we create a Tk object and call its withdraw method.
491 494 class Timer(object):
492 495 def __init__(self, func):
493 496 self.app = Tkinter.Tk()
494 497 self.app.withdraw()
495 498 self.func = func
496 499
497 500 def on_timer(self):
498 501 self.func()
499 502 self.app.after(poll_interval, self.on_timer)
500 503
501 504 def start(self):
502 505 self.on_timer() # Call it once to get things going.
503 506 self.app.mainloop()
504 507
505 508 self.timer = Timer(doi)
506 509 self.timer.start()
507 510
508 511
509 512 class GTKKernel(Kernel):
510 513 """A Kernel subclass with GTK support."""
511 514
512 515 def start(self):
513 516 """Start the kernel, coordinating with the GTK event loop"""
514 517 from .gui.gtkembed import GTKEmbed
515 518
516 519 gtk_kernel = GTKEmbed(self)
517 520 gtk_kernel.start()
518 521
519 522
520 523 #-----------------------------------------------------------------------------
521 524 # Kernel main and launch functions
522 525 #-----------------------------------------------------------------------------
523 526
524 527 def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0,
525 528 independent=False, pylab=False, colors=None):
526 529 """Launches a localhost kernel, binding to the specified ports.
527 530
528 531 Parameters
529 532 ----------
530 533 ip : str, optional
531 534 The ip address the kernel will bind to.
532 535
533 536 xrep_port : int, optional
534 537 The port to use for XREP channel.
535 538
536 539 pub_port : int, optional
537 540 The port to use for the SUB channel.
538 541
539 542 req_port : int, optional
540 543 The port to use for the REQ (raw input) channel.
541 544
542 545 hb_port : int, optional
543 546 The port to use for the hearbeat REP channel.
544 547
545 548 independent : bool, optional (default False)
546 549 If set, the kernel process is guaranteed to survive if this process
547 550 dies. If not set, an effort is made to ensure that the kernel is killed
548 551 when this process dies. Note that in this case it is still good practice
549 552 to kill kernels manually before exiting.
550 553
551 554 pylab : bool or string, optional (default False)
552 555 If not False, the kernel will be launched with pylab enabled. If a
553 556 string is passed, matplotlib will use the specified backend. Otherwise,
554 557 matplotlib's default backend will be used.
555 558
556 559 colors : None or string, optional (default None)
557 560 If not None, specify the color scheme. One of (NoColor, LightBG, Linux)
558 561
559 562 Returns
560 563 -------
561 564 A tuple of form:
562 565 (kernel_process, xrep_port, pub_port, req_port)
563 566 where kernel_process is a Popen object and the ports are integers.
564 567 """
565 568 extra_arguments = []
566 569 if pylab:
567 570 extra_arguments.append('--pylab')
568 571 if isinstance(pylab, basestring):
569 572 extra_arguments.append(pylab)
570 573 if ip is not None:
571 574 extra_arguments.append('--ip')
572 575 if isinstance(ip, basestring):
573 576 extra_arguments.append(ip)
574 577 if colors is not None:
575 578 extra_arguments.append('--colors')
576 579 extra_arguments.append(colors)
577 580 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
578 581 xrep_port, pub_port, req_port, hb_port,
579 582 independent, extra_arguments)
580 583
581 584
582 585 def main():
583 586 """ The IPython kernel main entry point.
584 587 """
585 588 parser = make_argument_parser()
586 589 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
587 590 const='auto', help = \
588 591 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
589 592 given, the GUI backend is matplotlib's, otherwise use one of: \
590 593 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
591 594 parser.add_argument('--colors',
592 595 type=str, dest='colors',
593 596 help="Set the color scheme (NoColor, Linux, and LightBG).",
594 597 metavar='ZMQInteractiveShell.colors')
595 598 namespace = parser.parse_args()
596 599
597 600 kernel_class = Kernel
598 601
599 602 kernel_classes = {
600 603 'qt' : QtKernel,
601 604 'qt4': QtKernel,
602 605 'inline': Kernel,
603 606 'wx' : WxKernel,
604 607 'tk' : TkKernel,
605 608 'gtk': GTKKernel,
606 609 }
607 610 if namespace.pylab:
608 611 if namespace.pylab == 'auto':
609 612 gui, backend = pylabtools.find_gui_and_backend()
610 613 else:
611 614 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
612 615 kernel_class = kernel_classes.get(gui)
613 616 if kernel_class is None:
614 617 raise ValueError('GUI is not supported: %r' % gui)
615 618 pylabtools.activate_matplotlib(backend)
616 619 if namespace.colors:
617 620 ZMQInteractiveShell.colors=namespace.colors
618 621
619 622 kernel = make_kernel(namespace, kernel_class, OutStream)
620 623
621 624 if namespace.pylab:
622 625 pylabtools.import_pylab(kernel.shell.user_ns, backend,
623 626 shell=kernel.shell)
624 627
625 628 start_kernel(namespace, kernel)
626 629
627 630
628 631 if __name__ == '__main__':
629 632 main()
@@ -1,119 +1,73 b''
1 1 """Produce SVG versions of active plots for display by the rich Qt frontend.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Imports
5 5 #-----------------------------------------------------------------------------
6 6 from __future__ import print_function
7 7
8 8 # Standard library imports
9 from cStringIO import StringIO
10 9
11 # System library imports.
12 10 import matplotlib
13 11 from matplotlib.backends.backend_svg import new_figure_manager
14 12 from matplotlib._pylab_helpers import Gcf
15 13
16 14 # Local imports.
17 from backend_payload import add_plot_payload
15 from IPython.core.displaypub import publish_display_data
16 from IPython.lib.pylabtools import figure_to_svg
18 17
19 18 #-----------------------------------------------------------------------------
20 19 # Functions
21 20 #-----------------------------------------------------------------------------
22 21
23 def show(close=True):
22 def show(close=False):
24 23 """Show all figures as SVG payloads sent to the IPython clients.
25 24
26 25 Parameters
27 26 ----------
28 27 close : bool, optional
29 28 If true, a ``plt.close('all')`` call is automatically issued after
30 sending all the SVG figures.
29 sending all the SVG figures. If this is set, the figures will entirely
30 removed from the internal list of figures.
31 31 """
32 32 for figure_manager in Gcf.get_all_fig_managers():
33 send_svg_canvas(figure_manager.canvas)
33 send_svg_figure(figure_manager.canvas.figure)
34 34 if close:
35 35 matplotlib.pyplot.close('all')
36 36
37
37 38 # This flag will be reset by draw_if_interactive when called
38 39 show._draw_called = False
39 40
40 41
41 def figsize(sizex, sizey):
42 """Set the default figure size to be [sizex, sizey].
43
44 This is just an easy to remember, convenience wrapper that sets::
45
46 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
47 """
48 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
49
50
51 def pastefig(*figs):
52 """Paste one or more figures into the console workspace.
53
54 If no arguments are given, all available figures are pasted. If the
55 argument list contains references to invalid figures, a warning is printed
56 but the function continues pasting further figures.
57
58 Parameters
59 ----------
60 figs : tuple
61 A tuple that can contain any mixture of integers and figure objects.
62 """
63 if not figs:
64 show(close=False)
65 else:
66 fig_managers = Gcf.get_all_fig_managers()
67 fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers]
68 + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] )
69
70 for fig in figs:
71 canvas = fig_index.get(fig)
72 if canvas is None:
73 print('Warning: figure %s not available.' % fig)
74 else:
75 send_svg_canvas(canvas)
76
77
78 def send_svg_canvas(canvas):
79 """Draw the current canvas and send it as an SVG payload.
80 """
81 # Set the background to white instead so it looks good on black. We store
82 # the current values to restore them at the end.
83 fc = canvas.figure.get_facecolor()
84 ec = canvas.figure.get_edgecolor()
85 canvas.figure.set_facecolor('white')
86 canvas.figure.set_edgecolor('white')
87 try:
88 add_plot_payload('svg', svg_from_canvas(canvas))
89 finally:
90 canvas.figure.set_facecolor(fc)
91 canvas.figure.set_edgecolor(ec)
92
93
94 def svg_from_canvas(canvas):
95 """ Return a string containing the SVG representation of a FigureCanvasSvg.
96 """
97 string_io = StringIO()
98 canvas.print_figure(string_io, format='svg')
99 return string_io.getvalue()
100
101
102 42 def draw_if_interactive():
103 43 """
104 44 Is called after every pylab drawing command
105 45 """
106 46 # We simply flag we were called and otherwise do nothing. At the end of
107 47 # the code execution, a separate call to show_close() will act upon this.
108 48 show._draw_called = True
109 49
110 50
111 51 def flush_svg():
112 52 """Call show, close all open figures, sending all SVG images.
113 53
114 54 This is meant to be called automatically and will call show() if, during
115 55 prior code execution, there had been any calls to draw_if_interactive.
116 56 """
117 57 if show._draw_called:
118 show(close=True)
58 # Show is called with the default close=False here, otherwise, the
59 # Figure will be closed and not available for future plotting.
60 show()
119 61 show._draw_called = False
62
63
64 def send_svg_figure(fig):
65 """Draw the current figure and send it as an SVG payload.
66 """
67 svg = figure_to_svg(fig)
68 publish_display_data(
69 'IPython.zmq.pylab.backend_inline.send_svg_figure',
70 'Matplotlib Plot',
71 {'image/svg+xml' : svg}
72 )
73
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now