##// 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 # Get the config being loaded so we can set attributes on it
1 # Get the config being loaded so we can set attributes on it
2 c = get_config()
2 c = get_config()
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Global options
5 # Global options
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7
7
8 # c.Global.display_banner = True
8 # c.Global.display_banner = True
9
9
10 # c.Global.classic = False
10 # c.Global.classic = False
11
11
12 # c.Global.nosep = True
12 # c.Global.nosep = True
13
13
14 # Set this to determine the detail of what is logged at startup.
14 # Set this to determine the detail of what is logged at startup.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
16 # c.Global.log_level = 20
16 # c.Global.log_level = 20
17
17
18 # This should be a list of importable Python modules that have an
18 # This should be a list of importable Python modules that have an
19 # load_in_ipython(ip) method. This method gets called when the extension
19 # load_in_ipython(ip) method. This method gets called when the extension
20 # is loaded. You can put your extensions anywhere they can be imported
20 # is loaded. You can put your extensions anywhere they can be imported
21 # but we add the extensions subdir of the ipython directory to sys.path
21 # but we add the extensions subdir of the ipython directory to sys.path
22 # during extension loading, so you can put them there as well.
22 # during extension loading, so you can put them there as well.
23 # c.Global.extensions = [
23 # c.Global.extensions = [
24 # 'myextension'
24 # 'myextension'
25 # ]
25 # ]
26
26
27 # These lines are run in IPython in the user's namespace after extensions
27 # These lines are run in IPython in the user's namespace after extensions
28 # are loaded. They can contain full IPython syntax with magics etc.
28 # are loaded. They can contain full IPython syntax with magics etc.
29 # c.Global.exec_lines = [
29 # c.Global.exec_lines = [
30 # 'import numpy',
30 # 'import numpy',
31 # 'a = 10; b = 20',
31 # 'a = 10; b = 20',
32 # '1/0'
32 # '1/0'
33 # ]
33 # ]
34
34
35 # These files are run in IPython in the user's namespace. Files with a .py
35 # These files are run in IPython in the user's namespace. Files with a .py
36 # extension need to be pure Python. Files with a .ipy extension can have
36 # extension need to be pure Python. Files with a .ipy extension can have
37 # custom IPython syntax (like magics, etc.).
37 # custom IPython syntax (like magics, etc.).
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
39 # c.Global.exec_files = [
39 # c.Global.exec_files = [
40 # 'mycode.py',
40 # 'mycode.py',
41 # 'fancy.ipy'
41 # 'fancy.ipy'
42 # ]
42 # ]
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # InteractiveShell options
45 # InteractiveShell options
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 # c.InteractiveShell.autocall = 1
48 # c.InteractiveShell.autocall = 1
49
49
50 # c.TerminalInteractiveShell.autoedit_syntax = False
50 # c.TerminalInteractiveShell.autoedit_syntax = False
51
51
52 # c.InteractiveShell.autoindent = True
52 # c.InteractiveShell.autoindent = True
53
53
54 # c.InteractiveShell.automagic = False
54 # c.InteractiveShell.automagic = False
55
55
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
57
57
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
59
59
60 # c.InteractiveShell.cache_size = 1000
60 # c.InteractiveShell.cache_size = 1000
61
61
62 # c.InteractiveShell.colors = 'LightBG'
62 # c.InteractiveShell.colors = 'LightBG'
63
63
64 # c.InteractiveShell.color_info = True
64 # c.InteractiveShell.color_info = True
65
65
66 # c.TerminalInteractiveShell.confirm_exit = True
66 # c.TerminalInteractiveShell.confirm_exit = True
67
67
68 # c.InteractiveShell.deep_reload = False
68 # c.InteractiveShell.deep_reload = False
69
69
70 # c.TerminalInteractiveShell.editor = 'nano'
70 # c.TerminalInteractiveShell.editor = 'nano'
71
71
72 # c.InteractiveShell.logstart = True
72 # c.InteractiveShell.logstart = True
73
73
74 # c.InteractiveShell.logfile = u'ipython_log.py'
74 # c.InteractiveShell.logfile = u'ipython_log.py'
75
75
76 # c.InteractiveShell.logappend = u'mylog.py'
76 # c.InteractiveShell.logappend = u'mylog.py'
77
77
78 # c.InteractiveShell.object_info_string_level = 0
78 # c.InteractiveShell.object_info_string_level = 0
79
79
80 # c.TerminalInteractiveShell.pager = 'less'
80 # c.TerminalInteractiveShell.pager = 'less'
81
81
82 # c.InteractiveShell.pdb = False
82 # c.InteractiveShell.pdb = False
83
83
84 # c.InteractiveShell.pprint = True
85
86 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
84 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
87 # c.InteractiveShell.prompt_in2 = ' .\D.: '
85 # c.InteractiveShell.prompt_in2 = ' .\D.: '
88 # c.InteractiveShell.prompt_out = 'Out[\#]: '
86 # c.InteractiveShell.prompt_out = 'Out[\#]: '
89 # c.InteractiveShell.prompts_pad_left = True
87 # c.InteractiveShell.prompts_pad_left = True
90
88
91 # c.InteractiveShell.quiet = False
89 # c.InteractiveShell.quiet = False
92
90
93 # c.InteractiveShell.history_length = 10000
91 # c.InteractiveShell.history_length = 10000
94
92
95 # Readline
93 # Readline
96 # c.InteractiveShell.readline_use = True
94 # c.InteractiveShell.readline_use = True
97
95
98 # c.InteractiveShell.readline_parse_and_bind = [
96 # c.InteractiveShell.readline_parse_and_bind = [
99 # 'tab: complete',
97 # 'tab: complete',
100 # '"\C-l": possible-completions',
98 # '"\C-l": possible-completions',
101 # 'set show-all-if-ambiguous on',
99 # 'set show-all-if-ambiguous on',
102 # '"\C-o": tab-insert',
100 # '"\C-o": tab-insert',
103 # '"\M-i": " "',
101 # '"\M-i": " "',
104 # '"\M-o": "\d\d\d\d"',
102 # '"\M-o": "\d\d\d\d"',
105 # '"\M-I": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
106 # '"\C-r": reverse-search-history',
104 # '"\C-r": reverse-search-history',
107 # '"\C-s": forward-search-history',
105 # '"\C-s": forward-search-history',
108 # '"\C-p": history-search-backward',
106 # '"\C-p": history-search-backward',
109 # '"\C-n": history-search-forward',
107 # '"\C-n": history-search-forward',
110 # '"\e[A": history-search-backward',
108 # '"\e[A": history-search-backward',
111 # '"\e[B": history-search-forward',
109 # '"\e[B": history-search-forward',
112 # '"\C-k": kill-line',
110 # '"\C-k": kill-line',
113 # '"\C-u": unix-line-discard',
111 # '"\C-u": unix-line-discard',
114 # ]
112 # ]
115 # c.InteractiveShell.readline_remove_delims = '-/~'
113 # c.InteractiveShell.readline_remove_delims = '-/~'
116 # c.InteractiveShell.readline_merge_completions = True
114 # c.InteractiveShell.readline_merge_completions = True
117 # c.InteractiveShell.readline_omit__names = 0
115 # c.InteractiveShell.readline_omit__names = 0
118
116
119 # c.TerminalInteractiveShell.screen_length = 0
117 # c.TerminalInteractiveShell.screen_length = 0
120
118
121 # c.InteractiveShell.separate_in = '\n'
119 # c.InteractiveShell.separate_in = '\n'
122 # c.InteractiveShell.separate_out = ''
120 # c.InteractiveShell.separate_out = ''
123 # c.InteractiveShell.separate_out2 = ''
121 # c.InteractiveShell.separate_out2 = ''
124
122
125 # c.TerminalInteractiveShell.term_title = False
123 # c.TerminalInteractiveShell.term_title = False
126
124
127 # c.InteractiveShell.wildcards_case_sensitive = True
125 # c.InteractiveShell.wildcards_case_sensitive = True
128
126
129 # c.InteractiveShell.xmode = 'Context'
127 # c.InteractiveShell.xmode = 'Context'
130
128
131 #-----------------------------------------------------------------------------
129 #-----------------------------------------------------------------------------
130 # Formatter and display options
131 #-----------------------------------------------------------------------------
132
133 # c.PlainTextFormatter.pprint = True
134
135 #-----------------------------------------------------------------------------
132 # PrefilterManager options
136 # PrefilterManager options
133 #-----------------------------------------------------------------------------
137 #-----------------------------------------------------------------------------
134
138
135 # c.PrefilterManager.multi_line_specials = True
139 # c.PrefilterManager.multi_line_specials = True
136
140
137 #-----------------------------------------------------------------------------
141 #-----------------------------------------------------------------------------
138 # AliasManager options
142 # AliasManager options
139 #-----------------------------------------------------------------------------
143 #-----------------------------------------------------------------------------
140
144
141 # Do this to disable all defaults
145 # Do this to disable all defaults
142 # c.AliasManager.default_aliases = []
146 # c.AliasManager.default_aliases = []
143
147
144 # c.AliasManager.user_aliases = [
148 # c.AliasManager.user_aliases = [
145 # ('foo', 'echo Hi')
149 # ('foo', 'echo Hi')
146 # ]
150 # ]
@@ -1,21 +1,29 b''
1 c = get_config()
1 c = get_config()
2
2
3 # This can be used at any point in a config file to load a sub config
3 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
4 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
5 load_subconfig('ipython_config.py')
6
6
7 lines = """
7 lines = """
8 from __future__ import division
8 from __future__ import division
9 from sympy import *
9 from sympy import *
10 x, y, z = symbols('xyz')
10 x, y, z = symbols('xyz')
11 k, m, n = symbols('kmn', integer=True)
11 k, m, n = symbols('kmn', integer=True)
12 f, g, h = map(Function, 'fgh')
12 f, g, h = map(Function, 'fgh')
13 """
13 """
14
14
15 # You have to make sure that attributes that are containers already
15 # You have to make sure that attributes that are containers already
16 # exist before using them. Simple assigning a new list will override
16 # exist before using them. Simple assigning a new list will override
17 # all previous values.
17 # all previous values.
18
18 if hasattr(c.Global, 'exec_lines'):
19 if hasattr(c.Global, 'exec_lines'):
19 c.Global.exec_lines.append(lines)
20 c.Global.exec_lines.append(lines)
20 else:
21 else:
21 c.Global.exec_lines = [lines]
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 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Displayhook for IPython.
2 """Displayhook for IPython.
3
3
4 This defines a callable class that IPython uses for `sys.displayhook`.
5
4 Authors:
6 Authors:
5
7
6 * Fernando Perez
8 * Fernando Perez
7 * Brian Granger
9 * Brian Granger
10 * Robert Kern
8 """
11 """
9
12
10 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2010 The IPython Development Team
14 # Copyright (C) 2008-2010 The IPython Development Team
12 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
13 #
16 #
14 # Distributed under the terms of the BSD License. The full license is in
17 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
18 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
17
20
18 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
19 # Imports
22 # Imports
20 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
21
24
22 import __builtin__
25 import __builtin__
23
26
24 from IPython.config.configurable import Configurable
27 from IPython.config.configurable import Configurable
25 from IPython.core import prompts
28 from IPython.core import prompts
26 import IPython.utils.generics
29 import IPython.utils.generics
27 import IPython.utils.io
30 import IPython.utils.io
28 from IPython.utils.traitlets import Instance, List
31 from IPython.utils.traitlets import Instance, List
29 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
30 from IPython.core.formatters import DefaultFormatter
31
33
32 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
33 # Main displayhook class
35 # Main displayhook class
34 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
35
37
36 # TODO: The DisplayHook class should be split into two classes, one that
38 # TODO: The DisplayHook class should be split into two classes, one that
37 # manages the prompts and their synchronization and another that just does the
39 # manages the prompts and their synchronization and another that just does the
38 # displayhook logic and calls into the prompt manager.
40 # displayhook logic and calls into the prompt manager.
39
41
40 # TODO: Move the various attributes (cache_size, colors, input_sep,
42 # TODO: Move the various attributes (cache_size, colors, input_sep,
41 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
43 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
42 # attributes of InteractiveShell. They should be on ONE object only and the
44 # attributes of InteractiveShell. They should be on ONE object only and the
43 # other objects should ask that one object for their values.
45 # other objects should ask that one object for their values.
44
46
45 class DisplayHook(Configurable):
47 class DisplayHook(Configurable):
46 """The custom IPython displayhook to replace sys.displayhook.
48 """The custom IPython displayhook to replace sys.displayhook.
47
49
48 This class does many things, but the basic idea is that it is a callable
50 This class does many things, but the basic idea is that it is a callable
49 that gets called anytime user code returns a value.
51 that gets called anytime user code returns a value.
50
52
51 Currently this class does more than just the displayhook logic and that
53 Currently this class does more than just the displayhook logic and that
52 extra logic should eventually be moved out of here.
54 extra logic should eventually be moved out of here.
53 """
55 """
54
56
55 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
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 def __init__(self, shell=None, cache_size=1000,
59 def __init__(self, shell=None, cache_size=1000,
71 colors='NoColor', input_sep='\n',
60 colors='NoColor', input_sep='\n',
72 output_sep='\n', output_sep2='',
61 output_sep='\n', output_sep2='',
73 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
62 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
74 config=None):
63 config=None):
75 super(DisplayHook, self).__init__(shell=shell, config=config)
64 super(DisplayHook, self).__init__(shell=shell, config=config)
76
65
77 cache_size_min = 3
66 cache_size_min = 3
78 if cache_size <= 0:
67 if cache_size <= 0:
79 self.do_full_cache = 0
68 self.do_full_cache = 0
80 cache_size = 0
69 cache_size = 0
81 elif cache_size < cache_size_min:
70 elif cache_size < cache_size_min:
82 self.do_full_cache = 0
71 self.do_full_cache = 0
83 cache_size = 0
72 cache_size = 0
84 warn('caching was disabled (min value for cache size is %s).' %
73 warn('caching was disabled (min value for cache size is %s).' %
85 cache_size_min,level=3)
74 cache_size_min,level=3)
86 else:
75 else:
87 self.do_full_cache = 1
76 self.do_full_cache = 1
88
77
89 self.cache_size = cache_size
78 self.cache_size = cache_size
90 self.input_sep = input_sep
79 self.input_sep = input_sep
91
80
92 # we need a reference to the user-level namespace
81 # we need a reference to the user-level namespace
93 self.shell = shell
82 self.shell = shell
94
83
95 # Set input prompt strings and colors
84 # Set input prompt strings and colors
96 if cache_size == 0:
85 if cache_size == 0:
97 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
86 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
98 or ps1.find(r'\N') > -1:
87 or ps1.find(r'\N') > -1:
99 ps1 = '>>> '
88 ps1 = '>>> '
100 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
89 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
101 or ps2.find(r'\N') > -1:
90 or ps2.find(r'\N') > -1:
102 ps2 = '... '
91 ps2 = '... '
103 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
92 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
104 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
93 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
105 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
94 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
106
95
107 self.color_table = prompts.PromptColors
96 self.color_table = prompts.PromptColors
108 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
97 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
109 pad_left=pad_left)
98 pad_left=pad_left)
110 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
99 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
111 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
100 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
112 pad_left=pad_left)
101 pad_left=pad_left)
113 self.set_colors(colors)
102 self.set_colors(colors)
114
103
115 # Store the last prompt string each time, we need it for aligning
104 # Store the last prompt string each time, we need it for aligning
116 # continuation and auto-rewrite prompts
105 # continuation and auto-rewrite prompts
117 self.last_prompt = ''
106 self.last_prompt = ''
118 self.output_sep = output_sep
107 self.output_sep = output_sep
119 self.output_sep2 = output_sep2
108 self.output_sep2 = output_sep2
120 self._,self.__,self.___ = '','',''
109 self._,self.__,self.___ = '','',''
121
110
122 # these are deliberately global:
111 # these are deliberately global:
123 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
112 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
124 self.shell.user_ns.update(to_user_ns)
113 self.shell.user_ns.update(to_user_ns)
125
114
126 @property
115 @property
127 def prompt_count(self):
116 def prompt_count(self):
128 return self.shell.execution_count
117 return self.shell.execution_count
129
118
130 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
119 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
131 if p_str is None:
120 if p_str is None:
132 if self.do_full_cache:
121 if self.do_full_cache:
133 return cache_def
122 return cache_def
134 else:
123 else:
135 return no_cache_def
124 return no_cache_def
136 else:
125 else:
137 return p_str
126 return p_str
138
127
139 def set_colors(self, colors):
128 def set_colors(self, colors):
140 """Set the active color scheme and configure colors for the three
129 """Set the active color scheme and configure colors for the three
141 prompt subsystems."""
130 prompt subsystems."""
142
131
143 # FIXME: This modifying of the global prompts.prompt_specials needs
132 # FIXME: This modifying of the global prompts.prompt_specials needs
144 # to be fixed. We need to refactor all of the prompts stuff to use
133 # to be fixed. We need to refactor all of the prompts stuff to use
145 # proper configuration and traits notifications.
134 # proper configuration and traits notifications.
146 if colors.lower()=='nocolor':
135 if colors.lower()=='nocolor':
147 prompts.prompt_specials = prompts.prompt_specials_nocolor
136 prompts.prompt_specials = prompts.prompt_specials_nocolor
148 else:
137 else:
149 prompts.prompt_specials = prompts.prompt_specials_color
138 prompts.prompt_specials = prompts.prompt_specials_color
150
139
151 self.color_table.set_active_scheme(colors)
140 self.color_table.set_active_scheme(colors)
152 self.prompt1.set_colors()
141 self.prompt1.set_colors()
153 self.prompt2.set_colors()
142 self.prompt2.set_colors()
154 self.prompt_out.set_colors()
143 self.prompt_out.set_colors()
155
144
156 #-------------------------------------------------------------------------
145 #-------------------------------------------------------------------------
157 # Methods used in __call__. Override these methods to modify the behavior
146 # Methods used in __call__. Override these methods to modify the behavior
158 # of the displayhook.
147 # of the displayhook.
159 #-------------------------------------------------------------------------
148 #-------------------------------------------------------------------------
160
149
161 def check_for_underscore(self):
150 def check_for_underscore(self):
162 """Check if the user has set the '_' variable by hand."""
151 """Check if the user has set the '_' variable by hand."""
163 # If something injected a '_' variable in __builtin__, delete
152 # If something injected a '_' variable in __builtin__, delete
164 # ipython's automatic one so we don't clobber that. gettext() in
153 # ipython's automatic one so we don't clobber that. gettext() in
165 # particular uses _, so we need to stay away from it.
154 # particular uses _, so we need to stay away from it.
166 if '_' in __builtin__.__dict__:
155 if '_' in __builtin__.__dict__:
167 try:
156 try:
168 del self.shell.user_ns['_']
157 del self.shell.user_ns['_']
169 except KeyError:
158 except KeyError:
170 pass
159 pass
171
160
172 def quiet(self):
161 def quiet(self):
173 """Should we silence the display hook because of ';'?"""
162 """Should we silence the display hook because of ';'?"""
174 # do not print output if input ends in ';'
163 # do not print output if input ends in ';'
175 try:
164 try:
176 if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'):
165 if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'):
177 return True
166 return True
178 except IndexError:
167 except IndexError:
179 # some uses of ipshellembed may fail here
168 # some uses of ipshellembed may fail here
180 pass
169 pass
181 return False
170 return False
182
171
183 def start_displayhook(self):
172 def start_displayhook(self):
184 """Start the displayhook, initializing resources."""
173 """Start the displayhook, initializing resources."""
185 pass
174 pass
186
175
187 def write_output_prompt(self):
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 # Use write, not print which adds an extra space.
182 # Use write, not print which adds an extra space.
190 IPython.utils.io.Term.cout.write(self.output_sep)
183 IPython.utils.io.Term.cout.write(self.output_sep)
191 outprompt = str(self.prompt_out)
184 outprompt = str(self.prompt_out)
192 if self.do_full_cache:
185 if self.do_full_cache:
193 IPython.utils.io.Term.cout.write(outprompt)
186 IPython.utils.io.Term.cout.write(outprompt)
194
187
195 def compute_result_repr(self, result):
188 def compute_format_data(self, result):
196 """Compute and return the repr of the object to be displayed.
189 """Compute format data of the object to be displayed.
197
190
198 This method only compute the string form of the repr and should NOT
191 The format data is a generalization of the :func:`repr` of an object.
199 actually print or write that to a stream.
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)
215 return self.shell.display_formatter.format(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))
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 # We want to print because we want to always make sure we have a
230 # We want to print because we want to always make sure we have a
216 # newline, even if all the prompt separators are ''. This is the
231 # newline, even if all the prompt separators are ''. This is the
217 # standard IPython behavior.
232 # standard IPython behavior.
233 result_repr = format_dict['text/plain']
218 if '\n' in result_repr:
234 if '\n' in result_repr:
219 # So that multi-line strings line up with the left column of
235 # So that multi-line strings line up with the left column of
220 # the screen, instead of having the output prompt mess up
236 # the screen, instead of having the output prompt mess up
221 # their first line.
237 # their first line.
222 # We use the ps_out_str template instead of the expanded prompt
238 # We use the ps_out_str template instead of the expanded prompt
223 # because the expansion may add ANSI escapes that will interfere
239 # because the expansion may add ANSI escapes that will interfere
224 # with our ability to determine whether or not we should add
240 # with our ability to determine whether or not we should add
225 # a newline.
241 # a newline.
226 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
242 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
227 # But avoid extraneous empty lines.
243 # But avoid extraneous empty lines.
228 result_repr = '\n' + result_repr
244 result_repr = '\n' + result_repr
229
245
230 print >>IPython.utils.io.Term.cout, result_repr
246 print >>IPython.utils.io.Term.cout, result_repr
231
247
232 def update_user_ns(self, result):
248 def update_user_ns(self, result):
233 """Update user_ns with various things like _, __, _1, etc."""
249 """Update user_ns with various things like _, __, _1, etc."""
234
250
235 # Avoid recursive reference when displaying _oh/Out
251 # Avoid recursive reference when displaying _oh/Out
236 if result is not self.shell.user_ns['_oh']:
252 if result is not self.shell.user_ns['_oh']:
237 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
253 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
238 warn('Output cache limit (currently '+
254 warn('Output cache limit (currently '+
239 `self.cache_size`+' entries) hit.\n'
255 `self.cache_size`+' entries) hit.\n'
240 'Flushing cache and resetting history counter...\n'
256 'Flushing cache and resetting history counter...\n'
241 'The only history variables available will be _,__,___ and _1\n'
257 'The only history variables available will be _,__,___ and _1\n'
242 'with the current result.')
258 'with the current result.')
243
259
244 self.flush()
260 self.flush()
245 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
261 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
246 # we cause buggy behavior for things like gettext).
262 # we cause buggy behavior for things like gettext).
247 if '_' not in __builtin__.__dict__:
263 if '_' not in __builtin__.__dict__:
248 self.___ = self.__
264 self.___ = self.__
249 self.__ = self._
265 self.__ = self._
250 self._ = result
266 self._ = result
251 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
267 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
252
268
253 # hackish access to top-level namespace to create _1,_2... dynamically
269 # hackish access to top-level namespace to create _1,_2... dynamically
254 to_main = {}
270 to_main = {}
255 if self.do_full_cache:
271 if self.do_full_cache:
256 new_result = '_'+`self.prompt_count`
272 new_result = '_'+`self.prompt_count`
257 to_main[new_result] = result
273 to_main[new_result] = result
258 self.shell.user_ns.update(to_main)
274 self.shell.user_ns.update(to_main)
259 self.shell.user_ns['_oh'][self.prompt_count] = result
275 self.shell.user_ns['_oh'][self.prompt_count] = result
260
276
261 def log_output(self, result):
277 def log_output(self, result):
262 """Log the output."""
278 """Log the output."""
263 if self.shell.logger.log_output:
279 if self.shell.logger.log_output:
264 self.shell.logger.log_write(repr(result), 'output')
280 self.shell.logger.log_write(repr(result), 'output')
265
281
266 def finish_displayhook(self):
282 def finish_displayhook(self):
267 """Finish up all displayhook activities."""
283 """Finish up all displayhook activities."""
268 IPython.utils.io.Term.cout.write(self.output_sep2)
284 IPython.utils.io.Term.cout.write(self.output_sep2)
269 IPython.utils.io.Term.cout.flush()
285 IPython.utils.io.Term.cout.flush()
270
286
271 def __call__(self, result=None):
287 def __call__(self, result=None):
272 """Printing with history cache management.
288 """Printing with history cache management.
273
289
274 This is invoked everytime the interpreter needs to print, and is
290 This is invoked everytime the interpreter needs to print, and is
275 activated by setting the variable sys.displayhook to it.
291 activated by setting the variable sys.displayhook to it.
276 """
292 """
277 self.check_for_underscore()
293 self.check_for_underscore()
278 if result is not None and not self.quiet():
294 if result is not None and not self.quiet():
279 self.start_displayhook()
295 self.start_displayhook()
280 self.write_output_prompt()
296 self.write_output_prompt()
281 result_repr, extra_formats = self.compute_result_repr(result)
297 format_dict = self.compute_format_data(result)
282 self.write_result_repr(result_repr, extra_formats)
298 self.write_format_data(format_dict)
283 self.update_user_ns(result)
299 self.update_user_ns(result)
284 self.log_output(result)
300 self.log_output(result)
285 self.finish_displayhook()
301 self.finish_displayhook()
286
302
287 def flush(self):
303 def flush(self):
288 if not self.do_full_cache:
304 if not self.do_full_cache:
289 raise ValueError,"You shouldn't have reached the cache flush "\
305 raise ValueError,"You shouldn't have reached the cache flush "\
290 "if full caching is not enabled!"
306 "if full caching is not enabled!"
291 # delete auto-generated vars from global namespace
307 # delete auto-generated vars from global namespace
292
308
293 for n in range(1,self.prompt_count + 1):
309 for n in range(1,self.prompt_count + 1):
294 key = '_'+`n`
310 key = '_'+`n`
295 try:
311 try:
296 del self.shell.user_ns[key]
312 del self.shell.user_ns[key]
297 except: pass
313 except: pass
298 self.shell.user_ns['_oh'].clear()
314 self.shell.user_ns['_oh'].clear()
299
315
300 if '_' not in __builtin__.__dict__:
316 if '_' not in __builtin__.__dict__:
301 self.shell.user_ns.update({'_':None,'__':None, '___':None})
317 self.shell.user_ns.update({'_':None,'__':None, '___':None})
302 import gc
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 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Displayhook formatters.
2 """Display formatters.
3
3
4 The DefaultFormatter is always present and may be configured from the
4
5 ipython_config.py file. For example, to add a pretty-printer for a numpy.dtype
5 Authors:
6 object::
6
7
7 * Robert Kern
8 def dtype_pprinter(obj, p, cycle):
8 * Brian Granger
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.
34 """
9 """
35 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
36 # Copyright (c) 2010, IPython Development Team.
11 # Copyright (c) 2010, IPython Development Team.
37 #
12 #
38 # Distributed under the terms of the Modified BSD License.
13 # Distributed under the terms of the Modified BSD License.
39 #
14 #
40 # The full license is in the file COPYING.txt, distributed with this software.
15 # The full license is in the file COPYING.txt, distributed with this software.
41 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
42
17
18 #-----------------------------------------------------------------------------
19 # Imports
20 #-----------------------------------------------------------------------------
21
43 # Stdlib imports
22 # Stdlib imports
44 import abc
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 # Our own imports
27 # Our own imports
48 from IPython.config.configurable import Configurable
28 from IPython.config.configurable import Configurable
49 from IPython.external import pretty
29 from IPython.external import pretty
50 from IPython.utils.traitlets import Bool, Dict, Int, Str
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):
138
58 """ The default pretty-printer.
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.
152 # Is the formatter enabled...
62 id = Str('default')
153 enabled = True
63
154
64 # The kind of data returned.
155 @abc.abstractmethod
65 # This is often, but not always a MIME type.
156 def __call__(self, obj):
66 format = Str('text/plain')
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 # Whether to pretty-print or not.
344 # Whether to pretty-print or not.
69 pprint = Bool(True, config=True)
345 pprint = Bool(True, config=True)
70
346
71 # Whether to be verbose or not.
347 # Whether to be verbose or not.
72 verbose = Bool(False, config=True)
348 verbose = Bool(False, config=True)
73
349
74 # The maximum width.
350 # The maximum width.
75 max_width = Int(79, config=True)
351 max_width = Int(79, config=True)
76
352
77 # The newline character.
353 # The newline character.
78 newline = Str('\n', config=True)
354 newline = Str('\n', config=True)
79
355
80 # The singleton prettyprinters.
356 # Use the default pretty printers from IPython.external.pretty.
81 # Maps the IDs of the builtin singleton objects to the format functions.
357 def _singleton_printers_default(self):
82 singleton_pprinters = Dict(config=True)
83 def _singleton_pprinters_default(self):
84 return pretty._singleton_pprinters.copy()
358 return pretty._singleton_pprinters.copy()
85
359
86 # The type-specific prettyprinters.
360 def _type_printers_default(self):
87 # Map type objects to the format functions.
88 type_pprinters = Dict(config=True)
89 def _type_pprinters_default(self):
90 return pretty._type_pprinters.copy()
361 return pretty._type_pprinters.copy()
91
362
92 # The deferred-import type-specific prettyprinters.
363 def _deferred_printers_default(self):
93 # Map (modulename, classname) pairs to the format functions.
94 deferred_pprinters = Dict(config=True)
95 def _deferred_pprinters_default(self):
96 return pretty._deferred_type_pprinters.copy()
364 return pretty._deferred_type_pprinters.copy()
97
365
98 #### FormatterABC interface ####
366 #### FormatterABC interface ####
99
367
100 def __call__(self, obj):
368 def __call__(self, obj):
101 """ Format the object.
369 """Compute the pretty representation of the object."""
102 """
103 if not self.pprint:
370 if not self.pprint:
104 try:
371 try:
105 return repr(obj)
372 return repr(obj)
106 except TypeError:
373 except TypeError:
107 return ''
374 return ''
108 else:
375 else:
376 # This uses use StringIO, as cStringIO doesn't handle unicode.
109 stream = StringIO()
377 stream = StringIO()
110 printer = pretty.RepresentationPrinter(stream, self.verbose,
378 printer = pretty.RepresentationPrinter(stream, self.verbose,
111 self.max_width, self.newline,
379 self.max_width, self.newline,
112 singleton_pprinters=self.singleton_pprinters,
380 singleton_pprinters=self.singleton_printers,
113 type_pprinters=self.type_pprinters,
381 type_pprinters=self.type_printers,
114 deferred_pprinters=self.deferred_pprinters)
382 deferred_pprinters=self.deferred_printers)
115 printer.pretty(obj)
383 printer.pretty(obj)
116 printer.flush()
384 printer.flush()
117 return stream.getvalue()
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):
391 To define the callables that compute the HTML representation of your
123 """
392 objects, define a :meth:`__html__` method or use the :meth:`for_type`
124 Add a pretty printer for a given type.
393 or :meth:`for_type_by_name` methods to register functions that handle
125 """
394 this.
126 oldfunc = self.type_pprinters.get(typ, None)
395 """
127 if func is not None:
396 format_type = Str('text/html')
128 # To support easy restoration of old pprinters, we need to ignore
129 # Nones.
130 self.type_pprinters[typ] = func
131 return oldfunc
132
397
133 def for_type_by_name(self, type_module, type_name, func):
398 print_method = Str('__html__')
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
145
399
146
400
147 class FormatterABC(object):
401 class SVGFormatter(BaseFormatter):
148 """ Abstract base class for Formatters.
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.
411 print_method = Str('__svg__')
153 id = 'abstract'
154
412
155 # The kind of data returned.
156 format = 'text/plain'
157
413
158 @abc.abstractmethod
414 class PNGFormatter(BaseFormatter):
159 def __call__(self, obj):
415 """A PNG formatter.
160 """ Return a JSONable representation of the object.
161
416
162 If the object cannot be formatted by this formatter, then return None
417 To define the callables that compute the PNG representation of your
163 """
418 objects, define a :meth:`__png__` method or use the :meth:`for_type`
164 try:
419 or :meth:`for_type_by_name` methods to register functions that handle
165 return repr(obj)
420 this. The raw data should be the base64 encoded raw png data.
166 except TypeError:
421 """
167 return None
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 """hooks for IPython.
1 """hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 hooks are simple functions, but they should be declared with 'self' as their
9 hooks are simple functions, but they should be declared with 'self' as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you need to put the
14 If you wish to define a new hook and activate it, you need to put the
15 necessary code into a python file which can be either imported or execfile()'d
15 necessary code into a python file which can be either imported or execfile()'d
16 from within your ipythonrc configuration.
16 from within your ipythonrc configuration.
17
17
18 For example, suppose that you have a module called 'myiphooks' in your
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 from IPython.core import ipapi
22 from IPython.core import ipapi
23 ip = ipapi.get()
23 ip = ipapi.get()
24
24
25 def calljed(self,filename, linenum):
25 def calljed(self,filename, linenum):
26 "My editor hook calls the jed editor directly."
26 "My editor hook calls the jed editor directly."
27 print "Calling my own editor, jed ..."
27 print "Calling my own editor, jed ..."
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise TryNext()
29 raise TryNext()
30
30
31 ip.set_hook('editor', calljed)
31 ip.set_hook('editor', calljed)
32
32
33 You can then enable the functionality by doing 'import myiphooks'
33 You can then enable the functionality by doing 'import myiphooks'
34 somewhere in your configuration files or ipython command line.
34 somewhere in your configuration files or ipython command line.
35 """
35 """
36
36
37 #*****************************************************************************
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
39 #
40 # Distributed under the terms of the BSD License. The full license is in
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 import os, bisect
44 import os, bisect
45 import sys
45 import sys
46
46
47 from IPython.core.error import TryNext
47 from IPython.core.error import TryNext
48 import IPython.utils.io
48 import IPython.utils.io
49
49
50 # List here all the default hooks. For now it's just the editor functions
50 # List here all the default hooks. For now it's just the editor functions
51 # but over time we'll move here all the public API for user-accessible things.
51 # but over time we'll move here all the public API for user-accessible things.
52
52
53 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
53 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
54 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
54 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
55 'generate_prompt', 'show_in_pager','pre_prompt_hook',
55 'generate_prompt', 'show_in_pager','pre_prompt_hook',
56 'pre_run_code_hook', 'clipboard_get']
56 'pre_run_code_hook', 'clipboard_get']
57
57
58 def editor(self,filename, linenum=None):
58 def editor(self,filename, linenum=None):
59 """Open the default editor at the given filename and linenumber.
59 """Open the default editor at the given filename and linenumber.
60
60
61 This is IPython's default editor hook, you can use it as an example to
61 This is IPython's default editor hook, you can use it as an example to
62 write your own modified one. To set your own editor function as the
62 write your own modified one. To set your own editor function as the
63 new editor hook, call ip.set_hook('editor',yourfunc)."""
63 new editor hook, call ip.set_hook('editor',yourfunc)."""
64
64
65 # IPython configures a default editor at startup by reading $EDITOR from
65 # IPython configures a default editor at startup by reading $EDITOR from
66 # the environment, and falling back on vi (unix) or notepad (win32).
66 # the environment, and falling back on vi (unix) or notepad (win32).
67 editor = self.editor
67 editor = self.editor
68
68
69 # marker for at which line to open the file (for existing objects)
69 # marker for at which line to open the file (for existing objects)
70 if linenum is None or editor=='notepad':
70 if linenum is None or editor=='notepad':
71 linemark = ''
71 linemark = ''
72 else:
72 else:
73 linemark = '+%d' % int(linenum)
73 linemark = '+%d' % int(linenum)
74
74
75 # Enclose in quotes if necessary and legal
75 # Enclose in quotes if necessary and legal
76 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
76 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
77 editor = '"%s"' % editor
77 editor = '"%s"' % editor
78
78
79 # Call the actual editor
79 # Call the actual editor
80 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
80 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
81 raise TryNext()
81 raise TryNext()
82
82
83 import tempfile
83 import tempfile
84 def fix_error_editor(self,filename,linenum,column,msg):
84 def fix_error_editor(self,filename,linenum,column,msg):
85 """Open the editor at the given filename, linenumber, column and
85 """Open the editor at the given filename, linenumber, column and
86 show an error message. This is used for correcting syntax errors.
86 show an error message. This is used for correcting syntax errors.
87 The current implementation only has special support for the VIM editor,
87 The current implementation only has special support for the VIM editor,
88 and falls back on the 'editor' hook if VIM is not used.
88 and falls back on the 'editor' hook if VIM is not used.
89
89
90 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
90 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
91 """
91 """
92 def vim_quickfix_file():
92 def vim_quickfix_file():
93 t = tempfile.NamedTemporaryFile()
93 t = tempfile.NamedTemporaryFile()
94 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
94 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
95 t.flush()
95 t.flush()
96 return t
96 return t
97 if os.path.basename(self.editor) != 'vim':
97 if os.path.basename(self.editor) != 'vim':
98 self.hooks.editor(filename,linenum)
98 self.hooks.editor(filename,linenum)
99 return
99 return
100 t = vim_quickfix_file()
100 t = vim_quickfix_file()
101 try:
101 try:
102 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
102 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
103 raise TryNext()
103 raise TryNext()
104 finally:
104 finally:
105 t.close()
105 t.close()
106
106
107
107
108 def synchronize_with_editor(self, filename, linenum, column):
108 def synchronize_with_editor(self, filename, linenum, column):
109 pass
109 pass
110
110
111
111
112 class CommandChainDispatcher:
112 class CommandChainDispatcher:
113 """ Dispatch calls to a chain of commands until some func can handle it
113 """ Dispatch calls to a chain of commands until some func can handle it
114
114
115 Usage: instantiate, execute "add" to add commands (with optional
115 Usage: instantiate, execute "add" to add commands (with optional
116 priority), execute normally via f() calling mechanism.
116 priority), execute normally via f() calling mechanism.
117
117
118 """
118 """
119 def __init__(self,commands=None):
119 def __init__(self,commands=None):
120 if commands is None:
120 if commands is None:
121 self.chain = []
121 self.chain = []
122 else:
122 else:
123 self.chain = commands
123 self.chain = commands
124
124
125
125
126 def __call__(self,*args, **kw):
126 def __call__(self,*args, **kw):
127 """ Command chain is called just like normal func.
127 """ Command chain is called just like normal func.
128
128
129 This will call all funcs in chain with the same args as were given to this
129 This will call all funcs in chain with the same args as were given to this
130 function, and return the result of first func that didn't raise
130 function, and return the result of first func that didn't raise
131 TryNext """
131 TryNext """
132
132
133 for prio,cmd in self.chain:
133 for prio,cmd in self.chain:
134 #print "prio",prio,"cmd",cmd #dbg
134 #print "prio",prio,"cmd",cmd #dbg
135 try:
135 try:
136 return cmd(*args, **kw)
136 return cmd(*args, **kw)
137 except TryNext, exc:
137 except TryNext, exc:
138 if exc.args or exc.kwargs:
138 if exc.args or exc.kwargs:
139 args = exc.args
139 args = exc.args
140 kw = exc.kwargs
140 kw = exc.kwargs
141 # if no function will accept it, raise TryNext up to the caller
141 # if no function will accept it, raise TryNext up to the caller
142 raise TryNext
142 raise TryNext
143
143
144 def __str__(self):
144 def __str__(self):
145 return str(self.chain)
145 return str(self.chain)
146
146
147 def add(self, func, priority=0):
147 def add(self, func, priority=0):
148 """ Add a func to the cmd chain with given priority """
148 """ Add a func to the cmd chain with given priority """
149 bisect.insort(self.chain,(priority,func))
149 bisect.insort(self.chain,(priority,func))
150
150
151 def __iter__(self):
151 def __iter__(self):
152 """ Return all objects in chain.
152 """ Return all objects in chain.
153
153
154 Handy if the objects are not callable.
154 Handy if the objects are not callable.
155 """
155 """
156 return iter(self.chain)
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 def input_prefilter(self,line):
159 def input_prefilter(self,line):
187 """ Default input prefilter
160 """ Default input prefilter
188
161
189 This returns the line as unchanged, so that the interpreter
162 This returns the line as unchanged, so that the interpreter
190 knows that nothing was done and proceeds with "classic" prefiltering
163 knows that nothing was done and proceeds with "classic" prefiltering
191 (%magics, !shell commands etc.).
164 (%magics, !shell commands etc.).
192
165
193 Note that leading whitespace is not passed to this hook. Prefilter
166 Note that leading whitespace is not passed to this hook. Prefilter
194 can't alter indentation.
167 can't alter indentation.
195
168
196 """
169 """
197 #print "attempt to rewrite",line #dbg
170 #print "attempt to rewrite",line #dbg
198 return line
171 return line
199
172
200
173
201 def shutdown_hook(self):
174 def shutdown_hook(self):
202 """ default shutdown hook
175 """ default shutdown hook
203
176
204 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
177 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
205 """
178 """
206
179
207 #print "default shutdown hook ok" # dbg
180 #print "default shutdown hook ok" # dbg
208 return
181 return
209
182
210
183
211 def late_startup_hook(self):
184 def late_startup_hook(self):
212 """ Executed after ipython has been constructed and configured
185 """ Executed after ipython has been constructed and configured
213
186
214 """
187 """
215 #print "default startup hook ok" # dbg
188 #print "default startup hook ok" # dbg
216
189
217
190
218 def generate_prompt(self, is_continuation):
191 def generate_prompt(self, is_continuation):
219 """ calculate and return a string with the prompt to display """
192 """ calculate and return a string with the prompt to display """
220 if is_continuation:
193 if is_continuation:
221 return str(self.displayhook.prompt2)
194 return str(self.displayhook.prompt2)
222 return str(self.displayhook.prompt1)
195 return str(self.displayhook.prompt1)
223
196
224
197
225 def show_in_pager(self,s):
198 def show_in_pager(self,s):
226 """ Run a string through pager """
199 """ Run a string through pager """
227 # raising TryNext here will use the default paging functionality
200 # raising TryNext here will use the default paging functionality
228 raise TryNext
201 raise TryNext
229
202
230
203
231 def pre_prompt_hook(self):
204 def pre_prompt_hook(self):
232 """ Run before displaying the next prompt
205 """ Run before displaying the next prompt
233
206
234 Use this e.g. to display output from asynchronous operations (in order
207 Use this e.g. to display output from asynchronous operations (in order
235 to not mess up text entry)
208 to not mess up text entry)
236 """
209 """
237
210
238 return None
211 return None
239
212
240
213
241 def pre_run_code_hook(self):
214 def pre_run_code_hook(self):
242 """ Executed before running the (prefiltered) code in IPython """
215 """ Executed before running the (prefiltered) code in IPython """
243 return None
216 return None
244
217
245
218
246 def clipboard_get(self):
219 def clipboard_get(self):
247 """ Get text from the clipboard.
220 """ Get text from the clipboard.
248 """
221 """
249 from IPython.lib.clipboard import (
222 from IPython.lib.clipboard import (
250 osx_clipboard_get, tkinter_clipboard_get,
223 osx_clipboard_get, tkinter_clipboard_get,
251 win32_clipboard_get
224 win32_clipboard_get
252 )
225 )
253 if sys.platform == 'win32':
226 if sys.platform == 'win32':
254 chain = [win32_clipboard_get, tkinter_clipboard_get]
227 chain = [win32_clipboard_get, tkinter_clipboard_get]
255 elif sys.platform == 'darwin':
228 elif sys.platform == 'darwin':
256 chain = [osx_clipboard_get, tkinter_clipboard_get]
229 chain = [osx_clipboard_get, tkinter_clipboard_get]
257 else:
230 else:
258 chain = [tkinter_clipboard_get]
231 chain = [tkinter_clipboard_get]
259 dispatcher = CommandChainDispatcher()
232 dispatcher = CommandChainDispatcher()
260 for func in chain:
233 for func in chain:
261 dispatcher.add(func)
234 dispatcher.add(func)
262 text = dispatcher()
235 text = dispatcher()
263 return text
236 return text
@@ -1,2543 +1,2555 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import atexit
23 import atexit
24 import codeop
24 import codeop
25 import os
25 import os
26 import re
26 import re
27 import sys
27 import sys
28 import tempfile
28 import tempfile
29 import types
29 import types
30 from contextlib import nested
30 from contextlib import nested
31
31
32 from IPython.config.configurable import Configurable
32 from IPython.config.configurable import Configurable
33 from IPython.core import debugger, oinspect
33 from IPython.core import debugger, oinspect
34 from IPython.core import history as ipcorehist
34 from IPython.core import history as ipcorehist
35 from IPython.core import page
35 from IPython.core import page
36 from IPython.core import prefilter
36 from IPython.core import prefilter
37 from IPython.core import shadowns
37 from IPython.core import shadowns
38 from IPython.core import ultratb
38 from IPython.core import ultratb
39 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
40 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.compilerop import CachingCompiler
41 from IPython.core.compilerop import CachingCompiler
42 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.displayhook import DisplayHook
43 from IPython.core.displayhook import DisplayHook
44 from IPython.core.displaypub import DisplayPublisher
44 from IPython.core.error import TryNext, UsageError
45 from IPython.core.error import TryNext, UsageError
45 from IPython.core.extensions import ExtensionManager
46 from IPython.core.extensions import ExtensionManager
46 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 from IPython.core.formatters import DisplayFormatter
47 from IPython.core.history import HistoryManager
49 from IPython.core.history import HistoryManager
48 from IPython.core.inputsplitter import IPythonInputSplitter
50 from IPython.core.inputsplitter import IPythonInputSplitter
49 from IPython.core.logger import Logger
51 from IPython.core.logger import Logger
50 from IPython.core.magic import Magic
52 from IPython.core.magic import Magic
51 from IPython.core.payload import PayloadManager
53 from IPython.core.payload import PayloadManager
52 from IPython.core.plugin import PluginManager
54 from IPython.core.plugin import PluginManager
53 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
55 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 from IPython.external.Itpl import ItplNS
56 from IPython.external.Itpl import ItplNS
55 from IPython.utils import PyColorize
57 from IPython.utils import PyColorize
56 from IPython.utils import io
58 from IPython.utils import io
57 from IPython.utils import pickleshare
59 from IPython.utils import pickleshare
58 from IPython.utils.doctestreload import doctest_reload
60 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.io import ask_yes_no, rprint
61 from IPython.utils.io import ask_yes_no, rprint
60 from IPython.utils.ipstruct import Struct
62 from IPython.utils.ipstruct import Struct
61 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
63 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.process import system, getoutput
64 from IPython.utils.process import system, getoutput
63 from IPython.utils.strdispatch import StrDispatch
65 from IPython.utils.strdispatch import StrDispatch
64 from IPython.utils.syspathcontext import prepended_to_syspath
66 from IPython.utils.syspathcontext import prepended_to_syspath
65 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
67 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
66 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
68 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 List, Unicode, Instance, Type)
69 List, Unicode, Instance, Type)
68 from IPython.utils.warn import warn, error, fatal
70 from IPython.utils.warn import warn, error, fatal
69 import IPython.core.hooks
71 import IPython.core.hooks
70
72
71 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
72 # Globals
74 # Globals
73 #-----------------------------------------------------------------------------
75 #-----------------------------------------------------------------------------
74
76
75 # compiled regexps for autoindent management
77 # compiled regexps for autoindent management
76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77
79
78 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
79 # Utilities
81 # Utilities
80 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
81
83
82 # store the builtin raw_input globally, and use this always, in case user code
84 # store the builtin raw_input globally, and use this always, in case user code
83 # overwrites it (like wx.py.PyShell does)
85 # overwrites it (like wx.py.PyShell does)
84 raw_input_original = raw_input
86 raw_input_original = raw_input
85
87
86 def softspace(file, newvalue):
88 def softspace(file, newvalue):
87 """Copied from code.py, to remove the dependency"""
89 """Copied from code.py, to remove the dependency"""
88
90
89 oldvalue = 0
91 oldvalue = 0
90 try:
92 try:
91 oldvalue = file.softspace
93 oldvalue = file.softspace
92 except AttributeError:
94 except AttributeError:
93 pass
95 pass
94 try:
96 try:
95 file.softspace = newvalue
97 file.softspace = newvalue
96 except (AttributeError, TypeError):
98 except (AttributeError, TypeError):
97 # "attribute-less object" or "read-only attributes"
99 # "attribute-less object" or "read-only attributes"
98 pass
100 pass
99 return oldvalue
101 return oldvalue
100
102
101
103
102 def no_op(*a, **kw): pass
104 def no_op(*a, **kw): pass
103
105
104 class SpaceInInput(Exception): pass
106 class SpaceInInput(Exception): pass
105
107
106 class Bunch: pass
108 class Bunch: pass
107
109
108
110
109 def get_default_colors():
111 def get_default_colors():
110 if sys.platform=='darwin':
112 if sys.platform=='darwin':
111 return "LightBG"
113 return "LightBG"
112 elif os.name=='nt':
114 elif os.name=='nt':
113 return 'Linux'
115 return 'Linux'
114 else:
116 else:
115 return 'Linux'
117 return 'Linux'
116
118
117
119
118 class SeparateStr(Str):
120 class SeparateStr(Str):
119 """A Str subclass to validate separate_in, separate_out, etc.
121 """A Str subclass to validate separate_in, separate_out, etc.
120
122
121 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
123 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 """
124 """
123
125
124 def validate(self, obj, value):
126 def validate(self, obj, value):
125 if value == '0': value = ''
127 if value == '0': value = ''
126 value = value.replace('\\n','\n')
128 value = value.replace('\\n','\n')
127 return super(SeparateStr, self).validate(obj, value)
129 return super(SeparateStr, self).validate(obj, value)
128
130
129 class MultipleInstanceError(Exception):
131 class MultipleInstanceError(Exception):
130 pass
132 pass
131
133
132
134
133 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
134 # Main IPython class
136 # Main IPython class
135 #-----------------------------------------------------------------------------
137 #-----------------------------------------------------------------------------
136
138
137 class InteractiveShell(Configurable, Magic):
139 class InteractiveShell(Configurable, Magic):
138 """An enhanced, interactive shell for Python."""
140 """An enhanced, interactive shell for Python."""
139
141
140 _instance = None
142 _instance = None
141 autocall = Enum((0,1,2), default_value=1, config=True)
143 autocall = Enum((0,1,2), default_value=1, config=True)
142 # TODO: remove all autoindent logic and put into frontends.
144 # TODO: remove all autoindent logic and put into frontends.
143 # We can't do this yet because even runlines uses the autoindent.
145 # We can't do this yet because even runlines uses the autoindent.
144 autoindent = CBool(True, config=True)
146 autoindent = CBool(True, config=True)
145 automagic = CBool(True, config=True)
147 automagic = CBool(True, config=True)
146 cache_size = Int(1000, config=True)
148 cache_size = Int(1000, config=True)
147 color_info = CBool(True, config=True)
149 color_info = CBool(True, config=True)
148 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
149 default_value=get_default_colors(), config=True)
151 default_value=get_default_colors(), config=True)
150 debug = CBool(False, config=True)
152 debug = CBool(False, config=True)
151 deep_reload = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
154 display_formatter = Instance(DisplayFormatter)
152 displayhook_class = Type(DisplayHook)
155 displayhook_class = Type(DisplayHook)
156 display_pub_class = Type(DisplayPublisher)
157
153 exit_now = CBool(False)
158 exit_now = CBool(False)
154 # Monotonically increasing execution counter
159 # Monotonically increasing execution counter
155 execution_count = Int(1)
160 execution_count = Int(1)
156 filename = Str("<ipython console>")
161 filename = Str("<ipython console>")
157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
162 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158
163
159 # Input splitter, to split entire cells of input into either individual
164 # Input splitter, to split entire cells of input into either individual
160 # interactive statements or whole blocks.
165 # interactive statements or whole blocks.
161 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
166 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 (), {})
167 (), {})
163 logstart = CBool(False, config=True)
168 logstart = CBool(False, config=True)
164 logfile = Str('', config=True)
169 logfile = Str('', config=True)
165 logappend = Str('', config=True)
170 logappend = Str('', config=True)
166 object_info_string_level = Enum((0,1,2), default_value=0,
171 object_info_string_level = Enum((0,1,2), default_value=0,
167 config=True)
172 config=True)
168 pdb = CBool(False, config=True)
173 pdb = CBool(False, config=True)
169
174
170 pprint = CBool(True, config=True)
171 profile = Str('', config=True)
175 profile = Str('', config=True)
172 prompt_in1 = Str('In [\\#]: ', config=True)
176 prompt_in1 = Str('In [\\#]: ', config=True)
173 prompt_in2 = Str(' .\\D.: ', config=True)
177 prompt_in2 = Str(' .\\D.: ', config=True)
174 prompt_out = Str('Out[\\#]: ', config=True)
178 prompt_out = Str('Out[\\#]: ', config=True)
175 prompts_pad_left = CBool(True, config=True)
179 prompts_pad_left = CBool(True, config=True)
176 quiet = CBool(False, config=True)
180 quiet = CBool(False, config=True)
177
181
178 history_length = Int(10000, config=True)
182 history_length = Int(10000, config=True)
179
183
180 # The readline stuff will eventually be moved to the terminal subclass
184 # The readline stuff will eventually be moved to the terminal subclass
181 # but for now, we can't do that as readline is welded in everywhere.
185 # but for now, we can't do that as readline is welded in everywhere.
182 readline_use = CBool(True, config=True)
186 readline_use = CBool(True, config=True)
183 readline_merge_completions = CBool(True, config=True)
187 readline_merge_completions = CBool(True, config=True)
184 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
188 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
185 readline_remove_delims = Str('-/~', config=True)
189 readline_remove_delims = Str('-/~', config=True)
186 readline_parse_and_bind = List([
190 readline_parse_and_bind = List([
187 'tab: complete',
191 'tab: complete',
188 '"\C-l": clear-screen',
192 '"\C-l": clear-screen',
189 'set show-all-if-ambiguous on',
193 'set show-all-if-ambiguous on',
190 '"\C-o": tab-insert',
194 '"\C-o": tab-insert',
191 '"\M-i": " "',
195 '"\M-i": " "',
192 '"\M-o": "\d\d\d\d"',
196 '"\M-o": "\d\d\d\d"',
193 '"\M-I": "\d\d\d\d"',
197 '"\M-I": "\d\d\d\d"',
194 '"\C-r": reverse-search-history',
198 '"\C-r": reverse-search-history',
195 '"\C-s": forward-search-history',
199 '"\C-s": forward-search-history',
196 '"\C-p": history-search-backward',
200 '"\C-p": history-search-backward',
197 '"\C-n": history-search-forward',
201 '"\C-n": history-search-forward',
198 '"\e[A": history-search-backward',
202 '"\e[A": history-search-backward',
199 '"\e[B": history-search-forward',
203 '"\e[B": history-search-forward',
200 '"\C-k": kill-line',
204 '"\C-k": kill-line',
201 '"\C-u": unix-line-discard',
205 '"\C-u": unix-line-discard',
202 ], allow_none=False, config=True)
206 ], allow_none=False, config=True)
203
207
204 # TODO: this part of prompt management should be moved to the frontends.
208 # TODO: this part of prompt management should be moved to the frontends.
205 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
209 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
206 separate_in = SeparateStr('\n', config=True)
210 separate_in = SeparateStr('\n', config=True)
207 separate_out = SeparateStr('', config=True)
211 separate_out = SeparateStr('', config=True)
208 separate_out2 = SeparateStr('', config=True)
212 separate_out2 = SeparateStr('', config=True)
209 wildcards_case_sensitive = CBool(True, config=True)
213 wildcards_case_sensitive = CBool(True, config=True)
210 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
214 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
211 default_value='Context', config=True)
215 default_value='Context', config=True)
212
216
213 # Subcomponents of InteractiveShell
217 # Subcomponents of InteractiveShell
214 alias_manager = Instance('IPython.core.alias.AliasManager')
218 alias_manager = Instance('IPython.core.alias.AliasManager')
215 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
219 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
216 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
220 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
217 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
221 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
218 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
222 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
219 plugin_manager = Instance('IPython.core.plugin.PluginManager')
223 plugin_manager = Instance('IPython.core.plugin.PluginManager')
220 payload_manager = Instance('IPython.core.payload.PayloadManager')
224 payload_manager = Instance('IPython.core.payload.PayloadManager')
221 history_manager = Instance('IPython.core.history.HistoryManager')
225 history_manager = Instance('IPython.core.history.HistoryManager')
222
226
223 # Private interface
227 # Private interface
224 _post_execute = set()
228 _post_execute = set()
225
229
226 def __init__(self, config=None, ipython_dir=None,
230 def __init__(self, config=None, ipython_dir=None,
227 user_ns=None, user_global_ns=None,
231 user_ns=None, user_global_ns=None,
228 custom_exceptions=((), None)):
232 custom_exceptions=((), None)):
229
233
230 # This is where traits with a config_key argument are updated
234 # This is where traits with a config_key argument are updated
231 # from the values on config.
235 # from the values on config.
232 super(InteractiveShell, self).__init__(config=config)
236 super(InteractiveShell, self).__init__(config=config)
233
237
234 # These are relatively independent and stateless
238 # These are relatively independent and stateless
235 self.init_ipython_dir(ipython_dir)
239 self.init_ipython_dir(ipython_dir)
236 self.init_instance_attrs()
240 self.init_instance_attrs()
237 self.init_environment()
241 self.init_environment()
238
242
239 # Create namespaces (user_ns, user_global_ns, etc.)
243 # Create namespaces (user_ns, user_global_ns, etc.)
240 self.init_create_namespaces(user_ns, user_global_ns)
244 self.init_create_namespaces(user_ns, user_global_ns)
241 # This has to be done after init_create_namespaces because it uses
245 # This has to be done after init_create_namespaces because it uses
242 # something in self.user_ns, but before init_sys_modules, which
246 # something in self.user_ns, but before init_sys_modules, which
243 # is the first thing to modify sys.
247 # is the first thing to modify sys.
244 # TODO: When we override sys.stdout and sys.stderr before this class
248 # TODO: When we override sys.stdout and sys.stderr before this class
245 # is created, we are saving the overridden ones here. Not sure if this
249 # is created, we are saving the overridden ones here. Not sure if this
246 # is what we want to do.
250 # is what we want to do.
247 self.save_sys_module_state()
251 self.save_sys_module_state()
248 self.init_sys_modules()
252 self.init_sys_modules()
249
253
250 self.init_history()
254 self.init_history()
251 self.init_encoding()
255 self.init_encoding()
252 self.init_prefilter()
256 self.init_prefilter()
253
257
254 Magic.__init__(self, self)
258 Magic.__init__(self, self)
255
259
256 self.init_syntax_highlighting()
260 self.init_syntax_highlighting()
257 self.init_hooks()
261 self.init_hooks()
258 self.init_pushd_popd_magic()
262 self.init_pushd_popd_magic()
259 # self.init_traceback_handlers use to be here, but we moved it below
263 # self.init_traceback_handlers use to be here, but we moved it below
260 # because it and init_io have to come after init_readline.
264 # because it and init_io have to come after init_readline.
261 self.init_user_ns()
265 self.init_user_ns()
262 self.init_logger()
266 self.init_logger()
263 self.init_alias()
267 self.init_alias()
264 self.init_builtins()
268 self.init_builtins()
265
269
266 # pre_config_initialization
270 # pre_config_initialization
267
271
268 # The next section should contain everything that was in ipmaker.
272 # The next section should contain everything that was in ipmaker.
269 self.init_logstart()
273 self.init_logstart()
270
274
271 # The following was in post_config_initialization
275 # The following was in post_config_initialization
272 self.init_inspector()
276 self.init_inspector()
273 # init_readline() must come before init_io(), because init_io uses
277 # init_readline() must come before init_io(), because init_io uses
274 # readline related things.
278 # readline related things.
275 self.init_readline()
279 self.init_readline()
276 # init_completer must come after init_readline, because it needs to
280 # init_completer must come after init_readline, because it needs to
277 # know whether readline is present or not system-wide to configure the
281 # know whether readline is present or not system-wide to configure the
278 # completers, since the completion machinery can now operate
282 # completers, since the completion machinery can now operate
279 # independently of readline (e.g. over the network)
283 # independently of readline (e.g. over the network)
280 self.init_completer()
284 self.init_completer()
281 # TODO: init_io() needs to happen before init_traceback handlers
285 # TODO: init_io() needs to happen before init_traceback handlers
282 # because the traceback handlers hardcode the stdout/stderr streams.
286 # because the traceback handlers hardcode the stdout/stderr streams.
283 # This logic in in debugger.Pdb and should eventually be changed.
287 # This logic in in debugger.Pdb and should eventually be changed.
284 self.init_io()
288 self.init_io()
285 self.init_traceback_handlers(custom_exceptions)
289 self.init_traceback_handlers(custom_exceptions)
286 self.init_prompts()
290 self.init_prompts()
291 self.init_display_formatter()
292 self.init_display_pub()
287 self.init_displayhook()
293 self.init_displayhook()
288 self.init_reload_doctest()
294 self.init_reload_doctest()
289 self.init_magics()
295 self.init_magics()
290 self.init_pdb()
296 self.init_pdb()
291 self.init_extension_manager()
297 self.init_extension_manager()
292 self.init_plugin_manager()
298 self.init_plugin_manager()
293 self.init_payload()
299 self.init_payload()
294 self.hooks.late_startup_hook()
300 self.hooks.late_startup_hook()
295 atexit.register(self.atexit_operations)
301 atexit.register(self.atexit_operations)
296
302
297 # While we're trying to have each part of the code directly access what it
303 # While we're trying to have each part of the code directly access what it
298 # needs without keeping redundant references to objects, we have too much
304 # needs without keeping redundant references to objects, we have too much
299 # legacy code that expects ip.db to exist, so let's make it a property that
305 # legacy code that expects ip.db to exist, so let's make it a property that
300 # retrieves the underlying object from our new history manager.
306 # retrieves the underlying object from our new history manager.
301 @property
307 @property
302 def db(self):
308 def db(self):
303 return self.history_manager.shadow_db
309 return self.history_manager.shadow_db
304
310
305 @classmethod
311 @classmethod
306 def instance(cls, *args, **kwargs):
312 def instance(cls, *args, **kwargs):
307 """Returns a global InteractiveShell instance."""
313 """Returns a global InteractiveShell instance."""
308 if cls._instance is None:
314 if cls._instance is None:
309 inst = cls(*args, **kwargs)
315 inst = cls(*args, **kwargs)
310 # Now make sure that the instance will also be returned by
316 # Now make sure that the instance will also be returned by
311 # the subclasses instance attribute.
317 # the subclasses instance attribute.
312 for subclass in cls.mro():
318 for subclass in cls.mro():
313 if issubclass(cls, subclass) and \
319 if issubclass(cls, subclass) and \
314 issubclass(subclass, InteractiveShell):
320 issubclass(subclass, InteractiveShell):
315 subclass._instance = inst
321 subclass._instance = inst
316 else:
322 else:
317 break
323 break
318 if isinstance(cls._instance, cls):
324 if isinstance(cls._instance, cls):
319 return cls._instance
325 return cls._instance
320 else:
326 else:
321 raise MultipleInstanceError(
327 raise MultipleInstanceError(
322 'Multiple incompatible subclass instances of '
328 'Multiple incompatible subclass instances of '
323 'InteractiveShell are being created.'
329 'InteractiveShell are being created.'
324 )
330 )
325
331
326 @classmethod
332 @classmethod
327 def initialized(cls):
333 def initialized(cls):
328 return hasattr(cls, "_instance")
334 return hasattr(cls, "_instance")
329
335
330 def get_ipython(self):
336 def get_ipython(self):
331 """Return the currently running IPython instance."""
337 """Return the currently running IPython instance."""
332 return self
338 return self
333
339
334 #-------------------------------------------------------------------------
340 #-------------------------------------------------------------------------
335 # Trait changed handlers
341 # Trait changed handlers
336 #-------------------------------------------------------------------------
342 #-------------------------------------------------------------------------
337
343
338 def _ipython_dir_changed(self, name, new):
344 def _ipython_dir_changed(self, name, new):
339 if not os.path.isdir(new):
345 if not os.path.isdir(new):
340 os.makedirs(new, mode = 0777)
346 os.makedirs(new, mode = 0777)
341
347
342 def set_autoindent(self,value=None):
348 def set_autoindent(self,value=None):
343 """Set the autoindent flag, checking for readline support.
349 """Set the autoindent flag, checking for readline support.
344
350
345 If called with no arguments, it acts as a toggle."""
351 If called with no arguments, it acts as a toggle."""
346
352
347 if not self.has_readline:
353 if not self.has_readline:
348 if os.name == 'posix':
354 if os.name == 'posix':
349 warn("The auto-indent feature requires the readline library")
355 warn("The auto-indent feature requires the readline library")
350 self.autoindent = 0
356 self.autoindent = 0
351 return
357 return
352 if value is None:
358 if value is None:
353 self.autoindent = not self.autoindent
359 self.autoindent = not self.autoindent
354 else:
360 else:
355 self.autoindent = value
361 self.autoindent = value
356
362
357 #-------------------------------------------------------------------------
363 #-------------------------------------------------------------------------
358 # init_* methods called by __init__
364 # init_* methods called by __init__
359 #-------------------------------------------------------------------------
365 #-------------------------------------------------------------------------
360
366
361 def init_ipython_dir(self, ipython_dir):
367 def init_ipython_dir(self, ipython_dir):
362 if ipython_dir is not None:
368 if ipython_dir is not None:
363 self.ipython_dir = ipython_dir
369 self.ipython_dir = ipython_dir
364 self.config.Global.ipython_dir = self.ipython_dir
370 self.config.Global.ipython_dir = self.ipython_dir
365 return
371 return
366
372
367 if hasattr(self.config.Global, 'ipython_dir'):
373 if hasattr(self.config.Global, 'ipython_dir'):
368 self.ipython_dir = self.config.Global.ipython_dir
374 self.ipython_dir = self.config.Global.ipython_dir
369 else:
375 else:
370 self.ipython_dir = get_ipython_dir()
376 self.ipython_dir = get_ipython_dir()
371
377
372 # All children can just read this
378 # All children can just read this
373 self.config.Global.ipython_dir = self.ipython_dir
379 self.config.Global.ipython_dir = self.ipython_dir
374
380
375 def init_instance_attrs(self):
381 def init_instance_attrs(self):
376 self.more = False
382 self.more = False
377
383
378 # command compiler
384 # command compiler
379 self.compile = CachingCompiler()
385 self.compile = CachingCompiler()
380
386
381 # User input buffers
387 # User input buffers
382 # NOTE: these variables are slated for full removal, once we are 100%
388 # NOTE: these variables are slated for full removal, once we are 100%
383 # sure that the new execution logic is solid. We will delte runlines,
389 # sure that the new execution logic is solid. We will delte runlines,
384 # push_line and these buffers, as all input will be managed by the
390 # push_line and these buffers, as all input will be managed by the
385 # frontends via an inputsplitter instance.
391 # frontends via an inputsplitter instance.
386 self.buffer = []
392 self.buffer = []
387 self.buffer_raw = []
393 self.buffer_raw = []
388
394
389 # Make an empty namespace, which extension writers can rely on both
395 # Make an empty namespace, which extension writers can rely on both
390 # existing and NEVER being used by ipython itself. This gives them a
396 # existing and NEVER being used by ipython itself. This gives them a
391 # convenient location for storing additional information and state
397 # convenient location for storing additional information and state
392 # their extensions may require, without fear of collisions with other
398 # their extensions may require, without fear of collisions with other
393 # ipython names that may develop later.
399 # ipython names that may develop later.
394 self.meta = Struct()
400 self.meta = Struct()
395
401
396 # Object variable to store code object waiting execution. This is
402 # Object variable to store code object waiting execution. This is
397 # used mainly by the multithreaded shells, but it can come in handy in
403 # used mainly by the multithreaded shells, but it can come in handy in
398 # other situations. No need to use a Queue here, since it's a single
404 # other situations. No need to use a Queue here, since it's a single
399 # item which gets cleared once run.
405 # item which gets cleared once run.
400 self.code_to_run = None
406 self.code_to_run = None
401
407
402 # Temporary files used for various purposes. Deleted at exit.
408 # Temporary files used for various purposes. Deleted at exit.
403 self.tempfiles = []
409 self.tempfiles = []
404
410
405 # Keep track of readline usage (later set by init_readline)
411 # Keep track of readline usage (later set by init_readline)
406 self.has_readline = False
412 self.has_readline = False
407
413
408 # keep track of where we started running (mainly for crash post-mortem)
414 # keep track of where we started running (mainly for crash post-mortem)
409 # This is not being used anywhere currently.
415 # This is not being used anywhere currently.
410 self.starting_dir = os.getcwd()
416 self.starting_dir = os.getcwd()
411
417
412 # Indentation management
418 # Indentation management
413 self.indent_current_nsp = 0
419 self.indent_current_nsp = 0
414
420
415 def init_environment(self):
421 def init_environment(self):
416 """Any changes we need to make to the user's environment."""
422 """Any changes we need to make to the user's environment."""
417 pass
423 pass
418
424
419 def init_encoding(self):
425 def init_encoding(self):
420 # Get system encoding at startup time. Certain terminals (like Emacs
426 # Get system encoding at startup time. Certain terminals (like Emacs
421 # under Win32 have it set to None, and we need to have a known valid
427 # under Win32 have it set to None, and we need to have a known valid
422 # encoding to use in the raw_input() method
428 # encoding to use in the raw_input() method
423 try:
429 try:
424 self.stdin_encoding = sys.stdin.encoding or 'ascii'
430 self.stdin_encoding = sys.stdin.encoding or 'ascii'
425 except AttributeError:
431 except AttributeError:
426 self.stdin_encoding = 'ascii'
432 self.stdin_encoding = 'ascii'
427
433
428 def init_syntax_highlighting(self):
434 def init_syntax_highlighting(self):
429 # Python source parser/formatter for syntax highlighting
435 # Python source parser/formatter for syntax highlighting
430 pyformat = PyColorize.Parser().format
436 pyformat = PyColorize.Parser().format
431 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
437 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
432
438
433 def init_pushd_popd_magic(self):
439 def init_pushd_popd_magic(self):
434 # for pushd/popd management
440 # for pushd/popd management
435 try:
441 try:
436 self.home_dir = get_home_dir()
442 self.home_dir = get_home_dir()
437 except HomeDirError, msg:
443 except HomeDirError, msg:
438 fatal(msg)
444 fatal(msg)
439
445
440 self.dir_stack = []
446 self.dir_stack = []
441
447
442 def init_logger(self):
448 def init_logger(self):
443 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
449 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
444 logmode='rotate')
450 logmode='rotate')
445
451
446 def init_logstart(self):
452 def init_logstart(self):
447 """Initialize logging in case it was requested at the command line.
453 """Initialize logging in case it was requested at the command line.
448 """
454 """
449 if self.logappend:
455 if self.logappend:
450 self.magic_logstart(self.logappend + ' append')
456 self.magic_logstart(self.logappend + ' append')
451 elif self.logfile:
457 elif self.logfile:
452 self.magic_logstart(self.logfile)
458 self.magic_logstart(self.logfile)
453 elif self.logstart:
459 elif self.logstart:
454 self.magic_logstart()
460 self.magic_logstart()
455
461
456 def init_builtins(self):
462 def init_builtins(self):
457 self.builtin_trap = BuiltinTrap(shell=self)
463 self.builtin_trap = BuiltinTrap(shell=self)
458
464
459 def init_inspector(self):
465 def init_inspector(self):
460 # Object inspector
466 # Object inspector
461 self.inspector = oinspect.Inspector(oinspect.InspectColors,
467 self.inspector = oinspect.Inspector(oinspect.InspectColors,
462 PyColorize.ANSICodeColors,
468 PyColorize.ANSICodeColors,
463 'NoColor',
469 'NoColor',
464 self.object_info_string_level)
470 self.object_info_string_level)
465
471
466 def init_io(self):
472 def init_io(self):
467 # This will just use sys.stdout and sys.stderr. If you want to
473 # This will just use sys.stdout and sys.stderr. If you want to
468 # override sys.stdout and sys.stderr themselves, you need to do that
474 # override sys.stdout and sys.stderr themselves, you need to do that
469 # *before* instantiating this class, because Term holds onto
475 # *before* instantiating this class, because Term holds onto
470 # references to the underlying streams.
476 # references to the underlying streams.
471 if sys.platform == 'win32' and self.has_readline:
477 if sys.platform == 'win32' and self.has_readline:
472 Term = io.IOTerm(cout=self.readline._outputfile,
478 Term = io.IOTerm(cout=self.readline._outputfile,
473 cerr=self.readline._outputfile)
479 cerr=self.readline._outputfile)
474 else:
480 else:
475 Term = io.IOTerm()
481 Term = io.IOTerm()
476 io.Term = Term
482 io.Term = Term
477
483
478 def init_prompts(self):
484 def init_prompts(self):
479 # TODO: This is a pass for now because the prompts are managed inside
485 # TODO: This is a pass for now because the prompts are managed inside
480 # the DisplayHook. Once there is a separate prompt manager, this
486 # the DisplayHook. Once there is a separate prompt manager, this
481 # will initialize that object and all prompt related information.
487 # will initialize that object and all prompt related information.
482 pass
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 def init_displayhook(self):
496 def init_displayhook(self):
485 # Initialize displayhook, set in/out prompts and printing system
497 # Initialize displayhook, set in/out prompts and printing system
486 self.displayhook = self.displayhook_class(
498 self.displayhook = self.displayhook_class(
487 config=self.config,
499 config=self.config,
488 shell=self,
500 shell=self,
489 cache_size=self.cache_size,
501 cache_size=self.cache_size,
490 input_sep = self.separate_in,
502 input_sep = self.separate_in,
491 output_sep = self.separate_out,
503 output_sep = self.separate_out,
492 output_sep2 = self.separate_out2,
504 output_sep2 = self.separate_out2,
493 ps1 = self.prompt_in1,
505 ps1 = self.prompt_in1,
494 ps2 = self.prompt_in2,
506 ps2 = self.prompt_in2,
495 ps_out = self.prompt_out,
507 ps_out = self.prompt_out,
496 pad_left = self.prompts_pad_left
508 pad_left = self.prompts_pad_left
497 )
509 )
498 # This is a context manager that installs/revmoes the displayhook at
510 # This is a context manager that installs/revmoes the displayhook at
499 # the appropriate time.
511 # the appropriate time.
500 self.display_trap = DisplayTrap(hook=self.displayhook)
512 self.display_trap = DisplayTrap(hook=self.displayhook)
501
513
502 def init_reload_doctest(self):
514 def init_reload_doctest(self):
503 # Do a proper resetting of doctest, including the necessary displayhook
515 # Do a proper resetting of doctest, including the necessary displayhook
504 # monkeypatching
516 # monkeypatching
505 try:
517 try:
506 doctest_reload()
518 doctest_reload()
507 except ImportError:
519 except ImportError:
508 warn("doctest module does not exist.")
520 warn("doctest module does not exist.")
509
521
510 #-------------------------------------------------------------------------
522 #-------------------------------------------------------------------------
511 # Things related to injections into the sys module
523 # Things related to injections into the sys module
512 #-------------------------------------------------------------------------
524 #-------------------------------------------------------------------------
513
525
514 def save_sys_module_state(self):
526 def save_sys_module_state(self):
515 """Save the state of hooks in the sys module.
527 """Save the state of hooks in the sys module.
516
528
517 This has to be called after self.user_ns is created.
529 This has to be called after self.user_ns is created.
518 """
530 """
519 self._orig_sys_module_state = {}
531 self._orig_sys_module_state = {}
520 self._orig_sys_module_state['stdin'] = sys.stdin
532 self._orig_sys_module_state['stdin'] = sys.stdin
521 self._orig_sys_module_state['stdout'] = sys.stdout
533 self._orig_sys_module_state['stdout'] = sys.stdout
522 self._orig_sys_module_state['stderr'] = sys.stderr
534 self._orig_sys_module_state['stderr'] = sys.stderr
523 self._orig_sys_module_state['excepthook'] = sys.excepthook
535 self._orig_sys_module_state['excepthook'] = sys.excepthook
524 try:
536 try:
525 self._orig_sys_modules_main_name = self.user_ns['__name__']
537 self._orig_sys_modules_main_name = self.user_ns['__name__']
526 except KeyError:
538 except KeyError:
527 pass
539 pass
528
540
529 def restore_sys_module_state(self):
541 def restore_sys_module_state(self):
530 """Restore the state of the sys module."""
542 """Restore the state of the sys module."""
531 try:
543 try:
532 for k, v in self._orig_sys_module_state.iteritems():
544 for k, v in self._orig_sys_module_state.iteritems():
533 setattr(sys, k, v)
545 setattr(sys, k, v)
534 except AttributeError:
546 except AttributeError:
535 pass
547 pass
536 # Reset what what done in self.init_sys_modules
548 # Reset what what done in self.init_sys_modules
537 try:
549 try:
538 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
550 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
539 except (AttributeError, KeyError):
551 except (AttributeError, KeyError):
540 pass
552 pass
541
553
542 #-------------------------------------------------------------------------
554 #-------------------------------------------------------------------------
543 # Things related to hooks
555 # Things related to hooks
544 #-------------------------------------------------------------------------
556 #-------------------------------------------------------------------------
545
557
546 def init_hooks(self):
558 def init_hooks(self):
547 # hooks holds pointers used for user-side customizations
559 # hooks holds pointers used for user-side customizations
548 self.hooks = Struct()
560 self.hooks = Struct()
549
561
550 self.strdispatchers = {}
562 self.strdispatchers = {}
551
563
552 # Set all default hooks, defined in the IPython.hooks module.
564 # Set all default hooks, defined in the IPython.hooks module.
553 hooks = IPython.core.hooks
565 hooks = IPython.core.hooks
554 for hook_name in hooks.__all__:
566 for hook_name in hooks.__all__:
555 # default hooks have priority 100, i.e. low; user hooks should have
567 # default hooks have priority 100, i.e. low; user hooks should have
556 # 0-100 priority
568 # 0-100 priority
557 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
569 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
558
570
559 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
571 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
560 """set_hook(name,hook) -> sets an internal IPython hook.
572 """set_hook(name,hook) -> sets an internal IPython hook.
561
573
562 IPython exposes some of its internal API as user-modifiable hooks. By
574 IPython exposes some of its internal API as user-modifiable hooks. By
563 adding your function to one of these hooks, you can modify IPython's
575 adding your function to one of these hooks, you can modify IPython's
564 behavior to call at runtime your own routines."""
576 behavior to call at runtime your own routines."""
565
577
566 # At some point in the future, this should validate the hook before it
578 # At some point in the future, this should validate the hook before it
567 # accepts it. Probably at least check that the hook takes the number
579 # accepts it. Probably at least check that the hook takes the number
568 # of args it's supposed to.
580 # of args it's supposed to.
569
581
570 f = types.MethodType(hook,self)
582 f = types.MethodType(hook,self)
571
583
572 # check if the hook is for strdispatcher first
584 # check if the hook is for strdispatcher first
573 if str_key is not None:
585 if str_key is not None:
574 sdp = self.strdispatchers.get(name, StrDispatch())
586 sdp = self.strdispatchers.get(name, StrDispatch())
575 sdp.add_s(str_key, f, priority )
587 sdp.add_s(str_key, f, priority )
576 self.strdispatchers[name] = sdp
588 self.strdispatchers[name] = sdp
577 return
589 return
578 if re_key is not None:
590 if re_key is not None:
579 sdp = self.strdispatchers.get(name, StrDispatch())
591 sdp = self.strdispatchers.get(name, StrDispatch())
580 sdp.add_re(re.compile(re_key), f, priority )
592 sdp.add_re(re.compile(re_key), f, priority )
581 self.strdispatchers[name] = sdp
593 self.strdispatchers[name] = sdp
582 return
594 return
583
595
584 dp = getattr(self.hooks, name, None)
596 dp = getattr(self.hooks, name, None)
585 if name not in IPython.core.hooks.__all__:
597 if name not in IPython.core.hooks.__all__:
586 print "Warning! Hook '%s' is not one of %s" % \
598 print "Warning! Hook '%s' is not one of %s" % \
587 (name, IPython.core.hooks.__all__ )
599 (name, IPython.core.hooks.__all__ )
588 if not dp:
600 if not dp:
589 dp = IPython.core.hooks.CommandChainDispatcher()
601 dp = IPython.core.hooks.CommandChainDispatcher()
590
602
591 try:
603 try:
592 dp.add(f,priority)
604 dp.add(f,priority)
593 except AttributeError:
605 except AttributeError:
594 # it was not commandchain, plain old func - replace
606 # it was not commandchain, plain old func - replace
595 dp = f
607 dp = f
596
608
597 setattr(self.hooks,name, dp)
609 setattr(self.hooks,name, dp)
598
610
599 def register_post_execute(self, func):
611 def register_post_execute(self, func):
600 """Register a function for calling after code execution.
612 """Register a function for calling after code execution.
601 """
613 """
602 if not callable(func):
614 if not callable(func):
603 raise ValueError('argument %s must be callable' % func)
615 raise ValueError('argument %s must be callable' % func)
604 self._post_execute.add(func)
616 self._post_execute.add(func)
605
617
606 #-------------------------------------------------------------------------
618 #-------------------------------------------------------------------------
607 # Things related to the "main" module
619 # Things related to the "main" module
608 #-------------------------------------------------------------------------
620 #-------------------------------------------------------------------------
609
621
610 def new_main_mod(self,ns=None):
622 def new_main_mod(self,ns=None):
611 """Return a new 'main' module object for user code execution.
623 """Return a new 'main' module object for user code execution.
612 """
624 """
613 main_mod = self._user_main_module
625 main_mod = self._user_main_module
614 init_fakemod_dict(main_mod,ns)
626 init_fakemod_dict(main_mod,ns)
615 return main_mod
627 return main_mod
616
628
617 def cache_main_mod(self,ns,fname):
629 def cache_main_mod(self,ns,fname):
618 """Cache a main module's namespace.
630 """Cache a main module's namespace.
619
631
620 When scripts are executed via %run, we must keep a reference to the
632 When scripts are executed via %run, we must keep a reference to the
621 namespace of their __main__ module (a FakeModule instance) around so
633 namespace of their __main__ module (a FakeModule instance) around so
622 that Python doesn't clear it, rendering objects defined therein
634 that Python doesn't clear it, rendering objects defined therein
623 useless.
635 useless.
624
636
625 This method keeps said reference in a private dict, keyed by the
637 This method keeps said reference in a private dict, keyed by the
626 absolute path of the module object (which corresponds to the script
638 absolute path of the module object (which corresponds to the script
627 path). This way, for multiple executions of the same script we only
639 path). This way, for multiple executions of the same script we only
628 keep one copy of the namespace (the last one), thus preventing memory
640 keep one copy of the namespace (the last one), thus preventing memory
629 leaks from old references while allowing the objects from the last
641 leaks from old references while allowing the objects from the last
630 execution to be accessible.
642 execution to be accessible.
631
643
632 Note: we can not allow the actual FakeModule instances to be deleted,
644 Note: we can not allow the actual FakeModule instances to be deleted,
633 because of how Python tears down modules (it hard-sets all their
645 because of how Python tears down modules (it hard-sets all their
634 references to None without regard for reference counts). This method
646 references to None without regard for reference counts). This method
635 must therefore make a *copy* of the given namespace, to allow the
647 must therefore make a *copy* of the given namespace, to allow the
636 original module's __dict__ to be cleared and reused.
648 original module's __dict__ to be cleared and reused.
637
649
638
650
639 Parameters
651 Parameters
640 ----------
652 ----------
641 ns : a namespace (a dict, typically)
653 ns : a namespace (a dict, typically)
642
654
643 fname : str
655 fname : str
644 Filename associated with the namespace.
656 Filename associated with the namespace.
645
657
646 Examples
658 Examples
647 --------
659 --------
648
660
649 In [10]: import IPython
661 In [10]: import IPython
650
662
651 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
663 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
652
664
653 In [12]: IPython.__file__ in _ip._main_ns_cache
665 In [12]: IPython.__file__ in _ip._main_ns_cache
654 Out[12]: True
666 Out[12]: True
655 """
667 """
656 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
668 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
657
669
658 def clear_main_mod_cache(self):
670 def clear_main_mod_cache(self):
659 """Clear the cache of main modules.
671 """Clear the cache of main modules.
660
672
661 Mainly for use by utilities like %reset.
673 Mainly for use by utilities like %reset.
662
674
663 Examples
675 Examples
664 --------
676 --------
665
677
666 In [15]: import IPython
678 In [15]: import IPython
667
679
668 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
680 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
669
681
670 In [17]: len(_ip._main_ns_cache) > 0
682 In [17]: len(_ip._main_ns_cache) > 0
671 Out[17]: True
683 Out[17]: True
672
684
673 In [18]: _ip.clear_main_mod_cache()
685 In [18]: _ip.clear_main_mod_cache()
674
686
675 In [19]: len(_ip._main_ns_cache) == 0
687 In [19]: len(_ip._main_ns_cache) == 0
676 Out[19]: True
688 Out[19]: True
677 """
689 """
678 self._main_ns_cache.clear()
690 self._main_ns_cache.clear()
679
691
680 #-------------------------------------------------------------------------
692 #-------------------------------------------------------------------------
681 # Things related to debugging
693 # Things related to debugging
682 #-------------------------------------------------------------------------
694 #-------------------------------------------------------------------------
683
695
684 def init_pdb(self):
696 def init_pdb(self):
685 # Set calling of pdb on exceptions
697 # Set calling of pdb on exceptions
686 # self.call_pdb is a property
698 # self.call_pdb is a property
687 self.call_pdb = self.pdb
699 self.call_pdb = self.pdb
688
700
689 def _get_call_pdb(self):
701 def _get_call_pdb(self):
690 return self._call_pdb
702 return self._call_pdb
691
703
692 def _set_call_pdb(self,val):
704 def _set_call_pdb(self,val):
693
705
694 if val not in (0,1,False,True):
706 if val not in (0,1,False,True):
695 raise ValueError,'new call_pdb value must be boolean'
707 raise ValueError,'new call_pdb value must be boolean'
696
708
697 # store value in instance
709 # store value in instance
698 self._call_pdb = val
710 self._call_pdb = val
699
711
700 # notify the actual exception handlers
712 # notify the actual exception handlers
701 self.InteractiveTB.call_pdb = val
713 self.InteractiveTB.call_pdb = val
702
714
703 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
715 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
704 'Control auto-activation of pdb at exceptions')
716 'Control auto-activation of pdb at exceptions')
705
717
706 def debugger(self,force=False):
718 def debugger(self,force=False):
707 """Call the pydb/pdb debugger.
719 """Call the pydb/pdb debugger.
708
720
709 Keywords:
721 Keywords:
710
722
711 - force(False): by default, this routine checks the instance call_pdb
723 - force(False): by default, this routine checks the instance call_pdb
712 flag and does not actually invoke the debugger if the flag is false.
724 flag and does not actually invoke the debugger if the flag is false.
713 The 'force' option forces the debugger to activate even if the flag
725 The 'force' option forces the debugger to activate even if the flag
714 is false.
726 is false.
715 """
727 """
716
728
717 if not (force or self.call_pdb):
729 if not (force or self.call_pdb):
718 return
730 return
719
731
720 if not hasattr(sys,'last_traceback'):
732 if not hasattr(sys,'last_traceback'):
721 error('No traceback has been produced, nothing to debug.')
733 error('No traceback has been produced, nothing to debug.')
722 return
734 return
723
735
724 # use pydb if available
736 # use pydb if available
725 if debugger.has_pydb:
737 if debugger.has_pydb:
726 from pydb import pm
738 from pydb import pm
727 else:
739 else:
728 # fallback to our internal debugger
740 # fallback to our internal debugger
729 pm = lambda : self.InteractiveTB.debugger(force=True)
741 pm = lambda : self.InteractiveTB.debugger(force=True)
730 self.history_saving_wrapper(pm)()
742 self.history_saving_wrapper(pm)()
731
743
732 #-------------------------------------------------------------------------
744 #-------------------------------------------------------------------------
733 # Things related to IPython's various namespaces
745 # Things related to IPython's various namespaces
734 #-------------------------------------------------------------------------
746 #-------------------------------------------------------------------------
735
747
736 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
748 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
737 # Create the namespace where the user will operate. user_ns is
749 # Create the namespace where the user will operate. user_ns is
738 # normally the only one used, and it is passed to the exec calls as
750 # normally the only one used, and it is passed to the exec calls as
739 # the locals argument. But we do carry a user_global_ns namespace
751 # the locals argument. But we do carry a user_global_ns namespace
740 # given as the exec 'globals' argument, This is useful in embedding
752 # given as the exec 'globals' argument, This is useful in embedding
741 # situations where the ipython shell opens in a context where the
753 # situations where the ipython shell opens in a context where the
742 # distinction between locals and globals is meaningful. For
754 # distinction between locals and globals is meaningful. For
743 # non-embedded contexts, it is just the same object as the user_ns dict.
755 # non-embedded contexts, it is just the same object as the user_ns dict.
744
756
745 # FIXME. For some strange reason, __builtins__ is showing up at user
757 # FIXME. For some strange reason, __builtins__ is showing up at user
746 # level as a dict instead of a module. This is a manual fix, but I
758 # level as a dict instead of a module. This is a manual fix, but I
747 # should really track down where the problem is coming from. Alex
759 # should really track down where the problem is coming from. Alex
748 # Schmolck reported this problem first.
760 # Schmolck reported this problem first.
749
761
750 # A useful post by Alex Martelli on this topic:
762 # A useful post by Alex Martelli on this topic:
751 # Re: inconsistent value from __builtins__
763 # Re: inconsistent value from __builtins__
752 # Von: Alex Martelli <aleaxit@yahoo.com>
764 # Von: Alex Martelli <aleaxit@yahoo.com>
753 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
765 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
754 # Gruppen: comp.lang.python
766 # Gruppen: comp.lang.python
755
767
756 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
768 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
757 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
769 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
758 # > <type 'dict'>
770 # > <type 'dict'>
759 # > >>> print type(__builtins__)
771 # > >>> print type(__builtins__)
760 # > <type 'module'>
772 # > <type 'module'>
761 # > Is this difference in return value intentional?
773 # > Is this difference in return value intentional?
762
774
763 # Well, it's documented that '__builtins__' can be either a dictionary
775 # Well, it's documented that '__builtins__' can be either a dictionary
764 # or a module, and it's been that way for a long time. Whether it's
776 # or a module, and it's been that way for a long time. Whether it's
765 # intentional (or sensible), I don't know. In any case, the idea is
777 # intentional (or sensible), I don't know. In any case, the idea is
766 # that if you need to access the built-in namespace directly, you
778 # that if you need to access the built-in namespace directly, you
767 # should start with "import __builtin__" (note, no 's') which will
779 # should start with "import __builtin__" (note, no 's') which will
768 # definitely give you a module. Yeah, it's somewhat confusing:-(.
780 # definitely give you a module. Yeah, it's somewhat confusing:-(.
769
781
770 # These routines return properly built dicts as needed by the rest of
782 # These routines return properly built dicts as needed by the rest of
771 # the code, and can also be used by extension writers to generate
783 # the code, and can also be used by extension writers to generate
772 # properly initialized namespaces.
784 # properly initialized namespaces.
773 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
785 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
774 user_global_ns)
786 user_global_ns)
775
787
776 # Assign namespaces
788 # Assign namespaces
777 # This is the namespace where all normal user variables live
789 # This is the namespace where all normal user variables live
778 self.user_ns = user_ns
790 self.user_ns = user_ns
779 self.user_global_ns = user_global_ns
791 self.user_global_ns = user_global_ns
780
792
781 # An auxiliary namespace that checks what parts of the user_ns were
793 # An auxiliary namespace that checks what parts of the user_ns were
782 # loaded at startup, so we can list later only variables defined in
794 # loaded at startup, so we can list later only variables defined in
783 # actual interactive use. Since it is always a subset of user_ns, it
795 # actual interactive use. Since it is always a subset of user_ns, it
784 # doesn't need to be separately tracked in the ns_table.
796 # doesn't need to be separately tracked in the ns_table.
785 self.user_ns_hidden = {}
797 self.user_ns_hidden = {}
786
798
787 # A namespace to keep track of internal data structures to prevent
799 # A namespace to keep track of internal data structures to prevent
788 # them from cluttering user-visible stuff. Will be updated later
800 # them from cluttering user-visible stuff. Will be updated later
789 self.internal_ns = {}
801 self.internal_ns = {}
790
802
791 # Now that FakeModule produces a real module, we've run into a nasty
803 # Now that FakeModule produces a real module, we've run into a nasty
792 # problem: after script execution (via %run), the module where the user
804 # problem: after script execution (via %run), the module where the user
793 # code ran is deleted. Now that this object is a true module (needed
805 # code ran is deleted. Now that this object is a true module (needed
794 # so docetst and other tools work correctly), the Python module
806 # so docetst and other tools work correctly), the Python module
795 # teardown mechanism runs over it, and sets to None every variable
807 # teardown mechanism runs over it, and sets to None every variable
796 # present in that module. Top-level references to objects from the
808 # present in that module. Top-level references to objects from the
797 # script survive, because the user_ns is updated with them. However,
809 # script survive, because the user_ns is updated with them. However,
798 # calling functions defined in the script that use other things from
810 # calling functions defined in the script that use other things from
799 # the script will fail, because the function's closure had references
811 # the script will fail, because the function's closure had references
800 # to the original objects, which are now all None. So we must protect
812 # to the original objects, which are now all None. So we must protect
801 # these modules from deletion by keeping a cache.
813 # these modules from deletion by keeping a cache.
802 #
814 #
803 # To avoid keeping stale modules around (we only need the one from the
815 # To avoid keeping stale modules around (we only need the one from the
804 # last run), we use a dict keyed with the full path to the script, so
816 # last run), we use a dict keyed with the full path to the script, so
805 # only the last version of the module is held in the cache. Note,
817 # only the last version of the module is held in the cache. Note,
806 # however, that we must cache the module *namespace contents* (their
818 # however, that we must cache the module *namespace contents* (their
807 # __dict__). Because if we try to cache the actual modules, old ones
819 # __dict__). Because if we try to cache the actual modules, old ones
808 # (uncached) could be destroyed while still holding references (such as
820 # (uncached) could be destroyed while still holding references (such as
809 # those held by GUI objects that tend to be long-lived)>
821 # those held by GUI objects that tend to be long-lived)>
810 #
822 #
811 # The %reset command will flush this cache. See the cache_main_mod()
823 # The %reset command will flush this cache. See the cache_main_mod()
812 # and clear_main_mod_cache() methods for details on use.
824 # and clear_main_mod_cache() methods for details on use.
813
825
814 # This is the cache used for 'main' namespaces
826 # This is the cache used for 'main' namespaces
815 self._main_ns_cache = {}
827 self._main_ns_cache = {}
816 # And this is the single instance of FakeModule whose __dict__ we keep
828 # And this is the single instance of FakeModule whose __dict__ we keep
817 # copying and clearing for reuse on each %run
829 # copying and clearing for reuse on each %run
818 self._user_main_module = FakeModule()
830 self._user_main_module = FakeModule()
819
831
820 # A table holding all the namespaces IPython deals with, so that
832 # A table holding all the namespaces IPython deals with, so that
821 # introspection facilities can search easily.
833 # introspection facilities can search easily.
822 self.ns_table = {'user':user_ns,
834 self.ns_table = {'user':user_ns,
823 'user_global':user_global_ns,
835 'user_global':user_global_ns,
824 'internal':self.internal_ns,
836 'internal':self.internal_ns,
825 'builtin':__builtin__.__dict__
837 'builtin':__builtin__.__dict__
826 }
838 }
827
839
828 # Similarly, track all namespaces where references can be held and that
840 # Similarly, track all namespaces where references can be held and that
829 # we can safely clear (so it can NOT include builtin). This one can be
841 # we can safely clear (so it can NOT include builtin). This one can be
830 # a simple list. Note that the main execution namespaces, user_ns and
842 # a simple list. Note that the main execution namespaces, user_ns and
831 # user_global_ns, can NOT be listed here, as clearing them blindly
843 # user_global_ns, can NOT be listed here, as clearing them blindly
832 # causes errors in object __del__ methods. Instead, the reset() method
844 # causes errors in object __del__ methods. Instead, the reset() method
833 # clears them manually and carefully.
845 # clears them manually and carefully.
834 self.ns_refs_table = [ self.user_ns_hidden,
846 self.ns_refs_table = [ self.user_ns_hidden,
835 self.internal_ns, self._main_ns_cache ]
847 self.internal_ns, self._main_ns_cache ]
836
848
837 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
849 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
838 """Return a valid local and global user interactive namespaces.
850 """Return a valid local and global user interactive namespaces.
839
851
840 This builds a dict with the minimal information needed to operate as a
852 This builds a dict with the minimal information needed to operate as a
841 valid IPython user namespace, which you can pass to the various
853 valid IPython user namespace, which you can pass to the various
842 embedding classes in ipython. The default implementation returns the
854 embedding classes in ipython. The default implementation returns the
843 same dict for both the locals and the globals to allow functions to
855 same dict for both the locals and the globals to allow functions to
844 refer to variables in the namespace. Customized implementations can
856 refer to variables in the namespace. Customized implementations can
845 return different dicts. The locals dictionary can actually be anything
857 return different dicts. The locals dictionary can actually be anything
846 following the basic mapping protocol of a dict, but the globals dict
858 following the basic mapping protocol of a dict, but the globals dict
847 must be a true dict, not even a subclass. It is recommended that any
859 must be a true dict, not even a subclass. It is recommended that any
848 custom object for the locals namespace synchronize with the globals
860 custom object for the locals namespace synchronize with the globals
849 dict somehow.
861 dict somehow.
850
862
851 Raises TypeError if the provided globals namespace is not a true dict.
863 Raises TypeError if the provided globals namespace is not a true dict.
852
864
853 Parameters
865 Parameters
854 ----------
866 ----------
855 user_ns : dict-like, optional
867 user_ns : dict-like, optional
856 The current user namespace. The items in this namespace should
868 The current user namespace. The items in this namespace should
857 be included in the output. If None, an appropriate blank
869 be included in the output. If None, an appropriate blank
858 namespace should be created.
870 namespace should be created.
859 user_global_ns : dict, optional
871 user_global_ns : dict, optional
860 The current user global namespace. The items in this namespace
872 The current user global namespace. The items in this namespace
861 should be included in the output. If None, an appropriate
873 should be included in the output. If None, an appropriate
862 blank namespace should be created.
874 blank namespace should be created.
863
875
864 Returns
876 Returns
865 -------
877 -------
866 A pair of dictionary-like object to be used as the local namespace
878 A pair of dictionary-like object to be used as the local namespace
867 of the interpreter and a dict to be used as the global namespace.
879 of the interpreter and a dict to be used as the global namespace.
868 """
880 """
869
881
870
882
871 # We must ensure that __builtin__ (without the final 's') is always
883 # We must ensure that __builtin__ (without the final 's') is always
872 # available and pointing to the __builtin__ *module*. For more details:
884 # available and pointing to the __builtin__ *module*. For more details:
873 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
885 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
874
886
875 if user_ns is None:
887 if user_ns is None:
876 # Set __name__ to __main__ to better match the behavior of the
888 # Set __name__ to __main__ to better match the behavior of the
877 # normal interpreter.
889 # normal interpreter.
878 user_ns = {'__name__' :'__main__',
890 user_ns = {'__name__' :'__main__',
879 '__builtin__' : __builtin__,
891 '__builtin__' : __builtin__,
880 '__builtins__' : __builtin__,
892 '__builtins__' : __builtin__,
881 }
893 }
882 else:
894 else:
883 user_ns.setdefault('__name__','__main__')
895 user_ns.setdefault('__name__','__main__')
884 user_ns.setdefault('__builtin__',__builtin__)
896 user_ns.setdefault('__builtin__',__builtin__)
885 user_ns.setdefault('__builtins__',__builtin__)
897 user_ns.setdefault('__builtins__',__builtin__)
886
898
887 if user_global_ns is None:
899 if user_global_ns is None:
888 user_global_ns = user_ns
900 user_global_ns = user_ns
889 if type(user_global_ns) is not dict:
901 if type(user_global_ns) is not dict:
890 raise TypeError("user_global_ns must be a true dict; got %r"
902 raise TypeError("user_global_ns must be a true dict; got %r"
891 % type(user_global_ns))
903 % type(user_global_ns))
892
904
893 return user_ns, user_global_ns
905 return user_ns, user_global_ns
894
906
895 def init_sys_modules(self):
907 def init_sys_modules(self):
896 # We need to insert into sys.modules something that looks like a
908 # We need to insert into sys.modules something that looks like a
897 # module but which accesses the IPython namespace, for shelve and
909 # module but which accesses the IPython namespace, for shelve and
898 # pickle to work interactively. Normally they rely on getting
910 # pickle to work interactively. Normally they rely on getting
899 # everything out of __main__, but for embedding purposes each IPython
911 # everything out of __main__, but for embedding purposes each IPython
900 # instance has its own private namespace, so we can't go shoving
912 # instance has its own private namespace, so we can't go shoving
901 # everything into __main__.
913 # everything into __main__.
902
914
903 # note, however, that we should only do this for non-embedded
915 # note, however, that we should only do this for non-embedded
904 # ipythons, which really mimic the __main__.__dict__ with their own
916 # ipythons, which really mimic the __main__.__dict__ with their own
905 # namespace. Embedded instances, on the other hand, should not do
917 # namespace. Embedded instances, on the other hand, should not do
906 # this because they need to manage the user local/global namespaces
918 # this because they need to manage the user local/global namespaces
907 # only, but they live within a 'normal' __main__ (meaning, they
919 # only, but they live within a 'normal' __main__ (meaning, they
908 # shouldn't overtake the execution environment of the script they're
920 # shouldn't overtake the execution environment of the script they're
909 # embedded in).
921 # embedded in).
910
922
911 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
923 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
912
924
913 try:
925 try:
914 main_name = self.user_ns['__name__']
926 main_name = self.user_ns['__name__']
915 except KeyError:
927 except KeyError:
916 raise KeyError('user_ns dictionary MUST have a "__name__" key')
928 raise KeyError('user_ns dictionary MUST have a "__name__" key')
917 else:
929 else:
918 sys.modules[main_name] = FakeModule(self.user_ns)
930 sys.modules[main_name] = FakeModule(self.user_ns)
919
931
920 def init_user_ns(self):
932 def init_user_ns(self):
921 """Initialize all user-visible namespaces to their minimum defaults.
933 """Initialize all user-visible namespaces to their minimum defaults.
922
934
923 Certain history lists are also initialized here, as they effectively
935 Certain history lists are also initialized here, as they effectively
924 act as user namespaces.
936 act as user namespaces.
925
937
926 Notes
938 Notes
927 -----
939 -----
928 All data structures here are only filled in, they are NOT reset by this
940 All data structures here are only filled in, they are NOT reset by this
929 method. If they were not empty before, data will simply be added to
941 method. If they were not empty before, data will simply be added to
930 therm.
942 therm.
931 """
943 """
932 # This function works in two parts: first we put a few things in
944 # This function works in two parts: first we put a few things in
933 # user_ns, and we sync that contents into user_ns_hidden so that these
945 # user_ns, and we sync that contents into user_ns_hidden so that these
934 # initial variables aren't shown by %who. After the sync, we add the
946 # initial variables aren't shown by %who. After the sync, we add the
935 # rest of what we *do* want the user to see with %who even on a new
947 # rest of what we *do* want the user to see with %who even on a new
936 # session (probably nothing, so theye really only see their own stuff)
948 # session (probably nothing, so theye really only see their own stuff)
937
949
938 # The user dict must *always* have a __builtin__ reference to the
950 # The user dict must *always* have a __builtin__ reference to the
939 # Python standard __builtin__ namespace, which must be imported.
951 # Python standard __builtin__ namespace, which must be imported.
940 # This is so that certain operations in prompt evaluation can be
952 # This is so that certain operations in prompt evaluation can be
941 # reliably executed with builtins. Note that we can NOT use
953 # reliably executed with builtins. Note that we can NOT use
942 # __builtins__ (note the 's'), because that can either be a dict or a
954 # __builtins__ (note the 's'), because that can either be a dict or a
943 # module, and can even mutate at runtime, depending on the context
955 # module, and can even mutate at runtime, depending on the context
944 # (Python makes no guarantees on it). In contrast, __builtin__ is
956 # (Python makes no guarantees on it). In contrast, __builtin__ is
945 # always a module object, though it must be explicitly imported.
957 # always a module object, though it must be explicitly imported.
946
958
947 # For more details:
959 # For more details:
948 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
960 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
949 ns = dict(__builtin__ = __builtin__)
961 ns = dict(__builtin__ = __builtin__)
950
962
951 # Put 'help' in the user namespace
963 # Put 'help' in the user namespace
952 try:
964 try:
953 from site import _Helper
965 from site import _Helper
954 ns['help'] = _Helper()
966 ns['help'] = _Helper()
955 except ImportError:
967 except ImportError:
956 warn('help() not available - check site.py')
968 warn('help() not available - check site.py')
957
969
958 # make global variables for user access to the histories
970 # make global variables for user access to the histories
959 ns['_ih'] = self.history_manager.input_hist_parsed
971 ns['_ih'] = self.history_manager.input_hist_parsed
960 ns['_oh'] = self.history_manager.output_hist
972 ns['_oh'] = self.history_manager.output_hist
961 ns['_dh'] = self.history_manager.dir_hist
973 ns['_dh'] = self.history_manager.dir_hist
962
974
963 ns['_sh'] = shadowns
975 ns['_sh'] = shadowns
964
976
965 # user aliases to input and output histories. These shouldn't show up
977 # user aliases to input and output histories. These shouldn't show up
966 # in %who, as they can have very large reprs.
978 # in %who, as they can have very large reprs.
967 ns['In'] = self.history_manager.input_hist_parsed
979 ns['In'] = self.history_manager.input_hist_parsed
968 ns['Out'] = self.history_manager.output_hist
980 ns['Out'] = self.history_manager.output_hist
969
981
970 # Store myself as the public api!!!
982 # Store myself as the public api!!!
971 ns['get_ipython'] = self.get_ipython
983 ns['get_ipython'] = self.get_ipython
972
984
973 # Sync what we've added so far to user_ns_hidden so these aren't seen
985 # Sync what we've added so far to user_ns_hidden so these aren't seen
974 # by %who
986 # by %who
975 self.user_ns_hidden.update(ns)
987 self.user_ns_hidden.update(ns)
976
988
977 # Anything put into ns now would show up in %who. Think twice before
989 # Anything put into ns now would show up in %who. Think twice before
978 # putting anything here, as we really want %who to show the user their
990 # putting anything here, as we really want %who to show the user their
979 # stuff, not our variables.
991 # stuff, not our variables.
980
992
981 # Finally, update the real user's namespace
993 # Finally, update the real user's namespace
982 self.user_ns.update(ns)
994 self.user_ns.update(ns)
983
995
984 def reset(self):
996 def reset(self):
985 """Clear all internal namespaces.
997 """Clear all internal namespaces.
986
998
987 Note that this is much more aggressive than %reset, since it clears
999 Note that this is much more aggressive than %reset, since it clears
988 fully all namespaces, as well as all input/output lists.
1000 fully all namespaces, as well as all input/output lists.
989 """
1001 """
990 # Clear histories
1002 # Clear histories
991 self.history_manager.reset()
1003 self.history_manager.reset()
992
1004
993 # Reset counter used to index all histories
1005 # Reset counter used to index all histories
994 self.execution_count = 0
1006 self.execution_count = 0
995
1007
996 # Restore the user namespaces to minimal usability
1008 # Restore the user namespaces to minimal usability
997 for ns in self.ns_refs_table:
1009 for ns in self.ns_refs_table:
998 ns.clear()
1010 ns.clear()
999
1011
1000 # The main execution namespaces must be cleared very carefully,
1012 # The main execution namespaces must be cleared very carefully,
1001 # skipping the deletion of the builtin-related keys, because doing so
1013 # skipping the deletion of the builtin-related keys, because doing so
1002 # would cause errors in many object's __del__ methods.
1014 # would cause errors in many object's __del__ methods.
1003 for ns in [self.user_ns, self.user_global_ns]:
1015 for ns in [self.user_ns, self.user_global_ns]:
1004 drop_keys = set(ns.keys())
1016 drop_keys = set(ns.keys())
1005 drop_keys.discard('__builtin__')
1017 drop_keys.discard('__builtin__')
1006 drop_keys.discard('__builtins__')
1018 drop_keys.discard('__builtins__')
1007 for k in drop_keys:
1019 for k in drop_keys:
1008 del ns[k]
1020 del ns[k]
1009
1021
1010 # Restore the user namespaces to minimal usability
1022 # Restore the user namespaces to minimal usability
1011 self.init_user_ns()
1023 self.init_user_ns()
1012
1024
1013 # Restore the default and user aliases
1025 # Restore the default and user aliases
1014 self.alias_manager.clear_aliases()
1026 self.alias_manager.clear_aliases()
1015 self.alias_manager.init_aliases()
1027 self.alias_manager.init_aliases()
1016
1028
1017 def reset_selective(self, regex=None):
1029 def reset_selective(self, regex=None):
1018 """Clear selective variables from internal namespaces based on a
1030 """Clear selective variables from internal namespaces based on a
1019 specified regular expression.
1031 specified regular expression.
1020
1032
1021 Parameters
1033 Parameters
1022 ----------
1034 ----------
1023 regex : string or compiled pattern, optional
1035 regex : string or compiled pattern, optional
1024 A regular expression pattern that will be used in searching
1036 A regular expression pattern that will be used in searching
1025 variable names in the users namespaces.
1037 variable names in the users namespaces.
1026 """
1038 """
1027 if regex is not None:
1039 if regex is not None:
1028 try:
1040 try:
1029 m = re.compile(regex)
1041 m = re.compile(regex)
1030 except TypeError:
1042 except TypeError:
1031 raise TypeError('regex must be a string or compiled pattern')
1043 raise TypeError('regex must be a string or compiled pattern')
1032 # Search for keys in each namespace that match the given regex
1044 # Search for keys in each namespace that match the given regex
1033 # If a match is found, delete the key/value pair.
1045 # If a match is found, delete the key/value pair.
1034 for ns in self.ns_refs_table:
1046 for ns in self.ns_refs_table:
1035 for var in ns:
1047 for var in ns:
1036 if m.search(var):
1048 if m.search(var):
1037 del ns[var]
1049 del ns[var]
1038
1050
1039 def push(self, variables, interactive=True):
1051 def push(self, variables, interactive=True):
1040 """Inject a group of variables into the IPython user namespace.
1052 """Inject a group of variables into the IPython user namespace.
1041
1053
1042 Parameters
1054 Parameters
1043 ----------
1055 ----------
1044 variables : dict, str or list/tuple of str
1056 variables : dict, str or list/tuple of str
1045 The variables to inject into the user's namespace. If a dict, a
1057 The variables to inject into the user's namespace. If a dict, a
1046 simple update is done. If a str, the string is assumed to have
1058 simple update is done. If a str, the string is assumed to have
1047 variable names separated by spaces. A list/tuple of str can also
1059 variable names separated by spaces. A list/tuple of str can also
1048 be used to give the variable names. If just the variable names are
1060 be used to give the variable names. If just the variable names are
1049 give (list/tuple/str) then the variable values looked up in the
1061 give (list/tuple/str) then the variable values looked up in the
1050 callers frame.
1062 callers frame.
1051 interactive : bool
1063 interactive : bool
1052 If True (default), the variables will be listed with the ``who``
1064 If True (default), the variables will be listed with the ``who``
1053 magic.
1065 magic.
1054 """
1066 """
1055 vdict = None
1067 vdict = None
1056
1068
1057 # We need a dict of name/value pairs to do namespace updates.
1069 # We need a dict of name/value pairs to do namespace updates.
1058 if isinstance(variables, dict):
1070 if isinstance(variables, dict):
1059 vdict = variables
1071 vdict = variables
1060 elif isinstance(variables, (basestring, list, tuple)):
1072 elif isinstance(variables, (basestring, list, tuple)):
1061 if isinstance(variables, basestring):
1073 if isinstance(variables, basestring):
1062 vlist = variables.split()
1074 vlist = variables.split()
1063 else:
1075 else:
1064 vlist = variables
1076 vlist = variables
1065 vdict = {}
1077 vdict = {}
1066 cf = sys._getframe(1)
1078 cf = sys._getframe(1)
1067 for name in vlist:
1079 for name in vlist:
1068 try:
1080 try:
1069 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1081 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1070 except:
1082 except:
1071 print ('Could not get variable %s from %s' %
1083 print ('Could not get variable %s from %s' %
1072 (name,cf.f_code.co_name))
1084 (name,cf.f_code.co_name))
1073 else:
1085 else:
1074 raise ValueError('variables must be a dict/str/list/tuple')
1086 raise ValueError('variables must be a dict/str/list/tuple')
1075
1087
1076 # Propagate variables to user namespace
1088 # Propagate variables to user namespace
1077 self.user_ns.update(vdict)
1089 self.user_ns.update(vdict)
1078
1090
1079 # And configure interactive visibility
1091 # And configure interactive visibility
1080 config_ns = self.user_ns_hidden
1092 config_ns = self.user_ns_hidden
1081 if interactive:
1093 if interactive:
1082 for name, val in vdict.iteritems():
1094 for name, val in vdict.iteritems():
1083 config_ns.pop(name, None)
1095 config_ns.pop(name, None)
1084 else:
1096 else:
1085 for name,val in vdict.iteritems():
1097 for name,val in vdict.iteritems():
1086 config_ns[name] = val
1098 config_ns[name] = val
1087
1099
1088 #-------------------------------------------------------------------------
1100 #-------------------------------------------------------------------------
1089 # Things related to object introspection
1101 # Things related to object introspection
1090 #-------------------------------------------------------------------------
1102 #-------------------------------------------------------------------------
1091
1103
1092 def _ofind(self, oname, namespaces=None):
1104 def _ofind(self, oname, namespaces=None):
1093 """Find an object in the available namespaces.
1105 """Find an object in the available namespaces.
1094
1106
1095 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1107 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1096
1108
1097 Has special code to detect magic functions.
1109 Has special code to detect magic functions.
1098 """
1110 """
1099 #oname = oname.strip()
1111 #oname = oname.strip()
1100 #print '1- oname: <%r>' % oname # dbg
1112 #print '1- oname: <%r>' % oname # dbg
1101 try:
1113 try:
1102 oname = oname.strip().encode('ascii')
1114 oname = oname.strip().encode('ascii')
1103 #print '2- oname: <%r>' % oname # dbg
1115 #print '2- oname: <%r>' % oname # dbg
1104 except UnicodeEncodeError:
1116 except UnicodeEncodeError:
1105 print 'Python identifiers can only contain ascii characters.'
1117 print 'Python identifiers can only contain ascii characters.'
1106 return dict(found=False)
1118 return dict(found=False)
1107
1119
1108 alias_ns = None
1120 alias_ns = None
1109 if namespaces is None:
1121 if namespaces is None:
1110 # Namespaces to search in:
1122 # Namespaces to search in:
1111 # Put them in a list. The order is important so that we
1123 # Put them in a list. The order is important so that we
1112 # find things in the same order that Python finds them.
1124 # find things in the same order that Python finds them.
1113 namespaces = [ ('Interactive', self.user_ns),
1125 namespaces = [ ('Interactive', self.user_ns),
1114 ('IPython internal', self.internal_ns),
1126 ('IPython internal', self.internal_ns),
1115 ('Python builtin', __builtin__.__dict__),
1127 ('Python builtin', __builtin__.__dict__),
1116 ('Alias', self.alias_manager.alias_table),
1128 ('Alias', self.alias_manager.alias_table),
1117 ]
1129 ]
1118 alias_ns = self.alias_manager.alias_table
1130 alias_ns = self.alias_manager.alias_table
1119
1131
1120 # initialize results to 'null'
1132 # initialize results to 'null'
1121 found = False; obj = None; ospace = None; ds = None;
1133 found = False; obj = None; ospace = None; ds = None;
1122 ismagic = False; isalias = False; parent = None
1134 ismagic = False; isalias = False; parent = None
1123
1135
1124 # We need to special-case 'print', which as of python2.6 registers as a
1136 # We need to special-case 'print', which as of python2.6 registers as a
1125 # function but should only be treated as one if print_function was
1137 # function but should only be treated as one if print_function was
1126 # loaded with a future import. In this case, just bail.
1138 # loaded with a future import. In this case, just bail.
1127 if (oname == 'print' and not (self.compile.compiler_flags &
1139 if (oname == 'print' and not (self.compile.compiler_flags &
1128 __future__.CO_FUTURE_PRINT_FUNCTION)):
1140 __future__.CO_FUTURE_PRINT_FUNCTION)):
1129 return {'found':found, 'obj':obj, 'namespace':ospace,
1141 return {'found':found, 'obj':obj, 'namespace':ospace,
1130 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1142 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1131
1143
1132 # Look for the given name by splitting it in parts. If the head is
1144 # Look for the given name by splitting it in parts. If the head is
1133 # found, then we look for all the remaining parts as members, and only
1145 # found, then we look for all the remaining parts as members, and only
1134 # declare success if we can find them all.
1146 # declare success if we can find them all.
1135 oname_parts = oname.split('.')
1147 oname_parts = oname.split('.')
1136 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1148 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1137 for nsname,ns in namespaces:
1149 for nsname,ns in namespaces:
1138 try:
1150 try:
1139 obj = ns[oname_head]
1151 obj = ns[oname_head]
1140 except KeyError:
1152 except KeyError:
1141 continue
1153 continue
1142 else:
1154 else:
1143 #print 'oname_rest:', oname_rest # dbg
1155 #print 'oname_rest:', oname_rest # dbg
1144 for part in oname_rest:
1156 for part in oname_rest:
1145 try:
1157 try:
1146 parent = obj
1158 parent = obj
1147 obj = getattr(obj,part)
1159 obj = getattr(obj,part)
1148 except:
1160 except:
1149 # Blanket except b/c some badly implemented objects
1161 # Blanket except b/c some badly implemented objects
1150 # allow __getattr__ to raise exceptions other than
1162 # allow __getattr__ to raise exceptions other than
1151 # AttributeError, which then crashes IPython.
1163 # AttributeError, which then crashes IPython.
1152 break
1164 break
1153 else:
1165 else:
1154 # If we finish the for loop (no break), we got all members
1166 # If we finish the for loop (no break), we got all members
1155 found = True
1167 found = True
1156 ospace = nsname
1168 ospace = nsname
1157 if ns == alias_ns:
1169 if ns == alias_ns:
1158 isalias = True
1170 isalias = True
1159 break # namespace loop
1171 break # namespace loop
1160
1172
1161 # Try to see if it's magic
1173 # Try to see if it's magic
1162 if not found:
1174 if not found:
1163 if oname.startswith(ESC_MAGIC):
1175 if oname.startswith(ESC_MAGIC):
1164 oname = oname[1:]
1176 oname = oname[1:]
1165 obj = getattr(self,'magic_'+oname,None)
1177 obj = getattr(self,'magic_'+oname,None)
1166 if obj is not None:
1178 if obj is not None:
1167 found = True
1179 found = True
1168 ospace = 'IPython internal'
1180 ospace = 'IPython internal'
1169 ismagic = True
1181 ismagic = True
1170
1182
1171 # Last try: special-case some literals like '', [], {}, etc:
1183 # Last try: special-case some literals like '', [], {}, etc:
1172 if not found and oname_head in ["''",'""','[]','{}','()']:
1184 if not found and oname_head in ["''",'""','[]','{}','()']:
1173 obj = eval(oname_head)
1185 obj = eval(oname_head)
1174 found = True
1186 found = True
1175 ospace = 'Interactive'
1187 ospace = 'Interactive'
1176
1188
1177 return {'found':found, 'obj':obj, 'namespace':ospace,
1189 return {'found':found, 'obj':obj, 'namespace':ospace,
1178 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1190 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1179
1191
1180 def _ofind_property(self, oname, info):
1192 def _ofind_property(self, oname, info):
1181 """Second part of object finding, to look for property details."""
1193 """Second part of object finding, to look for property details."""
1182 if info.found:
1194 if info.found:
1183 # Get the docstring of the class property if it exists.
1195 # Get the docstring of the class property if it exists.
1184 path = oname.split('.')
1196 path = oname.split('.')
1185 root = '.'.join(path[:-1])
1197 root = '.'.join(path[:-1])
1186 if info.parent is not None:
1198 if info.parent is not None:
1187 try:
1199 try:
1188 target = getattr(info.parent, '__class__')
1200 target = getattr(info.parent, '__class__')
1189 # The object belongs to a class instance.
1201 # The object belongs to a class instance.
1190 try:
1202 try:
1191 target = getattr(target, path[-1])
1203 target = getattr(target, path[-1])
1192 # The class defines the object.
1204 # The class defines the object.
1193 if isinstance(target, property):
1205 if isinstance(target, property):
1194 oname = root + '.__class__.' + path[-1]
1206 oname = root + '.__class__.' + path[-1]
1195 info = Struct(self._ofind(oname))
1207 info = Struct(self._ofind(oname))
1196 except AttributeError: pass
1208 except AttributeError: pass
1197 except AttributeError: pass
1209 except AttributeError: pass
1198
1210
1199 # We return either the new info or the unmodified input if the object
1211 # We return either the new info or the unmodified input if the object
1200 # hadn't been found
1212 # hadn't been found
1201 return info
1213 return info
1202
1214
1203 def _object_find(self, oname, namespaces=None):
1215 def _object_find(self, oname, namespaces=None):
1204 """Find an object and return a struct with info about it."""
1216 """Find an object and return a struct with info about it."""
1205 inf = Struct(self._ofind(oname, namespaces))
1217 inf = Struct(self._ofind(oname, namespaces))
1206 return Struct(self._ofind_property(oname, inf))
1218 return Struct(self._ofind_property(oname, inf))
1207
1219
1208 def _inspect(self, meth, oname, namespaces=None, **kw):
1220 def _inspect(self, meth, oname, namespaces=None, **kw):
1209 """Generic interface to the inspector system.
1221 """Generic interface to the inspector system.
1210
1222
1211 This function is meant to be called by pdef, pdoc & friends."""
1223 This function is meant to be called by pdef, pdoc & friends."""
1212 info = self._object_find(oname)
1224 info = self._object_find(oname)
1213 if info.found:
1225 if info.found:
1214 pmethod = getattr(self.inspector, meth)
1226 pmethod = getattr(self.inspector, meth)
1215 formatter = format_screen if info.ismagic else None
1227 formatter = format_screen if info.ismagic else None
1216 if meth == 'pdoc':
1228 if meth == 'pdoc':
1217 pmethod(info.obj, oname, formatter)
1229 pmethod(info.obj, oname, formatter)
1218 elif meth == 'pinfo':
1230 elif meth == 'pinfo':
1219 pmethod(info.obj, oname, formatter, info, **kw)
1231 pmethod(info.obj, oname, formatter, info, **kw)
1220 else:
1232 else:
1221 pmethod(info.obj, oname)
1233 pmethod(info.obj, oname)
1222 else:
1234 else:
1223 print 'Object `%s` not found.' % oname
1235 print 'Object `%s` not found.' % oname
1224 return 'not found' # so callers can take other action
1236 return 'not found' # so callers can take other action
1225
1237
1226 def object_inspect(self, oname):
1238 def object_inspect(self, oname):
1227 info = self._object_find(oname)
1239 info = self._object_find(oname)
1228 if info.found:
1240 if info.found:
1229 return self.inspector.info(info.obj, oname, info=info)
1241 return self.inspector.info(info.obj, oname, info=info)
1230 else:
1242 else:
1231 return oinspect.object_info(name=oname, found=False)
1243 return oinspect.object_info(name=oname, found=False)
1232
1244
1233 #-------------------------------------------------------------------------
1245 #-------------------------------------------------------------------------
1234 # Things related to history management
1246 # Things related to history management
1235 #-------------------------------------------------------------------------
1247 #-------------------------------------------------------------------------
1236
1248
1237 def init_history(self):
1249 def init_history(self):
1238 """Sets up the command history, and starts regular autosaves."""
1250 """Sets up the command history, and starts regular autosaves."""
1239 self.history_manager = HistoryManager(shell=self)
1251 self.history_manager = HistoryManager(shell=self)
1240
1252
1241 def save_history(self):
1253 def save_history(self):
1242 """Save input history to a file (via readline library)."""
1254 """Save input history to a file (via readline library)."""
1243 self.history_manager.save_history()
1255 self.history_manager.save_history()
1244
1256
1245 def reload_history(self):
1257 def reload_history(self):
1246 """Reload the input history from disk file."""
1258 """Reload the input history from disk file."""
1247 self.history_manager.reload_history()
1259 self.history_manager.reload_history()
1248
1260
1249 def history_saving_wrapper(self, func):
1261 def history_saving_wrapper(self, func):
1250 """ Wrap func for readline history saving
1262 """ Wrap func for readline history saving
1251
1263
1252 Convert func into callable that saves & restores
1264 Convert func into callable that saves & restores
1253 history around the call """
1265 history around the call """
1254
1266
1255 if self.has_readline:
1267 if self.has_readline:
1256 from IPython.utils import rlineimpl as readline
1268 from IPython.utils import rlineimpl as readline
1257 else:
1269 else:
1258 return func
1270 return func
1259
1271
1260 def wrapper():
1272 def wrapper():
1261 self.save_history()
1273 self.save_history()
1262 try:
1274 try:
1263 func()
1275 func()
1264 finally:
1276 finally:
1265 self.reload_history()
1277 self.reload_history()
1266 return wrapper
1278 return wrapper
1267
1279
1268 def get_history(self, index=None, raw=False, output=True):
1280 def get_history(self, index=None, raw=False, output=True):
1269 return self.history_manager.get_history(index, raw, output)
1281 return self.history_manager.get_history(index, raw, output)
1270
1282
1271
1283
1272 #-------------------------------------------------------------------------
1284 #-------------------------------------------------------------------------
1273 # Things related to exception handling and tracebacks (not debugging)
1285 # Things related to exception handling and tracebacks (not debugging)
1274 #-------------------------------------------------------------------------
1286 #-------------------------------------------------------------------------
1275
1287
1276 def init_traceback_handlers(self, custom_exceptions):
1288 def init_traceback_handlers(self, custom_exceptions):
1277 # Syntax error handler.
1289 # Syntax error handler.
1278 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1290 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1279
1291
1280 # The interactive one is initialized with an offset, meaning we always
1292 # The interactive one is initialized with an offset, meaning we always
1281 # want to remove the topmost item in the traceback, which is our own
1293 # want to remove the topmost item in the traceback, which is our own
1282 # internal code. Valid modes: ['Plain','Context','Verbose']
1294 # internal code. Valid modes: ['Plain','Context','Verbose']
1283 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1295 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1284 color_scheme='NoColor',
1296 color_scheme='NoColor',
1285 tb_offset = 1,
1297 tb_offset = 1,
1286 check_cache=self.compile.check_cache)
1298 check_cache=self.compile.check_cache)
1287
1299
1288 # The instance will store a pointer to the system-wide exception hook,
1300 # The instance will store a pointer to the system-wide exception hook,
1289 # so that runtime code (such as magics) can access it. This is because
1301 # so that runtime code (such as magics) can access it. This is because
1290 # during the read-eval loop, it may get temporarily overwritten.
1302 # during the read-eval loop, it may get temporarily overwritten.
1291 self.sys_excepthook = sys.excepthook
1303 self.sys_excepthook = sys.excepthook
1292
1304
1293 # and add any custom exception handlers the user may have specified
1305 # and add any custom exception handlers the user may have specified
1294 self.set_custom_exc(*custom_exceptions)
1306 self.set_custom_exc(*custom_exceptions)
1295
1307
1296 # Set the exception mode
1308 # Set the exception mode
1297 self.InteractiveTB.set_mode(mode=self.xmode)
1309 self.InteractiveTB.set_mode(mode=self.xmode)
1298
1310
1299 def set_custom_exc(self, exc_tuple, handler):
1311 def set_custom_exc(self, exc_tuple, handler):
1300 """set_custom_exc(exc_tuple,handler)
1312 """set_custom_exc(exc_tuple,handler)
1301
1313
1302 Set a custom exception handler, which will be called if any of the
1314 Set a custom exception handler, which will be called if any of the
1303 exceptions in exc_tuple occur in the mainloop (specifically, in the
1315 exceptions in exc_tuple occur in the mainloop (specifically, in the
1304 run_code() method.
1316 run_code() method.
1305
1317
1306 Inputs:
1318 Inputs:
1307
1319
1308 - exc_tuple: a *tuple* of valid exceptions to call the defined
1320 - exc_tuple: a *tuple* of valid exceptions to call the defined
1309 handler for. It is very important that you use a tuple, and NOT A
1321 handler for. It is very important that you use a tuple, and NOT A
1310 LIST here, because of the way Python's except statement works. If
1322 LIST here, because of the way Python's except statement works. If
1311 you only want to trap a single exception, use a singleton tuple:
1323 you only want to trap a single exception, use a singleton tuple:
1312
1324
1313 exc_tuple == (MyCustomException,)
1325 exc_tuple == (MyCustomException,)
1314
1326
1315 - handler: this must be defined as a function with the following
1327 - handler: this must be defined as a function with the following
1316 basic interface::
1328 basic interface::
1317
1329
1318 def my_handler(self, etype, value, tb, tb_offset=None)
1330 def my_handler(self, etype, value, tb, tb_offset=None)
1319 ...
1331 ...
1320 # The return value must be
1332 # The return value must be
1321 return structured_traceback
1333 return structured_traceback
1322
1334
1323 This will be made into an instance method (via types.MethodType)
1335 This will be made into an instance method (via types.MethodType)
1324 of IPython itself, and it will be called if any of the exceptions
1336 of IPython itself, and it will be called if any of the exceptions
1325 listed in the exc_tuple are caught. If the handler is None, an
1337 listed in the exc_tuple are caught. If the handler is None, an
1326 internal basic one is used, which just prints basic info.
1338 internal basic one is used, which just prints basic info.
1327
1339
1328 WARNING: by putting in your own exception handler into IPython's main
1340 WARNING: by putting in your own exception handler into IPython's main
1329 execution loop, you run a very good chance of nasty crashes. This
1341 execution loop, you run a very good chance of nasty crashes. This
1330 facility should only be used if you really know what you are doing."""
1342 facility should only be used if you really know what you are doing."""
1331
1343
1332 assert type(exc_tuple)==type(()) , \
1344 assert type(exc_tuple)==type(()) , \
1333 "The custom exceptions must be given AS A TUPLE."
1345 "The custom exceptions must be given AS A TUPLE."
1334
1346
1335 def dummy_handler(self,etype,value,tb):
1347 def dummy_handler(self,etype,value,tb):
1336 print '*** Simple custom exception handler ***'
1348 print '*** Simple custom exception handler ***'
1337 print 'Exception type :',etype
1349 print 'Exception type :',etype
1338 print 'Exception value:',value
1350 print 'Exception value:',value
1339 print 'Traceback :',tb
1351 print 'Traceback :',tb
1340 print 'Source code :','\n'.join(self.buffer)
1352 print 'Source code :','\n'.join(self.buffer)
1341
1353
1342 if handler is None: handler = dummy_handler
1354 if handler is None: handler = dummy_handler
1343
1355
1344 self.CustomTB = types.MethodType(handler,self)
1356 self.CustomTB = types.MethodType(handler,self)
1345 self.custom_exceptions = exc_tuple
1357 self.custom_exceptions = exc_tuple
1346
1358
1347 def excepthook(self, etype, value, tb):
1359 def excepthook(self, etype, value, tb):
1348 """One more defense for GUI apps that call sys.excepthook.
1360 """One more defense for GUI apps that call sys.excepthook.
1349
1361
1350 GUI frameworks like wxPython trap exceptions and call
1362 GUI frameworks like wxPython trap exceptions and call
1351 sys.excepthook themselves. I guess this is a feature that
1363 sys.excepthook themselves. I guess this is a feature that
1352 enables them to keep running after exceptions that would
1364 enables them to keep running after exceptions that would
1353 otherwise kill their mainloop. This is a bother for IPython
1365 otherwise kill their mainloop. This is a bother for IPython
1354 which excepts to catch all of the program exceptions with a try:
1366 which excepts to catch all of the program exceptions with a try:
1355 except: statement.
1367 except: statement.
1356
1368
1357 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1369 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1358 any app directly invokes sys.excepthook, it will look to the user like
1370 any app directly invokes sys.excepthook, it will look to the user like
1359 IPython crashed. In order to work around this, we can disable the
1371 IPython crashed. In order to work around this, we can disable the
1360 CrashHandler and replace it with this excepthook instead, which prints a
1372 CrashHandler and replace it with this excepthook instead, which prints a
1361 regular traceback using our InteractiveTB. In this fashion, apps which
1373 regular traceback using our InteractiveTB. In this fashion, apps which
1362 call sys.excepthook will generate a regular-looking exception from
1374 call sys.excepthook will generate a regular-looking exception from
1363 IPython, and the CrashHandler will only be triggered by real IPython
1375 IPython, and the CrashHandler will only be triggered by real IPython
1364 crashes.
1376 crashes.
1365
1377
1366 This hook should be used sparingly, only in places which are not likely
1378 This hook should be used sparingly, only in places which are not likely
1367 to be true IPython errors.
1379 to be true IPython errors.
1368 """
1380 """
1369 self.showtraceback((etype,value,tb),tb_offset=0)
1381 self.showtraceback((etype,value,tb),tb_offset=0)
1370
1382
1371 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1383 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1372 exception_only=False):
1384 exception_only=False):
1373 """Display the exception that just occurred.
1385 """Display the exception that just occurred.
1374
1386
1375 If nothing is known about the exception, this is the method which
1387 If nothing is known about the exception, this is the method which
1376 should be used throughout the code for presenting user tracebacks,
1388 should be used throughout the code for presenting user tracebacks,
1377 rather than directly invoking the InteractiveTB object.
1389 rather than directly invoking the InteractiveTB object.
1378
1390
1379 A specific showsyntaxerror() also exists, but this method can take
1391 A specific showsyntaxerror() also exists, but this method can take
1380 care of calling it if needed, so unless you are explicitly catching a
1392 care of calling it if needed, so unless you are explicitly catching a
1381 SyntaxError exception, don't try to analyze the stack manually and
1393 SyntaxError exception, don't try to analyze the stack manually and
1382 simply call this method."""
1394 simply call this method."""
1383
1395
1384 try:
1396 try:
1385 if exc_tuple is None:
1397 if exc_tuple is None:
1386 etype, value, tb = sys.exc_info()
1398 etype, value, tb = sys.exc_info()
1387 else:
1399 else:
1388 etype, value, tb = exc_tuple
1400 etype, value, tb = exc_tuple
1389
1401
1390 if etype is None:
1402 if etype is None:
1391 if hasattr(sys, 'last_type'):
1403 if hasattr(sys, 'last_type'):
1392 etype, value, tb = sys.last_type, sys.last_value, \
1404 etype, value, tb = sys.last_type, sys.last_value, \
1393 sys.last_traceback
1405 sys.last_traceback
1394 else:
1406 else:
1395 self.write_err('No traceback available to show.\n')
1407 self.write_err('No traceback available to show.\n')
1396 return
1408 return
1397
1409
1398 if etype is SyntaxError:
1410 if etype is SyntaxError:
1399 # Though this won't be called by syntax errors in the input
1411 # Though this won't be called by syntax errors in the input
1400 # line, there may be SyntaxError cases whith imported code.
1412 # line, there may be SyntaxError cases whith imported code.
1401 self.showsyntaxerror(filename)
1413 self.showsyntaxerror(filename)
1402 elif etype is UsageError:
1414 elif etype is UsageError:
1403 print "UsageError:", value
1415 print "UsageError:", value
1404 else:
1416 else:
1405 # WARNING: these variables are somewhat deprecated and not
1417 # WARNING: these variables are somewhat deprecated and not
1406 # necessarily safe to use in a threaded environment, but tools
1418 # necessarily safe to use in a threaded environment, but tools
1407 # like pdb depend on their existence, so let's set them. If we
1419 # like pdb depend on their existence, so let's set them. If we
1408 # find problems in the field, we'll need to revisit their use.
1420 # find problems in the field, we'll need to revisit their use.
1409 sys.last_type = etype
1421 sys.last_type = etype
1410 sys.last_value = value
1422 sys.last_value = value
1411 sys.last_traceback = tb
1423 sys.last_traceback = tb
1412
1424
1413 if etype in self.custom_exceptions:
1425 if etype in self.custom_exceptions:
1414 # FIXME: Old custom traceback objects may just return a
1426 # FIXME: Old custom traceback objects may just return a
1415 # string, in that case we just put it into a list
1427 # string, in that case we just put it into a list
1416 stb = self.CustomTB(etype, value, tb, tb_offset)
1428 stb = self.CustomTB(etype, value, tb, tb_offset)
1417 if isinstance(ctb, basestring):
1429 if isinstance(ctb, basestring):
1418 stb = [stb]
1430 stb = [stb]
1419 else:
1431 else:
1420 if exception_only:
1432 if exception_only:
1421 stb = ['An exception has occurred, use %tb to see '
1433 stb = ['An exception has occurred, use %tb to see '
1422 'the full traceback.\n']
1434 'the full traceback.\n']
1423 stb.extend(self.InteractiveTB.get_exception_only(etype,
1435 stb.extend(self.InteractiveTB.get_exception_only(etype,
1424 value))
1436 value))
1425 else:
1437 else:
1426 stb = self.InteractiveTB.structured_traceback(etype,
1438 stb = self.InteractiveTB.structured_traceback(etype,
1427 value, tb, tb_offset=tb_offset)
1439 value, tb, tb_offset=tb_offset)
1428 # FIXME: the pdb calling should be done by us, not by
1440 # FIXME: the pdb calling should be done by us, not by
1429 # the code computing the traceback.
1441 # the code computing the traceback.
1430 if self.InteractiveTB.call_pdb:
1442 if self.InteractiveTB.call_pdb:
1431 # pdb mucks up readline, fix it back
1443 # pdb mucks up readline, fix it back
1432 self.set_readline_completer()
1444 self.set_readline_completer()
1433
1445
1434 # Actually show the traceback
1446 # Actually show the traceback
1435 self._showtraceback(etype, value, stb)
1447 self._showtraceback(etype, value, stb)
1436
1448
1437 except KeyboardInterrupt:
1449 except KeyboardInterrupt:
1438 self.write_err("\nKeyboardInterrupt\n")
1450 self.write_err("\nKeyboardInterrupt\n")
1439
1451
1440 def _showtraceback(self, etype, evalue, stb):
1452 def _showtraceback(self, etype, evalue, stb):
1441 """Actually show a traceback.
1453 """Actually show a traceback.
1442
1454
1443 Subclasses may override this method to put the traceback on a different
1455 Subclasses may override this method to put the traceback on a different
1444 place, like a side channel.
1456 place, like a side channel.
1445 """
1457 """
1446 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1458 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1447
1459
1448 def showsyntaxerror(self, filename=None):
1460 def showsyntaxerror(self, filename=None):
1449 """Display the syntax error that just occurred.
1461 """Display the syntax error that just occurred.
1450
1462
1451 This doesn't display a stack trace because there isn't one.
1463 This doesn't display a stack trace because there isn't one.
1452
1464
1453 If a filename is given, it is stuffed in the exception instead
1465 If a filename is given, it is stuffed in the exception instead
1454 of what was there before (because Python's parser always uses
1466 of what was there before (because Python's parser always uses
1455 "<string>" when reading from a string).
1467 "<string>" when reading from a string).
1456 """
1468 """
1457 etype, value, last_traceback = sys.exc_info()
1469 etype, value, last_traceback = sys.exc_info()
1458
1470
1459 # See note about these variables in showtraceback() above
1471 # See note about these variables in showtraceback() above
1460 sys.last_type = etype
1472 sys.last_type = etype
1461 sys.last_value = value
1473 sys.last_value = value
1462 sys.last_traceback = last_traceback
1474 sys.last_traceback = last_traceback
1463
1475
1464 if filename and etype is SyntaxError:
1476 if filename and etype is SyntaxError:
1465 # Work hard to stuff the correct filename in the exception
1477 # Work hard to stuff the correct filename in the exception
1466 try:
1478 try:
1467 msg, (dummy_filename, lineno, offset, line) = value
1479 msg, (dummy_filename, lineno, offset, line) = value
1468 except:
1480 except:
1469 # Not the format we expect; leave it alone
1481 # Not the format we expect; leave it alone
1470 pass
1482 pass
1471 else:
1483 else:
1472 # Stuff in the right filename
1484 # Stuff in the right filename
1473 try:
1485 try:
1474 # Assume SyntaxError is a class exception
1486 # Assume SyntaxError is a class exception
1475 value = SyntaxError(msg, (filename, lineno, offset, line))
1487 value = SyntaxError(msg, (filename, lineno, offset, line))
1476 except:
1488 except:
1477 # If that failed, assume SyntaxError is a string
1489 # If that failed, assume SyntaxError is a string
1478 value = msg, (filename, lineno, offset, line)
1490 value = msg, (filename, lineno, offset, line)
1479 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1491 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1480 self._showtraceback(etype, value, stb)
1492 self._showtraceback(etype, value, stb)
1481
1493
1482 #-------------------------------------------------------------------------
1494 #-------------------------------------------------------------------------
1483 # Things related to readline
1495 # Things related to readline
1484 #-------------------------------------------------------------------------
1496 #-------------------------------------------------------------------------
1485
1497
1486 def init_readline(self):
1498 def init_readline(self):
1487 """Command history completion/saving/reloading."""
1499 """Command history completion/saving/reloading."""
1488
1500
1489 if self.readline_use:
1501 if self.readline_use:
1490 import IPython.utils.rlineimpl as readline
1502 import IPython.utils.rlineimpl as readline
1491
1503
1492 self.rl_next_input = None
1504 self.rl_next_input = None
1493 self.rl_do_indent = False
1505 self.rl_do_indent = False
1494
1506
1495 if not self.readline_use or not readline.have_readline:
1507 if not self.readline_use or not readline.have_readline:
1496 self.has_readline = False
1508 self.has_readline = False
1497 self.readline = None
1509 self.readline = None
1498 # Set a number of methods that depend on readline to be no-op
1510 # Set a number of methods that depend on readline to be no-op
1499 self.set_readline_completer = no_op
1511 self.set_readline_completer = no_op
1500 self.set_custom_completer = no_op
1512 self.set_custom_completer = no_op
1501 self.set_completer_frame = no_op
1513 self.set_completer_frame = no_op
1502 warn('Readline services not available or not loaded.')
1514 warn('Readline services not available or not loaded.')
1503 else:
1515 else:
1504 self.has_readline = True
1516 self.has_readline = True
1505 self.readline = readline
1517 self.readline = readline
1506 sys.modules['readline'] = readline
1518 sys.modules['readline'] = readline
1507
1519
1508 # Platform-specific configuration
1520 # Platform-specific configuration
1509 if os.name == 'nt':
1521 if os.name == 'nt':
1510 # FIXME - check with Frederick to see if we can harmonize
1522 # FIXME - check with Frederick to see if we can harmonize
1511 # naming conventions with pyreadline to avoid this
1523 # naming conventions with pyreadline to avoid this
1512 # platform-dependent check
1524 # platform-dependent check
1513 self.readline_startup_hook = readline.set_pre_input_hook
1525 self.readline_startup_hook = readline.set_pre_input_hook
1514 else:
1526 else:
1515 self.readline_startup_hook = readline.set_startup_hook
1527 self.readline_startup_hook = readline.set_startup_hook
1516
1528
1517 # Load user's initrc file (readline config)
1529 # Load user's initrc file (readline config)
1518 # Or if libedit is used, load editrc.
1530 # Or if libedit is used, load editrc.
1519 inputrc_name = os.environ.get('INPUTRC')
1531 inputrc_name = os.environ.get('INPUTRC')
1520 if inputrc_name is None:
1532 if inputrc_name is None:
1521 home_dir = get_home_dir()
1533 home_dir = get_home_dir()
1522 if home_dir is not None:
1534 if home_dir is not None:
1523 inputrc_name = '.inputrc'
1535 inputrc_name = '.inputrc'
1524 if readline.uses_libedit:
1536 if readline.uses_libedit:
1525 inputrc_name = '.editrc'
1537 inputrc_name = '.editrc'
1526 inputrc_name = os.path.join(home_dir, inputrc_name)
1538 inputrc_name = os.path.join(home_dir, inputrc_name)
1527 if os.path.isfile(inputrc_name):
1539 if os.path.isfile(inputrc_name):
1528 try:
1540 try:
1529 readline.read_init_file(inputrc_name)
1541 readline.read_init_file(inputrc_name)
1530 except:
1542 except:
1531 warn('Problems reading readline initialization file <%s>'
1543 warn('Problems reading readline initialization file <%s>'
1532 % inputrc_name)
1544 % inputrc_name)
1533
1545
1534 # Configure readline according to user's prefs
1546 # Configure readline according to user's prefs
1535 # This is only done if GNU readline is being used. If libedit
1547 # This is only done if GNU readline is being used. If libedit
1536 # is being used (as on Leopard) the readline config is
1548 # is being used (as on Leopard) the readline config is
1537 # not run as the syntax for libedit is different.
1549 # not run as the syntax for libedit is different.
1538 if not readline.uses_libedit:
1550 if not readline.uses_libedit:
1539 for rlcommand in self.readline_parse_and_bind:
1551 for rlcommand in self.readline_parse_and_bind:
1540 #print "loading rl:",rlcommand # dbg
1552 #print "loading rl:",rlcommand # dbg
1541 readline.parse_and_bind(rlcommand)
1553 readline.parse_and_bind(rlcommand)
1542
1554
1543 # Remove some chars from the delimiters list. If we encounter
1555 # Remove some chars from the delimiters list. If we encounter
1544 # unicode chars, discard them.
1556 # unicode chars, discard them.
1545 delims = readline.get_completer_delims().encode("ascii", "ignore")
1557 delims = readline.get_completer_delims().encode("ascii", "ignore")
1546 delims = delims.translate(None, self.readline_remove_delims)
1558 delims = delims.translate(None, self.readline_remove_delims)
1547 delims = delims.replace(ESC_MAGIC, '')
1559 delims = delims.replace(ESC_MAGIC, '')
1548 readline.set_completer_delims(delims)
1560 readline.set_completer_delims(delims)
1549 # otherwise we end up with a monster history after a while:
1561 # otherwise we end up with a monster history after a while:
1550 readline.set_history_length(self.history_length)
1562 readline.set_history_length(self.history_length)
1551 try:
1563 try:
1552 #print '*** Reading readline history' # dbg
1564 #print '*** Reading readline history' # dbg
1553 self.reload_history()
1565 self.reload_history()
1554 except IOError:
1566 except IOError:
1555 pass # It doesn't exist yet.
1567 pass # It doesn't exist yet.
1556
1568
1557 # Configure auto-indent for all platforms
1569 # Configure auto-indent for all platforms
1558 self.set_autoindent(self.autoindent)
1570 self.set_autoindent(self.autoindent)
1559
1571
1560 def set_next_input(self, s):
1572 def set_next_input(self, s):
1561 """ Sets the 'default' input string for the next command line.
1573 """ Sets the 'default' input string for the next command line.
1562
1574
1563 Requires readline.
1575 Requires readline.
1564
1576
1565 Example:
1577 Example:
1566
1578
1567 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1579 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1568 [D:\ipython]|2> Hello Word_ # cursor is here
1580 [D:\ipython]|2> Hello Word_ # cursor is here
1569 """
1581 """
1570
1582
1571 self.rl_next_input = s
1583 self.rl_next_input = s
1572
1584
1573 # Maybe move this to the terminal subclass?
1585 # Maybe move this to the terminal subclass?
1574 def pre_readline(self):
1586 def pre_readline(self):
1575 """readline hook to be used at the start of each line.
1587 """readline hook to be used at the start of each line.
1576
1588
1577 Currently it handles auto-indent only."""
1589 Currently it handles auto-indent only."""
1578
1590
1579 if self.rl_do_indent:
1591 if self.rl_do_indent:
1580 self.readline.insert_text(self._indent_current_str())
1592 self.readline.insert_text(self._indent_current_str())
1581 if self.rl_next_input is not None:
1593 if self.rl_next_input is not None:
1582 self.readline.insert_text(self.rl_next_input)
1594 self.readline.insert_text(self.rl_next_input)
1583 self.rl_next_input = None
1595 self.rl_next_input = None
1584
1596
1585 def _indent_current_str(self):
1597 def _indent_current_str(self):
1586 """return the current level of indentation as a string"""
1598 """return the current level of indentation as a string"""
1587 return self.input_splitter.indent_spaces * ' '
1599 return self.input_splitter.indent_spaces * ' '
1588
1600
1589 #-------------------------------------------------------------------------
1601 #-------------------------------------------------------------------------
1590 # Things related to text completion
1602 # Things related to text completion
1591 #-------------------------------------------------------------------------
1603 #-------------------------------------------------------------------------
1592
1604
1593 def init_completer(self):
1605 def init_completer(self):
1594 """Initialize the completion machinery.
1606 """Initialize the completion machinery.
1595
1607
1596 This creates completion machinery that can be used by client code,
1608 This creates completion machinery that can be used by client code,
1597 either interactively in-process (typically triggered by the readline
1609 either interactively in-process (typically triggered by the readline
1598 library), programatically (such as in test suites) or out-of-prcess
1610 library), programatically (such as in test suites) or out-of-prcess
1599 (typically over the network by remote frontends).
1611 (typically over the network by remote frontends).
1600 """
1612 """
1601 from IPython.core.completer import IPCompleter
1613 from IPython.core.completer import IPCompleter
1602 from IPython.core.completerlib import (module_completer,
1614 from IPython.core.completerlib import (module_completer,
1603 magic_run_completer, cd_completer)
1615 magic_run_completer, cd_completer)
1604
1616
1605 self.Completer = IPCompleter(self,
1617 self.Completer = IPCompleter(self,
1606 self.user_ns,
1618 self.user_ns,
1607 self.user_global_ns,
1619 self.user_global_ns,
1608 self.readline_omit__names,
1620 self.readline_omit__names,
1609 self.alias_manager.alias_table,
1621 self.alias_manager.alias_table,
1610 self.has_readline)
1622 self.has_readline)
1611
1623
1612 # Add custom completers to the basic ones built into IPCompleter
1624 # Add custom completers to the basic ones built into IPCompleter
1613 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1625 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1614 self.strdispatchers['complete_command'] = sdisp
1626 self.strdispatchers['complete_command'] = sdisp
1615 self.Completer.custom_completers = sdisp
1627 self.Completer.custom_completers = sdisp
1616
1628
1617 self.set_hook('complete_command', module_completer, str_key = 'import')
1629 self.set_hook('complete_command', module_completer, str_key = 'import')
1618 self.set_hook('complete_command', module_completer, str_key = 'from')
1630 self.set_hook('complete_command', module_completer, str_key = 'from')
1619 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1631 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1620 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1632 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1621
1633
1622 # Only configure readline if we truly are using readline. IPython can
1634 # Only configure readline if we truly are using readline. IPython can
1623 # do tab-completion over the network, in GUIs, etc, where readline
1635 # do tab-completion over the network, in GUIs, etc, where readline
1624 # itself may be absent
1636 # itself may be absent
1625 if self.has_readline:
1637 if self.has_readline:
1626 self.set_readline_completer()
1638 self.set_readline_completer()
1627
1639
1628 def complete(self, text, line=None, cursor_pos=None):
1640 def complete(self, text, line=None, cursor_pos=None):
1629 """Return the completed text and a list of completions.
1641 """Return the completed text and a list of completions.
1630
1642
1631 Parameters
1643 Parameters
1632 ----------
1644 ----------
1633
1645
1634 text : string
1646 text : string
1635 A string of text to be completed on. It can be given as empty and
1647 A string of text to be completed on. It can be given as empty and
1636 instead a line/position pair are given. In this case, the
1648 instead a line/position pair are given. In this case, the
1637 completer itself will split the line like readline does.
1649 completer itself will split the line like readline does.
1638
1650
1639 line : string, optional
1651 line : string, optional
1640 The complete line that text is part of.
1652 The complete line that text is part of.
1641
1653
1642 cursor_pos : int, optional
1654 cursor_pos : int, optional
1643 The position of the cursor on the input line.
1655 The position of the cursor on the input line.
1644
1656
1645 Returns
1657 Returns
1646 -------
1658 -------
1647 text : string
1659 text : string
1648 The actual text that was completed.
1660 The actual text that was completed.
1649
1661
1650 matches : list
1662 matches : list
1651 A sorted list with all possible completions.
1663 A sorted list with all possible completions.
1652
1664
1653 The optional arguments allow the completion to take more context into
1665 The optional arguments allow the completion to take more context into
1654 account, and are part of the low-level completion API.
1666 account, and are part of the low-level completion API.
1655
1667
1656 This is a wrapper around the completion mechanism, similar to what
1668 This is a wrapper around the completion mechanism, similar to what
1657 readline does at the command line when the TAB key is hit. By
1669 readline does at the command line when the TAB key is hit. By
1658 exposing it as a method, it can be used by other non-readline
1670 exposing it as a method, it can be used by other non-readline
1659 environments (such as GUIs) for text completion.
1671 environments (such as GUIs) for text completion.
1660
1672
1661 Simple usage example:
1673 Simple usage example:
1662
1674
1663 In [1]: x = 'hello'
1675 In [1]: x = 'hello'
1664
1676
1665 In [2]: _ip.complete('x.l')
1677 In [2]: _ip.complete('x.l')
1666 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1678 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1667 """
1679 """
1668
1680
1669 # Inject names into __builtin__ so we can complete on the added names.
1681 # Inject names into __builtin__ so we can complete on the added names.
1670 with self.builtin_trap:
1682 with self.builtin_trap:
1671 return self.Completer.complete(text, line, cursor_pos)
1683 return self.Completer.complete(text, line, cursor_pos)
1672
1684
1673 def set_custom_completer(self, completer, pos=0):
1685 def set_custom_completer(self, completer, pos=0):
1674 """Adds a new custom completer function.
1686 """Adds a new custom completer function.
1675
1687
1676 The position argument (defaults to 0) is the index in the completers
1688 The position argument (defaults to 0) is the index in the completers
1677 list where you want the completer to be inserted."""
1689 list where you want the completer to be inserted."""
1678
1690
1679 newcomp = types.MethodType(completer,self.Completer)
1691 newcomp = types.MethodType(completer,self.Completer)
1680 self.Completer.matchers.insert(pos,newcomp)
1692 self.Completer.matchers.insert(pos,newcomp)
1681
1693
1682 def set_readline_completer(self):
1694 def set_readline_completer(self):
1683 """Reset readline's completer to be our own."""
1695 """Reset readline's completer to be our own."""
1684 self.readline.set_completer(self.Completer.rlcomplete)
1696 self.readline.set_completer(self.Completer.rlcomplete)
1685
1697
1686 def set_completer_frame(self, frame=None):
1698 def set_completer_frame(self, frame=None):
1687 """Set the frame of the completer."""
1699 """Set the frame of the completer."""
1688 if frame:
1700 if frame:
1689 self.Completer.namespace = frame.f_locals
1701 self.Completer.namespace = frame.f_locals
1690 self.Completer.global_namespace = frame.f_globals
1702 self.Completer.global_namespace = frame.f_globals
1691 else:
1703 else:
1692 self.Completer.namespace = self.user_ns
1704 self.Completer.namespace = self.user_ns
1693 self.Completer.global_namespace = self.user_global_ns
1705 self.Completer.global_namespace = self.user_global_ns
1694
1706
1695 #-------------------------------------------------------------------------
1707 #-------------------------------------------------------------------------
1696 # Things related to magics
1708 # Things related to magics
1697 #-------------------------------------------------------------------------
1709 #-------------------------------------------------------------------------
1698
1710
1699 def init_magics(self):
1711 def init_magics(self):
1700 # FIXME: Move the color initialization to the DisplayHook, which
1712 # FIXME: Move the color initialization to the DisplayHook, which
1701 # should be split into a prompt manager and displayhook. We probably
1713 # should be split into a prompt manager and displayhook. We probably
1702 # even need a centralize colors management object.
1714 # even need a centralize colors management object.
1703 self.magic_colors(self.colors)
1715 self.magic_colors(self.colors)
1704 # History was moved to a separate module
1716 # History was moved to a separate module
1705 from . import history
1717 from . import history
1706 history.init_ipython(self)
1718 history.init_ipython(self)
1707
1719
1708 def magic(self,arg_s):
1720 def magic(self,arg_s):
1709 """Call a magic function by name.
1721 """Call a magic function by name.
1710
1722
1711 Input: a string containing the name of the magic function to call and
1723 Input: a string containing the name of the magic function to call and
1712 any additional arguments to be passed to the magic.
1724 any additional arguments to be passed to the magic.
1713
1725
1714 magic('name -opt foo bar') is equivalent to typing at the ipython
1726 magic('name -opt foo bar') is equivalent to typing at the ipython
1715 prompt:
1727 prompt:
1716
1728
1717 In[1]: %name -opt foo bar
1729 In[1]: %name -opt foo bar
1718
1730
1719 To call a magic without arguments, simply use magic('name').
1731 To call a magic without arguments, simply use magic('name').
1720
1732
1721 This provides a proper Python function to call IPython's magics in any
1733 This provides a proper Python function to call IPython's magics in any
1722 valid Python code you can type at the interpreter, including loops and
1734 valid Python code you can type at the interpreter, including loops and
1723 compound statements.
1735 compound statements.
1724 """
1736 """
1725 args = arg_s.split(' ',1)
1737 args = arg_s.split(' ',1)
1726 magic_name = args[0]
1738 magic_name = args[0]
1727 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1739 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1728
1740
1729 try:
1741 try:
1730 magic_args = args[1]
1742 magic_args = args[1]
1731 except IndexError:
1743 except IndexError:
1732 magic_args = ''
1744 magic_args = ''
1733 fn = getattr(self,'magic_'+magic_name,None)
1745 fn = getattr(self,'magic_'+magic_name,None)
1734 if fn is None:
1746 if fn is None:
1735 error("Magic function `%s` not found." % magic_name)
1747 error("Magic function `%s` not found." % magic_name)
1736 else:
1748 else:
1737 magic_args = self.var_expand(magic_args,1)
1749 magic_args = self.var_expand(magic_args,1)
1738 with nested(self.builtin_trap,):
1750 with nested(self.builtin_trap,):
1739 result = fn(magic_args)
1751 result = fn(magic_args)
1740 return result
1752 return result
1741
1753
1742 def define_magic(self, magicname, func):
1754 def define_magic(self, magicname, func):
1743 """Expose own function as magic function for ipython
1755 """Expose own function as magic function for ipython
1744
1756
1745 def foo_impl(self,parameter_s=''):
1757 def foo_impl(self,parameter_s=''):
1746 'My very own magic!. (Use docstrings, IPython reads them).'
1758 'My very own magic!. (Use docstrings, IPython reads them).'
1747 print 'Magic function. Passed parameter is between < >:'
1759 print 'Magic function. Passed parameter is between < >:'
1748 print '<%s>' % parameter_s
1760 print '<%s>' % parameter_s
1749 print 'The self object is:',self
1761 print 'The self object is:',self
1750
1762
1751 self.define_magic('foo',foo_impl)
1763 self.define_magic('foo',foo_impl)
1752 """
1764 """
1753
1765
1754 import new
1766 import new
1755 im = types.MethodType(func,self)
1767 im = types.MethodType(func,self)
1756 old = getattr(self, "magic_" + magicname, None)
1768 old = getattr(self, "magic_" + magicname, None)
1757 setattr(self, "magic_" + magicname, im)
1769 setattr(self, "magic_" + magicname, im)
1758 return old
1770 return old
1759
1771
1760 #-------------------------------------------------------------------------
1772 #-------------------------------------------------------------------------
1761 # Things related to macros
1773 # Things related to macros
1762 #-------------------------------------------------------------------------
1774 #-------------------------------------------------------------------------
1763
1775
1764 def define_macro(self, name, themacro):
1776 def define_macro(self, name, themacro):
1765 """Define a new macro
1777 """Define a new macro
1766
1778
1767 Parameters
1779 Parameters
1768 ----------
1780 ----------
1769 name : str
1781 name : str
1770 The name of the macro.
1782 The name of the macro.
1771 themacro : str or Macro
1783 themacro : str or Macro
1772 The action to do upon invoking the macro. If a string, a new
1784 The action to do upon invoking the macro. If a string, a new
1773 Macro object is created by passing the string to it.
1785 Macro object is created by passing the string to it.
1774 """
1786 """
1775
1787
1776 from IPython.core import macro
1788 from IPython.core import macro
1777
1789
1778 if isinstance(themacro, basestring):
1790 if isinstance(themacro, basestring):
1779 themacro = macro.Macro(themacro)
1791 themacro = macro.Macro(themacro)
1780 if not isinstance(themacro, macro.Macro):
1792 if not isinstance(themacro, macro.Macro):
1781 raise ValueError('A macro must be a string or a Macro instance.')
1793 raise ValueError('A macro must be a string or a Macro instance.')
1782 self.user_ns[name] = themacro
1794 self.user_ns[name] = themacro
1783
1795
1784 #-------------------------------------------------------------------------
1796 #-------------------------------------------------------------------------
1785 # Things related to the running of system commands
1797 # Things related to the running of system commands
1786 #-------------------------------------------------------------------------
1798 #-------------------------------------------------------------------------
1787
1799
1788 def system(self, cmd):
1800 def system(self, cmd):
1789 """Call the given cmd in a subprocess.
1801 """Call the given cmd in a subprocess.
1790
1802
1791 Parameters
1803 Parameters
1792 ----------
1804 ----------
1793 cmd : str
1805 cmd : str
1794 Command to execute (can not end in '&', as bacground processes are
1806 Command to execute (can not end in '&', as bacground processes are
1795 not supported.
1807 not supported.
1796 """
1808 """
1797 # We do not support backgrounding processes because we either use
1809 # We do not support backgrounding processes because we either use
1798 # pexpect or pipes to read from. Users can always just call
1810 # pexpect or pipes to read from. Users can always just call
1799 # os.system() if they really want a background process.
1811 # os.system() if they really want a background process.
1800 if cmd.endswith('&'):
1812 if cmd.endswith('&'):
1801 raise OSError("Background processes not supported.")
1813 raise OSError("Background processes not supported.")
1802
1814
1803 return system(self.var_expand(cmd, depth=2))
1815 return system(self.var_expand(cmd, depth=2))
1804
1816
1805 def getoutput(self, cmd, split=True):
1817 def getoutput(self, cmd, split=True):
1806 """Get output (possibly including stderr) from a subprocess.
1818 """Get output (possibly including stderr) from a subprocess.
1807
1819
1808 Parameters
1820 Parameters
1809 ----------
1821 ----------
1810 cmd : str
1822 cmd : str
1811 Command to execute (can not end in '&', as background processes are
1823 Command to execute (can not end in '&', as background processes are
1812 not supported.
1824 not supported.
1813 split : bool, optional
1825 split : bool, optional
1814
1826
1815 If True, split the output into an IPython SList. Otherwise, an
1827 If True, split the output into an IPython SList. Otherwise, an
1816 IPython LSString is returned. These are objects similar to normal
1828 IPython LSString is returned. These are objects similar to normal
1817 lists and strings, with a few convenience attributes for easier
1829 lists and strings, with a few convenience attributes for easier
1818 manipulation of line-based output. You can use '?' on them for
1830 manipulation of line-based output. You can use '?' on them for
1819 details.
1831 details.
1820 """
1832 """
1821 if cmd.endswith('&'):
1833 if cmd.endswith('&'):
1822 raise OSError("Background processes not supported.")
1834 raise OSError("Background processes not supported.")
1823 out = getoutput(self.var_expand(cmd, depth=2))
1835 out = getoutput(self.var_expand(cmd, depth=2))
1824 if split:
1836 if split:
1825 out = SList(out.splitlines())
1837 out = SList(out.splitlines())
1826 else:
1838 else:
1827 out = LSString(out)
1839 out = LSString(out)
1828 return out
1840 return out
1829
1841
1830 #-------------------------------------------------------------------------
1842 #-------------------------------------------------------------------------
1831 # Things related to aliases
1843 # Things related to aliases
1832 #-------------------------------------------------------------------------
1844 #-------------------------------------------------------------------------
1833
1845
1834 def init_alias(self):
1846 def init_alias(self):
1835 self.alias_manager = AliasManager(shell=self, config=self.config)
1847 self.alias_manager = AliasManager(shell=self, config=self.config)
1836 self.ns_table['alias'] = self.alias_manager.alias_table,
1848 self.ns_table['alias'] = self.alias_manager.alias_table,
1837
1849
1838 #-------------------------------------------------------------------------
1850 #-------------------------------------------------------------------------
1839 # Things related to extensions and plugins
1851 # Things related to extensions and plugins
1840 #-------------------------------------------------------------------------
1852 #-------------------------------------------------------------------------
1841
1853
1842 def init_extension_manager(self):
1854 def init_extension_manager(self):
1843 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1855 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1844
1856
1845 def init_plugin_manager(self):
1857 def init_plugin_manager(self):
1846 self.plugin_manager = PluginManager(config=self.config)
1858 self.plugin_manager = PluginManager(config=self.config)
1847
1859
1848 #-------------------------------------------------------------------------
1860 #-------------------------------------------------------------------------
1849 # Things related to payloads
1861 # Things related to payloads
1850 #-------------------------------------------------------------------------
1862 #-------------------------------------------------------------------------
1851
1863
1852 def init_payload(self):
1864 def init_payload(self):
1853 self.payload_manager = PayloadManager(config=self.config)
1865 self.payload_manager = PayloadManager(config=self.config)
1854
1866
1855 #-------------------------------------------------------------------------
1867 #-------------------------------------------------------------------------
1856 # Things related to the prefilter
1868 # Things related to the prefilter
1857 #-------------------------------------------------------------------------
1869 #-------------------------------------------------------------------------
1858
1870
1859 def init_prefilter(self):
1871 def init_prefilter(self):
1860 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1872 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1861 # Ultimately this will be refactored in the new interpreter code, but
1873 # Ultimately this will be refactored in the new interpreter code, but
1862 # for now, we should expose the main prefilter method (there's legacy
1874 # for now, we should expose the main prefilter method (there's legacy
1863 # code out there that may rely on this).
1875 # code out there that may rely on this).
1864 self.prefilter = self.prefilter_manager.prefilter_lines
1876 self.prefilter = self.prefilter_manager.prefilter_lines
1865
1877
1866 def auto_rewrite_input(self, cmd):
1878 def auto_rewrite_input(self, cmd):
1867 """Print to the screen the rewritten form of the user's command.
1879 """Print to the screen the rewritten form of the user's command.
1868
1880
1869 This shows visual feedback by rewriting input lines that cause
1881 This shows visual feedback by rewriting input lines that cause
1870 automatic calling to kick in, like::
1882 automatic calling to kick in, like::
1871
1883
1872 /f x
1884 /f x
1873
1885
1874 into::
1886 into::
1875
1887
1876 ------> f(x)
1888 ------> f(x)
1877
1889
1878 after the user's input prompt. This helps the user understand that the
1890 after the user's input prompt. This helps the user understand that the
1879 input line was transformed automatically by IPython.
1891 input line was transformed automatically by IPython.
1880 """
1892 """
1881 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1893 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1882
1894
1883 try:
1895 try:
1884 # plain ascii works better w/ pyreadline, on some machines, so
1896 # plain ascii works better w/ pyreadline, on some machines, so
1885 # we use it and only print uncolored rewrite if we have unicode
1897 # we use it and only print uncolored rewrite if we have unicode
1886 rw = str(rw)
1898 rw = str(rw)
1887 print >> IPython.utils.io.Term.cout, rw
1899 print >> IPython.utils.io.Term.cout, rw
1888 except UnicodeEncodeError:
1900 except UnicodeEncodeError:
1889 print "------> " + cmd
1901 print "------> " + cmd
1890
1902
1891 #-------------------------------------------------------------------------
1903 #-------------------------------------------------------------------------
1892 # Things related to extracting values/expressions from kernel and user_ns
1904 # Things related to extracting values/expressions from kernel and user_ns
1893 #-------------------------------------------------------------------------
1905 #-------------------------------------------------------------------------
1894
1906
1895 def _simple_error(self):
1907 def _simple_error(self):
1896 etype, value = sys.exc_info()[:2]
1908 etype, value = sys.exc_info()[:2]
1897 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1909 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1898
1910
1899 def user_variables(self, names):
1911 def user_variables(self, names):
1900 """Get a list of variable names from the user's namespace.
1912 """Get a list of variable names from the user's namespace.
1901
1913
1902 Parameters
1914 Parameters
1903 ----------
1915 ----------
1904 names : list of strings
1916 names : list of strings
1905 A list of names of variables to be read from the user namespace.
1917 A list of names of variables to be read from the user namespace.
1906
1918
1907 Returns
1919 Returns
1908 -------
1920 -------
1909 A dict, keyed by the input names and with the repr() of each value.
1921 A dict, keyed by the input names and with the repr() of each value.
1910 """
1922 """
1911 out = {}
1923 out = {}
1912 user_ns = self.user_ns
1924 user_ns = self.user_ns
1913 for varname in names:
1925 for varname in names:
1914 try:
1926 try:
1915 value = repr(user_ns[varname])
1927 value = repr(user_ns[varname])
1916 except:
1928 except:
1917 value = self._simple_error()
1929 value = self._simple_error()
1918 out[varname] = value
1930 out[varname] = value
1919 return out
1931 return out
1920
1932
1921 def user_expressions(self, expressions):
1933 def user_expressions(self, expressions):
1922 """Evaluate a dict of expressions in the user's namespace.
1934 """Evaluate a dict of expressions in the user's namespace.
1923
1935
1924 Parameters
1936 Parameters
1925 ----------
1937 ----------
1926 expressions : dict
1938 expressions : dict
1927 A dict with string keys and string values. The expression values
1939 A dict with string keys and string values. The expression values
1928 should be valid Python expressions, each of which will be evaluated
1940 should be valid Python expressions, each of which will be evaluated
1929 in the user namespace.
1941 in the user namespace.
1930
1942
1931 Returns
1943 Returns
1932 -------
1944 -------
1933 A dict, keyed like the input expressions dict, with the repr() of each
1945 A dict, keyed like the input expressions dict, with the repr() of each
1934 value.
1946 value.
1935 """
1947 """
1936 out = {}
1948 out = {}
1937 user_ns = self.user_ns
1949 user_ns = self.user_ns
1938 global_ns = self.user_global_ns
1950 global_ns = self.user_global_ns
1939 for key, expr in expressions.iteritems():
1951 for key, expr in expressions.iteritems():
1940 try:
1952 try:
1941 value = repr(eval(expr, global_ns, user_ns))
1953 value = repr(eval(expr, global_ns, user_ns))
1942 except:
1954 except:
1943 value = self._simple_error()
1955 value = self._simple_error()
1944 out[key] = value
1956 out[key] = value
1945 return out
1957 return out
1946
1958
1947 #-------------------------------------------------------------------------
1959 #-------------------------------------------------------------------------
1948 # Things related to the running of code
1960 # Things related to the running of code
1949 #-------------------------------------------------------------------------
1961 #-------------------------------------------------------------------------
1950
1962
1951 def ex(self, cmd):
1963 def ex(self, cmd):
1952 """Execute a normal python statement in user namespace."""
1964 """Execute a normal python statement in user namespace."""
1953 with nested(self.builtin_trap,):
1965 with nested(self.builtin_trap,):
1954 exec cmd in self.user_global_ns, self.user_ns
1966 exec cmd in self.user_global_ns, self.user_ns
1955
1967
1956 def ev(self, expr):
1968 def ev(self, expr):
1957 """Evaluate python expression expr in user namespace.
1969 """Evaluate python expression expr in user namespace.
1958
1970
1959 Returns the result of evaluation
1971 Returns the result of evaluation
1960 """
1972 """
1961 with nested(self.builtin_trap,):
1973 with nested(self.builtin_trap,):
1962 return eval(expr, self.user_global_ns, self.user_ns)
1974 return eval(expr, self.user_global_ns, self.user_ns)
1963
1975
1964 def safe_execfile(self, fname, *where, **kw):
1976 def safe_execfile(self, fname, *where, **kw):
1965 """A safe version of the builtin execfile().
1977 """A safe version of the builtin execfile().
1966
1978
1967 This version will never throw an exception, but instead print
1979 This version will never throw an exception, but instead print
1968 helpful error messages to the screen. This only works on pure
1980 helpful error messages to the screen. This only works on pure
1969 Python files with the .py extension.
1981 Python files with the .py extension.
1970
1982
1971 Parameters
1983 Parameters
1972 ----------
1984 ----------
1973 fname : string
1985 fname : string
1974 The name of the file to be executed.
1986 The name of the file to be executed.
1975 where : tuple
1987 where : tuple
1976 One or two namespaces, passed to execfile() as (globals,locals).
1988 One or two namespaces, passed to execfile() as (globals,locals).
1977 If only one is given, it is passed as both.
1989 If only one is given, it is passed as both.
1978 exit_ignore : bool (False)
1990 exit_ignore : bool (False)
1979 If True, then silence SystemExit for non-zero status (it is always
1991 If True, then silence SystemExit for non-zero status (it is always
1980 silenced for zero status, as it is so common).
1992 silenced for zero status, as it is so common).
1981 """
1993 """
1982 kw.setdefault('exit_ignore', False)
1994 kw.setdefault('exit_ignore', False)
1983
1995
1984 fname = os.path.abspath(os.path.expanduser(fname))
1996 fname = os.path.abspath(os.path.expanduser(fname))
1985
1997
1986 # Make sure we have a .py file
1998 # Make sure we have a .py file
1987 if not fname.endswith('.py'):
1999 if not fname.endswith('.py'):
1988 warn('File must end with .py to be run using execfile: <%s>' % fname)
2000 warn('File must end with .py to be run using execfile: <%s>' % fname)
1989
2001
1990 # Make sure we can open the file
2002 # Make sure we can open the file
1991 try:
2003 try:
1992 with open(fname) as thefile:
2004 with open(fname) as thefile:
1993 pass
2005 pass
1994 except:
2006 except:
1995 warn('Could not open file <%s> for safe execution.' % fname)
2007 warn('Could not open file <%s> for safe execution.' % fname)
1996 return
2008 return
1997
2009
1998 # Find things also in current directory. This is needed to mimic the
2010 # Find things also in current directory. This is needed to mimic the
1999 # behavior of running a script from the system command line, where
2011 # behavior of running a script from the system command line, where
2000 # Python inserts the script's directory into sys.path
2012 # Python inserts the script's directory into sys.path
2001 dname = os.path.dirname(fname)
2013 dname = os.path.dirname(fname)
2002
2014
2003 with prepended_to_syspath(dname):
2015 with prepended_to_syspath(dname):
2004 try:
2016 try:
2005 execfile(fname,*where)
2017 execfile(fname,*where)
2006 except SystemExit, status:
2018 except SystemExit, status:
2007 # If the call was made with 0 or None exit status (sys.exit(0)
2019 # If the call was made with 0 or None exit status (sys.exit(0)
2008 # or sys.exit() ), don't bother showing a traceback, as both of
2020 # or sys.exit() ), don't bother showing a traceback, as both of
2009 # these are considered normal by the OS:
2021 # these are considered normal by the OS:
2010 # > python -c'import sys;sys.exit(0)'; echo $?
2022 # > python -c'import sys;sys.exit(0)'; echo $?
2011 # 0
2023 # 0
2012 # > python -c'import sys;sys.exit()'; echo $?
2024 # > python -c'import sys;sys.exit()'; echo $?
2013 # 0
2025 # 0
2014 # For other exit status, we show the exception unless
2026 # For other exit status, we show the exception unless
2015 # explicitly silenced, but only in short form.
2027 # explicitly silenced, but only in short form.
2016 if status.code not in (0, None) and not kw['exit_ignore']:
2028 if status.code not in (0, None) and not kw['exit_ignore']:
2017 self.showtraceback(exception_only=True)
2029 self.showtraceback(exception_only=True)
2018 except:
2030 except:
2019 self.showtraceback()
2031 self.showtraceback()
2020
2032
2021 def safe_execfile_ipy(self, fname):
2033 def safe_execfile_ipy(self, fname):
2022 """Like safe_execfile, but for .ipy files with IPython syntax.
2034 """Like safe_execfile, but for .ipy files with IPython syntax.
2023
2035
2024 Parameters
2036 Parameters
2025 ----------
2037 ----------
2026 fname : str
2038 fname : str
2027 The name of the file to execute. The filename must have a
2039 The name of the file to execute. The filename must have a
2028 .ipy extension.
2040 .ipy extension.
2029 """
2041 """
2030 fname = os.path.abspath(os.path.expanduser(fname))
2042 fname = os.path.abspath(os.path.expanduser(fname))
2031
2043
2032 # Make sure we have a .py file
2044 # Make sure we have a .py file
2033 if not fname.endswith('.ipy'):
2045 if not fname.endswith('.ipy'):
2034 warn('File must end with .py to be run using execfile: <%s>' % fname)
2046 warn('File must end with .py to be run using execfile: <%s>' % fname)
2035
2047
2036 # Make sure we can open the file
2048 # Make sure we can open the file
2037 try:
2049 try:
2038 with open(fname) as thefile:
2050 with open(fname) as thefile:
2039 pass
2051 pass
2040 except:
2052 except:
2041 warn('Could not open file <%s> for safe execution.' % fname)
2053 warn('Could not open file <%s> for safe execution.' % fname)
2042 return
2054 return
2043
2055
2044 # Find things also in current directory. This is needed to mimic the
2056 # Find things also in current directory. This is needed to mimic the
2045 # behavior of running a script from the system command line, where
2057 # behavior of running a script from the system command line, where
2046 # Python inserts the script's directory into sys.path
2058 # Python inserts the script's directory into sys.path
2047 dname = os.path.dirname(fname)
2059 dname = os.path.dirname(fname)
2048
2060
2049 with prepended_to_syspath(dname):
2061 with prepended_to_syspath(dname):
2050 try:
2062 try:
2051 with open(fname) as thefile:
2063 with open(fname) as thefile:
2052 # self.run_cell currently captures all exceptions
2064 # self.run_cell currently captures all exceptions
2053 # raised in user code. It would be nice if there were
2065 # raised in user code. It would be nice if there were
2054 # versions of runlines, execfile that did raise, so
2066 # versions of runlines, execfile that did raise, so
2055 # we could catch the errors.
2067 # we could catch the errors.
2056 self.run_cell(thefile.read())
2068 self.run_cell(thefile.read())
2057 except:
2069 except:
2058 self.showtraceback()
2070 self.showtraceback()
2059 warn('Unknown failure executing file: <%s>' % fname)
2071 warn('Unknown failure executing file: <%s>' % fname)
2060
2072
2061 def run_cell(self, cell):
2073 def run_cell(self, cell):
2062 """Run the contents of an entire multiline 'cell' of code.
2074 """Run the contents of an entire multiline 'cell' of code.
2063
2075
2064 The cell is split into separate blocks which can be executed
2076 The cell is split into separate blocks which can be executed
2065 individually. Then, based on how many blocks there are, they are
2077 individually. Then, based on how many blocks there are, they are
2066 executed as follows:
2078 executed as follows:
2067
2079
2068 - A single block: 'single' mode.
2080 - A single block: 'single' mode.
2069
2081
2070 If there's more than one block, it depends:
2082 If there's more than one block, it depends:
2071
2083
2072 - if the last one is no more than two lines long, run all but the last
2084 - if the last one is no more than two lines long, run all but the last
2073 in 'exec' mode and the very last one in 'single' mode. This makes it
2085 in 'exec' mode and the very last one in 'single' mode. This makes it
2074 easy to type simple expressions at the end to see computed values. -
2086 easy to type simple expressions at the end to see computed values. -
2075 otherwise (last one is also multiline), run all in 'exec' mode
2087 otherwise (last one is also multiline), run all in 'exec' mode
2076
2088
2077 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2089 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2078 results are displayed and output prompts are computed. In 'exec' mode,
2090 results are displayed and output prompts are computed. In 'exec' mode,
2079 no results are displayed unless :func:`print` is called explicitly;
2091 no results are displayed unless :func:`print` is called explicitly;
2080 this mode is more akin to running a script.
2092 this mode is more akin to running a script.
2081
2093
2082 Parameters
2094 Parameters
2083 ----------
2095 ----------
2084 cell : str
2096 cell : str
2085 A single or multiline string.
2097 A single or multiline string.
2086 """
2098 """
2087
2099
2088 # We need to break up the input into executable blocks that can be run
2100 # We need to break up the input into executable blocks that can be run
2089 # in 'single' mode, to provide comfortable user behavior.
2101 # in 'single' mode, to provide comfortable user behavior.
2090 blocks = self.input_splitter.split_blocks(cell)
2102 blocks = self.input_splitter.split_blocks(cell)
2091
2103
2092 if not blocks:
2104 if not blocks:
2093 return
2105 return
2094
2106
2095 # Store the 'ipython' version of the cell as well, since that's what
2107 # Store the 'ipython' version of the cell as well, since that's what
2096 # needs to go into the translated history and get executed (the
2108 # needs to go into the translated history and get executed (the
2097 # original cell may contain non-python syntax).
2109 # original cell may contain non-python syntax).
2098 ipy_cell = ''.join(blocks)
2110 ipy_cell = ''.join(blocks)
2099
2111
2100 # Store raw and processed history
2112 # Store raw and processed history
2101 self.history_manager.store_inputs(ipy_cell, cell)
2113 self.history_manager.store_inputs(ipy_cell, cell)
2102
2114
2103 self.logger.log(ipy_cell, cell)
2115 self.logger.log(ipy_cell, cell)
2104 # dbg code!!!
2116 # dbg code!!!
2105 if 0:
2117 if 0:
2106 def myapp(self, val): # dbg
2118 def myapp(self, val): # dbg
2107 import traceback as tb
2119 import traceback as tb
2108 stack = ''.join(tb.format_stack())
2120 stack = ''.join(tb.format_stack())
2109 print 'Value:', val
2121 print 'Value:', val
2110 print 'Stack:\n', stack
2122 print 'Stack:\n', stack
2111 list.append(self, val)
2123 list.append(self, val)
2112
2124
2113 import new
2125 import new
2114 self.history_manager.input_hist_parsed.append = types.MethodType(myapp,
2126 self.history_manager.input_hist_parsed.append = types.MethodType(myapp,
2115 self.history_manager.input_hist_parsed)
2127 self.history_manager.input_hist_parsed)
2116 # End dbg
2128 # End dbg
2117
2129
2118 # All user code execution must happen with our context managers active
2130 # All user code execution must happen with our context managers active
2119 with nested(self.builtin_trap, self.display_trap):
2131 with nested(self.builtin_trap, self.display_trap):
2120
2132
2121 # Single-block input should behave like an interactive prompt
2133 # Single-block input should behave like an interactive prompt
2122 if len(blocks) == 1:
2134 if len(blocks) == 1:
2123 # since we return here, we need to update the execution count
2135 # since we return here, we need to update the execution count
2124 out = self.run_one_block(blocks[0])
2136 out = self.run_one_block(blocks[0])
2125 self.execution_count += 1
2137 self.execution_count += 1
2126 return out
2138 return out
2127
2139
2128 # In multi-block input, if the last block is a simple (one-two
2140 # In multi-block input, if the last block is a simple (one-two
2129 # lines) expression, run it in single mode so it produces output.
2141 # lines) expression, run it in single mode so it produces output.
2130 # Otherwise just feed the whole thing to run_code. This seems like
2142 # Otherwise just feed the whole thing to run_code. This seems like
2131 # a reasonable usability design.
2143 # a reasonable usability design.
2132 last = blocks[-1]
2144 last = blocks[-1]
2133 last_nlines = len(last.splitlines())
2145 last_nlines = len(last.splitlines())
2134
2146
2135 # Note: below, whenever we call run_code, we must sync history
2147 # Note: below, whenever we call run_code, we must sync history
2136 # ourselves, because run_code is NOT meant to manage history at all.
2148 # ourselves, because run_code is NOT meant to manage history at all.
2137 if last_nlines < 2:
2149 if last_nlines < 2:
2138 # Here we consider the cell split between 'body' and 'last',
2150 # Here we consider the cell split between 'body' and 'last',
2139 # store all history and execute 'body', and if successful, then
2151 # store all history and execute 'body', and if successful, then
2140 # proceed to execute 'last'.
2152 # proceed to execute 'last'.
2141
2153
2142 # Get the main body to run as a cell
2154 # Get the main body to run as a cell
2143 ipy_body = ''.join(blocks[:-1])
2155 ipy_body = ''.join(blocks[:-1])
2144 retcode = self.run_source(ipy_body, symbol='exec',
2156 retcode = self.run_source(ipy_body, symbol='exec',
2145 post_execute=False)
2157 post_execute=False)
2146 if retcode==0:
2158 if retcode==0:
2147 # And the last expression via runlines so it produces output
2159 # And the last expression via runlines so it produces output
2148 self.run_one_block(last)
2160 self.run_one_block(last)
2149 else:
2161 else:
2150 # Run the whole cell as one entity, storing both raw and
2162 # Run the whole cell as one entity, storing both raw and
2151 # processed input in history
2163 # processed input in history
2152 self.run_source(ipy_cell, symbol='exec')
2164 self.run_source(ipy_cell, symbol='exec')
2153
2165
2154 # Each cell is a *single* input, regardless of how many lines it has
2166 # Each cell is a *single* input, regardless of how many lines it has
2155 self.execution_count += 1
2167 self.execution_count += 1
2156
2168
2157 def run_one_block(self, block):
2169 def run_one_block(self, block):
2158 """Run a single interactive block.
2170 """Run a single interactive block.
2159
2171
2160 If the block is single-line, dynamic transformations are applied to it
2172 If the block is single-line, dynamic transformations are applied to it
2161 (like automagics, autocall and alias recognition).
2173 (like automagics, autocall and alias recognition).
2162 """
2174 """
2163 if len(block.splitlines()) <= 1:
2175 if len(block.splitlines()) <= 1:
2164 out = self.run_single_line(block)
2176 out = self.run_single_line(block)
2165 else:
2177 else:
2166 out = self.run_code(block)
2178 out = self.run_code(block)
2167 return out
2179 return out
2168
2180
2169 def run_single_line(self, line):
2181 def run_single_line(self, line):
2170 """Run a single-line interactive statement.
2182 """Run a single-line interactive statement.
2171
2183
2172 This assumes the input has been transformed to IPython syntax by
2184 This assumes the input has been transformed to IPython syntax by
2173 applying all static transformations (those with an explicit prefix like
2185 applying all static transformations (those with an explicit prefix like
2174 % or !), but it will further try to apply the dynamic ones.
2186 % or !), but it will further try to apply the dynamic ones.
2175
2187
2176 It does not update history.
2188 It does not update history.
2177 """
2189 """
2178 tline = self.prefilter_manager.prefilter_line(line)
2190 tline = self.prefilter_manager.prefilter_line(line)
2179 return self.run_source(tline)
2191 return self.run_source(tline)
2180
2192
2181 # PENDING REMOVAL: this method is slated for deletion, once our new
2193 # PENDING REMOVAL: this method is slated for deletion, once our new
2182 # input logic has been 100% moved to frontends and is stable.
2194 # input logic has been 100% moved to frontends and is stable.
2183 def runlines(self, lines, clean=False):
2195 def runlines(self, lines, clean=False):
2184 """Run a string of one or more lines of source.
2196 """Run a string of one or more lines of source.
2185
2197
2186 This method is capable of running a string containing multiple source
2198 This method is capable of running a string containing multiple source
2187 lines, as if they had been entered at the IPython prompt. Since it
2199 lines, as if they had been entered at the IPython prompt. Since it
2188 exposes IPython's processing machinery, the given strings can contain
2200 exposes IPython's processing machinery, the given strings can contain
2189 magic calls (%magic), special shell access (!cmd), etc.
2201 magic calls (%magic), special shell access (!cmd), etc.
2190 """
2202 """
2191
2203
2192 if isinstance(lines, (list, tuple)):
2204 if isinstance(lines, (list, tuple)):
2193 lines = '\n'.join(lines)
2205 lines = '\n'.join(lines)
2194
2206
2195 if clean:
2207 if clean:
2196 lines = self._cleanup_ipy_script(lines)
2208 lines = self._cleanup_ipy_script(lines)
2197
2209
2198 # We must start with a clean buffer, in case this is run from an
2210 # We must start with a clean buffer, in case this is run from an
2199 # interactive IPython session (via a magic, for example).
2211 # interactive IPython session (via a magic, for example).
2200 self.reset_buffer()
2212 self.reset_buffer()
2201 lines = lines.splitlines()
2213 lines = lines.splitlines()
2202
2214
2203 # Since we will prefilter all lines, store the user's raw input too
2215 # Since we will prefilter all lines, store the user's raw input too
2204 # before we apply any transformations
2216 # before we apply any transformations
2205 self.buffer_raw[:] = [ l+'\n' for l in lines]
2217 self.buffer_raw[:] = [ l+'\n' for l in lines]
2206
2218
2207 more = False
2219 more = False
2208 prefilter_lines = self.prefilter_manager.prefilter_lines
2220 prefilter_lines = self.prefilter_manager.prefilter_lines
2209 with nested(self.builtin_trap, self.display_trap):
2221 with nested(self.builtin_trap, self.display_trap):
2210 for line in lines:
2222 for line in lines:
2211 # skip blank lines so we don't mess up the prompt counter, but
2223 # skip blank lines so we don't mess up the prompt counter, but
2212 # do NOT skip even a blank line if we are in a code block (more
2224 # do NOT skip even a blank line if we are in a code block (more
2213 # is true)
2225 # is true)
2214
2226
2215 if line or more:
2227 if line or more:
2216 more = self.push_line(prefilter_lines(line, more))
2228 more = self.push_line(prefilter_lines(line, more))
2217 # IPython's run_source returns None if there was an error
2229 # IPython's run_source returns None if there was an error
2218 # compiling the code. This allows us to stop processing
2230 # compiling the code. This allows us to stop processing
2219 # right away, so the user gets the error message at the
2231 # right away, so the user gets the error message at the
2220 # right place.
2232 # right place.
2221 if more is None:
2233 if more is None:
2222 break
2234 break
2223 # final newline in case the input didn't have it, so that the code
2235 # final newline in case the input didn't have it, so that the code
2224 # actually does get executed
2236 # actually does get executed
2225 if more:
2237 if more:
2226 self.push_line('\n')
2238 self.push_line('\n')
2227
2239
2228 def run_source(self, source, filename=None,
2240 def run_source(self, source, filename=None,
2229 symbol='single', post_execute=True):
2241 symbol='single', post_execute=True):
2230 """Compile and run some source in the interpreter.
2242 """Compile and run some source in the interpreter.
2231
2243
2232 Arguments are as for compile_command().
2244 Arguments are as for compile_command().
2233
2245
2234 One several things can happen:
2246 One several things can happen:
2235
2247
2236 1) The input is incorrect; compile_command() raised an
2248 1) The input is incorrect; compile_command() raised an
2237 exception (SyntaxError or OverflowError). A syntax traceback
2249 exception (SyntaxError or OverflowError). A syntax traceback
2238 will be printed by calling the showsyntaxerror() method.
2250 will be printed by calling the showsyntaxerror() method.
2239
2251
2240 2) The input is incomplete, and more input is required;
2252 2) The input is incomplete, and more input is required;
2241 compile_command() returned None. Nothing happens.
2253 compile_command() returned None. Nothing happens.
2242
2254
2243 3) The input is complete; compile_command() returned a code
2255 3) The input is complete; compile_command() returned a code
2244 object. The code is executed by calling self.run_code() (which
2256 object. The code is executed by calling self.run_code() (which
2245 also handles run-time exceptions, except for SystemExit).
2257 also handles run-time exceptions, except for SystemExit).
2246
2258
2247 The return value is:
2259 The return value is:
2248
2260
2249 - True in case 2
2261 - True in case 2
2250
2262
2251 - False in the other cases, unless an exception is raised, where
2263 - False in the other cases, unless an exception is raised, where
2252 None is returned instead. This can be used by external callers to
2264 None is returned instead. This can be used by external callers to
2253 know whether to continue feeding input or not.
2265 know whether to continue feeding input or not.
2254
2266
2255 The return value can be used to decide whether to use sys.ps1 or
2267 The return value can be used to decide whether to use sys.ps1 or
2256 sys.ps2 to prompt the next line."""
2268 sys.ps2 to prompt the next line."""
2257
2269
2258 # We need to ensure that the source is unicode from here on.
2270 # We need to ensure that the source is unicode from here on.
2259 if type(source)==str:
2271 if type(source)==str:
2260 usource = source.decode(self.stdin_encoding)
2272 usource = source.decode(self.stdin_encoding)
2261 else:
2273 else:
2262 usource = source
2274 usource = source
2263
2275
2264 if 0: # dbg
2276 if 0: # dbg
2265 print 'Source:', repr(source) # dbg
2277 print 'Source:', repr(source) # dbg
2266 print 'USource:', repr(usource) # dbg
2278 print 'USource:', repr(usource) # dbg
2267 print 'type:', type(source) # dbg
2279 print 'type:', type(source) # dbg
2268 print 'encoding', self.stdin_encoding # dbg
2280 print 'encoding', self.stdin_encoding # dbg
2269
2281
2270 try:
2282 try:
2271 code = self.compile(usource, symbol, self.execution_count)
2283 code = self.compile(usource, symbol, self.execution_count)
2272 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2284 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2273 # Case 1
2285 # Case 1
2274 self.showsyntaxerror(filename)
2286 self.showsyntaxerror(filename)
2275 return None
2287 return None
2276
2288
2277 if code is None:
2289 if code is None:
2278 # Case 2
2290 # Case 2
2279 return True
2291 return True
2280
2292
2281 # Case 3
2293 # Case 3
2282 # We store the code object so that threaded shells and
2294 # We store the code object so that threaded shells and
2283 # custom exception handlers can access all this info if needed.
2295 # custom exception handlers can access all this info if needed.
2284 # The source corresponding to this can be obtained from the
2296 # The source corresponding to this can be obtained from the
2285 # buffer attribute as '\n'.join(self.buffer).
2297 # buffer attribute as '\n'.join(self.buffer).
2286 self.code_to_run = code
2298 self.code_to_run = code
2287 # now actually execute the code object
2299 # now actually execute the code object
2288 if self.run_code(code, post_execute) == 0:
2300 if self.run_code(code, post_execute) == 0:
2289 return False
2301 return False
2290 else:
2302 else:
2291 return None
2303 return None
2292
2304
2293 # For backwards compatibility
2305 # For backwards compatibility
2294 runsource = run_source
2306 runsource = run_source
2295
2307
2296 def run_code(self, code_obj, post_execute=True):
2308 def run_code(self, code_obj, post_execute=True):
2297 """Execute a code object.
2309 """Execute a code object.
2298
2310
2299 When an exception occurs, self.showtraceback() is called to display a
2311 When an exception occurs, self.showtraceback() is called to display a
2300 traceback.
2312 traceback.
2301
2313
2302 Return value: a flag indicating whether the code to be run completed
2314 Return value: a flag indicating whether the code to be run completed
2303 successfully:
2315 successfully:
2304
2316
2305 - 0: successful execution.
2317 - 0: successful execution.
2306 - 1: an error occurred.
2318 - 1: an error occurred.
2307 """
2319 """
2308
2320
2309 # Set our own excepthook in case the user code tries to call it
2321 # Set our own excepthook in case the user code tries to call it
2310 # directly, so that the IPython crash handler doesn't get triggered
2322 # directly, so that the IPython crash handler doesn't get triggered
2311 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2323 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2312
2324
2313 # we save the original sys.excepthook in the instance, in case config
2325 # we save the original sys.excepthook in the instance, in case config
2314 # code (such as magics) needs access to it.
2326 # code (such as magics) needs access to it.
2315 self.sys_excepthook = old_excepthook
2327 self.sys_excepthook = old_excepthook
2316 outflag = 1 # happens in more places, so it's easier as default
2328 outflag = 1 # happens in more places, so it's easier as default
2317 try:
2329 try:
2318 try:
2330 try:
2319 self.hooks.pre_run_code_hook()
2331 self.hooks.pre_run_code_hook()
2320 #rprint('Running code') # dbg
2332 #rprint('Running code') # dbg
2321 exec code_obj in self.user_global_ns, self.user_ns
2333 exec code_obj in self.user_global_ns, self.user_ns
2322 finally:
2334 finally:
2323 # Reset our crash handler in place
2335 # Reset our crash handler in place
2324 sys.excepthook = old_excepthook
2336 sys.excepthook = old_excepthook
2325 except SystemExit:
2337 except SystemExit:
2326 self.reset_buffer()
2338 self.reset_buffer()
2327 self.showtraceback(exception_only=True)
2339 self.showtraceback(exception_only=True)
2328 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2340 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2329 except self.custom_exceptions:
2341 except self.custom_exceptions:
2330 etype,value,tb = sys.exc_info()
2342 etype,value,tb = sys.exc_info()
2331 self.CustomTB(etype,value,tb)
2343 self.CustomTB(etype,value,tb)
2332 except:
2344 except:
2333 self.showtraceback()
2345 self.showtraceback()
2334 else:
2346 else:
2335 outflag = 0
2347 outflag = 0
2336 if softspace(sys.stdout, 0):
2348 if softspace(sys.stdout, 0):
2337 print
2349 print
2338
2350
2339 # Execute any registered post-execution functions. Here, any errors
2351 # Execute any registered post-execution functions. Here, any errors
2340 # are reported only minimally and just on the terminal, because the
2352 # are reported only minimally and just on the terminal, because the
2341 # main exception channel may be occupied with a user traceback.
2353 # main exception channel may be occupied with a user traceback.
2342 # FIXME: we need to think this mechanism a little more carefully.
2354 # FIXME: we need to think this mechanism a little more carefully.
2343 if post_execute:
2355 if post_execute:
2344 for func in self._post_execute:
2356 for func in self._post_execute:
2345 try:
2357 try:
2346 func()
2358 func()
2347 except:
2359 except:
2348 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2360 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2349 func
2361 func
2350 print >> io.Term.cout, head
2362 print >> io.Term.cout, head
2351 print >> io.Term.cout, self._simple_error()
2363 print >> io.Term.cout, self._simple_error()
2352 print >> io.Term.cout, 'Removing from post_execute'
2364 print >> io.Term.cout, 'Removing from post_execute'
2353 self._post_execute.remove(func)
2365 self._post_execute.remove(func)
2354
2366
2355 # Flush out code object which has been run (and source)
2367 # Flush out code object which has been run (and source)
2356 self.code_to_run = None
2368 self.code_to_run = None
2357 return outflag
2369 return outflag
2358
2370
2359 # For backwards compatibility
2371 # For backwards compatibility
2360 runcode = run_code
2372 runcode = run_code
2361
2373
2362 # PENDING REMOVAL: this method is slated for deletion, once our new
2374 # PENDING REMOVAL: this method is slated for deletion, once our new
2363 # input logic has been 100% moved to frontends and is stable.
2375 # input logic has been 100% moved to frontends and is stable.
2364 def push_line(self, line):
2376 def push_line(self, line):
2365 """Push a line to the interpreter.
2377 """Push a line to the interpreter.
2366
2378
2367 The line should not have a trailing newline; it may have
2379 The line should not have a trailing newline; it may have
2368 internal newlines. The line is appended to a buffer and the
2380 internal newlines. The line is appended to a buffer and the
2369 interpreter's run_source() method is called with the
2381 interpreter's run_source() method is called with the
2370 concatenated contents of the buffer as source. If this
2382 concatenated contents of the buffer as source. If this
2371 indicates that the command was executed or invalid, the buffer
2383 indicates that the command was executed or invalid, the buffer
2372 is reset; otherwise, the command is incomplete, and the buffer
2384 is reset; otherwise, the command is incomplete, and the buffer
2373 is left as it was after the line was appended. The return
2385 is left as it was after the line was appended. The return
2374 value is 1 if more input is required, 0 if the line was dealt
2386 value is 1 if more input is required, 0 if the line was dealt
2375 with in some way (this is the same as run_source()).
2387 with in some way (this is the same as run_source()).
2376 """
2388 """
2377
2389
2378 # autoindent management should be done here, and not in the
2390 # autoindent management should be done here, and not in the
2379 # interactive loop, since that one is only seen by keyboard input. We
2391 # interactive loop, since that one is only seen by keyboard input. We
2380 # need this done correctly even for code run via runlines (which uses
2392 # need this done correctly even for code run via runlines (which uses
2381 # push).
2393 # push).
2382
2394
2383 #print 'push line: <%s>' % line # dbg
2395 #print 'push line: <%s>' % line # dbg
2384 self.buffer.append(line)
2396 self.buffer.append(line)
2385 full_source = '\n'.join(self.buffer)
2397 full_source = '\n'.join(self.buffer)
2386 more = self.run_source(full_source, self.filename)
2398 more = self.run_source(full_source, self.filename)
2387 if not more:
2399 if not more:
2388 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2400 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2389 full_source)
2401 full_source)
2390 self.reset_buffer()
2402 self.reset_buffer()
2391 self.execution_count += 1
2403 self.execution_count += 1
2392 return more
2404 return more
2393
2405
2394 def reset_buffer(self):
2406 def reset_buffer(self):
2395 """Reset the input buffer."""
2407 """Reset the input buffer."""
2396 self.buffer[:] = []
2408 self.buffer[:] = []
2397 self.buffer_raw[:] = []
2409 self.buffer_raw[:] = []
2398 self.input_splitter.reset()
2410 self.input_splitter.reset()
2399
2411
2400 # For backwards compatibility
2412 # For backwards compatibility
2401 resetbuffer = reset_buffer
2413 resetbuffer = reset_buffer
2402
2414
2403 def _is_secondary_block_start(self, s):
2415 def _is_secondary_block_start(self, s):
2404 if not s.endswith(':'):
2416 if not s.endswith(':'):
2405 return False
2417 return False
2406 if (s.startswith('elif') or
2418 if (s.startswith('elif') or
2407 s.startswith('else') or
2419 s.startswith('else') or
2408 s.startswith('except') or
2420 s.startswith('except') or
2409 s.startswith('finally')):
2421 s.startswith('finally')):
2410 return True
2422 return True
2411
2423
2412 def _cleanup_ipy_script(self, script):
2424 def _cleanup_ipy_script(self, script):
2413 """Make a script safe for self.runlines()
2425 """Make a script safe for self.runlines()
2414
2426
2415 Currently, IPython is lines based, with blocks being detected by
2427 Currently, IPython is lines based, with blocks being detected by
2416 empty lines. This is a problem for block based scripts that may
2428 empty lines. This is a problem for block based scripts that may
2417 not have empty lines after blocks. This script adds those empty
2429 not have empty lines after blocks. This script adds those empty
2418 lines to make scripts safe for running in the current line based
2430 lines to make scripts safe for running in the current line based
2419 IPython.
2431 IPython.
2420 """
2432 """
2421 res = []
2433 res = []
2422 lines = script.splitlines()
2434 lines = script.splitlines()
2423 level = 0
2435 level = 0
2424
2436
2425 for l in lines:
2437 for l in lines:
2426 lstripped = l.lstrip()
2438 lstripped = l.lstrip()
2427 stripped = l.strip()
2439 stripped = l.strip()
2428 if not stripped:
2440 if not stripped:
2429 continue
2441 continue
2430 newlevel = len(l) - len(lstripped)
2442 newlevel = len(l) - len(lstripped)
2431 if level > 0 and newlevel == 0 and \
2443 if level > 0 and newlevel == 0 and \
2432 not self._is_secondary_block_start(stripped):
2444 not self._is_secondary_block_start(stripped):
2433 # add empty line
2445 # add empty line
2434 res.append('')
2446 res.append('')
2435 res.append(l)
2447 res.append(l)
2436 level = newlevel
2448 level = newlevel
2437
2449
2438 return '\n'.join(res) + '\n'
2450 return '\n'.join(res) + '\n'
2439
2451
2440 #-------------------------------------------------------------------------
2452 #-------------------------------------------------------------------------
2441 # Things related to GUI support and pylab
2453 # Things related to GUI support and pylab
2442 #-------------------------------------------------------------------------
2454 #-------------------------------------------------------------------------
2443
2455
2444 def enable_pylab(self, gui=None):
2456 def enable_pylab(self, gui=None):
2445 raise NotImplementedError('Implement enable_pylab in a subclass')
2457 raise NotImplementedError('Implement enable_pylab in a subclass')
2446
2458
2447 #-------------------------------------------------------------------------
2459 #-------------------------------------------------------------------------
2448 # Utilities
2460 # Utilities
2449 #-------------------------------------------------------------------------
2461 #-------------------------------------------------------------------------
2450
2462
2451 def var_expand(self,cmd,depth=0):
2463 def var_expand(self,cmd,depth=0):
2452 """Expand python variables in a string.
2464 """Expand python variables in a string.
2453
2465
2454 The depth argument indicates how many frames above the caller should
2466 The depth argument indicates how many frames above the caller should
2455 be walked to look for the local namespace where to expand variables.
2467 be walked to look for the local namespace where to expand variables.
2456
2468
2457 The global namespace for expansion is always the user's interactive
2469 The global namespace for expansion is always the user's interactive
2458 namespace.
2470 namespace.
2459 """
2471 """
2460
2472
2461 return str(ItplNS(cmd,
2473 return str(ItplNS(cmd,
2462 self.user_ns, # globals
2474 self.user_ns, # globals
2463 # Skip our own frame in searching for locals:
2475 # Skip our own frame in searching for locals:
2464 sys._getframe(depth+1).f_locals # locals
2476 sys._getframe(depth+1).f_locals # locals
2465 ))
2477 ))
2466
2478
2467 def mktempfile(self, data=None, prefix='ipython_edit_'):
2479 def mktempfile(self, data=None, prefix='ipython_edit_'):
2468 """Make a new tempfile and return its filename.
2480 """Make a new tempfile and return its filename.
2469
2481
2470 This makes a call to tempfile.mktemp, but it registers the created
2482 This makes a call to tempfile.mktemp, but it registers the created
2471 filename internally so ipython cleans it up at exit time.
2483 filename internally so ipython cleans it up at exit time.
2472
2484
2473 Optional inputs:
2485 Optional inputs:
2474
2486
2475 - data(None): if data is given, it gets written out to the temp file
2487 - data(None): if data is given, it gets written out to the temp file
2476 immediately, and the file is closed again."""
2488 immediately, and the file is closed again."""
2477
2489
2478 filename = tempfile.mktemp('.py', prefix)
2490 filename = tempfile.mktemp('.py', prefix)
2479 self.tempfiles.append(filename)
2491 self.tempfiles.append(filename)
2480
2492
2481 if data:
2493 if data:
2482 tmp_file = open(filename,'w')
2494 tmp_file = open(filename,'w')
2483 tmp_file.write(data)
2495 tmp_file.write(data)
2484 tmp_file.close()
2496 tmp_file.close()
2485 return filename
2497 return filename
2486
2498
2487 # TODO: This should be removed when Term is refactored.
2499 # TODO: This should be removed when Term is refactored.
2488 def write(self,data):
2500 def write(self,data):
2489 """Write a string to the default output"""
2501 """Write a string to the default output"""
2490 io.Term.cout.write(data)
2502 io.Term.cout.write(data)
2491
2503
2492 # TODO: This should be removed when Term is refactored.
2504 # TODO: This should be removed when Term is refactored.
2493 def write_err(self,data):
2505 def write_err(self,data):
2494 """Write a string to the default error output"""
2506 """Write a string to the default error output"""
2495 io.Term.cerr.write(data)
2507 io.Term.cerr.write(data)
2496
2508
2497 def ask_yes_no(self,prompt,default=True):
2509 def ask_yes_no(self,prompt,default=True):
2498 if self.quiet:
2510 if self.quiet:
2499 return True
2511 return True
2500 return ask_yes_no(prompt,default)
2512 return ask_yes_no(prompt,default)
2501
2513
2502 def show_usage(self):
2514 def show_usage(self):
2503 """Show a usage message"""
2515 """Show a usage message"""
2504 page.page(IPython.core.usage.interactive_usage)
2516 page.page(IPython.core.usage.interactive_usage)
2505
2517
2506 #-------------------------------------------------------------------------
2518 #-------------------------------------------------------------------------
2507 # Things related to IPython exiting
2519 # Things related to IPython exiting
2508 #-------------------------------------------------------------------------
2520 #-------------------------------------------------------------------------
2509 def atexit_operations(self):
2521 def atexit_operations(self):
2510 """This will be executed at the time of exit.
2522 """This will be executed at the time of exit.
2511
2523
2512 Cleanup operations and saving of persistent data that is done
2524 Cleanup operations and saving of persistent data that is done
2513 unconditionally by IPython should be performed here.
2525 unconditionally by IPython should be performed here.
2514
2526
2515 For things that may depend on startup flags or platform specifics (such
2527 For things that may depend on startup flags or platform specifics (such
2516 as having readline or not), register a separate atexit function in the
2528 as having readline or not), register a separate atexit function in the
2517 code that has the appropriate information, rather than trying to
2529 code that has the appropriate information, rather than trying to
2518 clutter
2530 clutter
2519 """
2531 """
2520 # Cleanup all tempfiles left around
2532 # Cleanup all tempfiles left around
2521 for tfile in self.tempfiles:
2533 for tfile in self.tempfiles:
2522 try:
2534 try:
2523 os.unlink(tfile)
2535 os.unlink(tfile)
2524 except OSError:
2536 except OSError:
2525 pass
2537 pass
2526
2538
2527 self.save_history()
2539 self.save_history()
2528
2540
2529 # Clear all user namespaces to release all references cleanly.
2541 # Clear all user namespaces to release all references cleanly.
2530 self.reset()
2542 self.reset()
2531
2543
2532 # Run user hooks
2544 # Run user hooks
2533 self.hooks.shutdown_hook()
2545 self.hooks.shutdown_hook()
2534
2546
2535 def cleanup(self):
2547 def cleanup(self):
2536 self.restore_sys_module_state()
2548 self.restore_sys_module_state()
2537
2549
2538
2550
2539 class InteractiveShellABC(object):
2551 class InteractiveShellABC(object):
2540 """An abstract base class for InteractiveShell."""
2552 """An abstract base class for InteractiveShell."""
2541 __metaclass__ = abc.ABCMeta
2553 __metaclass__ = abc.ABCMeta
2542
2554
2543 InteractiveShellABC.register(InteractiveShell)
2555 InteractiveShellABC.register(InteractiveShell)
1 NO CONTENT: modified file
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 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Usage information for the main IPython applications.
2 """Usage information for the main IPython applications.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008-2010 The IPython Development Team
5 # Copyright (C) 2008-2010 The IPython Development Team
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 import sys
12 import sys
13 from IPython.core import release
13 from IPython.core import release
14
14
15 cl_usage = """\
15 cl_usage = """\
16 ipython [options] [files]
16 ipython [options] [files]
17
17
18 IPython: an enhanced interactive Python shell.
18 IPython: an enhanced interactive Python shell.
19
19
20 A Python shell with automatic history (input and output), dynamic object
20 A Python shell with automatic history (input and output), dynamic object
21 introspection, easier configuration, command completion, access to the
21 introspection, easier configuration, command completion, access to the
22 system shell and more. IPython can also be embedded in running programs.
22 system shell and more. IPython can also be embedded in running programs.
23
23
24 If invoked with no options, it executes all the files listed in sequence
24 If invoked with no options, it executes all the files listed in sequence
25 and exits, use -i to enter interactive mode after running the files. Files
25 and exits, use -i to enter interactive mode after running the files. Files
26 ending in .py will be treated as normal Python, but files ending in .ipy
26 ending in .py will be treated as normal Python, but files ending in .ipy
27 can contain special IPython syntax (magic commands, shell expansions, etc.)
27 can contain special IPython syntax (magic commands, shell expansions, etc.)
28
28
29 Please note that some of the configuration options are not available at the
29 Please note that some of the configuration options are not available at the
30 command line, simply because they are not practical here. Look into your
30 command line, simply because they are not practical here. Look into your
31 ipython_config.py configuration file for details on those.
31 ipython_config.py configuration file for details on those.
32
32
33 This file typically installed in the $HOME/.ipython directory. For Windows
33 This file typically installed in the $HOME/.ipython directory. For Windows
34 users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most
34 users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most
35 instances.
35 instances.
36
36
37 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
37 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
38 you can change its default location by setting any path you want in this
38 you can change its default location by setting any path you want in this
39 environment variable.
39 environment variable.
40
40
41 For more information, see the manual available in HTML and PDF in your
41 For more information, see the manual available in HTML and PDF in your
42 installation, or online at http://ipython.scipy.org.
42 installation, or online at http://ipython.scipy.org.
43 """
43 """
44
44
45 interactive_usage = """
45 interactive_usage = """
46 IPython -- An enhanced Interactive Python
46 IPython -- An enhanced Interactive Python
47 =========================================
47 =========================================
48
48
49 IPython offers a combination of convenient shell features, special commands
49 IPython offers a combination of convenient shell features, special commands
50 and a history mechanism for both input (command history) and output (results
50 and a history mechanism for both input (command history) and output (results
51 caching, similar to Mathematica). It is intended to be a fully compatible
51 caching, similar to Mathematica). It is intended to be a fully compatible
52 replacement for the standard Python interpreter, while offering vastly
52 replacement for the standard Python interpreter, while offering vastly
53 improved functionality and flexibility.
53 improved functionality and flexibility.
54
54
55 At your system command line, type 'ipython -help' to see the command line
55 At your system command line, type 'ipython -help' to see the command line
56 options available. This document only describes interactive features.
56 options available. This document only describes interactive features.
57
57
58 Warning: IPython relies on the existence of a global variable called __IP which
58 Warning: IPython relies on the existence of a global variable called __IP which
59 controls the shell itself. If you redefine __IP to anything, bizarre behavior
59 controls the shell itself. If you redefine __IP to anything, bizarre behavior
60 will quickly occur.
60 will quickly occur.
61
61
62 MAIN FEATURES
62 MAIN FEATURES
63
63
64 * Access to the standard Python help. As of Python 2.1, a help system is
64 * Access to the standard Python help. As of Python 2.1, a help system is
65 available with access to object docstrings and the Python manuals. Simply
65 available with access to object docstrings and the Python manuals. Simply
66 type 'help' (no quotes) to access it.
66 type 'help' (no quotes) to access it.
67
67
68 * Magic commands: type %magic for information on the magic subsystem.
68 * Magic commands: type %magic for information on the magic subsystem.
69
69
70 * System command aliases, via the %alias command or the ipythonrc config file.
70 * System command aliases, via the %alias command or the ipythonrc config file.
71
71
72 * Dynamic object information:
72 * Dynamic object information:
73
73
74 Typing ?word or word? prints detailed information about an object. If
74 Typing ?word or word? prints detailed information about an object. If
75 certain strings in the object are too long (docstrings, code, etc.) they get
75 certain strings in the object are too long (docstrings, code, etc.) they get
76 snipped in the center for brevity.
76 snipped in the center for brevity.
77
77
78 Typing ??word or word?? gives access to the full information without
78 Typing ??word or word?? gives access to the full information without
79 snipping long strings. Long strings are sent to the screen through the less
79 snipping long strings. Long strings are sent to the screen through the less
80 pager if longer than the screen, printed otherwise.
80 pager if longer than the screen, printed otherwise.
81
81
82 The ?/?? system gives access to the full source code for any object (if
82 The ?/?? system gives access to the full source code for any object (if
83 available), shows function prototypes and other useful information.
83 available), shows function prototypes and other useful information.
84
84
85 If you just want to see an object's docstring, type '%pdoc object' (without
85 If you just want to see an object's docstring, type '%pdoc object' (without
86 quotes, and without % if you have automagic on).
86 quotes, and without % if you have automagic on).
87
87
88 Both %pdoc and ?/?? give you access to documentation even on things which are
88 Both %pdoc and ?/?? give you access to documentation even on things which are
89 not explicitely defined. Try for example typing {}.get? or after import os,
89 not explicitely defined. Try for example typing {}.get? or after import os,
90 type os.path.abspath??. The magic functions %pdef, %source and %file operate
90 type os.path.abspath??. The magic functions %pdef, %source and %file operate
91 similarly.
91 similarly.
92
92
93 * Completion in the local namespace, by typing TAB at the prompt.
93 * Completion in the local namespace, by typing TAB at the prompt.
94
94
95 At any time, hitting tab will complete any available python commands or
95 At any time, hitting tab will complete any available python commands or
96 variable names, and show you a list of the possible completions if there's
96 variable names, and show you a list of the possible completions if there's
97 no unambiguous one. It will also complete filenames in the current directory.
97 no unambiguous one. It will also complete filenames in the current directory.
98
98
99 This feature requires the readline and rlcomplete modules, so it won't work
99 This feature requires the readline and rlcomplete modules, so it won't work
100 if your Python lacks readline support (such as under Windows).
100 if your Python lacks readline support (such as under Windows).
101
101
102 * Search previous command history in two ways (also requires readline):
102 * Search previous command history in two ways (also requires readline):
103
103
104 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
104 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
105 search through only the history items that match what you've typed so
105 search through only the history items that match what you've typed so
106 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
106 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
107 normal arrow keys.
107 normal arrow keys.
108
108
109 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
109 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
110 your history for lines that match what you've typed so far, completing as
110 your history for lines that match what you've typed so far, completing as
111 much as it can.
111 much as it can.
112
112
113 * Persistent command history across sessions (readline required).
113 * Persistent command history across sessions (readline required).
114
114
115 * Logging of input with the ability to save and restore a working session.
115 * Logging of input with the ability to save and restore a working session.
116
116
117 * System escape with !. Typing !ls will run 'ls' in the current directory.
117 * System escape with !. Typing !ls will run 'ls' in the current directory.
118
118
119 * The reload command does a 'deep' reload of a module: changes made to the
119 * The reload command does a 'deep' reload of a module: changes made to the
120 module since you imported will actually be available without having to exit.
120 module since you imported will actually be available without having to exit.
121
121
122 * Verbose and colored exception traceback printouts. See the magic xmode and
122 * Verbose and colored exception traceback printouts. See the magic xmode and
123 xcolor functions for details (just type %magic).
123 xcolor functions for details (just type %magic).
124
124
125 * Input caching system:
125 * Input caching system:
126
126
127 IPython offers numbered prompts (In/Out) with input and output caching. All
127 IPython offers numbered prompts (In/Out) with input and output caching. All
128 input is saved and can be retrieved as variables (besides the usual arrow
128 input is saved and can be retrieved as variables (besides the usual arrow
129 key recall).
129 key recall).
130
130
131 The following GLOBAL variables always exist (so don't overwrite them!):
131 The following GLOBAL variables always exist (so don't overwrite them!):
132 _i: stores previous input.
132 _i: stores previous input.
133 _ii: next previous.
133 _ii: next previous.
134 _iii: next-next previous.
134 _iii: next-next previous.
135 _ih : a list of all input _ih[n] is the input from line n.
135 _ih : a list of all input _ih[n] is the input from line n.
136
136
137 Additionally, global variables named _i<n> are dynamically created (<n>
137 Additionally, global variables named _i<n> are dynamically created (<n>
138 being the prompt counter), such that _i<n> == _ih[<n>]
138 being the prompt counter), such that _i<n> == _ih[<n>]
139
139
140 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
140 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
141
141
142 You can create macros which contain multiple input lines from this history,
142 You can create macros which contain multiple input lines from this history,
143 for later re-execution, with the %macro function.
143 for later re-execution, with the %macro function.
144
144
145 The history function %hist allows you to see any part of your input history
145 The history function %hist allows you to see any part of your input history
146 by printing a range of the _i variables. Note that inputs which contain
146 by printing a range of the _i variables. Note that inputs which contain
147 magic functions (%) appear in the history with a prepended comment. This is
147 magic functions (%) appear in the history with a prepended comment. This is
148 because they aren't really valid Python code, so you can't exec them.
148 because they aren't really valid Python code, so you can't exec them.
149
149
150 * Output caching system:
150 * Output caching system:
151
151
152 For output that is returned from actions, a system similar to the input
152 For output that is returned from actions, a system similar to the input
153 cache exists but using _ instead of _i. Only actions that produce a result
153 cache exists but using _ instead of _i. Only actions that produce a result
154 (NOT assignments, for example) are cached. If you are familiar with
154 (NOT assignments, for example) are cached. If you are familiar with
155 Mathematica, IPython's _ variables behave exactly like Mathematica's %
155 Mathematica, IPython's _ variables behave exactly like Mathematica's %
156 variables.
156 variables.
157
157
158 The following GLOBAL variables always exist (so don't overwrite them!):
158 The following GLOBAL variables always exist (so don't overwrite them!):
159 _ (one underscore): previous output.
159 _ (one underscore): previous output.
160 __ (two underscores): next previous.
160 __ (two underscores): next previous.
161 ___ (three underscores): next-next previous.
161 ___ (three underscores): next-next previous.
162
162
163 Global variables named _<n> are dynamically created (<n> being the prompt
163 Global variables named _<n> are dynamically created (<n> being the prompt
164 counter), such that the result of output <n> is always available as _<n>.
164 counter), such that the result of output <n> is always available as _<n>.
165
165
166 Finally, a global dictionary named _oh exists with entries for all lines
166 Finally, a global dictionary named _oh exists with entries for all lines
167 which generated output.
167 which generated output.
168
168
169 * Directory history:
169 * Directory history:
170
170
171 Your history of visited directories is kept in the global list _dh, and the
171 Your history of visited directories is kept in the global list _dh, and the
172 magic %cd command can be used to go to any entry in that list.
172 magic %cd command can be used to go to any entry in that list.
173
173
174 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
174 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
175
175
176 1. Auto-parentheses
176 1. Auto-parentheses
177 Callable objects (i.e. functions, methods, etc) can be invoked like
177 Callable objects (i.e. functions, methods, etc) can be invoked like
178 this (notice the commas between the arguments):
178 this (notice the commas between the arguments):
179 >>> callable_ob arg1, arg2, arg3
179 >>> callable_ob arg1, arg2, arg3
180 and the input will be translated to this:
180 and the input will be translated to this:
181 --> callable_ob(arg1, arg2, arg3)
181 --> callable_ob(arg1, arg2, arg3)
182 You can force auto-parentheses by using '/' as the first character
182 You can force auto-parentheses by using '/' as the first character
183 of a line. For example:
183 of a line. For example:
184 >>> /globals # becomes 'globals()'
184 >>> /globals # becomes 'globals()'
185 Note that the '/' MUST be the first character on the line! This
185 Note that the '/' MUST be the first character on the line! This
186 won't work:
186 won't work:
187 >>> print /globals # syntax error
187 >>> print /globals # syntax error
188
188
189 In most cases the automatic algorithm should work, so you should
189 In most cases the automatic algorithm should work, so you should
190 rarely need to explicitly invoke /. One notable exception is if you
190 rarely need to explicitly invoke /. One notable exception is if you
191 are trying to call a function with a list of tuples as arguments (the
191 are trying to call a function with a list of tuples as arguments (the
192 parenthesis will confuse IPython):
192 parenthesis will confuse IPython):
193 In [1]: zip (1,2,3),(4,5,6) # won't work
193 In [1]: zip (1,2,3),(4,5,6) # won't work
194 but this will work:
194 but this will work:
195 In [2]: /zip (1,2,3),(4,5,6)
195 In [2]: /zip (1,2,3),(4,5,6)
196 ------> zip ((1,2,3),(4,5,6))
196 ------> zip ((1,2,3),(4,5,6))
197 Out[2]= [(1, 4), (2, 5), (3, 6)]
197 Out[2]= [(1, 4), (2, 5), (3, 6)]
198
198
199 IPython tells you that it has altered your command line by
199 IPython tells you that it has altered your command line by
200 displaying the new command line preceded by -->. e.g.:
200 displaying the new command line preceded by -->. e.g.:
201 In [18]: callable list
201 In [18]: callable list
202 -------> callable (list)
202 -------> callable (list)
203
203
204 2. Auto-Quoting
204 2. Auto-Quoting
205 You can force auto-quoting of a function's arguments by using ',' as
205 You can force auto-quoting of a function's arguments by using ',' as
206 the first character of a line. For example:
206 the first character of a line. For example:
207 >>> ,my_function /home/me # becomes my_function("/home/me")
207 >>> ,my_function /home/me # becomes my_function("/home/me")
208
208
209 If you use ';' instead, the whole argument is quoted as a single
209 If you use ';' instead, the whole argument is quoted as a single
210 string (while ',' splits on whitespace):
210 string (while ',' splits on whitespace):
211 >>> ,my_function a b c # becomes my_function("a","b","c")
211 >>> ,my_function a b c # becomes my_function("a","b","c")
212 >>> ;my_function a b c # becomes my_function("a b c")
212 >>> ;my_function a b c # becomes my_function("a b c")
213
213
214 Note that the ',' MUST be the first character on the line! This
214 Note that the ',' MUST be the first character on the line! This
215 won't work:
215 won't work:
216 >>> x = ,my_function /home/me # syntax error
216 >>> x = ,my_function /home/me # syntax error
217 """
217 """
218
218
219 interactive_usage_min = """\
219 interactive_usage_min = """\
220 An enhanced console for Python.
220 An enhanced console for Python.
221 Some of its features are:
221 Some of its features are:
222 - Readline support if the readline library is present.
222 - Readline support if the readline library is present.
223 - Tab completion in the local namespace.
223 - Tab completion in the local namespace.
224 - Logging of input, see command-line options.
224 - Logging of input, see command-line options.
225 - System shell escape via ! , eg !ls.
225 - System shell escape via ! , eg !ls.
226 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
226 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
227 - Keeps track of locally defined variables via %who, %whos.
227 - Keeps track of locally defined variables via %who, %whos.
228 - Show object information with a ? eg ?x or x? (use ?? for more info).
228 - Show object information with a ? eg ?x or x? (use ?? for more info).
229 """
229 """
230
230
231 quick_reference = r"""
231 quick_reference = r"""
232 IPython -- An enhanced Interactive Python - Quick Reference Card
232 IPython -- An enhanced Interactive Python - Quick Reference Card
233 ================================================================
233 ================================================================
234
234
235 obj?, obj?? : Get help, or more help for object (also works as
235 obj?, obj?? : Get help, or more help for object (also works as
236 ?obj, ??obj).
236 ?obj, ??obj).
237 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
237 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
238 %magic : Information about IPython's 'magic' % functions.
238 %magic : Information about IPython's 'magic' % functions.
239
239
240 Magic functions are prefixed by %, and typically take their arguments without
240 Magic functions are prefixed by %, and typically take their arguments without
241 parentheses, quotes or even commas for convenience.
241 parentheses, quotes or even commas for convenience.
242
242
243 Example magic function calls:
243 Example magic function calls:
244
244
245 %alias d ls -F : 'd' is now an alias for 'ls -F'
245 %alias d ls -F : 'd' is now an alias for 'ls -F'
246 alias d ls -F : Works if 'alias' not a python name
246 alias d ls -F : Works if 'alias' not a python name
247 alist = %alias : Get list of aliases to 'alist'
247 alist = %alias : Get list of aliases to 'alist'
248 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
248 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
249 %cd?? : See help AND source for magic %cd
249 %cd?? : See help AND source for magic %cd
250
250
251 System commands:
251 System commands:
252
252
253 !cp a.txt b/ : System command escape, calls os.system()
253 !cp a.txt b/ : System command escape, calls os.system()
254 cp a.txt b/ : after %rehashx, most system commands work without !
254 cp a.txt b/ : after %rehashx, most system commands work without !
255 cp ${f}.txt $bar : Variable expansion in magics and system commands
255 cp ${f}.txt $bar : Variable expansion in magics and system commands
256 files = !ls /usr : Capture sytem command output
256 files = !ls /usr : Capture sytem command output
257 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
257 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
258
258
259 History:
259 History:
260
260
261 _i, _ii, _iii : Previous, next previous, next next previous input
261 _i, _ii, _iii : Previous, next previous, next next previous input
262 _i4, _ih[2:5] : Input history line 4, lines 2-4
262 _i4, _ih[2:5] : Input history line 4, lines 2-4
263 exec _i81 : Execute input history line #81 again
263 exec _i81 : Execute input history line #81 again
264 %rep 81 : Edit input history line #81
264 %rep 81 : Edit input history line #81
265 _, __, ___ : previous, next previous, next next previous output
265 _, __, ___ : previous, next previous, next next previous output
266 _dh : Directory history
266 _dh : Directory history
267 _oh : Output history
267 _oh : Output history
268 %hist : Command history. '%hist -g foo' search history for 'foo'
268 %hist : Command history. '%hist -g foo' search history for 'foo'
269
269
270 Autocall:
270 Autocall:
271
271
272 f 1,2 : f(1,2)
272 f 1,2 : f(1,2)
273 /f 1,2 : f(1,2) (forced autoparen)
273 /f 1,2 : f(1,2) (forced autoparen)
274 ,f 1 2 : f("1","2")
274 ,f 1 2 : f("1","2")
275 ;f 1 2 : f("1 2")
275 ;f 1 2 : f("1 2")
276
276
277 Remember: TAB completion works in many contexts, not just file names
277 Remember: TAB completion works in many contexts, not just file names
278 or python names.
278 or python names.
279
279
280 The following magic functions are currently available:
280 The following magic functions are currently available:
281
281
282 """
282 """
283
283
284 gui_reference = """\
284 gui_reference = """\
285 ===============================
285 ===============================
286 The graphical IPython console
286 The graphical IPython console
287 ===============================
287 ===============================
288
288
289 This console is designed to emulate the look, feel and workflow of a terminal
289 This console is designed to emulate the look, feel and workflow of a terminal
290 environment, while adding a number of enhancements that are simply not possible
290 environment, while adding a number of enhancements that are simply not possible
291 in a real terminal, such as inline syntax highlighting, true multiline editing,
291 in a real terminal, such as inline syntax highlighting, true multiline editing,
292 inline graphics and much more.
292 inline graphics and much more.
293
293
294 This quick reference document contains the basic information you'll need to
294 This quick reference document contains the basic information you'll need to
295 know to make the most efficient use of it. For the various command line
295 know to make the most efficient use of it. For the various command line
296 options available at startup, type ``--help`` at the command line.
296 options available at startup, type ``--help`` at the command line.
297
297
298
298
299 Multiline editing
299 Multiline editing
300 =================
300 =================
301
301
302 The graphical console is capable of true multiline editing, but it also tries
302 The graphical console is capable of true multiline editing, but it also tries
303 to behave intuitively like a terminal when possible. If you are used to
303 to behave intuitively like a terminal when possible. If you are used to
304 IPyhton's old terminal behavior, you should find the transition painless, and
304 IPyhton's old terminal behavior, you should find the transition painless, and
305 once you learn a few basic keybindings it will be a much more efficient
305 once you learn a few basic keybindings it will be a much more efficient
306 environment.
306 environment.
307
307
308 For single expressions or indented blocks, the console behaves almost like the
308 For single expressions or indented blocks, the console behaves almost like the
309 terminal IPython: single expressions are immediately evaluated, and indented
309 terminal IPython: single expressions are immediately evaluated, and indented
310 blocks are evaluated once a single blank line is entered::
310 blocks are evaluated once a single blank line is entered::
311
311
312 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
312 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
313 Hello IPython!
313 Hello IPython!
314
314
315 In [2]: for i in range(10):
315 In [2]: for i in range(10):
316 ...: print i,
316 ...: print i,
317 ...:
317 ...:
318 0 1 2 3 4 5 6 7 8 9
318 0 1 2 3 4 5 6 7 8 9
319
319
320 If you want to enter more than one expression in a single input block
320 If you want to enter more than one expression in a single input block
321 (something not possible in the terminal), you can use ``Control-Enter`` at the
321 (something not possible in the terminal), you can use ``Control-Enter`` at the
322 end of your first line instead of ``Enter``. At that point the console goes
322 end of your first line instead of ``Enter``. At that point the console goes
323 into 'cell mode' and even if your inputs are not indented, it will continue
323 into 'cell mode' and even if your inputs are not indented, it will continue
324 accepting arbitrarily many lines until either you enter an extra blank line or
324 accepting arbitrarily many lines until either you enter an extra blank line or
325 you hit ``Shift-Enter`` (the key binding that forces execution). When a
325 you hit ``Shift-Enter`` (the key binding that forces execution). When a
326 multiline cell is entered, IPython analyzes it and executes its code producing
326 multiline cell is entered, IPython analyzes it and executes its code producing
327 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
327 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
328 cell is executed as if it was a script. An example should clarify this::
328 cell is executed as if it was a script. An example should clarify this::
329
329
330 In [3]: x=1 # Hit C-Enter here
330 In [3]: x=1 # Hit C-Enter here
331 ...: y=2 # from now on, regular Enter is sufficient
331 ...: y=2 # from now on, regular Enter is sufficient
332 ...: z=3
332 ...: z=3
333 ...: x**2 # This does *not* produce an Out[] value
333 ...: x**2 # This does *not* produce an Out[] value
334 ...: x+y+z # Only the last expression does
334 ...: x+y+z # Only the last expression does
335 ...:
335 ...:
336 Out[3]: 6
336 Out[3]: 6
337
337
338 The behavior where an extra blank line forces execution is only active if you
338 The behavior where an extra blank line forces execution is only active if you
339 are actually typing at the keyboard each line, and is meant to make it mimic
339 are actually typing at the keyboard each line, and is meant to make it mimic
340 the IPython terminal behavior. If you paste a long chunk of input (for example
340 the IPython terminal behavior. If you paste a long chunk of input (for example
341 a long script copied form an editor or web browser), it can contain arbitrarily
341 a long script copied form an editor or web browser), it can contain arbitrarily
342 many intermediate blank lines and they won't cause any problems. As always,
342 many intermediate blank lines and they won't cause any problems. As always,
343 you can then make it execute by appending a blank line *at the end* or hitting
343 you can then make it execute by appending a blank line *at the end* or hitting
344 ``Shift-Enter`` anywhere within the cell.
344 ``Shift-Enter`` anywhere within the cell.
345
345
346 With the up arrow key, you can retrieve previous blocks of input that contain
346 With the up arrow key, you can retrieve previous blocks of input that contain
347 multiple lines. You can move inside of a multiline cell like you would in any
347 multiple lines. You can move inside of a multiline cell like you would in any
348 text editor. When you want it executed, the simplest thing to do is to hit the
348 text editor. When you want it executed, the simplest thing to do is to hit the
349 force execution key, ``Shift-Enter`` (though you can also navigate to the end
349 force execution key, ``Shift-Enter`` (though you can also navigate to the end
350 and append a blank line by using ``Enter`` twice).
350 and append a blank line by using ``Enter`` twice).
351
351
352 If you've edited a multiline cell and accidentally navigate out of it with the
352 If you've edited a multiline cell and accidentally navigate out of it with the
353 up or down arrow keys, IPython will clear the cell and replace it with the
353 up or down arrow keys, IPython will clear the cell and replace it with the
354 contents of the one above or below that you navigated to. If this was an
354 contents of the one above or below that you navigated to. If this was an
355 accident and you want to retrieve the cell you were editing, use the Undo
355 accident and you want to retrieve the cell you were editing, use the Undo
356 keybinding, ``Control-z``.
356 keybinding, ``Control-z``.
357
357
358
358
359 Key bindings
359 Key bindings
360 ============
360 ============
361
361
362 The IPython console supports most of the basic Emacs line-oriented keybindings,
362 The IPython console supports most of the basic Emacs line-oriented keybindings,
363 in addition to some of its own.
363 in addition to some of its own.
364
364
365 The keybinding prefixes mean:
365 The keybinding prefixes mean:
366
366
367 - ``C``: Control
367 - ``C``: Control
368 - ``S``: Shift
368 - ``S``: Shift
369 - ``M``: Meta (typically the Alt key)
369 - ``M``: Meta (typically the Alt key)
370
370
371 The keybindings themselves are:
371 The keybindings themselves are:
372
372
373 - ``Enter``: insert new line (may cause execution, see above).
373 - ``Enter``: insert new line (may cause execution, see above).
374 - ``C-Enter``: force new line, *never* causes execution.
374 - ``C-Enter``: force new line, *never* causes execution.
375 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
375 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
376 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
376 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
377 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
377 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
378 - ``C-v``: paste text from clipboard.
378 - ``C-v``: paste text from clipboard.
379 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
379 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
380 - ``C-S-z``: redo.
380 - ``C-S-z``: redo.
381 - ``C-o``: move to 'other' area, between pager and terminal.
381 - ``C-o``: move to 'other' area, between pager and terminal.
382 - ``C-l``: clear terminal.
382 - ``C-l``: clear terminal.
383 - ``C-a``: go to beginning of line.
383 - ``C-a``: go to beginning of line.
384 - ``C-e``: go to end of line.
384 - ``C-e``: go to end of line.
385 - ``C-k``: kill from cursor to the end of the line.
385 - ``C-k``: kill from cursor to the end of the line.
386 - ``C-y``: yank (paste)
386 - ``C-y``: yank (paste)
387 - ``C-p``: previous line (like up arrow)
387 - ``C-p``: previous line (like up arrow)
388 - ``C-n``: next line (like down arrow)
388 - ``C-n``: next line (like down arrow)
389 - ``C-f``: forward (like right arrow)
389 - ``C-f``: forward (like right arrow)
390 - ``C-b``: back (like left arrow)
390 - ``C-b``: back (like left arrow)
391 - ``C-d``: delete next character.
391 - ``C-d``: delete next character.
392 - ``M-<``: move to the beginning of the input region.
392 - ``M-<``: move to the beginning of the input region.
393 - ``M->``: move to the end of the input region.
393 - ``M->``: move to the end of the input region.
394 - ``M-d``: delete next word.
394 - ``M-d``: delete next word.
395 - ``M-Backspace``: delete previous word.
395 - ``M-Backspace``: delete previous word.
396 - ``C-.``: force a kernel restart (a confirmation dialog appears).
396 - ``C-.``: force a kernel restart (a confirmation dialog appears).
397 - ``C-+``: increase font size.
397 - ``C-+``: increase font size.
398 - ``C--``: decrease font size.
398 - ``C--``: decrease font size.
399
399
400 The IPython pager
400 The IPython pager
401 =================
401 =================
402
402
403 IPython will show long blocks of text from many sources using a builtin pager.
403 IPython will show long blocks of text from many sources using a builtin pager.
404 You can control where this pager appears with the ``--paging`` command-line
404 You can control where this pager appears with the ``--paging`` command-line
405 flag:
405 flag:
406
406
407 - default: it is overlaid on top of the main terminal. You must quit the pager
407 - default: it is overlaid on top of the main terminal. You must quit the pager
408 to get back to the terminal (similar to how a pager such as ``less`` or
408 to get back to the terminal (similar to how a pager such as ``less`` or
409 ``more`` works).
409 ``more`` works).
410
410
411 - vertical: the console is made double-tall, and the pager appears on the
411 - vertical: the console is made double-tall, and the pager appears on the
412 bottom area when needed. You can view its contents while using the terminal.
412 bottom area when needed. You can view its contents while using the terminal.
413
413
414 - horizontal: the console is made double-wide, and the pager appears on the
414 - horizontal: the console is made double-wide, and the pager appears on the
415 right area when needed. You can view its contents while using the terminal.
415 right area when needed. You can view its contents while using the terminal.
416
416
417 If you use the vertical or horizontal paging modes, you can navigate between
417 If you use the vertical or horizontal paging modes, you can navigate between
418 terminal and pager as follows:
418 terminal and pager as follows:
419
419
420 - Tab key: goes from pager to terminal (but not the other way around).
420 - Tab key: goes from pager to terminal (but not the other way around).
421 - Control-o: goes from one to another always.
421 - Control-o: goes from one to another always.
422 - Mouse: click on either.
422 - Mouse: click on either.
423
423
424 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
424 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
425 focus on the pager area).
425 focus on the pager area).
426
426
427
427
428 Running subprocesses
428 Running subprocesses
429 ====================
429 ====================
430
430
431 The graphical IPython console uses the ``pexpect`` module to run subprocesses
431 The graphical IPython console uses the ``pexpect`` module to run subprocesses
432 when you type ``!command``. This has a number of advantages (true asynchronous
432 when you type ``!command``. This has a number of advantages (true asynchronous
433 output from subprocesses as well as very robust termination of rogue
433 output from subprocesses as well as very robust termination of rogue
434 subprocesses with ``Control-C``), as well as some limitations. The main
434 subprocesses with ``Control-C``), as well as some limitations. The main
435 limitation is that you can *not* interact back with the subprocess, so anything
435 limitation is that you can *not* interact back with the subprocess, so anything
436 that invokes a pager or expects you to type input into it will block and hang
436 that invokes a pager or expects you to type input into it will block and hang
437 (you can kill it with ``Control-C``).
437 (you can kill it with ``Control-C``).
438
438
439 We have provided as magics ``%less`` to page files (aliased to ``%more``),
439 We have provided as magics ``%less`` to page files (aliased to ``%more``),
440 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
440 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
441 most common commands you'd want to call in your subshell and that would cause
441 most common commands you'd want to call in your subshell and that would cause
442 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
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 Inline matplotlib graphics
470 Inline matplotlib graphics
446 ==========================
471 ==========================
447
472
448 The IPython console is capable of displaying matplotlib figures inline, in SVG
473 The IPython console is capable of displaying matplotlib figures inline, in SVG
449 format. If started with the ``--pylab inline`` flag, then all figures are
474 format. If started with the ``--pylab inline`` flag, then all figures are
450 rendered inline automatically. If started with ``--pylab`` or ``--pylab <your
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
476 backend>``, then a GUI backend will be used, but IPython's ``display()`` and
452 added to the global and ``plt`` namespaces. You can paste any figure that is
477 ``getfigs()`` functions can be used to view plots inline::
453 currently open in a window with this function; type ``pastefig?`` for
478
454 additional details."""
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 quick_guide = """\
485 quick_guide = """\
457 ? -> Introduction and overview of IPython's features.
486 ? -> Introduction and overview of IPython's features.
458 %quickref -> Quick reference.
487 %quickref -> Quick reference.
459 help -> Python's own help system.
488 help -> Python's own help system.
460 object? -> Details about 'object', use 'object??' for extra details.
489 object? -> Details about 'object', use 'object??' for extra details.
461 """
490 """
462
491
463 gui_note = """\
492 gui_note = """\
464 %guiref -> A brief reference about the graphical user interface.
493 %guiref -> A brief reference about the graphical user interface.
465 """
494 """
466
495
467 default_banner_parts = [
496 default_banner_parts = [
468 'Python %s\n' % (sys.version.split('\n')[0],),
497 'Python %s\n' % (sys.version.split('\n')[0],),
469 'Type "copyright", "credits" or "license" for more information.\n\n',
498 'Type "copyright", "credits" or "license" for more information.\n\n',
470 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
499 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
471 quick_guide
500 quick_guide
472 ]
501 ]
473
502
474 default_gui_banner_parts = default_banner_parts + [gui_note]
503 default_gui_banner_parts = default_banner_parts + [gui_note]
475
504
476 default_banner = ''.join(default_banner_parts)
505 default_banner = ''.join(default_banner_parts)
477
506
478 default_gui_banner = ''.join(default_gui_banner_parts)
507 default_gui_banner = ''.join(default_gui_banner_parts)
@@ -1,598 +1,598 b''
1 from __future__ import print_function
1 from __future__ import print_function
2
2
3 # Standard library imports
3 # Standard library imports
4 from collections import namedtuple
4 from collections import namedtuple
5 import sys
5 import sys
6 import time
6 import time
7
7
8 # System library imports
8 # System library imports
9 from pygments.lexers import PythonLexer
9 from pygments.lexers import PythonLexer
10 from PyQt4 import QtCore, QtGui
10 from PyQt4 import QtCore, QtGui
11
11
12 # Local imports
12 # Local imports
13 from IPython.core.inputsplitter import InputSplitter, transform_classic_prompt
13 from IPython.core.inputsplitter import InputSplitter, transform_classic_prompt
14 from IPython.core.oinspect import call_tip
14 from IPython.core.oinspect import call_tip
15 from IPython.frontend.qt.base_frontend_mixin import BaseFrontendMixin
15 from IPython.frontend.qt.base_frontend_mixin import BaseFrontendMixin
16 from IPython.utils.traitlets import Bool
16 from IPython.utils.traitlets import Bool
17 from bracket_matcher import BracketMatcher
17 from bracket_matcher import BracketMatcher
18 from call_tip_widget import CallTipWidget
18 from call_tip_widget import CallTipWidget
19 from completion_lexer import CompletionLexer
19 from completion_lexer import CompletionLexer
20 from history_console_widget import HistoryConsoleWidget
20 from history_console_widget import HistoryConsoleWidget
21 from pygments_highlighter import PygmentsHighlighter
21 from pygments_highlighter import PygmentsHighlighter
22
22
23
23
24 class FrontendHighlighter(PygmentsHighlighter):
24 class FrontendHighlighter(PygmentsHighlighter):
25 """ A PygmentsHighlighter that can be turned on and off and that ignores
25 """ A PygmentsHighlighter that can be turned on and off and that ignores
26 prompts.
26 prompts.
27 """
27 """
28
28
29 def __init__(self, frontend):
29 def __init__(self, frontend):
30 super(FrontendHighlighter, self).__init__(frontend._control.document())
30 super(FrontendHighlighter, self).__init__(frontend._control.document())
31 self._current_offset = 0
31 self._current_offset = 0
32 self._frontend = frontend
32 self._frontend = frontend
33 self.highlighting_on = False
33 self.highlighting_on = False
34
34
35 def highlightBlock(self, qstring):
35 def highlightBlock(self, qstring):
36 """ Highlight a block of text. Reimplemented to highlight selectively.
36 """ Highlight a block of text. Reimplemented to highlight selectively.
37 """
37 """
38 if not self.highlighting_on:
38 if not self.highlighting_on:
39 return
39 return
40
40
41 # The input to this function is unicode string that may contain
41 # The input to this function is unicode string that may contain
42 # paragraph break characters, non-breaking spaces, etc. Here we acquire
42 # paragraph break characters, non-breaking spaces, etc. Here we acquire
43 # the string as plain text so we can compare it.
43 # the string as plain text so we can compare it.
44 current_block = self.currentBlock()
44 current_block = self.currentBlock()
45 string = self._frontend._get_block_plain_text(current_block)
45 string = self._frontend._get_block_plain_text(current_block)
46
46
47 # Decide whether to check for the regular or continuation prompt.
47 # Decide whether to check for the regular or continuation prompt.
48 if current_block.contains(self._frontend._prompt_pos):
48 if current_block.contains(self._frontend._prompt_pos):
49 prompt = self._frontend._prompt
49 prompt = self._frontend._prompt
50 else:
50 else:
51 prompt = self._frontend._continuation_prompt
51 prompt = self._frontend._continuation_prompt
52
52
53 # Don't highlight the part of the string that contains the prompt.
53 # Don't highlight the part of the string that contains the prompt.
54 if string.startswith(prompt):
54 if string.startswith(prompt):
55 self._current_offset = len(prompt)
55 self._current_offset = len(prompt)
56 qstring.remove(0, len(prompt))
56 qstring.remove(0, len(prompt))
57 else:
57 else:
58 self._current_offset = 0
58 self._current_offset = 0
59
59
60 PygmentsHighlighter.highlightBlock(self, qstring)
60 PygmentsHighlighter.highlightBlock(self, qstring)
61
61
62 def rehighlightBlock(self, block):
62 def rehighlightBlock(self, block):
63 """ Reimplemented to temporarily enable highlighting if disabled.
63 """ Reimplemented to temporarily enable highlighting if disabled.
64 """
64 """
65 old = self.highlighting_on
65 old = self.highlighting_on
66 self.highlighting_on = True
66 self.highlighting_on = True
67 super(FrontendHighlighter, self).rehighlightBlock(block)
67 super(FrontendHighlighter, self).rehighlightBlock(block)
68 self.highlighting_on = old
68 self.highlighting_on = old
69
69
70 def setFormat(self, start, count, format):
70 def setFormat(self, start, count, format):
71 """ Reimplemented to highlight selectively.
71 """ Reimplemented to highlight selectively.
72 """
72 """
73 start += self._current_offset
73 start += self._current_offset
74 PygmentsHighlighter.setFormat(self, start, count, format)
74 PygmentsHighlighter.setFormat(self, start, count, format)
75
75
76
76
77 class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin):
77 class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin):
78 """ A Qt frontend for a generic Python kernel.
78 """ A Qt frontend for a generic Python kernel.
79 """
79 """
80
80
81 # An option and corresponding signal for overriding the default kernel
81 # An option and corresponding signal for overriding the default kernel
82 # interrupt behavior.
82 # interrupt behavior.
83 custom_interrupt = Bool(False)
83 custom_interrupt = Bool(False)
84 custom_interrupt_requested = QtCore.pyqtSignal()
84 custom_interrupt_requested = QtCore.pyqtSignal()
85
85
86 # An option and corresponding signals for overriding the default kernel
86 # An option and corresponding signals for overriding the default kernel
87 # restart behavior.
87 # restart behavior.
88 custom_restart = Bool(False)
88 custom_restart = Bool(False)
89 custom_restart_kernel_died = QtCore.pyqtSignal(float)
89 custom_restart_kernel_died = QtCore.pyqtSignal(float)
90 custom_restart_requested = QtCore.pyqtSignal()
90 custom_restart_requested = QtCore.pyqtSignal()
91
91
92 # Emitted when an 'execute_reply' has been received from the kernel and
92 # Emitted when an 'execute_reply' has been received from the kernel and
93 # processed by the FrontendWidget.
93 # processed by the FrontendWidget.
94 executed = QtCore.pyqtSignal(object)
94 executed = QtCore.pyqtSignal(object)
95
95
96 # Emitted when an exit request has been received from the kernel.
96 # Emitted when an exit request has been received from the kernel.
97 exit_requested = QtCore.pyqtSignal()
97 exit_requested = QtCore.pyqtSignal()
98
98
99 # Protected class variables.
99 # Protected class variables.
100 _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos'])
100 _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos'])
101 _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos'])
101 _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos'])
102 _ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind'])
102 _ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind'])
103 _input_splitter_class = InputSplitter
103 _input_splitter_class = InputSplitter
104 _local_kernel = False
104 _local_kernel = False
105
105
106 #---------------------------------------------------------------------------
106 #---------------------------------------------------------------------------
107 # 'object' interface
107 # 'object' interface
108 #---------------------------------------------------------------------------
108 #---------------------------------------------------------------------------
109
109
110 def __init__(self, *args, **kw):
110 def __init__(self, *args, **kw):
111 super(FrontendWidget, self).__init__(*args, **kw)
111 super(FrontendWidget, self).__init__(*args, **kw)
112
112
113 # FrontendWidget protected variables.
113 # FrontendWidget protected variables.
114 self._bracket_matcher = BracketMatcher(self._control)
114 self._bracket_matcher = BracketMatcher(self._control)
115 self._call_tip_widget = CallTipWidget(self._control)
115 self._call_tip_widget = CallTipWidget(self._control)
116 self._completion_lexer = CompletionLexer(PythonLexer())
116 self._completion_lexer = CompletionLexer(PythonLexer())
117 self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None)
117 self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None)
118 self._hidden = False
118 self._hidden = False
119 self._highlighter = FrontendHighlighter(self)
119 self._highlighter = FrontendHighlighter(self)
120 self._input_splitter = self._input_splitter_class(input_mode='cell')
120 self._input_splitter = self._input_splitter_class(input_mode='cell')
121 self._kernel_manager = None
121 self._kernel_manager = None
122 self._request_info = {}
122 self._request_info = {}
123
123
124 # Configure the ConsoleWidget.
124 # Configure the ConsoleWidget.
125 self.tab_width = 4
125 self.tab_width = 4
126 self._set_continuation_prompt('... ')
126 self._set_continuation_prompt('... ')
127
127
128 # Configure the CallTipWidget.
128 # Configure the CallTipWidget.
129 self._call_tip_widget.setFont(self.font)
129 self._call_tip_widget.setFont(self.font)
130 self.font_changed.connect(self._call_tip_widget.setFont)
130 self.font_changed.connect(self._call_tip_widget.setFont)
131
131
132 # Configure actions.
132 # Configure actions.
133 action = self._copy_raw_action
133 action = self._copy_raw_action
134 key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C
134 key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C
135 action.setEnabled(False)
135 action.setEnabled(False)
136 action.setShortcut(QtGui.QKeySequence(key))
136 action.setShortcut(QtGui.QKeySequence(key))
137 action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
137 action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
138 action.triggered.connect(self.copy_raw)
138 action.triggered.connect(self.copy_raw)
139 self.copy_available.connect(action.setEnabled)
139 self.copy_available.connect(action.setEnabled)
140 self.addAction(action)
140 self.addAction(action)
141
141
142 # Connect signal handlers.
142 # Connect signal handlers.
143 document = self._control.document()
143 document = self._control.document()
144 document.contentsChange.connect(self._document_contents_change)
144 document.contentsChange.connect(self._document_contents_change)
145
145
146 # set flag for whether we are connected via localhost
146 # set flag for whether we are connected via localhost
147 self._local_kernel = kw.get('local_kernel', FrontendWidget._local_kernel)
147 self._local_kernel = kw.get('local_kernel', FrontendWidget._local_kernel)
148
148
149 #---------------------------------------------------------------------------
149 #---------------------------------------------------------------------------
150 # 'ConsoleWidget' public interface
150 # 'ConsoleWidget' public interface
151 #---------------------------------------------------------------------------
151 #---------------------------------------------------------------------------
152
152
153 def copy(self):
153 def copy(self):
154 """ Copy the currently selected text to the clipboard, removing prompts.
154 """ Copy the currently selected text to the clipboard, removing prompts.
155 """
155 """
156 text = unicode(self._control.textCursor().selection().toPlainText())
156 text = unicode(self._control.textCursor().selection().toPlainText())
157 if text:
157 if text:
158 lines = map(transform_classic_prompt, text.splitlines())
158 lines = map(transform_classic_prompt, text.splitlines())
159 text = '\n'.join(lines)
159 text = '\n'.join(lines)
160 QtGui.QApplication.clipboard().setText(text)
160 QtGui.QApplication.clipboard().setText(text)
161
161
162 #---------------------------------------------------------------------------
162 #---------------------------------------------------------------------------
163 # 'ConsoleWidget' abstract interface
163 # 'ConsoleWidget' abstract interface
164 #---------------------------------------------------------------------------
164 #---------------------------------------------------------------------------
165
165
166 def _is_complete(self, source, interactive):
166 def _is_complete(self, source, interactive):
167 """ Returns whether 'source' can be completely processed and a new
167 """ Returns whether 'source' can be completely processed and a new
168 prompt created. When triggered by an Enter/Return key press,
168 prompt created. When triggered by an Enter/Return key press,
169 'interactive' is True; otherwise, it is False.
169 'interactive' is True; otherwise, it is False.
170 """
170 """
171 complete = self._input_splitter.push(source)
171 complete = self._input_splitter.push(source)
172 if interactive:
172 if interactive:
173 complete = not self._input_splitter.push_accepts_more()
173 complete = not self._input_splitter.push_accepts_more()
174 return complete
174 return complete
175
175
176 def _execute(self, source, hidden):
176 def _execute(self, source, hidden):
177 """ Execute 'source'. If 'hidden', do not show any output.
177 """ Execute 'source'. If 'hidden', do not show any output.
178
178
179 See parent class :meth:`execute` docstring for full details.
179 See parent class :meth:`execute` docstring for full details.
180 """
180 """
181 msg_id = self.kernel_manager.xreq_channel.execute(source, hidden)
181 msg_id = self.kernel_manager.xreq_channel.execute(source, hidden)
182 self._request_info['execute'] = self._ExecutionRequest(msg_id, 'user')
182 self._request_info['execute'] = self._ExecutionRequest(msg_id, 'user')
183 self._hidden = hidden
183 self._hidden = hidden
184
184
185 def _prompt_started_hook(self):
185 def _prompt_started_hook(self):
186 """ Called immediately after a new prompt is displayed.
186 """ Called immediately after a new prompt is displayed.
187 """
187 """
188 if not self._reading:
188 if not self._reading:
189 self._highlighter.highlighting_on = True
189 self._highlighter.highlighting_on = True
190
190
191 def _prompt_finished_hook(self):
191 def _prompt_finished_hook(self):
192 """ Called immediately after a prompt is finished, i.e. when some input
192 """ Called immediately after a prompt is finished, i.e. when some input
193 will be processed and a new prompt displayed.
193 will be processed and a new prompt displayed.
194 """
194 """
195 if not self._reading:
195 if not self._reading:
196 self._highlighter.highlighting_on = False
196 self._highlighter.highlighting_on = False
197
197
198 def _tab_pressed(self):
198 def _tab_pressed(self):
199 """ Called when the tab key is pressed. Returns whether to continue
199 """ Called when the tab key is pressed. Returns whether to continue
200 processing the event.
200 processing the event.
201 """
201 """
202 # Perform tab completion if:
202 # Perform tab completion if:
203 # 1) The cursor is in the input buffer.
203 # 1) The cursor is in the input buffer.
204 # 2) There is a non-whitespace character before the cursor.
204 # 2) There is a non-whitespace character before the cursor.
205 text = self._get_input_buffer_cursor_line()
205 text = self._get_input_buffer_cursor_line()
206 if text is None:
206 if text is None:
207 return False
207 return False
208 complete = bool(text[:self._get_input_buffer_cursor_column()].strip())
208 complete = bool(text[:self._get_input_buffer_cursor_column()].strip())
209 if complete:
209 if complete:
210 self._complete()
210 self._complete()
211 return not complete
211 return not complete
212
212
213 #---------------------------------------------------------------------------
213 #---------------------------------------------------------------------------
214 # 'ConsoleWidget' protected interface
214 # 'ConsoleWidget' protected interface
215 #---------------------------------------------------------------------------
215 #---------------------------------------------------------------------------
216
216
217 def _context_menu_make(self, pos):
217 def _context_menu_make(self, pos):
218 """ Reimplemented to add an action for raw copy.
218 """ Reimplemented to add an action for raw copy.
219 """
219 """
220 menu = super(FrontendWidget, self)._context_menu_make(pos)
220 menu = super(FrontendWidget, self)._context_menu_make(pos)
221 for before_action in menu.actions():
221 for before_action in menu.actions():
222 if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \
222 if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \
223 QtGui.QKeySequence.ExactMatch:
223 QtGui.QKeySequence.ExactMatch:
224 menu.insertAction(before_action, self._copy_raw_action)
224 menu.insertAction(before_action, self._copy_raw_action)
225 break
225 break
226 return menu
226 return menu
227
227
228 def _event_filter_console_keypress(self, event):
228 def _event_filter_console_keypress(self, event):
229 """ Reimplemented for execution interruption and smart backspace.
229 """ Reimplemented for execution interruption and smart backspace.
230 """
230 """
231 key = event.key()
231 key = event.key()
232 if self._control_key_down(event.modifiers(), include_command=False):
232 if self._control_key_down(event.modifiers(), include_command=False):
233
233
234 if key == QtCore.Qt.Key_C and self._executing:
234 if key == QtCore.Qt.Key_C and self._executing:
235 self.interrupt_kernel()
235 self.interrupt_kernel()
236 return True
236 return True
237
237
238 elif key == QtCore.Qt.Key_Period:
238 elif key == QtCore.Qt.Key_Period:
239 message = 'Are you sure you want to restart the kernel?'
239 message = 'Are you sure you want to restart the kernel?'
240 self.restart_kernel(message, now=False)
240 self.restart_kernel(message, now=False)
241 return True
241 return True
242
242
243 elif not event.modifiers() & QtCore.Qt.AltModifier:
243 elif not event.modifiers() & QtCore.Qt.AltModifier:
244
244
245 # Smart backspace: remove four characters in one backspace if:
245 # Smart backspace: remove four characters in one backspace if:
246 # 1) everything left of the cursor is whitespace
246 # 1) everything left of the cursor is whitespace
247 # 2) the four characters immediately left of the cursor are spaces
247 # 2) the four characters immediately left of the cursor are spaces
248 if key == QtCore.Qt.Key_Backspace:
248 if key == QtCore.Qt.Key_Backspace:
249 col = self._get_input_buffer_cursor_column()
249 col = self._get_input_buffer_cursor_column()
250 cursor = self._control.textCursor()
250 cursor = self._control.textCursor()
251 if col > 3 and not cursor.hasSelection():
251 if col > 3 and not cursor.hasSelection():
252 text = self._get_input_buffer_cursor_line()[:col]
252 text = self._get_input_buffer_cursor_line()[:col]
253 if text.endswith(' ') and not text.strip():
253 if text.endswith(' ') and not text.strip():
254 cursor.movePosition(QtGui.QTextCursor.Left,
254 cursor.movePosition(QtGui.QTextCursor.Left,
255 QtGui.QTextCursor.KeepAnchor, 4)
255 QtGui.QTextCursor.KeepAnchor, 4)
256 cursor.removeSelectedText()
256 cursor.removeSelectedText()
257 return True
257 return True
258
258
259 return super(FrontendWidget, self)._event_filter_console_keypress(event)
259 return super(FrontendWidget, self)._event_filter_console_keypress(event)
260
260
261 def _insert_continuation_prompt(self, cursor):
261 def _insert_continuation_prompt(self, cursor):
262 """ Reimplemented for auto-indentation.
262 """ Reimplemented for auto-indentation.
263 """
263 """
264 super(FrontendWidget, self)._insert_continuation_prompt(cursor)
264 super(FrontendWidget, self)._insert_continuation_prompt(cursor)
265 cursor.insertText(' ' * self._input_splitter.indent_spaces)
265 cursor.insertText(' ' * self._input_splitter.indent_spaces)
266
266
267 #---------------------------------------------------------------------------
267 #---------------------------------------------------------------------------
268 # 'BaseFrontendMixin' abstract interface
268 # 'BaseFrontendMixin' abstract interface
269 #---------------------------------------------------------------------------
269 #---------------------------------------------------------------------------
270
270
271 def _handle_complete_reply(self, rep):
271 def _handle_complete_reply(self, rep):
272 """ Handle replies for tab completion.
272 """ Handle replies for tab completion.
273 """
273 """
274 cursor = self._get_cursor()
274 cursor = self._get_cursor()
275 info = self._request_info.get('complete')
275 info = self._request_info.get('complete')
276 if info and info.id == rep['parent_header']['msg_id'] and \
276 if info and info.id == rep['parent_header']['msg_id'] and \
277 info.pos == cursor.position():
277 info.pos == cursor.position():
278 text = '.'.join(self._get_context())
278 text = '.'.join(self._get_context())
279 cursor.movePosition(QtGui.QTextCursor.Left, n=len(text))
279 cursor.movePosition(QtGui.QTextCursor.Left, n=len(text))
280 self._complete_with_items(cursor, rep['content']['matches'])
280 self._complete_with_items(cursor, rep['content']['matches'])
281
281
282 def _handle_execute_reply(self, msg):
282 def _handle_execute_reply(self, msg):
283 """ Handles replies for code execution.
283 """ Handles replies for code execution.
284 """
284 """
285 info = self._request_info.get('execute')
285 info = self._request_info.get('execute')
286 if info and info.id == msg['parent_header']['msg_id'] and \
286 if info and info.id == msg['parent_header']['msg_id'] and \
287 info.kind == 'user' and not self._hidden:
287 info.kind == 'user' and not self._hidden:
288 # Make sure that all output from the SUB channel has been processed
288 # Make sure that all output from the SUB channel has been processed
289 # before writing a new prompt.
289 # before writing a new prompt.
290 self.kernel_manager.sub_channel.flush()
290 self.kernel_manager.sub_channel.flush()
291
291
292 # Reset the ANSI style information to prevent bad text in stdout
292 # Reset the ANSI style information to prevent bad text in stdout
293 # from messing up our colors. We're not a true terminal so we're
293 # from messing up our colors. We're not a true terminal so we're
294 # allowed to do this.
294 # allowed to do this.
295 if self.ansi_codes:
295 if self.ansi_codes:
296 self._ansi_processor.reset_sgr()
296 self._ansi_processor.reset_sgr()
297
297
298 content = msg['content']
298 content = msg['content']
299 status = content['status']
299 status = content['status']
300 if status == 'ok':
300 if status == 'ok':
301 self._process_execute_ok(msg)
301 self._process_execute_ok(msg)
302 elif status == 'error':
302 elif status == 'error':
303 self._process_execute_error(msg)
303 self._process_execute_error(msg)
304 elif status == 'abort':
304 elif status == 'abort':
305 self._process_execute_abort(msg)
305 self._process_execute_abort(msg)
306
306
307 self._show_interpreter_prompt_for_reply(msg)
307 self._show_interpreter_prompt_for_reply(msg)
308 self.executed.emit(msg)
308 self.executed.emit(msg)
309
309
310 def _handle_input_request(self, msg):
310 def _handle_input_request(self, msg):
311 """ Handle requests for raw_input.
311 """ Handle requests for raw_input.
312 """
312 """
313 if self._hidden:
313 if self._hidden:
314 raise RuntimeError('Request for raw input during hidden execution.')
314 raise RuntimeError('Request for raw input during hidden execution.')
315
315
316 # Make sure that all output from the SUB channel has been processed
316 # Make sure that all output from the SUB channel has been processed
317 # before entering readline mode.
317 # before entering readline mode.
318 self.kernel_manager.sub_channel.flush()
318 self.kernel_manager.sub_channel.flush()
319
319
320 def callback(line):
320 def callback(line):
321 self.kernel_manager.rep_channel.input(line)
321 self.kernel_manager.rep_channel.input(line)
322 self._readline(msg['content']['prompt'], callback=callback)
322 self._readline(msg['content']['prompt'], callback=callback)
323
323
324 def _handle_kernel_died(self, since_last_heartbeat):
324 def _handle_kernel_died(self, since_last_heartbeat):
325 """ Handle the kernel's death by asking if the user wants to restart.
325 """ Handle the kernel's death by asking if the user wants to restart.
326 """
326 """
327 if self.custom_restart:
327 if self.custom_restart:
328 self.custom_restart_kernel_died.emit(since_last_heartbeat)
328 self.custom_restart_kernel_died.emit(since_last_heartbeat)
329 else:
329 else:
330 message = 'The kernel heartbeat has been inactive for %.2f ' \
330 message = 'The kernel heartbeat has been inactive for %.2f ' \
331 'seconds. Do you want to restart the kernel? You may ' \
331 'seconds. Do you want to restart the kernel? You may ' \
332 'first want to check the network connection.' % \
332 'first want to check the network connection.' % \
333 since_last_heartbeat
333 since_last_heartbeat
334 self.restart_kernel(message, now=True)
334 self.restart_kernel(message, now=True)
335
335
336 def _handle_object_info_reply(self, rep):
336 def _handle_object_info_reply(self, rep):
337 """ Handle replies for call tips.
337 """ Handle replies for call tips.
338 """
338 """
339 cursor = self._get_cursor()
339 cursor = self._get_cursor()
340 info = self._request_info.get('call_tip')
340 info = self._request_info.get('call_tip')
341 if info and info.id == rep['parent_header']['msg_id'] and \
341 if info and info.id == rep['parent_header']['msg_id'] and \
342 info.pos == cursor.position():
342 info.pos == cursor.position():
343 # Get the information for a call tip. For now we format the call
343 # Get the information for a call tip. For now we format the call
344 # line as string, later we can pass False to format_call and
344 # line as string, later we can pass False to format_call and
345 # syntax-highlight it ourselves for nicer formatting in the
345 # syntax-highlight it ourselves for nicer formatting in the
346 # calltip.
346 # calltip.
347 call_info, doc = call_tip(rep['content'], format_call=True)
347 call_info, doc = call_tip(rep['content'], format_call=True)
348 if call_info or doc:
348 if call_info or doc:
349 self._call_tip_widget.show_call_info(call_info, doc)
349 self._call_tip_widget.show_call_info(call_info, doc)
350
350
351 def _handle_pyout(self, msg):
351 def _handle_pyout(self, msg):
352 """ Handle display hook output.
352 """ Handle display hook output.
353 """
353 """
354 if not self._hidden and self._is_from_this_session(msg):
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 def _handle_stream(self, msg):
357 def _handle_stream(self, msg):
358 """ Handle stdout, stderr, and stdin.
358 """ Handle stdout, stderr, and stdin.
359 """
359 """
360 if not self._hidden and self._is_from_this_session(msg):
360 if not self._hidden and self._is_from_this_session(msg):
361 # Most consoles treat tabs as being 8 space characters. Convert tabs
361 # Most consoles treat tabs as being 8 space characters. Convert tabs
362 # to spaces so that output looks as expected regardless of this
362 # to spaces so that output looks as expected regardless of this
363 # widget's tab width.
363 # widget's tab width.
364 text = msg['content']['data'].expandtabs(8)
364 text = msg['content']['data'].expandtabs(8)
365
365
366 self._append_plain_text(text)
366 self._append_plain_text(text)
367 self._control.moveCursor(QtGui.QTextCursor.End)
367 self._control.moveCursor(QtGui.QTextCursor.End)
368
368
369 def _handle_shutdown_reply(self, msg):
369 def _handle_shutdown_reply(self, msg):
370 """ Handle shutdown signal, only if from other console.
370 """ Handle shutdown signal, only if from other console.
371 """
371 """
372 if not self._hidden and not self._is_from_this_session(msg):
372 if not self._hidden and not self._is_from_this_session(msg):
373 if self._local_kernel:
373 if self._local_kernel:
374 if not msg['content']['restart']:
374 if not msg['content']['restart']:
375 sys.exit(0)
375 sys.exit(0)
376 else:
376 else:
377 # we just got notified of a restart!
377 # we just got notified of a restart!
378 time.sleep(0.25) # wait 1/4 sec to reset
378 time.sleep(0.25) # wait 1/4 sec to reset
379 # lest the request for a new prompt
379 # lest the request for a new prompt
380 # goes to the old kernel
380 # goes to the old kernel
381 self.reset()
381 self.reset()
382 else: # remote kernel, prompt on Kernel shutdown/reset
382 else: # remote kernel, prompt on Kernel shutdown/reset
383 title = self.window().windowTitle()
383 title = self.window().windowTitle()
384 if not msg['content']['restart']:
384 if not msg['content']['restart']:
385 reply = QtGui.QMessageBox.question(self, title,
385 reply = QtGui.QMessageBox.question(self, title,
386 "Kernel has been shutdown permanently. Close the Console?",
386 "Kernel has been shutdown permanently. Close the Console?",
387 QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
387 QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
388 if reply == QtGui.QMessageBox.Yes:
388 if reply == QtGui.QMessageBox.Yes:
389 sys.exit(0)
389 sys.exit(0)
390 else:
390 else:
391 reply = QtGui.QMessageBox.question(self, title,
391 reply = QtGui.QMessageBox.question(self, title,
392 "Kernel has been reset. Clear the Console?",
392 "Kernel has been reset. Clear the Console?",
393 QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
393 QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
394 if reply == QtGui.QMessageBox.Yes:
394 if reply == QtGui.QMessageBox.Yes:
395 time.sleep(0.25) # wait 1/4 sec to reset
395 time.sleep(0.25) # wait 1/4 sec to reset
396 # lest the request for a new prompt
396 # lest the request for a new prompt
397 # goes to the old kernel
397 # goes to the old kernel
398 self.reset()
398 self.reset()
399
399
400 def _started_channels(self):
400 def _started_channels(self):
401 """ Called when the KernelManager channels have started listening or
401 """ Called when the KernelManager channels have started listening or
402 when the frontend is assigned an already listening KernelManager.
402 when the frontend is assigned an already listening KernelManager.
403 """
403 """
404 self.reset()
404 self.reset()
405
405
406 #---------------------------------------------------------------------------
406 #---------------------------------------------------------------------------
407 # 'FrontendWidget' public interface
407 # 'FrontendWidget' public interface
408 #---------------------------------------------------------------------------
408 #---------------------------------------------------------------------------
409
409
410 def copy_raw(self):
410 def copy_raw(self):
411 """ Copy the currently selected text to the clipboard without attempting
411 """ Copy the currently selected text to the clipboard without attempting
412 to remove prompts or otherwise alter the text.
412 to remove prompts or otherwise alter the text.
413 """
413 """
414 self._control.copy()
414 self._control.copy()
415
415
416 def execute_file(self, path, hidden=False):
416 def execute_file(self, path, hidden=False):
417 """ Attempts to execute file with 'path'. If 'hidden', no output is
417 """ Attempts to execute file with 'path'. If 'hidden', no output is
418 shown.
418 shown.
419 """
419 """
420 self.execute('execfile("%s")' % path, hidden=hidden)
420 self.execute('execfile("%s")' % path, hidden=hidden)
421
421
422 def interrupt_kernel(self):
422 def interrupt_kernel(self):
423 """ Attempts to interrupt the running kernel.
423 """ Attempts to interrupt the running kernel.
424 """
424 """
425 if self.custom_interrupt:
425 if self.custom_interrupt:
426 self.custom_interrupt_requested.emit()
426 self.custom_interrupt_requested.emit()
427 elif self.kernel_manager.has_kernel:
427 elif self.kernel_manager.has_kernel:
428 self.kernel_manager.interrupt_kernel()
428 self.kernel_manager.interrupt_kernel()
429 else:
429 else:
430 self._append_plain_text('Kernel process is either remote or '
430 self._append_plain_text('Kernel process is either remote or '
431 'unspecified. Cannot interrupt.\n')
431 'unspecified. Cannot interrupt.\n')
432
432
433 def reset(self):
433 def reset(self):
434 """ Resets the widget to its initial state. Similar to ``clear``, but
434 """ Resets the widget to its initial state. Similar to ``clear``, but
435 also re-writes the banner and aborts execution if necessary.
435 also re-writes the banner and aborts execution if necessary.
436 """
436 """
437 if self._executing:
437 if self._executing:
438 self._executing = False
438 self._executing = False
439 self._request_info['execute'] = None
439 self._request_info['execute'] = None
440 self._reading = False
440 self._reading = False
441 self._highlighter.highlighting_on = False
441 self._highlighter.highlighting_on = False
442
442
443 self._control.clear()
443 self._control.clear()
444 self._append_plain_text(self._get_banner())
444 self._append_plain_text(self._get_banner())
445 self._show_interpreter_prompt()
445 self._show_interpreter_prompt()
446
446
447 def restart_kernel(self, message, now=False):
447 def restart_kernel(self, message, now=False):
448 """ Attempts to restart the running kernel.
448 """ Attempts to restart the running kernel.
449 """
449 """
450 # FIXME: now should be configurable via a checkbox in the dialog. Right
450 # FIXME: now should be configurable via a checkbox in the dialog. Right
451 # now at least the heartbeat path sets it to True and the manual restart
451 # now at least the heartbeat path sets it to True and the manual restart
452 # to False. But those should just be the pre-selected states of a
452 # to False. But those should just be the pre-selected states of a
453 # checkbox that the user could override if so desired. But I don't know
453 # checkbox that the user could override if so desired. But I don't know
454 # enough Qt to go implementing the checkbox now.
454 # enough Qt to go implementing the checkbox now.
455
455
456 if self.custom_restart:
456 if self.custom_restart:
457 self.custom_restart_requested.emit()
457 self.custom_restart_requested.emit()
458
458
459 elif self.kernel_manager.has_kernel:
459 elif self.kernel_manager.has_kernel:
460 # Pause the heart beat channel to prevent further warnings.
460 # Pause the heart beat channel to prevent further warnings.
461 self.kernel_manager.hb_channel.pause()
461 self.kernel_manager.hb_channel.pause()
462
462
463 # Prompt the user to restart the kernel. Un-pause the heartbeat if
463 # Prompt the user to restart the kernel. Un-pause the heartbeat if
464 # they decline. (If they accept, the heartbeat will be un-paused
464 # they decline. (If they accept, the heartbeat will be un-paused
465 # automatically when the kernel is restarted.)
465 # automatically when the kernel is restarted.)
466 buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
466 buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
467 result = QtGui.QMessageBox.question(self, 'Restart kernel?',
467 result = QtGui.QMessageBox.question(self, 'Restart kernel?',
468 message, buttons)
468 message, buttons)
469 if result == QtGui.QMessageBox.Yes:
469 if result == QtGui.QMessageBox.Yes:
470 try:
470 try:
471 self.kernel_manager.restart_kernel(now=now)
471 self.kernel_manager.restart_kernel(now=now)
472 except RuntimeError:
472 except RuntimeError:
473 self._append_plain_text('Kernel started externally. '
473 self._append_plain_text('Kernel started externally. '
474 'Cannot restart.\n')
474 'Cannot restart.\n')
475 else:
475 else:
476 self.reset()
476 self.reset()
477 else:
477 else:
478 self.kernel_manager.hb_channel.unpause()
478 self.kernel_manager.hb_channel.unpause()
479
479
480 else:
480 else:
481 self._append_plain_text('Kernel process is either remote or '
481 self._append_plain_text('Kernel process is either remote or '
482 'unspecified. Cannot restart.\n')
482 'unspecified. Cannot restart.\n')
483
483
484 #---------------------------------------------------------------------------
484 #---------------------------------------------------------------------------
485 # 'FrontendWidget' protected interface
485 # 'FrontendWidget' protected interface
486 #---------------------------------------------------------------------------
486 #---------------------------------------------------------------------------
487
487
488 def _call_tip(self):
488 def _call_tip(self):
489 """ Shows a call tip, if appropriate, at the current cursor location.
489 """ Shows a call tip, if appropriate, at the current cursor location.
490 """
490 """
491 # Decide if it makes sense to show a call tip
491 # Decide if it makes sense to show a call tip
492 cursor = self._get_cursor()
492 cursor = self._get_cursor()
493 cursor.movePosition(QtGui.QTextCursor.Left)
493 cursor.movePosition(QtGui.QTextCursor.Left)
494 if cursor.document().characterAt(cursor.position()).toAscii() != '(':
494 if cursor.document().characterAt(cursor.position()).toAscii() != '(':
495 return False
495 return False
496 context = self._get_context(cursor)
496 context = self._get_context(cursor)
497 if not context:
497 if not context:
498 return False
498 return False
499
499
500 # Send the metadata request to the kernel
500 # Send the metadata request to the kernel
501 name = '.'.join(context)
501 name = '.'.join(context)
502 msg_id = self.kernel_manager.xreq_channel.object_info(name)
502 msg_id = self.kernel_manager.xreq_channel.object_info(name)
503 pos = self._get_cursor().position()
503 pos = self._get_cursor().position()
504 self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos)
504 self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos)
505 return True
505 return True
506
506
507 def _complete(self):
507 def _complete(self):
508 """ Performs completion at the current cursor location.
508 """ Performs completion at the current cursor location.
509 """
509 """
510 context = self._get_context()
510 context = self._get_context()
511 if context:
511 if context:
512 # Send the completion request to the kernel
512 # Send the completion request to the kernel
513 msg_id = self.kernel_manager.xreq_channel.complete(
513 msg_id = self.kernel_manager.xreq_channel.complete(
514 '.'.join(context), # text
514 '.'.join(context), # text
515 self._get_input_buffer_cursor_line(), # line
515 self._get_input_buffer_cursor_line(), # line
516 self._get_input_buffer_cursor_column(), # cursor_pos
516 self._get_input_buffer_cursor_column(), # cursor_pos
517 self.input_buffer) # block
517 self.input_buffer) # block
518 pos = self._get_cursor().position()
518 pos = self._get_cursor().position()
519 info = self._CompletionRequest(msg_id, pos)
519 info = self._CompletionRequest(msg_id, pos)
520 self._request_info['complete'] = info
520 self._request_info['complete'] = info
521
521
522 def _get_banner(self):
522 def _get_banner(self):
523 """ Gets a banner to display at the beginning of a session.
523 """ Gets a banner to display at the beginning of a session.
524 """
524 """
525 banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \
525 banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \
526 '"license" for more information.'
526 '"license" for more information.'
527 return banner % (sys.version, sys.platform)
527 return banner % (sys.version, sys.platform)
528
528
529 def _get_context(self, cursor=None):
529 def _get_context(self, cursor=None):
530 """ Gets the context for the specified cursor (or the current cursor
530 """ Gets the context for the specified cursor (or the current cursor
531 if none is specified).
531 if none is specified).
532 """
532 """
533 if cursor is None:
533 if cursor is None:
534 cursor = self._get_cursor()
534 cursor = self._get_cursor()
535 cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
535 cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
536 QtGui.QTextCursor.KeepAnchor)
536 QtGui.QTextCursor.KeepAnchor)
537 text = unicode(cursor.selection().toPlainText())
537 text = unicode(cursor.selection().toPlainText())
538 return self._completion_lexer.get_context(text)
538 return self._completion_lexer.get_context(text)
539
539
540 def _process_execute_abort(self, msg):
540 def _process_execute_abort(self, msg):
541 """ Process a reply for an aborted execution request.
541 """ Process a reply for an aborted execution request.
542 """
542 """
543 self._append_plain_text("ERROR: execution aborted\n")
543 self._append_plain_text("ERROR: execution aborted\n")
544
544
545 def _process_execute_error(self, msg):
545 def _process_execute_error(self, msg):
546 """ Process a reply for an execution request that resulted in an error.
546 """ Process a reply for an execution request that resulted in an error.
547 """
547 """
548 content = msg['content']
548 content = msg['content']
549 # If a SystemExit is passed along, this means exit() was called - also
549 # If a SystemExit is passed along, this means exit() was called - also
550 # all the ipython %exit magic syntax of '-k' to be used to keep
550 # all the ipython %exit magic syntax of '-k' to be used to keep
551 # the kernel running
551 # the kernel running
552 if content['ename']=='SystemExit':
552 if content['ename']=='SystemExit':
553 keepkernel = content['evalue']=='-k' or content['evalue']=='True'
553 keepkernel = content['evalue']=='-k' or content['evalue']=='True'
554 self._keep_kernel_on_exit = keepkernel
554 self._keep_kernel_on_exit = keepkernel
555 self.exit_requested.emit()
555 self.exit_requested.emit()
556 else:
556 else:
557 traceback = ''.join(content['traceback'])
557 traceback = ''.join(content['traceback'])
558 self._append_plain_text(traceback)
558 self._append_plain_text(traceback)
559
559
560 def _process_execute_ok(self, msg):
560 def _process_execute_ok(self, msg):
561 """ Process a reply for a successful execution equest.
561 """ Process a reply for a successful execution equest.
562 """
562 """
563 payload = msg['content']['payload']
563 payload = msg['content']['payload']
564 for item in payload:
564 for item in payload:
565 if not self._process_execute_payload(item):
565 if not self._process_execute_payload(item):
566 warning = 'Warning: received unknown payload of type %s'
566 warning = 'Warning: received unknown payload of type %s'
567 print(warning % repr(item['source']))
567 print(warning % repr(item['source']))
568
568
569 def _process_execute_payload(self, item):
569 def _process_execute_payload(self, item):
570 """ Process a single payload item from the list of payload items in an
570 """ Process a single payload item from the list of payload items in an
571 execution reply. Returns whether the payload was handled.
571 execution reply. Returns whether the payload was handled.
572 """
572 """
573 # The basic FrontendWidget doesn't handle payloads, as they are a
573 # The basic FrontendWidget doesn't handle payloads, as they are a
574 # mechanism for going beyond the standard Python interpreter model.
574 # mechanism for going beyond the standard Python interpreter model.
575 return False
575 return False
576
576
577 def _show_interpreter_prompt(self):
577 def _show_interpreter_prompt(self):
578 """ Shows a prompt for the interpreter.
578 """ Shows a prompt for the interpreter.
579 """
579 """
580 self._show_prompt('>>> ')
580 self._show_prompt('>>> ')
581
581
582 def _show_interpreter_prompt_for_reply(self, msg):
582 def _show_interpreter_prompt_for_reply(self, msg):
583 """ Shows a prompt for the interpreter given an 'execute_reply' message.
583 """ Shows a prompt for the interpreter given an 'execute_reply' message.
584 """
584 """
585 self._show_interpreter_prompt()
585 self._show_interpreter_prompt()
586
586
587 #------ Signal handlers ----------------------------------------------------
587 #------ Signal handlers ----------------------------------------------------
588
588
589 def _document_contents_change(self, position, removed, added):
589 def _document_contents_change(self, position, removed, added):
590 """ Called whenever the document's content changes. Display a call tip
590 """ Called whenever the document's content changes. Display a call tip
591 if appropriate.
591 if appropriate.
592 """
592 """
593 # Calculate where the cursor should be *after* the change:
593 # Calculate where the cursor should be *after* the change:
594 position += added
594 position += added
595
595
596 document = self._control.document()
596 document = self._control.document()
597 if position == self._get_cursor().position():
597 if position == self._get_cursor().position():
598 self._call_tip()
598 self._call_tip()
@@ -1,467 +1,497 b''
1 """ A FrontendWidget that emulates the interface of the console IPython and
1 """ A FrontendWidget that emulates the interface of the console IPython and
2 supports the additional functionality provided by the IPython kernel.
2 supports the additional functionality provided by the IPython kernel.
3
3
4 TODO: Add support for retrieving the system default editor. Requires code
4 TODO: Add support for retrieving the system default editor. Requires code
5 paths for Windows (use the registry), Mac OS (use LaunchServices), and
5 paths for Windows (use the registry), Mac OS (use LaunchServices), and
6 Linux (use the xdg system).
6 Linux (use the xdg system).
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Imports
10 # Imports
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 # Standard library imports
13 # Standard library imports
14 from collections import namedtuple
14 from collections import namedtuple
15 import re
15 import re
16 from subprocess import Popen
16 from subprocess import Popen
17 from textwrap import dedent
17 from textwrap import dedent
18
18
19 # System library imports
19 # System library imports
20 from PyQt4 import QtCore, QtGui
20 from PyQt4 import QtCore, QtGui
21
21
22 # Local imports
22 # Local imports
23 from IPython.core.inputsplitter import IPythonInputSplitter, \
23 from IPython.core.inputsplitter import IPythonInputSplitter, \
24 transform_ipy_prompt
24 transform_ipy_prompt
25 from IPython.core.usage import default_gui_banner
25 from IPython.core.usage import default_gui_banner
26 from IPython.utils.traitlets import Bool, Str
26 from IPython.utils.traitlets import Bool, Str
27 from frontend_widget import FrontendWidget
27 from frontend_widget import FrontendWidget
28 from styles import (default_light_style_sheet, default_light_syntax_style,
28 from styles import (default_light_style_sheet, default_light_syntax_style,
29 default_dark_style_sheet, default_dark_syntax_style,
29 default_dark_style_sheet, default_dark_syntax_style,
30 default_bw_style_sheet, default_bw_syntax_style)
30 default_bw_style_sheet, default_bw_syntax_style)
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Constants
33 # Constants
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36 # Default strings to build and display input and output prompts (and separators
36 # Default strings to build and display input and output prompts (and separators
37 # in between)
37 # in between)
38 default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
38 default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
39 default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
39 default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
40 default_input_sep = '\n'
40 default_input_sep = '\n'
41 default_output_sep = ''
41 default_output_sep = ''
42 default_output_sep2 = ''
42 default_output_sep2 = ''
43
43
44 # Base path for most payload sources.
44 # Base path for most payload sources.
45 zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell'
45 zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell'
46
46
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48 # IPythonWidget class
48 # IPythonWidget class
49 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
50
50
51 class IPythonWidget(FrontendWidget):
51 class IPythonWidget(FrontendWidget):
52 """ A FrontendWidget for an IPython kernel.
52 """ A FrontendWidget for an IPython kernel.
53 """
53 """
54
54
55 # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
55 # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
56 # an editor is needed for a file. This overrides 'editor' and 'editor_line'
56 # an editor is needed for a file. This overrides 'editor' and 'editor_line'
57 # settings.
57 # settings.
58 custom_edit = Bool(False)
58 custom_edit = Bool(False)
59 custom_edit_requested = QtCore.pyqtSignal(object, object)
59 custom_edit_requested = QtCore.pyqtSignal(object, object)
60
60
61 # A command for invoking a system text editor. If the string contains a
61 # A command for invoking a system text editor. If the string contains a
62 # {filename} format specifier, it will be used. Otherwise, the filename will
62 # {filename} format specifier, it will be used. Otherwise, the filename will
63 # be appended to the end the command.
63 # be appended to the end the command.
64 editor = Str('default', config=True)
64 editor = Str('default', config=True)
65
65
66 # The editor command to use when a specific line number is requested. The
66 # The editor command to use when a specific line number is requested. The
67 # string should contain two format specifiers: {line} and {filename}. If
67 # string should contain two format specifiers: {line} and {filename}. If
68 # this parameter is not specified, the line number option to the %edit magic
68 # this parameter is not specified, the line number option to the %edit magic
69 # will be ignored.
69 # will be ignored.
70 editor_line = Str(config=True)
70 editor_line = Str(config=True)
71
71
72 # A CSS stylesheet. The stylesheet can contain classes for:
72 # A CSS stylesheet. The stylesheet can contain classes for:
73 # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
73 # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
74 # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
74 # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
75 # 3. IPython: .error, .in-prompt, .out-prompt, etc
75 # 3. IPython: .error, .in-prompt, .out-prompt, etc
76 style_sheet = Str(config=True)
76 style_sheet = Str(config=True)
77
77
78 # If not empty, use this Pygments style for syntax highlighting. Otherwise,
78 # If not empty, use this Pygments style for syntax highlighting. Otherwise,
79 # the style sheet is queried for Pygments style information.
79 # the style sheet is queried for Pygments style information.
80 syntax_style = Str(config=True)
80 syntax_style = Str(config=True)
81
81
82 # Prompts.
82 # Prompts.
83 in_prompt = Str(default_in_prompt, config=True)
83 in_prompt = Str(default_in_prompt, config=True)
84 out_prompt = Str(default_out_prompt, config=True)
84 out_prompt = Str(default_out_prompt, config=True)
85 input_sep = Str(default_input_sep, config=True)
85 input_sep = Str(default_input_sep, config=True)
86 output_sep = Str(default_output_sep, config=True)
86 output_sep = Str(default_output_sep, config=True)
87 output_sep2 = Str(default_output_sep2, config=True)
87 output_sep2 = Str(default_output_sep2, config=True)
88
88
89 # FrontendWidget protected class variables.
89 # FrontendWidget protected class variables.
90 _input_splitter_class = IPythonInputSplitter
90 _input_splitter_class = IPythonInputSplitter
91
91
92 # IPythonWidget protected class variables.
92 # IPythonWidget protected class variables.
93 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
93 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
94 _payload_source_edit = zmq_shell_source + '.edit_magic'
94 _payload_source_edit = zmq_shell_source + '.edit_magic'
95 _payload_source_exit = zmq_shell_source + '.ask_exit'
95 _payload_source_exit = zmq_shell_source + '.ask_exit'
96 _payload_source_loadpy = zmq_shell_source + '.magic_loadpy'
96 _payload_source_loadpy = zmq_shell_source + '.magic_loadpy'
97 _payload_source_page = 'IPython.zmq.page.page'
97 _payload_source_page = 'IPython.zmq.page.page'
98
98
99 #---------------------------------------------------------------------------
99 #---------------------------------------------------------------------------
100 # 'object' interface
100 # 'object' interface
101 #---------------------------------------------------------------------------
101 #---------------------------------------------------------------------------
102
102
103 def __init__(self, *args, **kw):
103 def __init__(self, *args, **kw):
104 super(IPythonWidget, self).__init__(*args, **kw)
104 super(IPythonWidget, self).__init__(*args, **kw)
105
105
106 # IPythonWidget protected variables.
106 # IPythonWidget protected variables.
107 self._code_to_load = None
107 self._code_to_load = None
108 self._payload_handlers = {
108 self._payload_handlers = {
109 self._payload_source_edit : self._handle_payload_edit,
109 self._payload_source_edit : self._handle_payload_edit,
110 self._payload_source_exit : self._handle_payload_exit,
110 self._payload_source_exit : self._handle_payload_exit,
111 self._payload_source_page : self._handle_payload_page,
111 self._payload_source_page : self._handle_payload_page,
112 self._payload_source_loadpy : self._handle_payload_loadpy }
112 self._payload_source_loadpy : self._handle_payload_loadpy }
113 self._previous_prompt_obj = None
113 self._previous_prompt_obj = None
114 self._keep_kernel_on_exit = None
114 self._keep_kernel_on_exit = None
115
115
116 # Initialize widget styling.
116 # Initialize widget styling.
117 if self.style_sheet:
117 if self.style_sheet:
118 self._style_sheet_changed()
118 self._style_sheet_changed()
119 self._syntax_style_changed()
119 self._syntax_style_changed()
120 else:
120 else:
121 self.set_default_style()
121 self.set_default_style()
122
122
123 #---------------------------------------------------------------------------
123 #---------------------------------------------------------------------------
124 # 'BaseFrontendMixin' abstract interface
124 # 'BaseFrontendMixin' abstract interface
125 #---------------------------------------------------------------------------
125 #---------------------------------------------------------------------------
126
126
127 def _handle_complete_reply(self, rep):
127 def _handle_complete_reply(self, rep):
128 """ Reimplemented to support IPython's improved completion machinery.
128 """ Reimplemented to support IPython's improved completion machinery.
129 """
129 """
130 cursor = self._get_cursor()
130 cursor = self._get_cursor()
131 info = self._request_info.get('complete')
131 info = self._request_info.get('complete')
132 if info and info.id == rep['parent_header']['msg_id'] and \
132 if info and info.id == rep['parent_header']['msg_id'] and \
133 info.pos == cursor.position():
133 info.pos == cursor.position():
134 matches = rep['content']['matches']
134 matches = rep['content']['matches']
135 text = rep['content']['matched_text']
135 text = rep['content']['matched_text']
136 offset = len(text)
136 offset = len(text)
137
137
138 # Clean up matches with period and path separators if the matched
138 # Clean up matches with period and path separators if the matched
139 # text has not been transformed. This is done by truncating all
139 # text has not been transformed. This is done by truncating all
140 # but the last component and then suitably decreasing the offset
140 # but the last component and then suitably decreasing the offset
141 # between the current cursor position and the start of completion.
141 # between the current cursor position and the start of completion.
142 if len(matches) > 1 and matches[0][:offset] == text:
142 if len(matches) > 1 and matches[0][:offset] == text:
143 parts = re.split(r'[./\\]', text)
143 parts = re.split(r'[./\\]', text)
144 sep_count = len(parts) - 1
144 sep_count = len(parts) - 1
145 if sep_count:
145 if sep_count:
146 chop_length = sum(map(len, parts[:sep_count])) + sep_count
146 chop_length = sum(map(len, parts[:sep_count])) + sep_count
147 matches = [ match[chop_length:] for match in matches ]
147 matches = [ match[chop_length:] for match in matches ]
148 offset -= chop_length
148 offset -= chop_length
149
149
150 # Move the cursor to the start of the match and complete.
150 # Move the cursor to the start of the match and complete.
151 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
151 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
152 self._complete_with_items(cursor, matches)
152 self._complete_with_items(cursor, matches)
153
153
154 def _handle_execute_reply(self, msg):
154 def _handle_execute_reply(self, msg):
155 """ Reimplemented to support prompt requests.
155 """ Reimplemented to support prompt requests.
156 """
156 """
157 info = self._request_info.get('execute')
157 info = self._request_info.get('execute')
158 if info and info.id == msg['parent_header']['msg_id']:
158 if info and info.id == msg['parent_header']['msg_id']:
159 if info.kind == 'prompt':
159 if info.kind == 'prompt':
160 number = msg['content']['execution_count'] + 1
160 number = msg['content']['execution_count'] + 1
161 self._show_interpreter_prompt(number)
161 self._show_interpreter_prompt(number)
162 else:
162 else:
163 super(IPythonWidget, self)._handle_execute_reply(msg)
163 super(IPythonWidget, self)._handle_execute_reply(msg)
164
164
165 def _handle_history_reply(self, msg):
165 def _handle_history_reply(self, msg):
166 """ Implemented to handle history replies, which are only supported by
166 """ Implemented to handle history replies, which are only supported by
167 the IPython kernel.
167 the IPython kernel.
168 """
168 """
169 history_dict = msg['content']['history']
169 history_dict = msg['content']['history']
170 input_history_dict = {}
170 input_history_dict = {}
171 for key,val in history_dict.items():
171 for key,val in history_dict.items():
172 input_history_dict[int(key)] = val
172 input_history_dict[int(key)] = val
173 items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ]
173 items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ]
174 self._set_history(items)
174 self._set_history(items)
175
175
176 def _handle_pyout(self, msg):
176 def _handle_pyout(self, msg):
177 """ Reimplemented for IPython-style "display hook".
177 """ Reimplemented for IPython-style "display hook".
178 """
178 """
179 if not self._hidden and self._is_from_this_session(msg):
179 if not self._hidden and self._is_from_this_session(msg):
180 content = msg['content']
180 content = msg['content']
181 prompt_number = content['execution_count']
181 prompt_number = content['execution_count']
182 self._append_plain_text(self.output_sep)
182 data = content['data']
183 self._append_html(self._make_out_prompt(prompt_number))
183 if data.has_key('text/html'):
184 self._append_plain_text(content['data']+self.output_sep2)
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 def _started_channels(self):
216 def _started_channels(self):
187 """ Reimplemented to make a history request.
217 """ Reimplemented to make a history request.
188 """
218 """
189 super(IPythonWidget, self)._started_channels()
219 super(IPythonWidget, self)._started_channels()
190 self.kernel_manager.xreq_channel.history(raw=True, output=False)
220 self.kernel_manager.xreq_channel.history(raw=True, output=False)
191
221
192 #---------------------------------------------------------------------------
222 #---------------------------------------------------------------------------
193 # 'ConsoleWidget' public interface
223 # 'ConsoleWidget' public interface
194 #---------------------------------------------------------------------------
224 #---------------------------------------------------------------------------
195
225
196 def copy(self):
226 def copy(self):
197 """ Copy the currently selected text to the clipboard, removing prompts
227 """ Copy the currently selected text to the clipboard, removing prompts
198 if possible.
228 if possible.
199 """
229 """
200 text = unicode(self._control.textCursor().selection().toPlainText())
230 text = unicode(self._control.textCursor().selection().toPlainText())
201 if text:
231 if text:
202 lines = map(transform_ipy_prompt, text.splitlines())
232 lines = map(transform_ipy_prompt, text.splitlines())
203 text = '\n'.join(lines)
233 text = '\n'.join(lines)
204 QtGui.QApplication.clipboard().setText(text)
234 QtGui.QApplication.clipboard().setText(text)
205
235
206 #---------------------------------------------------------------------------
236 #---------------------------------------------------------------------------
207 # 'FrontendWidget' public interface
237 # 'FrontendWidget' public interface
208 #---------------------------------------------------------------------------
238 #---------------------------------------------------------------------------
209
239
210 def execute_file(self, path, hidden=False):
240 def execute_file(self, path, hidden=False):
211 """ Reimplemented to use the 'run' magic.
241 """ Reimplemented to use the 'run' magic.
212 """
242 """
213 self.execute('%%run %s' % path, hidden=hidden)
243 self.execute('%%run %s' % path, hidden=hidden)
214
244
215 #---------------------------------------------------------------------------
245 #---------------------------------------------------------------------------
216 # 'FrontendWidget' protected interface
246 # 'FrontendWidget' protected interface
217 #---------------------------------------------------------------------------
247 #---------------------------------------------------------------------------
218
248
219 def _complete(self):
249 def _complete(self):
220 """ Reimplemented to support IPython's improved completion machinery.
250 """ Reimplemented to support IPython's improved completion machinery.
221 """
251 """
222 # We let the kernel split the input line, so we *always* send an empty
252 # We let the kernel split the input line, so we *always* send an empty
223 # text field. Readline-based frontends do get a real text field which
253 # text field. Readline-based frontends do get a real text field which
224 # they can use.
254 # they can use.
225 text = ''
255 text = ''
226
256
227 # Send the completion request to the kernel
257 # Send the completion request to the kernel
228 msg_id = self.kernel_manager.xreq_channel.complete(
258 msg_id = self.kernel_manager.xreq_channel.complete(
229 text, # text
259 text, # text
230 self._get_input_buffer_cursor_line(), # line
260 self._get_input_buffer_cursor_line(), # line
231 self._get_input_buffer_cursor_column(), # cursor_pos
261 self._get_input_buffer_cursor_column(), # cursor_pos
232 self.input_buffer) # block
262 self.input_buffer) # block
233 pos = self._get_cursor().position()
263 pos = self._get_cursor().position()
234 info = self._CompletionRequest(msg_id, pos)
264 info = self._CompletionRequest(msg_id, pos)
235 self._request_info['complete'] = info
265 self._request_info['complete'] = info
236
266
237 def _get_banner(self):
267 def _get_banner(self):
238 """ Reimplemented to return IPython's default banner.
268 """ Reimplemented to return IPython's default banner.
239 """
269 """
240 return default_gui_banner
270 return default_gui_banner
241
271
242 def _process_execute_error(self, msg):
272 def _process_execute_error(self, msg):
243 """ Reimplemented for IPython-style traceback formatting.
273 """ Reimplemented for IPython-style traceback formatting.
244 """
274 """
245 content = msg['content']
275 content = msg['content']
246 traceback = '\n'.join(content['traceback']) + '\n'
276 traceback = '\n'.join(content['traceback']) + '\n'
247 if False:
277 if False:
248 # FIXME: For now, tracebacks come as plain text, so we can't use
278 # FIXME: For now, tracebacks come as plain text, so we can't use
249 # the html renderer yet. Once we refactor ultratb to produce
279 # the html renderer yet. Once we refactor ultratb to produce
250 # properly styled tracebacks, this branch should be the default
280 # properly styled tracebacks, this branch should be the default
251 traceback = traceback.replace(' ', '&nbsp;')
281 traceback = traceback.replace(' ', '&nbsp;')
252 traceback = traceback.replace('\n', '<br/>')
282 traceback = traceback.replace('\n', '<br/>')
253
283
254 ename = content['ename']
284 ename = content['ename']
255 ename_styled = '<span class="error">%s</span>' % ename
285 ename_styled = '<span class="error">%s</span>' % ename
256 traceback = traceback.replace(ename, ename_styled)
286 traceback = traceback.replace(ename, ename_styled)
257
287
258 self._append_html(traceback)
288 self._append_html(traceback)
259 else:
289 else:
260 # This is the fallback for now, using plain text with ansi escapes
290 # This is the fallback for now, using plain text with ansi escapes
261 self._append_plain_text(traceback)
291 self._append_plain_text(traceback)
262
292
263 def _process_execute_payload(self, item):
293 def _process_execute_payload(self, item):
264 """ Reimplemented to dispatch payloads to handler methods.
294 """ Reimplemented to dispatch payloads to handler methods.
265 """
295 """
266 handler = self._payload_handlers.get(item['source'])
296 handler = self._payload_handlers.get(item['source'])
267 if handler is None:
297 if handler is None:
268 # We have no handler for this type of payload, simply ignore it
298 # We have no handler for this type of payload, simply ignore it
269 return False
299 return False
270 else:
300 else:
271 handler(item)
301 handler(item)
272 return True
302 return True
273
303
274 def _show_interpreter_prompt(self, number=None):
304 def _show_interpreter_prompt(self, number=None):
275 """ Reimplemented for IPython-style prompts.
305 """ Reimplemented for IPython-style prompts.
276 """
306 """
277 # If a number was not specified, make a prompt number request.
307 # If a number was not specified, make a prompt number request.
278 if number is None:
308 if number is None:
279 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
309 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
280 info = self._ExecutionRequest(msg_id, 'prompt')
310 info = self._ExecutionRequest(msg_id, 'prompt')
281 self._request_info['execute'] = info
311 self._request_info['execute'] = info
282 return
312 return
283
313
284 # Show a new prompt and save information about it so that it can be
314 # Show a new prompt and save information about it so that it can be
285 # updated later if the prompt number turns out to be wrong.
315 # updated later if the prompt number turns out to be wrong.
286 self._prompt_sep = self.input_sep
316 self._prompt_sep = self.input_sep
287 self._show_prompt(self._make_in_prompt(number), html=True)
317 self._show_prompt(self._make_in_prompt(number), html=True)
288 block = self._control.document().lastBlock()
318 block = self._control.document().lastBlock()
289 length = len(self._prompt)
319 length = len(self._prompt)
290 self._previous_prompt_obj = self._PromptBlock(block, length, number)
320 self._previous_prompt_obj = self._PromptBlock(block, length, number)
291
321
292 # Update continuation prompt to reflect (possibly) new prompt length.
322 # Update continuation prompt to reflect (possibly) new prompt length.
293 self._set_continuation_prompt(
323 self._set_continuation_prompt(
294 self._make_continuation_prompt(self._prompt), html=True)
324 self._make_continuation_prompt(self._prompt), html=True)
295
325
296 # Load code from the %loadpy magic, if necessary.
326 # Load code from the %loadpy magic, if necessary.
297 if self._code_to_load is not None:
327 if self._code_to_load is not None:
298 self.input_buffer = dedent(unicode(self._code_to_load).rstrip())
328 self.input_buffer = dedent(unicode(self._code_to_load).rstrip())
299 self._code_to_load = None
329 self._code_to_load = None
300
330
301 def _show_interpreter_prompt_for_reply(self, msg):
331 def _show_interpreter_prompt_for_reply(self, msg):
302 """ Reimplemented for IPython-style prompts.
332 """ Reimplemented for IPython-style prompts.
303 """
333 """
304 # Update the old prompt number if necessary.
334 # Update the old prompt number if necessary.
305 content = msg['content']
335 content = msg['content']
306 previous_prompt_number = content['execution_count']
336 previous_prompt_number = content['execution_count']
307 if self._previous_prompt_obj and \
337 if self._previous_prompt_obj and \
308 self._previous_prompt_obj.number != previous_prompt_number:
338 self._previous_prompt_obj.number != previous_prompt_number:
309 block = self._previous_prompt_obj.block
339 block = self._previous_prompt_obj.block
310
340
311 # Make sure the prompt block has not been erased.
341 # Make sure the prompt block has not been erased.
312 if block.isValid() and not block.text().isEmpty():
342 if block.isValid() and not block.text().isEmpty():
313
343
314 # Remove the old prompt and insert a new prompt.
344 # Remove the old prompt and insert a new prompt.
315 cursor = QtGui.QTextCursor(block)
345 cursor = QtGui.QTextCursor(block)
316 cursor.movePosition(QtGui.QTextCursor.Right,
346 cursor.movePosition(QtGui.QTextCursor.Right,
317 QtGui.QTextCursor.KeepAnchor,
347 QtGui.QTextCursor.KeepAnchor,
318 self._previous_prompt_obj.length)
348 self._previous_prompt_obj.length)
319 prompt = self._make_in_prompt(previous_prompt_number)
349 prompt = self._make_in_prompt(previous_prompt_number)
320 self._prompt = self._insert_html_fetching_plain_text(
350 self._prompt = self._insert_html_fetching_plain_text(
321 cursor, prompt)
351 cursor, prompt)
322
352
323 # When the HTML is inserted, Qt blows away the syntax
353 # When the HTML is inserted, Qt blows away the syntax
324 # highlighting for the line, so we need to rehighlight it.
354 # highlighting for the line, so we need to rehighlight it.
325 self._highlighter.rehighlightBlock(cursor.block())
355 self._highlighter.rehighlightBlock(cursor.block())
326
356
327 self._previous_prompt_obj = None
357 self._previous_prompt_obj = None
328
358
329 # Show a new prompt with the kernel's estimated prompt number.
359 # Show a new prompt with the kernel's estimated prompt number.
330 self._show_interpreter_prompt(previous_prompt_number + 1)
360 self._show_interpreter_prompt(previous_prompt_number + 1)
331
361
332 #---------------------------------------------------------------------------
362 #---------------------------------------------------------------------------
333 # 'IPythonWidget' interface
363 # 'IPythonWidget' interface
334 #---------------------------------------------------------------------------
364 #---------------------------------------------------------------------------
335
365
336 def set_default_style(self, colors='lightbg'):
366 def set_default_style(self, colors='lightbg'):
337 """ Sets the widget style to the class defaults.
367 """ Sets the widget style to the class defaults.
338
368
339 Parameters:
369 Parameters:
340 -----------
370 -----------
341 colors : str, optional (default lightbg)
371 colors : str, optional (default lightbg)
342 Whether to use the default IPython light background or dark
372 Whether to use the default IPython light background or dark
343 background or B&W style.
373 background or B&W style.
344 """
374 """
345 colors = colors.lower()
375 colors = colors.lower()
346 if colors=='lightbg':
376 if colors=='lightbg':
347 self.style_sheet = default_light_style_sheet
377 self.style_sheet = default_light_style_sheet
348 self.syntax_style = default_light_syntax_style
378 self.syntax_style = default_light_syntax_style
349 elif colors=='linux':
379 elif colors=='linux':
350 self.style_sheet = default_dark_style_sheet
380 self.style_sheet = default_dark_style_sheet
351 self.syntax_style = default_dark_syntax_style
381 self.syntax_style = default_dark_syntax_style
352 elif colors=='nocolor':
382 elif colors=='nocolor':
353 self.style_sheet = default_bw_style_sheet
383 self.style_sheet = default_bw_style_sheet
354 self.syntax_style = default_bw_syntax_style
384 self.syntax_style = default_bw_syntax_style
355 else:
385 else:
356 raise KeyError("No such color scheme: %s"%colors)
386 raise KeyError("No such color scheme: %s"%colors)
357
387
358 #---------------------------------------------------------------------------
388 #---------------------------------------------------------------------------
359 # 'IPythonWidget' protected interface
389 # 'IPythonWidget' protected interface
360 #---------------------------------------------------------------------------
390 #---------------------------------------------------------------------------
361
391
362 def _edit(self, filename, line=None):
392 def _edit(self, filename, line=None):
363 """ Opens a Python script for editing.
393 """ Opens a Python script for editing.
364
394
365 Parameters:
395 Parameters:
366 -----------
396 -----------
367 filename : str
397 filename : str
368 A path to a local system file.
398 A path to a local system file.
369
399
370 line : int, optional
400 line : int, optional
371 A line of interest in the file.
401 A line of interest in the file.
372 """
402 """
373 if self.custom_edit:
403 if self.custom_edit:
374 self.custom_edit_requested.emit(filename, line)
404 self.custom_edit_requested.emit(filename, line)
375 elif self.editor == 'default':
405 elif self.editor == 'default':
376 self._append_plain_text('No default editor available.\n')
406 self._append_plain_text('No default editor available.\n')
377 else:
407 else:
378 try:
408 try:
379 filename = '"%s"' % filename
409 filename = '"%s"' % filename
380 if line and self.editor_line:
410 if line and self.editor_line:
381 command = self.editor_line.format(filename=filename,
411 command = self.editor_line.format(filename=filename,
382 line=line)
412 line=line)
383 else:
413 else:
384 try:
414 try:
385 command = self.editor.format()
415 command = self.editor.format()
386 except KeyError:
416 except KeyError:
387 command = self.editor.format(filename=filename)
417 command = self.editor.format(filename=filename)
388 else:
418 else:
389 command += ' ' + filename
419 command += ' ' + filename
390 except KeyError:
420 except KeyError:
391 self._append_plain_text('Invalid editor command.\n')
421 self._append_plain_text('Invalid editor command.\n')
392 else:
422 else:
393 try:
423 try:
394 Popen(command, shell=True)
424 Popen(command, shell=True)
395 except OSError:
425 except OSError:
396 msg = 'Opening editor with command "%s" failed.\n'
426 msg = 'Opening editor with command "%s" failed.\n'
397 self._append_plain_text(msg % command)
427 self._append_plain_text(msg % command)
398
428
399 def _make_in_prompt(self, number):
429 def _make_in_prompt(self, number):
400 """ Given a prompt number, returns an HTML In prompt.
430 """ Given a prompt number, returns an HTML In prompt.
401 """
431 """
402 body = self.in_prompt % number
432 body = self.in_prompt % number
403 return '<span class="in-prompt">%s</span>' % body
433 return '<span class="in-prompt">%s</span>' % body
404
434
405 def _make_continuation_prompt(self, prompt):
435 def _make_continuation_prompt(self, prompt):
406 """ Given a plain text version of an In prompt, returns an HTML
436 """ Given a plain text version of an In prompt, returns an HTML
407 continuation prompt.
437 continuation prompt.
408 """
438 """
409 end_chars = '...: '
439 end_chars = '...: '
410 space_count = len(prompt.lstrip('\n')) - len(end_chars)
440 space_count = len(prompt.lstrip('\n')) - len(end_chars)
411 body = '&nbsp;' * space_count + end_chars
441 body = '&nbsp;' * space_count + end_chars
412 return '<span class="in-prompt">%s</span>' % body
442 return '<span class="in-prompt">%s</span>' % body
413
443
414 def _make_out_prompt(self, number):
444 def _make_out_prompt(self, number):
415 """ Given a prompt number, returns an HTML Out prompt.
445 """ Given a prompt number, returns an HTML Out prompt.
416 """
446 """
417 body = self.out_prompt % number
447 body = self.out_prompt % number
418 return '<span class="out-prompt">%s</span>' % body
448 return '<span class="out-prompt">%s</span>' % body
419
449
420 #------ Payload handlers --------------------------------------------------
450 #------ Payload handlers --------------------------------------------------
421
451
422 # Payload handlers with a generic interface: each takes the opaque payload
452 # Payload handlers with a generic interface: each takes the opaque payload
423 # dict, unpacks it and calls the underlying functions with the necessary
453 # dict, unpacks it and calls the underlying functions with the necessary
424 # arguments.
454 # arguments.
425
455
426 def _handle_payload_edit(self, item):
456 def _handle_payload_edit(self, item):
427 self._edit(item['filename'], item['line_number'])
457 self._edit(item['filename'], item['line_number'])
428
458
429 def _handle_payload_exit(self, item):
459 def _handle_payload_exit(self, item):
430 self._keep_kernel_on_exit = item['keepkernel']
460 self._keep_kernel_on_exit = item['keepkernel']
431 self.exit_requested.emit()
461 self.exit_requested.emit()
432
462
433 def _handle_payload_loadpy(self, item):
463 def _handle_payload_loadpy(self, item):
434 # Simple save the text of the .py file for later. The text is written
464 # Simple save the text of the .py file for later. The text is written
435 # to the buffer when _prompt_started_hook is called.
465 # to the buffer when _prompt_started_hook is called.
436 self._code_to_load = item['text']
466 self._code_to_load = item['text']
437
467
438 def _handle_payload_page(self, item):
468 def _handle_payload_page(self, item):
439 # Since the plain text widget supports only a very small subset of HTML
469 # Since the plain text widget supports only a very small subset of HTML
440 # and we have no control over the HTML source, we only page HTML
470 # and we have no control over the HTML source, we only page HTML
441 # payloads in the rich text widget.
471 # payloads in the rich text widget.
442 if item['html'] and self.kind == 'rich':
472 if item['html'] and self.kind == 'rich':
443 self._page(item['html'], html=True)
473 self._page(item['html'], html=True)
444 else:
474 else:
445 self._page(item['text'], html=False)
475 self._page(item['text'], html=False)
446
476
447 #------ Trait change handlers ---------------------------------------------
477 #------ Trait change handlers --------------------------------------------
448
478
449 def _style_sheet_changed(self):
479 def _style_sheet_changed(self):
450 """ Set the style sheets of the underlying widgets.
480 """ Set the style sheets of the underlying widgets.
451 """
481 """
452 self.setStyleSheet(self.style_sheet)
482 self.setStyleSheet(self.style_sheet)
453 self._control.document().setDefaultStyleSheet(self.style_sheet)
483 self._control.document().setDefaultStyleSheet(self.style_sheet)
454 if self._page_control:
484 if self._page_control:
455 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
485 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
456
486
457 bg_color = self._control.palette().background().color()
487 bg_color = self._control.palette().background().color()
458 self._ansi_processor.set_background_color(bg_color)
488 self._ansi_processor.set_background_color(bg_color)
459
489
460 def _syntax_style_changed(self):
490 def _syntax_style_changed(self):
461 """ Set the style for the syntax highlighter.
491 """ Set the style for the syntax highlighter.
462 """
492 """
463 if self.syntax_style:
493 if self.syntax_style:
464 self._highlighter.set_style(self.syntax_style)
494 self._highlighter.set_style(self.syntax_style)
465 else:
495 else:
466 self._highlighter.set_style_sheet(self.style_sheet)
496 self._highlighter.set_style_sheet(self.style_sheet)
467
497
@@ -1,195 +1,271 b''
1 # System library imports
1 # System library imports
2 import os
2 import os
3 import re
3 import re
4 from base64 import decodestring
4 from PyQt4 import QtCore, QtGui
5 from PyQt4 import QtCore, QtGui
5
6
6 # Local imports
7 # Local imports
7 from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image
8 from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image
8 from ipython_widget import IPythonWidget
9 from ipython_widget import IPythonWidget
9
10
10
11
11 class RichIPythonWidget(IPythonWidget):
12 class RichIPythonWidget(IPythonWidget):
12 """ An IPythonWidget that supports rich text, including lists, images, and
13 """ An IPythonWidget that supports rich text, including lists, images, and
13 tables. Note that raw performance will be reduced compared to the plain
14 tables. Note that raw performance will be reduced compared to the plain
14 text version.
15 text version.
15 """
16 """
16
17
17 # RichIPythonWidget protected class variables.
18 # RichIPythonWidget protected class variables.
18 _payload_source_plot = 'IPython.zmq.pylab.backend_payload.add_plot_payload'
19 _payload_source_plot = 'IPython.zmq.pylab.backend_payload.add_plot_payload'
19 _svg_text_format_property = 1
20 _svg_text_format_property = 1
20
21
21 #---------------------------------------------------------------------------
22 #---------------------------------------------------------------------------
22 # 'object' interface
23 # 'object' interface
23 #---------------------------------------------------------------------------
24 #---------------------------------------------------------------------------
24
25
25 def __init__(self, *args, **kw):
26 def __init__(self, *args, **kw):
26 """ Create a RichIPythonWidget.
27 """ Create a RichIPythonWidget.
27 """
28 """
28 kw['kind'] = 'rich'
29 kw['kind'] = 'rich'
29 super(RichIPythonWidget, self).__init__(*args, **kw)
30 super(RichIPythonWidget, self).__init__(*args, **kw)
30 # Dictionary for resolving Qt names to images when
31 # Dictionary for resolving Qt names to images when
31 # generating XHTML output
32 # generating XHTML output
32 self._name_to_svg = {}
33 self._name_to_svg = {}
33
34
34 #---------------------------------------------------------------------------
35 #---------------------------------------------------------------------------
35 # 'ConsoleWidget' protected interface
36 # 'ConsoleWidget' protected interface
36 #---------------------------------------------------------------------------
37 #---------------------------------------------------------------------------
37
38
38 def _context_menu_make(self, pos):
39 def _context_menu_make(self, pos):
39 """ Reimplemented to return a custom context menu for images.
40 """ Reimplemented to return a custom context menu for images.
40 """
41 """
41 format = self._control.cursorForPosition(pos).charFormat()
42 format = self._control.cursorForPosition(pos).charFormat()
42 name = format.stringProperty(QtGui.QTextFormat.ImageName)
43 name = format.stringProperty(QtGui.QTextFormat.ImageName)
43 if name.isEmpty():
44 if name.isEmpty():
44 menu = super(RichIPythonWidget, self)._context_menu_make(pos)
45 menu = super(RichIPythonWidget, self)._context_menu_make(pos)
45 else:
46 else:
46 menu = QtGui.QMenu()
47 menu = QtGui.QMenu()
47
48
48 menu.addAction('Copy Image', lambda: self._copy_image(name))
49 menu.addAction('Copy Image', lambda: self._copy_image(name))
49 menu.addAction('Save Image As...', lambda: self._save_image(name))
50 menu.addAction('Save Image As...', lambda: self._save_image(name))
50 menu.addSeparator()
51 menu.addSeparator()
51
52
52 svg = format.stringProperty(self._svg_text_format_property)
53 svg = format.stringProperty(self._svg_text_format_property)
53 if not svg.isEmpty():
54 if not svg.isEmpty():
54 menu.addSeparator()
55 menu.addSeparator()
55 menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg))
56 menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg))
56 menu.addAction('Save SVG As...',
57 menu.addAction('Save SVG As...',
57 lambda: save_svg(svg, self._control))
58 lambda: save_svg(svg, self._control))
58 return menu
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 # 'FrontendWidget' protected interface
115 # 'FrontendWidget' protected interface
62 #---------------------------------------------------------------------------
116 #---------------------------------------------------------------------------
63
117
64 def _process_execute_payload(self, item):
118 def _process_execute_payload(self, item):
65 """ Reimplemented to handle matplotlib plot payloads.
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 if item['source'] == self._payload_source_plot:
123 if item['source'] == self._payload_source_plot:
68 if item['format'] == 'svg':
124 if item['format'] == 'svg':
69 svg = item['data']
125 svg = item['data']
70 try:
126 self._append_svg(svg)
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()
82 return True
127 return True
83 else:
128 else:
84 # Add other plot formats here!
129 # Add other plot formats here!
85 return False
130 return False
86 else:
131 else:
87 return super(RichIPythonWidget, self)._process_execute_payload(item)
132 return super(RichIPythonWidget, self)._process_execute_payload(item)
88
133
89 #---------------------------------------------------------------------------
134 #---------------------------------------------------------------------------
90 # 'RichIPythonWidget' protected interface
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 def _add_image(self, image):
169 def _add_image(self, image):
94 """ Adds the specified QImage to the document and returns a
170 """ Adds the specified QImage to the document and returns a
95 QTextImageFormat that references it.
171 QTextImageFormat that references it.
96 """
172 """
97 document = self._control.document()
173 document = self._control.document()
98 name = QtCore.QString.number(image.cacheKey())
174 name = QtCore.QString.number(image.cacheKey())
99 document.addResource(QtGui.QTextDocument.ImageResource,
175 document.addResource(QtGui.QTextDocument.ImageResource,
100 QtCore.QUrl(name), image)
176 QtCore.QUrl(name), image)
101 format = QtGui.QTextImageFormat()
177 format = QtGui.QTextImageFormat()
102 format.setName(name)
178 format.setName(name)
103 return format
179 return format
104
180
105 def _copy_image(self, name):
181 def _copy_image(self, name):
106 """ Copies the ImageResource with 'name' to the clipboard.
182 """ Copies the ImageResource with 'name' to the clipboard.
107 """
183 """
108 image = self._get_image(name)
184 image = self._get_image(name)
109 QtGui.QApplication.clipboard().setImage(image)
185 QtGui.QApplication.clipboard().setImage(image)
110
186
111 def _get_image(self, name):
187 def _get_image(self, name):
112 """ Returns the QImage stored as the ImageResource with 'name'.
188 """ Returns the QImage stored as the ImageResource with 'name'.
113 """
189 """
114 document = self._control.document()
190 document = self._control.document()
115 variant = document.resource(QtGui.QTextDocument.ImageResource,
191 variant = document.resource(QtGui.QTextDocument.ImageResource,
116 QtCore.QUrl(name))
192 QtCore.QUrl(name))
117 return variant.toPyObject()
193 return variant.toPyObject()
118
194
119 def _save_image(self, name, format='PNG'):
195 def _save_image(self, name, format='PNG'):
120 """ Shows a save dialog for the ImageResource with 'name'.
196 """ Shows a save dialog for the ImageResource with 'name'.
121 """
197 """
122 dialog = QtGui.QFileDialog(self._control, 'Save Image')
198 dialog = QtGui.QFileDialog(self._control, 'Save Image')
123 dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
199 dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
124 dialog.setDefaultSuffix(format.lower())
200 dialog.setDefaultSuffix(format.lower())
125 dialog.setNameFilter('%s file (*.%s)' % (format, format.lower()))
201 dialog.setNameFilter('%s file (*.%s)' % (format, format.lower()))
126 if dialog.exec_():
202 if dialog.exec_():
127 filename = dialog.selectedFiles()[0]
203 filename = dialog.selectedFiles()[0]
128 image = self._get_image(name)
204 image = self._get_image(name)
129 image.save(filename, format)
205 image.save(filename, format)
130
206
131 def image_tag(self, match, path = None, format = "png"):
207 def image_tag(self, match, path = None, format = "png"):
132 """ Return (X)HTML mark-up for the image-tag given by match.
208 """ Return (X)HTML mark-up for the image-tag given by match.
133
209
134 Parameters
210 Parameters
135 ----------
211 ----------
136 match : re.SRE_Match
212 match : re.SRE_Match
137 A match to an HTML image tag as exported by Qt, with
213 A match to an HTML image tag as exported by Qt, with
138 match.group("Name") containing the matched image ID.
214 match.group("Name") containing the matched image ID.
139
215
140 path : string|None, optional [default None]
216 path : string|None, optional [default None]
141 If not None, specifies a path to which supporting files
217 If not None, specifies a path to which supporting files
142 may be written (e.g., for linked images).
218 may be written (e.g., for linked images).
143 If None, all images are to be included inline.
219 If None, all images are to be included inline.
144
220
145 format : "png"|"svg", optional [default "png"]
221 format : "png"|"svg", optional [default "png"]
146 Format for returned or referenced images.
222 Format for returned or referenced images.
147
223
148 Subclasses supporting image display should override this
224 Subclasses supporting image display should override this
149 method.
225 method.
150 """
226 """
151
227
152 if(format == "png"):
228 if(format == "png"):
153 try:
229 try:
154 image = self._get_image(match.group("name"))
230 image = self._get_image(match.group("name"))
155 except KeyError:
231 except KeyError:
156 return "<b>Couldn't find image %s</b>" % match.group("name")
232 return "<b>Couldn't find image %s</b>" % match.group("name")
157
233
158 if(path is not None):
234 if(path is not None):
159 if not os.path.exists(path):
235 if not os.path.exists(path):
160 os.mkdir(path)
236 os.mkdir(path)
161 relpath = os.path.basename(path)
237 relpath = os.path.basename(path)
162 if(image.save("%s/qt_img%s.png" % (path,match.group("name")),
238 if(image.save("%s/qt_img%s.png" % (path,match.group("name")),
163 "PNG")):
239 "PNG")):
164 return '<img src="%s/qt_img%s.png">' % (relpath,
240 return '<img src="%s/qt_img%s.png">' % (relpath,
165 match.group("name"))
241 match.group("name"))
166 else:
242 else:
167 return "<b>Couldn't save image!</b>"
243 return "<b>Couldn't save image!</b>"
168 else:
244 else:
169 ba = QtCore.QByteArray()
245 ba = QtCore.QByteArray()
170 buffer_ = QtCore.QBuffer(ba)
246 buffer_ = QtCore.QBuffer(ba)
171 buffer_.open(QtCore.QIODevice.WriteOnly)
247 buffer_.open(QtCore.QIODevice.WriteOnly)
172 image.save(buffer_, "PNG")
248 image.save(buffer_, "PNG")
173 buffer_.close()
249 buffer_.close()
174 return '<img src="data:image/png;base64,\n%s\n" />' % (
250 return '<img src="data:image/png;base64,\n%s\n" />' % (
175 re.sub(r'(.{60})',r'\1\n',str(ba.toBase64())))
251 re.sub(r'(.{60})',r'\1\n',str(ba.toBase64())))
176
252
177 elif(format == "svg"):
253 elif(format == "svg"):
178 try:
254 try:
179 svg = str(self._name_to_svg[match.group("name")])
255 svg = str(self._name_to_svg[match.group("name")])
180 except KeyError:
256 except KeyError:
181 return "<b>Couldn't find image %s</b>" % match.group("name")
257 return "<b>Couldn't find image %s</b>" % match.group("name")
182
258
183 # Not currently checking path, because it's tricky to find a
259 # Not currently checking path, because it's tricky to find a
184 # cross-browser way to embed external SVG images (e.g., via
260 # cross-browser way to embed external SVG images (e.g., via
185 # object or embed tags).
261 # object or embed tags).
186
262
187 # Chop stand-alone header from matplotlib SVG
263 # Chop stand-alone header from matplotlib SVG
188 offset = svg.find("<svg")
264 offset = svg.find("<svg")
189 assert(offset > -1)
265 assert(offset > -1)
190
266
191 return svg[offset:]
267 return svg[offset:]
192
268
193 else:
269 else:
194 return '<b>Unrecognized image format</b>'
270 return '<b>Unrecognized image format</b>'
195
271
@@ -1,240 +1,242 b''
1 """ Defines a KernelManager that provides signals and slots.
1 """ Defines a KernelManager that provides signals and slots.
2 """
2 """
3
3
4 # System library imports.
4 # System library imports.
5 from PyQt4 import QtCore
5 from PyQt4 import QtCore
6
6
7 # IPython imports.
7 # IPython imports.
8 from IPython.utils.traitlets import Type
8 from IPython.utils.traitlets import Type
9 from IPython.zmq.kernelmanager import KernelManager, SubSocketChannel, \
9 from IPython.zmq.kernelmanager import KernelManager, SubSocketChannel, \
10 XReqSocketChannel, RepSocketChannel, HBSocketChannel
10 XReqSocketChannel, RepSocketChannel, HBSocketChannel
11 from util import MetaQObjectHasTraits, SuperQObject
11 from util import MetaQObjectHasTraits, SuperQObject
12
12
13
13
14 class SocketChannelQObject(SuperQObject):
14 class SocketChannelQObject(SuperQObject):
15
15
16 # Emitted when the channel is started.
16 # Emitted when the channel is started.
17 started = QtCore.pyqtSignal()
17 started = QtCore.pyqtSignal()
18
18
19 # Emitted when the channel is stopped.
19 # Emitted when the channel is stopped.
20 stopped = QtCore.pyqtSignal()
20 stopped = QtCore.pyqtSignal()
21
21
22 #---------------------------------------------------------------------------
22 #---------------------------------------------------------------------------
23 # 'ZmqSocketChannel' interface
23 # 'ZmqSocketChannel' interface
24 #---------------------------------------------------------------------------
24 #---------------------------------------------------------------------------
25
25
26 def start(self):
26 def start(self):
27 """ Reimplemented to emit signal.
27 """ Reimplemented to emit signal.
28 """
28 """
29 super(SocketChannelQObject, self).start()
29 super(SocketChannelQObject, self).start()
30 self.started.emit()
30 self.started.emit()
31
31
32 def stop(self):
32 def stop(self):
33 """ Reimplemented to emit signal.
33 """ Reimplemented to emit signal.
34 """
34 """
35 super(SocketChannelQObject, self).stop()
35 super(SocketChannelQObject, self).stop()
36 self.stopped.emit()
36 self.stopped.emit()
37
37
38
38
39 class QtXReqSocketChannel(SocketChannelQObject, XReqSocketChannel):
39 class QtXReqSocketChannel(SocketChannelQObject, XReqSocketChannel):
40
40
41 # Emitted when any message is received.
41 # Emitted when any message is received.
42 message_received = QtCore.pyqtSignal(object)
42 message_received = QtCore.pyqtSignal(object)
43
43
44 # Emitted when a reply has been received for the corresponding request
44 # Emitted when a reply has been received for the corresponding request
45 # type.
45 # type.
46 execute_reply = QtCore.pyqtSignal(object)
46 execute_reply = QtCore.pyqtSignal(object)
47 complete_reply = QtCore.pyqtSignal(object)
47 complete_reply = QtCore.pyqtSignal(object)
48 object_info_reply = QtCore.pyqtSignal(object)
48 object_info_reply = QtCore.pyqtSignal(object)
49
49
50 # Emitted when the first reply comes back.
50 # Emitted when the first reply comes back.
51 first_reply = QtCore.pyqtSignal()
51 first_reply = QtCore.pyqtSignal()
52
52
53 # Used by the first_reply signal logic to determine if a reply is the
53 # Used by the first_reply signal logic to determine if a reply is the
54 # first.
54 # first.
55 _handlers_called = False
55 _handlers_called = False
56
56
57 #---------------------------------------------------------------------------
57 #---------------------------------------------------------------------------
58 # 'XReqSocketChannel' interface
58 # 'XReqSocketChannel' interface
59 #---------------------------------------------------------------------------
59 #---------------------------------------------------------------------------
60
60
61 def call_handlers(self, msg):
61 def call_handlers(self, msg):
62 """ Reimplemented to emit signals instead of making callbacks.
62 """ Reimplemented to emit signals instead of making callbacks.
63 """
63 """
64 # Emit the generic signal.
64 # Emit the generic signal.
65 self.message_received.emit(msg)
65 self.message_received.emit(msg)
66
66
67 # Emit signals for specialized message types.
67 # Emit signals for specialized message types.
68 msg_type = msg['msg_type']
68 msg_type = msg['msg_type']
69 signal = getattr(self, msg_type, None)
69 signal = getattr(self, msg_type, None)
70 if signal:
70 if signal:
71 signal.emit(msg)
71 signal.emit(msg)
72
72
73 if not self._handlers_called:
73 if not self._handlers_called:
74 self.first_reply.emit()
74 self.first_reply.emit()
75 self._handlers_called = True
75 self._handlers_called = True
76
76
77 #---------------------------------------------------------------------------
77 #---------------------------------------------------------------------------
78 # 'QtXReqSocketChannel' interface
78 # 'QtXReqSocketChannel' interface
79 #---------------------------------------------------------------------------
79 #---------------------------------------------------------------------------
80
80
81 def reset_first_reply(self):
81 def reset_first_reply(self):
82 """ Reset the first_reply signal to fire again on the next reply.
82 """ Reset the first_reply signal to fire again on the next reply.
83 """
83 """
84 self._handlers_called = False
84 self._handlers_called = False
85
85
86
86
87 class QtSubSocketChannel(SocketChannelQObject, SubSocketChannel):
87 class QtSubSocketChannel(SocketChannelQObject, SubSocketChannel):
88
88
89 # Emitted when any message is received.
89 # Emitted when any message is received.
90 message_received = QtCore.pyqtSignal(object)
90 message_received = QtCore.pyqtSignal(object)
91
91
92 # Emitted when a message of type 'stream' is received.
92 # Emitted when a message of type 'stream' is received.
93 stream_received = QtCore.pyqtSignal(object)
93 stream_received = QtCore.pyqtSignal(object)
94
94
95 # Emitted when a message of type 'pyin' is received.
95 # Emitted when a message of type 'pyin' is received.
96 pyin_received = QtCore.pyqtSignal(object)
96 pyin_received = QtCore.pyqtSignal(object)
97
97
98 # Emitted when a message of type 'pyout' is received.
98 # Emitted when a message of type 'pyout' is received.
99 pyout_received = QtCore.pyqtSignal(object)
99 pyout_received = QtCore.pyqtSignal(object)
100
100
101 # Emitted when a message of type 'pyerr' is received.
101 # Emitted when a message of type 'pyerr' is received.
102 pyerr_received = QtCore.pyqtSignal(object)
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 # Emitted when a crash report message is received from the kernel's
107 # Emitted when a crash report message is received from the kernel's
105 # last-resort sys.excepthook.
108 # last-resort sys.excepthook.
106 crash_received = QtCore.pyqtSignal(object)
109 crash_received = QtCore.pyqtSignal(object)
107
110
108 # Emitted when a shutdown is noticed.
111 # Emitted when a shutdown is noticed.
109 shutdown_reply_received = QtCore.pyqtSignal(object)
112 shutdown_reply_received = QtCore.pyqtSignal(object)
110
113
111 #---------------------------------------------------------------------------
114 #---------------------------------------------------------------------------
112 # 'SubSocketChannel' interface
115 # 'SubSocketChannel' interface
113 #---------------------------------------------------------------------------
116 #---------------------------------------------------------------------------
114
117
115 def call_handlers(self, msg):
118 def call_handlers(self, msg):
116 """ Reimplemented to emit signals instead of making callbacks.
119 """ Reimplemented to emit signals instead of making callbacks.
117 """
120 """
118 # Emit the generic signal.
121 # Emit the generic signal.
119 self.message_received.emit(msg)
122 self.message_received.emit(msg)
120
121 # Emit signals for specialized message types.
123 # Emit signals for specialized message types.
122 msg_type = msg['msg_type']
124 msg_type = msg['msg_type']
123 signal = getattr(self, msg_type + '_received', None)
125 signal = getattr(self, msg_type + '_received', None)
124 if signal:
126 if signal:
125 signal.emit(msg)
127 signal.emit(msg)
126 elif msg_type in ('stdout', 'stderr'):
128 elif msg_type in ('stdout', 'stderr'):
127 self.stream_received.emit(msg)
129 self.stream_received.emit(msg)
128
130
129 def flush(self):
131 def flush(self):
130 """ Reimplemented to ensure that signals are dispatched immediately.
132 """ Reimplemented to ensure that signals are dispatched immediately.
131 """
133 """
132 super(QtSubSocketChannel, self).flush()
134 super(QtSubSocketChannel, self).flush()
133 QtCore.QCoreApplication.instance().processEvents()
135 QtCore.QCoreApplication.instance().processEvents()
134
136
135
137
136 class QtRepSocketChannel(SocketChannelQObject, RepSocketChannel):
138 class QtRepSocketChannel(SocketChannelQObject, RepSocketChannel):
137
139
138 # Emitted when any message is received.
140 # Emitted when any message is received.
139 message_received = QtCore.pyqtSignal(object)
141 message_received = QtCore.pyqtSignal(object)
140
142
141 # Emitted when an input request is received.
143 # Emitted when an input request is received.
142 input_requested = QtCore.pyqtSignal(object)
144 input_requested = QtCore.pyqtSignal(object)
143
145
144 #---------------------------------------------------------------------------
146 #---------------------------------------------------------------------------
145 # 'RepSocketChannel' interface
147 # 'RepSocketChannel' interface
146 #---------------------------------------------------------------------------
148 #---------------------------------------------------------------------------
147
149
148 def call_handlers(self, msg):
150 def call_handlers(self, msg):
149 """ Reimplemented to emit signals instead of making callbacks.
151 """ Reimplemented to emit signals instead of making callbacks.
150 """
152 """
151 # Emit the generic signal.
153 # Emit the generic signal.
152 self.message_received.emit(msg)
154 self.message_received.emit(msg)
153
155
154 # Emit signals for specialized message types.
156 # Emit signals for specialized message types.
155 msg_type = msg['msg_type']
157 msg_type = msg['msg_type']
156 if msg_type == 'input_request':
158 if msg_type == 'input_request':
157 self.input_requested.emit(msg)
159 self.input_requested.emit(msg)
158
160
159
161
160 class QtHBSocketChannel(SocketChannelQObject, HBSocketChannel):
162 class QtHBSocketChannel(SocketChannelQObject, HBSocketChannel):
161
163
162 # Emitted when the kernel has died.
164 # Emitted when the kernel has died.
163 kernel_died = QtCore.pyqtSignal(object)
165 kernel_died = QtCore.pyqtSignal(object)
164
166
165 #---------------------------------------------------------------------------
167 #---------------------------------------------------------------------------
166 # 'HBSocketChannel' interface
168 # 'HBSocketChannel' interface
167 #---------------------------------------------------------------------------
169 #---------------------------------------------------------------------------
168
170
169 def call_handlers(self, since_last_heartbeat):
171 def call_handlers(self, since_last_heartbeat):
170 """ Reimplemented to emit signals instead of making callbacks.
172 """ Reimplemented to emit signals instead of making callbacks.
171 """
173 """
172 # Emit the generic signal.
174 # Emit the generic signal.
173 self.kernel_died.emit(since_last_heartbeat)
175 self.kernel_died.emit(since_last_heartbeat)
174
176
175
177
176 class QtKernelManager(KernelManager, SuperQObject):
178 class QtKernelManager(KernelManager, SuperQObject):
177 """ A KernelManager that provides signals and slots.
179 """ A KernelManager that provides signals and slots.
178 """
180 """
179
181
180 __metaclass__ = MetaQObjectHasTraits
182 __metaclass__ = MetaQObjectHasTraits
181
183
182 # Emitted when the kernel manager has started listening.
184 # Emitted when the kernel manager has started listening.
183 started_channels = QtCore.pyqtSignal()
185 started_channels = QtCore.pyqtSignal()
184
186
185 # Emitted when the kernel manager has stopped listening.
187 # Emitted when the kernel manager has stopped listening.
186 stopped_channels = QtCore.pyqtSignal()
188 stopped_channels = QtCore.pyqtSignal()
187
189
188 # Use Qt-specific channel classes that emit signals.
190 # Use Qt-specific channel classes that emit signals.
189 sub_channel_class = Type(QtSubSocketChannel)
191 sub_channel_class = Type(QtSubSocketChannel)
190 xreq_channel_class = Type(QtXReqSocketChannel)
192 xreq_channel_class = Type(QtXReqSocketChannel)
191 rep_channel_class = Type(QtRepSocketChannel)
193 rep_channel_class = Type(QtRepSocketChannel)
192 hb_channel_class = Type(QtHBSocketChannel)
194 hb_channel_class = Type(QtHBSocketChannel)
193
195
194 #---------------------------------------------------------------------------
196 #---------------------------------------------------------------------------
195 # 'KernelManager' interface
197 # 'KernelManager' interface
196 #---------------------------------------------------------------------------
198 #---------------------------------------------------------------------------
197
199
198 #------ Kernel process management ------------------------------------------
200 #------ Kernel process management ------------------------------------------
199
201
200 def start_kernel(self, *args, **kw):
202 def start_kernel(self, *args, **kw):
201 """ Reimplemented for proper heartbeat management.
203 """ Reimplemented for proper heartbeat management.
202 """
204 """
203 if self._xreq_channel is not None:
205 if self._xreq_channel is not None:
204 self._xreq_channel.reset_first_reply()
206 self._xreq_channel.reset_first_reply()
205 super(QtKernelManager, self).start_kernel(*args, **kw)
207 super(QtKernelManager, self).start_kernel(*args, **kw)
206
208
207 #------ Channel management -------------------------------------------------
209 #------ Channel management -------------------------------------------------
208
210
209 def start_channels(self, *args, **kw):
211 def start_channels(self, *args, **kw):
210 """ Reimplemented to emit signal.
212 """ Reimplemented to emit signal.
211 """
213 """
212 super(QtKernelManager, self).start_channels(*args, **kw)
214 super(QtKernelManager, self).start_channels(*args, **kw)
213 self.started_channels.emit()
215 self.started_channels.emit()
214
216
215 def stop_channels(self):
217 def stop_channels(self):
216 """ Reimplemented to emit signal.
218 """ Reimplemented to emit signal.
217 """
219 """
218 super(QtKernelManager, self).stop_channels()
220 super(QtKernelManager, self).stop_channels()
219 self.stopped_channels.emit()
221 self.stopped_channels.emit()
220
222
221 @property
223 @property
222 def xreq_channel(self):
224 def xreq_channel(self):
223 """ Reimplemented for proper heartbeat management.
225 """ Reimplemented for proper heartbeat management.
224 """
226 """
225 if self._xreq_channel is None:
227 if self._xreq_channel is None:
226 self._xreq_channel = super(QtKernelManager, self).xreq_channel
228 self._xreq_channel = super(QtKernelManager, self).xreq_channel
227 self._xreq_channel.first_reply.connect(self._first_reply)
229 self._xreq_channel.first_reply.connect(self._first_reply)
228 return self._xreq_channel
230 return self._xreq_channel
229
231
230 #---------------------------------------------------------------------------
232 #---------------------------------------------------------------------------
231 # Protected interface
233 # Protected interface
232 #---------------------------------------------------------------------------
234 #---------------------------------------------------------------------------
233
235
234 def _first_reply(self):
236 def _first_reply(self):
235 """ Unpauses the heartbeat channel when the first reply is received on
237 """ Unpauses the heartbeat channel when the first reply is received on
236 the execute channel. Note that this will *not* start the heartbeat
238 the execute channel. Note that this will *not* start the heartbeat
237 channel if it is not already running!
239 channel if it is not already running!
238 """
240 """
239 if self._hb_channel is not None:
241 if self._hb_channel is not None:
240 self._hb_channel.unpause()
242 self._hb_channel.unpause()
@@ -1,664 +1,664 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6
6
7 Authors
7 Authors
8 -------
8 -------
9
9
10 * Brian Granger
10 * Brian Granger
11 * Fernando Perez
11 * Fernando Perez
12 """
12 """
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Copyright (C) 2008-2010 The IPython Development Team
15 # Copyright (C) 2008-2010 The IPython Development Team
16 #
16 #
17 # Distributed under the terms of the BSD License. The full license is in
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
18 # the file COPYING, distributed as part of this software.
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Imports
22 # Imports
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 from __future__ import absolute_import
25 from __future__ import absolute_import
26
26
27 import logging
27 import logging
28 import os
28 import os
29 import sys
29 import sys
30
30
31 from IPython.core import release
31 from IPython.core import release
32 from IPython.core.crashhandler import CrashHandler
32 from IPython.core.crashhandler import CrashHandler
33 from IPython.core.application import Application, BaseAppConfigLoader
33 from IPython.core.application import Application, BaseAppConfigLoader
34 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
34 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
35 from IPython.config.loader import (
35 from IPython.config.loader import (
36 Config,
36 Config,
37 PyFileConfigLoader
37 PyFileConfigLoader
38 )
38 )
39 from IPython.lib import inputhook
39 from IPython.lib import inputhook
40 from IPython.utils.path import filefind, get_ipython_dir
40 from IPython.utils.path import filefind, get_ipython_dir
41 from IPython.core import usage
41 from IPython.core import usage
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Globals, utilities and helpers
44 # Globals, utilities and helpers
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 #: The default config file name for this application.
47 #: The default config file name for this application.
48 default_config_file_name = u'ipython_config.py'
48 default_config_file_name = u'ipython_config.py'
49
49
50
50
51 class IPAppConfigLoader(BaseAppConfigLoader):
51 class IPAppConfigLoader(BaseAppConfigLoader):
52
52
53 def _add_arguments(self):
53 def _add_arguments(self):
54 super(IPAppConfigLoader, self)._add_arguments()
54 super(IPAppConfigLoader, self)._add_arguments()
55 paa = self.parser.add_argument
55 paa = self.parser.add_argument
56 paa('-p',
56 paa('-p',
57 '--profile', dest='Global.profile', type=unicode,
57 '--profile', dest='Global.profile', type=unicode,
58 help=
58 help=
59 """The string name of the ipython profile to be used. Assume that your
59 """The string name of the ipython profile to be used. Assume that your
60 config file is ipython_config-<name>.py (looks in current dir first,
60 config file is ipython_config-<name>.py (looks in current dir first,
61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
62 config files for different tasks, especially if include your basic one
62 config files for different tasks, especially if include your basic one
63 in your more specialized ones. You can keep a basic
63 in your more specialized ones. You can keep a basic
64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
65 include this one and load extra things for particular tasks.""",
65 include this one and load extra things for particular tasks.""",
66 metavar='Global.profile')
66 metavar='Global.profile')
67 paa('--config-file',
67 paa('--config-file',
68 dest='Global.config_file', type=unicode,
68 dest='Global.config_file', type=unicode,
69 help=
69 help=
70 """Set the config file name to override default. Normally IPython
70 """Set the config file name to override default. Normally IPython
71 loads ipython_config.py (from current directory) or
71 loads ipython_config.py (from current directory) or
72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
73 fails, IPython starts with a bare bones configuration (no modules
73 fails, IPython starts with a bare bones configuration (no modules
74 loaded at all).""",
74 loaded at all).""",
75 metavar='Global.config_file')
75 metavar='Global.config_file')
76 paa('--autocall',
76 paa('--autocall',
77 dest='InteractiveShell.autocall', type=int,
77 dest='InteractiveShell.autocall', type=int,
78 help=
78 help=
79 """Make IPython automatically call any callable object even if you
79 """Make IPython automatically call any callable object even if you
80 didn't type explicit parentheses. For example, 'str 43' becomes
80 didn't type explicit parentheses. For example, 'str 43' becomes
81 'str(43)' automatically. The value can be '0' to disable the feature,
81 'str(43)' automatically. The value can be '0' to disable the feature,
82 '1' for 'smart' autocall, where it is not applied if there are no more
82 '1' for 'smart' autocall, where it is not applied if there are no more
83 arguments on the line, and '2' for 'full' autocall, where all callable
83 arguments on the line, and '2' for 'full' autocall, where all callable
84 objects are automatically called (even if no arguments are present).
84 objects are automatically called (even if no arguments are present).
85 The default is '1'.""",
85 The default is '1'.""",
86 metavar='InteractiveShell.autocall')
86 metavar='InteractiveShell.autocall')
87 paa('--autoindent',
87 paa('--autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
89 help='Turn on autoindenting.')
89 help='Turn on autoindenting.')
90 paa('--no-autoindent',
90 paa('--no-autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
92 help='Turn off autoindenting.')
92 help='Turn off autoindenting.')
93 paa('--automagic',
93 paa('--automagic',
94 action='store_true', dest='InteractiveShell.automagic',
94 action='store_true', dest='InteractiveShell.automagic',
95 help=
95 help=
96 """Turn on the auto calling of magic commands. Type %%magic at the
96 """Turn on the auto calling of magic commands. Type %%magic at the
97 IPython prompt for more information.""")
97 IPython prompt for more information.""")
98 paa('--no-automagic',
98 paa('--no-automagic',
99 action='store_false', dest='InteractiveShell.automagic',
99 action='store_false', dest='InteractiveShell.automagic',
100 help='Turn off the auto calling of magic commands.')
100 help='Turn off the auto calling of magic commands.')
101 paa('--autoedit-syntax',
101 paa('--autoedit-syntax',
102 action='store_true', dest='TerminalInteractiveShell.autoedit_syntax',
102 action='store_true', dest='TerminalInteractiveShell.autoedit_syntax',
103 help='Turn on auto editing of files with syntax errors.')
103 help='Turn on auto editing of files with syntax errors.')
104 paa('--no-autoedit-syntax',
104 paa('--no-autoedit-syntax',
105 action='store_false', dest='TerminalInteractiveShell.autoedit_syntax',
105 action='store_false', dest='TerminalInteractiveShell.autoedit_syntax',
106 help='Turn off auto editing of files with syntax errors.')
106 help='Turn off auto editing of files with syntax errors.')
107 paa('--banner',
107 paa('--banner',
108 action='store_true', dest='Global.display_banner',
108 action='store_true', dest='Global.display_banner',
109 help='Display a banner upon starting IPython.')
109 help='Display a banner upon starting IPython.')
110 paa('--no-banner',
110 paa('--no-banner',
111 action='store_false', dest='Global.display_banner',
111 action='store_false', dest='Global.display_banner',
112 help="Don't display a banner upon starting IPython.")
112 help="Don't display a banner upon starting IPython.")
113 paa('--cache-size',
113 paa('--cache-size',
114 type=int, dest='InteractiveShell.cache_size',
114 type=int, dest='InteractiveShell.cache_size',
115 help=
115 help=
116 """Set the size of the output cache. The default is 1000, you can
116 """Set the size of the output cache. The default is 1000, you can
117 change it permanently in your config file. Setting it to 0 completely
117 change it permanently in your config file. Setting it to 0 completely
118 disables the caching system, and the minimum value accepted is 20 (if
118 disables the caching system, and the minimum value accepted is 20 (if
119 you provide a value less than 20, it is reset to 0 and a warning is
119 you provide a value less than 20, it is reset to 0 and a warning is
120 issued). This limit is defined because otherwise you'll spend more
120 issued). This limit is defined because otherwise you'll spend more
121 time re-flushing a too small cache than working""",
121 time re-flushing a too small cache than working""",
122 metavar='InteractiveShell.cache_size')
122 metavar='InteractiveShell.cache_size')
123 paa('--classic',
123 paa('--classic',
124 action='store_true', dest='Global.classic',
124 action='store_true', dest='Global.classic',
125 help="Gives IPython a similar feel to the classic Python prompt.")
125 help="Gives IPython a similar feel to the classic Python prompt.")
126 paa('--colors',
126 paa('--colors',
127 type=str, dest='InteractiveShell.colors',
127 type=str, dest='InteractiveShell.colors',
128 help="Set the color scheme (NoColor, Linux, and LightBG).",
128 help="Set the color scheme (NoColor, Linux, and LightBG).",
129 metavar='InteractiveShell.colors')
129 metavar='InteractiveShell.colors')
130 paa('--color-info',
130 paa('--color-info',
131 action='store_true', dest='InteractiveShell.color_info',
131 action='store_true', dest='InteractiveShell.color_info',
132 help=
132 help=
133 """IPython can display information about objects via a set of func-
133 """IPython can display information about objects via a set of func-
134 tions, and optionally can use colors for this, syntax highlighting
134 tions, and optionally can use colors for this, syntax highlighting
135 source code and various other elements. However, because this
135 source code and various other elements. However, because this
136 information is passed through a pager (like 'less') and many pagers get
136 information is passed through a pager (like 'less') and many pagers get
137 confused with color codes, this option is off by default. You can test
137 confused with color codes, this option is off by default. You can test
138 it and turn it on permanently in your ipython_config.py file if it
138 it and turn it on permanently in your ipython_config.py file if it
139 works for you. Test it and turn it on permanently if it works with
139 works for you. Test it and turn it on permanently if it works with
140 your system. The magic function %%color_info allows you to toggle this
140 your system. The magic function %%color_info allows you to toggle this
141 inter- actively for testing.""")
141 inter- actively for testing.""")
142 paa('--no-color-info',
142 paa('--no-color-info',
143 action='store_false', dest='InteractiveShell.color_info',
143 action='store_false', dest='InteractiveShell.color_info',
144 help="Disable using colors for info related things.")
144 help="Disable using colors for info related things.")
145 paa('--confirm-exit',
145 paa('--confirm-exit',
146 action='store_true', dest='TerminalInteractiveShell.confirm_exit',
146 action='store_true', dest='TerminalInteractiveShell.confirm_exit',
147 help=
147 help=
148 """Set to confirm when you try to exit IPython with an EOF (Control-D
148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 '%%Exit', you can force a direct exit without any confirmation.""")
150 '%%Exit', you can force a direct exit without any confirmation.""")
151 paa('--no-confirm-exit',
151 paa('--no-confirm-exit',
152 action='store_false', dest='TerminalInteractiveShell.confirm_exit',
152 action='store_false', dest='TerminalInteractiveShell.confirm_exit',
153 help="Don't prompt the user when exiting.")
153 help="Don't prompt the user when exiting.")
154 paa('--deep-reload',
154 paa('--deep-reload',
155 action='store_true', dest='InteractiveShell.deep_reload',
155 action='store_true', dest='InteractiveShell.deep_reload',
156 help=
156 help=
157 """Enable deep (recursive) reloading by default. IPython can use the
157 """Enable deep (recursive) reloading by default. IPython can use the
158 deep_reload module which reloads changes in modules recursively (it
158 deep_reload module which reloads changes in modules recursively (it
159 replaces the reload() function, so you don't need to change anything to
159 replaces the reload() function, so you don't need to change anything to
160 use it). deep_reload() forces a full reload of modules whose code may
160 use it). deep_reload() forces a full reload of modules whose code may
161 have changed, which the default reload() function does not. When
161 have changed, which the default reload() function does not. When
162 deep_reload is off, IPython will use the normal reload(), but
162 deep_reload is off, IPython will use the normal reload(), but
163 deep_reload will still be available as dreload(). This fea- ture is off
163 deep_reload will still be available as dreload(). This fea- ture is off
164 by default [which means that you have both normal reload() and
164 by default [which means that you have both normal reload() and
165 dreload()].""")
165 dreload()].""")
166 paa('--no-deep-reload',
166 paa('--no-deep-reload',
167 action='store_false', dest='InteractiveShell.deep_reload',
167 action='store_false', dest='InteractiveShell.deep_reload',
168 help="Disable deep (recursive) reloading by default.")
168 help="Disable deep (recursive) reloading by default.")
169 paa('--editor',
169 paa('--editor',
170 type=str, dest='TerminalInteractiveShell.editor',
170 type=str, dest='TerminalInteractiveShell.editor',
171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 metavar='TerminalInteractiveShell.editor')
172 metavar='TerminalInteractiveShell.editor')
173 paa('--log','-l',
173 paa('--log','-l',
174 action='store_true', dest='InteractiveShell.logstart',
174 action='store_true', dest='InteractiveShell.logstart',
175 help="Start logging to the default log file (./ipython_log.py).")
175 help="Start logging to the default log file (./ipython_log.py).")
176 paa('--logfile','-lf',
176 paa('--logfile','-lf',
177 type=unicode, dest='InteractiveShell.logfile',
177 type=unicode, dest='InteractiveShell.logfile',
178 help="Start logging to logfile with this name.",
178 help="Start logging to logfile with this name.",
179 metavar='InteractiveShell.logfile')
179 metavar='InteractiveShell.logfile')
180 paa('--log-append','-la',
180 paa('--log-append','-la',
181 type=unicode, dest='InteractiveShell.logappend',
181 type=unicode, dest='InteractiveShell.logappend',
182 help="Start logging to the given file in append mode.",
182 help="Start logging to the given file in append mode.",
183 metavar='InteractiveShell.logfile')
183 metavar='InteractiveShell.logfile')
184 paa('--pdb',
184 paa('--pdb',
185 action='store_true', dest='InteractiveShell.pdb',
185 action='store_true', dest='InteractiveShell.pdb',
186 help="Enable auto calling the pdb debugger after every exception.")
186 help="Enable auto calling the pdb debugger after every exception.")
187 paa('--no-pdb',
187 paa('--no-pdb',
188 action='store_false', dest='InteractiveShell.pdb',
188 action='store_false', dest='InteractiveShell.pdb',
189 help="Disable auto calling the pdb debugger after every exception.")
189 help="Disable auto calling the pdb debugger after every exception.")
190 paa('--pprint',
190 paa('--pprint',
191 action='store_true', dest='InteractiveShell.pprint',
191 action='store_true', dest='PlainTextFormatter.pprint',
192 help="Enable auto pretty printing of results.")
192 help="Enable auto pretty printing of results.")
193 paa('--no-pprint',
193 paa('--no-pprint',
194 action='store_false', dest='InteractiveShell.pprint',
194 action='store_false', dest='PlainTextFormatter.pprint',
195 help="Disable auto auto pretty printing of results.")
195 help="Disable auto auto pretty printing of results.")
196 paa('--prompt-in1','-pi1',
196 paa('--prompt-in1','-pi1',
197 type=str, dest='InteractiveShell.prompt_in1',
197 type=str, dest='InteractiveShell.prompt_in1',
198 help=
198 help=
199 """Set the main input prompt ('In [\#]: '). Note that if you are using
199 """Set the main input prompt ('In [\#]: '). Note that if you are using
200 numbered prompts, the number is represented with a '\#' in the string.
200 numbered prompts, the number is represented with a '\#' in the string.
201 Don't forget to quote strings with spaces embedded in them. Most
201 Don't forget to quote strings with spaces embedded in them. Most
202 bash-like escapes can be used to customize IPython's prompts, as well
202 bash-like escapes can be used to customize IPython's prompts, as well
203 as a few additional ones which are IPython-spe- cific. All valid
203 as a few additional ones which are IPython-spe- cific. All valid
204 prompt escapes are described in detail in the Customization section of
204 prompt escapes are described in detail in the Customization section of
205 the IPython manual.""",
205 the IPython manual.""",
206 metavar='InteractiveShell.prompt_in1')
206 metavar='InteractiveShell.prompt_in1')
207 paa('--prompt-in2','-pi2',
207 paa('--prompt-in2','-pi2',
208 type=str, dest='InteractiveShell.prompt_in2',
208 type=str, dest='InteractiveShell.prompt_in2',
209 help=
209 help=
210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
211 option, but used for the continuation prompts. The special sequence
211 option, but used for the continuation prompts. The special sequence
212 '\D' is similar to '\#', but with all digits replaced by dots (so you
212 '\D' is similar to '\#', but with all digits replaced by dots (so you
213 can have your continuation prompt aligned with your input prompt).
213 can have your continuation prompt aligned with your input prompt).
214 Default: ' .\D.: ' (note three spaces at the start for alignment with
214 Default: ' .\D.: ' (note three spaces at the start for alignment with
215 'In [\#]')""",
215 'In [\#]')""",
216 metavar='InteractiveShell.prompt_in2')
216 metavar='InteractiveShell.prompt_in2')
217 paa('--prompt-out','-po',
217 paa('--prompt-out','-po',
218 type=str, dest='InteractiveShell.prompt_out',
218 type=str, dest='InteractiveShell.prompt_out',
219 help="Set the output prompt ('Out[\#]:')",
219 help="Set the output prompt ('Out[\#]:')",
220 metavar='InteractiveShell.prompt_out')
220 metavar='InteractiveShell.prompt_out')
221 paa('--quick',
221 paa('--quick',
222 action='store_true', dest='Global.quick',
222 action='store_true', dest='Global.quick',
223 help="Enable quick startup with no config files.")
223 help="Enable quick startup with no config files.")
224 paa('--readline',
224 paa('--readline',
225 action='store_true', dest='InteractiveShell.readline_use',
225 action='store_true', dest='InteractiveShell.readline_use',
226 help="Enable readline for command line usage.")
226 help="Enable readline for command line usage.")
227 paa('--no-readline',
227 paa('--no-readline',
228 action='store_false', dest='InteractiveShell.readline_use',
228 action='store_false', dest='InteractiveShell.readline_use',
229 help="Disable readline for command line usage.")
229 help="Disable readline for command line usage.")
230 paa('--screen-length','-sl',
230 paa('--screen-length','-sl',
231 type=int, dest='TerminalInteractiveShell.screen_length',
231 type=int, dest='TerminalInteractiveShell.screen_length',
232 help=
232 help=
233 """Number of lines of your screen, used to control printing of very
233 """Number of lines of your screen, used to control printing of very
234 long strings. Strings longer than this number of lines will be sent
234 long strings. Strings longer than this number of lines will be sent
235 through a pager instead of directly printed. The default value for
235 through a pager instead of directly printed. The default value for
236 this is 0, which means IPython will auto-detect your screen size every
236 this is 0, which means IPython will auto-detect your screen size every
237 time it needs to print certain potentially long strings (this doesn't
237 time it needs to print certain potentially long strings (this doesn't
238 change the behavior of the 'print' keyword, it's only triggered
238 change the behavior of the 'print' keyword, it's only triggered
239 internally). If for some reason this isn't working well (it needs
239 internally). If for some reason this isn't working well (it needs
240 curses support), specify it yourself. Otherwise don't change the
240 curses support), specify it yourself. Otherwise don't change the
241 default.""",
241 default.""",
242 metavar='TerminalInteractiveShell.screen_length')
242 metavar='TerminalInteractiveShell.screen_length')
243 paa('--separate-in','-si',
243 paa('--separate-in','-si',
244 type=str, dest='InteractiveShell.separate_in',
244 type=str, dest='InteractiveShell.separate_in',
245 help="Separator before input prompts. Default '\\n'.",
245 help="Separator before input prompts. Default '\\n'.",
246 metavar='InteractiveShell.separate_in')
246 metavar='InteractiveShell.separate_in')
247 paa('--separate-out','-so',
247 paa('--separate-out','-so',
248 type=str, dest='InteractiveShell.separate_out',
248 type=str, dest='InteractiveShell.separate_out',
249 help="Separator before output prompts. Default 0 (nothing).",
249 help="Separator before output prompts. Default 0 (nothing).",
250 metavar='InteractiveShell.separate_out')
250 metavar='InteractiveShell.separate_out')
251 paa('--separate-out2','-so2',
251 paa('--separate-out2','-so2',
252 type=str, dest='InteractiveShell.separate_out2',
252 type=str, dest='InteractiveShell.separate_out2',
253 help="Separator after output prompts. Default 0 (nonight).",
253 help="Separator after output prompts. Default 0 (nonight).",
254 metavar='InteractiveShell.separate_out2')
254 metavar='InteractiveShell.separate_out2')
255 paa('--no-sep',
255 paa('--no-sep',
256 action='store_true', dest='Global.nosep',
256 action='store_true', dest='Global.nosep',
257 help="Eliminate all spacing between prompts.")
257 help="Eliminate all spacing between prompts.")
258 paa('--term-title',
258 paa('--term-title',
259 action='store_true', dest='TerminalInteractiveShell.term_title',
259 action='store_true', dest='TerminalInteractiveShell.term_title',
260 help="Enable auto setting the terminal title.")
260 help="Enable auto setting the terminal title.")
261 paa('--no-term-title',
261 paa('--no-term-title',
262 action='store_false', dest='TerminalInteractiveShell.term_title',
262 action='store_false', dest='TerminalInteractiveShell.term_title',
263 help="Disable auto setting the terminal title.")
263 help="Disable auto setting the terminal title.")
264 paa('--xmode',
264 paa('--xmode',
265 type=str, dest='InteractiveShell.xmode',
265 type=str, dest='InteractiveShell.xmode',
266 help=
266 help=
267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
268 similar to python's normal traceback printing. Context: prints 5 lines
268 similar to python's normal traceback printing. Context: prints 5 lines
269 of context source code around each line in the traceback. Verbose:
269 of context source code around each line in the traceback. Verbose:
270 similar to Context, but additionally prints the variables currently
270 similar to Context, but additionally prints the variables currently
271 visible where the exception happened (shortening their strings if too
271 visible where the exception happened (shortening their strings if too
272 long). This can potentially be very slow, if you happen to have a huge
272 long). This can potentially be very slow, if you happen to have a huge
273 data structure whose string representation is complex to compute.
273 data structure whose string representation is complex to compute.
274 Your computer may appear to freeze for a while with cpu usage at 100%%.
274 Your computer may appear to freeze for a while with cpu usage at 100%%.
275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
276 it more than once).
276 it more than once).
277 """,
277 """,
278 metavar='InteractiveShell.xmode')
278 metavar='InteractiveShell.xmode')
279 paa('--ext',
279 paa('--ext',
280 type=str, dest='Global.extra_extension',
280 type=str, dest='Global.extra_extension',
281 help="The dotted module name of an IPython extension to load.",
281 help="The dotted module name of an IPython extension to load.",
282 metavar='Global.extra_extension')
282 metavar='Global.extra_extension')
283 paa('-c',
283 paa('-c',
284 type=str, dest='Global.code_to_run',
284 type=str, dest='Global.code_to_run',
285 help="Execute the given command string.",
285 help="Execute the given command string.",
286 metavar='Global.code_to_run')
286 metavar='Global.code_to_run')
287 paa('-i',
287 paa('-i',
288 action='store_true', dest='Global.force_interact',
288 action='store_true', dest='Global.force_interact',
289 help=
289 help=
290 "If running code from the command line, become interactive afterwards.")
290 "If running code from the command line, become interactive afterwards.")
291
291
292 # Options to start with GUI control enabled from the beginning
292 # Options to start with GUI control enabled from the beginning
293 paa('--gui',
293 paa('--gui',
294 type=str, dest='Global.gui',
294 type=str, dest='Global.gui',
295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
296 metavar='gui-mode')
296 metavar='gui-mode')
297 paa('--pylab','-pylab',
297 paa('--pylab','-pylab',
298 type=str, dest='Global.pylab',
298 type=str, dest='Global.pylab',
299 nargs='?', const='auto', metavar='gui-mode',
299 nargs='?', const='auto', metavar='gui-mode',
300 help="Pre-load matplotlib and numpy for interactive use. "+
300 help="Pre-load matplotlib and numpy for interactive use. "+
301 "If no value is given, the gui backend is matplotlib's, else use "+
301 "If no value is given, the gui backend is matplotlib's, else use "+
302 "one of: ['tk', 'qt', 'wx', 'gtk'].")
302 "one of: ['tk', 'qt', 'wx', 'gtk'].")
303
303
304 # Legacy GUI options. Leave them in for backwards compatibility, but the
304 # Legacy GUI options. Leave them in for backwards compatibility, but the
305 # 'thread' names are really a misnomer now.
305 # 'thread' names are really a misnomer now.
306 paa('--wthread', '-wthread',
306 paa('--wthread', '-wthread',
307 action='store_true', dest='Global.wthread',
307 action='store_true', dest='Global.wthread',
308 help=
308 help=
309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
311 action='store_true', dest='Global.q4thread',
311 action='store_true', dest='Global.q4thread',
312 help=
312 help=
313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
314 (DEPRECATED, use --gui qt)""")
314 (DEPRECATED, use --gui qt)""")
315 paa('--gthread', '-gthread',
315 paa('--gthread', '-gthread',
316 action='store_true', dest='Global.gthread',
316 action='store_true', dest='Global.gthread',
317 help=
317 help=
318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
319
319
320
320
321 #-----------------------------------------------------------------------------
321 #-----------------------------------------------------------------------------
322 # Crash handler for this application
322 # Crash handler for this application
323 #-----------------------------------------------------------------------------
323 #-----------------------------------------------------------------------------
324
324
325 _message_template = """\
325 _message_template = """\
326 Oops, $self.app_name crashed. We do our best to make it stable, but...
326 Oops, $self.app_name crashed. We do our best to make it stable, but...
327
327
328 A crash report was automatically generated with the following information:
328 A crash report was automatically generated with the following information:
329 - A verbatim copy of the crash traceback.
329 - A verbatim copy of the crash traceback.
330 - A copy of your input history during this session.
330 - A copy of your input history during this session.
331 - Data on your current $self.app_name configuration.
331 - Data on your current $self.app_name configuration.
332
332
333 It was left in the file named:
333 It was left in the file named:
334 \t'$self.crash_report_fname'
334 \t'$self.crash_report_fname'
335 If you can email this file to the developers, the information in it will help
335 If you can email this file to the developers, the information in it will help
336 them in understanding and correcting the problem.
336 them in understanding and correcting the problem.
337
337
338 You can mail it to: $self.contact_name at $self.contact_email
338 You can mail it to: $self.contact_name at $self.contact_email
339 with the subject '$self.app_name Crash Report'.
339 with the subject '$self.app_name Crash Report'.
340
340
341 If you want to do it now, the following command will work (under Unix):
341 If you want to do it now, the following command will work (under Unix):
342 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
342 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
343
343
344 To ensure accurate tracking of this issue, please file a report about it at:
344 To ensure accurate tracking of this issue, please file a report about it at:
345 $self.bug_tracker
345 $self.bug_tracker
346 """
346 """
347
347
348 class IPAppCrashHandler(CrashHandler):
348 class IPAppCrashHandler(CrashHandler):
349 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
349 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
350
350
351 message_template = _message_template
351 message_template = _message_template
352
352
353 def __init__(self, app):
353 def __init__(self, app):
354 contact_name = release.authors['Fernando'][0]
354 contact_name = release.authors['Fernando'][0]
355 contact_email = release.authors['Fernando'][1]
355 contact_email = release.authors['Fernando'][1]
356 bug_tracker = 'http://github.com/ipython/ipython/issues'
356 bug_tracker = 'http://github.com/ipython/ipython/issues'
357 super(IPAppCrashHandler,self).__init__(
357 super(IPAppCrashHandler,self).__init__(
358 app, contact_name, contact_email, bug_tracker
358 app, contact_name, contact_email, bug_tracker
359 )
359 )
360
360
361 def make_report(self,traceback):
361 def make_report(self,traceback):
362 """Return a string containing a crash report."""
362 """Return a string containing a crash report."""
363
363
364 sec_sep = self.section_sep
364 sec_sep = self.section_sep
365 # Start with parent report
365 # Start with parent report
366 report = [super(IPAppCrashHandler, self).make_report(traceback)]
366 report = [super(IPAppCrashHandler, self).make_report(traceback)]
367 # Add interactive-specific info we may have
367 # Add interactive-specific info we may have
368 rpt_add = report.append
368 rpt_add = report.append
369 try:
369 try:
370 rpt_add(sec_sep+"History of session input:")
370 rpt_add(sec_sep+"History of session input:")
371 for line in self.app.shell.user_ns['_ih']:
371 for line in self.app.shell.user_ns['_ih']:
372 rpt_add(line)
372 rpt_add(line)
373 rpt_add('\n*** Last line of input (may not be in above history):\n')
373 rpt_add('\n*** Last line of input (may not be in above history):\n')
374 rpt_add(self.app.shell._last_input_line+'\n')
374 rpt_add(self.app.shell._last_input_line+'\n')
375 except:
375 except:
376 pass
376 pass
377
377
378 return ''.join(report)
378 return ''.join(report)
379
379
380
380
381 #-----------------------------------------------------------------------------
381 #-----------------------------------------------------------------------------
382 # Main classes and functions
382 # Main classes and functions
383 #-----------------------------------------------------------------------------
383 #-----------------------------------------------------------------------------
384
384
385 class IPythonApp(Application):
385 class IPythonApp(Application):
386 name = u'ipython'
386 name = u'ipython'
387 #: argparse formats better the 'usage' than the 'description' field
387 #: argparse formats better the 'usage' than the 'description' field
388 description = None
388 description = None
389 usage = usage.cl_usage
389 usage = usage.cl_usage
390 command_line_loader = IPAppConfigLoader
390 command_line_loader = IPAppConfigLoader
391 default_config_file_name = default_config_file_name
391 default_config_file_name = default_config_file_name
392 crash_handler_class = IPAppCrashHandler
392 crash_handler_class = IPAppCrashHandler
393
393
394 def create_default_config(self):
394 def create_default_config(self):
395 super(IPythonApp, self).create_default_config()
395 super(IPythonApp, self).create_default_config()
396 # Eliminate multiple lookups
396 # Eliminate multiple lookups
397 Global = self.default_config.Global
397 Global = self.default_config.Global
398
398
399 # Set all default values
399 # Set all default values
400 Global.display_banner = True
400 Global.display_banner = True
401
401
402 # If the -c flag is given or a file is given to run at the cmd line
402 # If the -c flag is given or a file is given to run at the cmd line
403 # like "ipython foo.py", normally we exit without starting the main
403 # like "ipython foo.py", normally we exit without starting the main
404 # loop. The force_interact config variable allows a user to override
404 # loop. The force_interact config variable allows a user to override
405 # this and interact. It is also set by the -i cmd line flag, just
405 # this and interact. It is also set by the -i cmd line flag, just
406 # like Python.
406 # like Python.
407 Global.force_interact = False
407 Global.force_interact = False
408
408
409 # By default always interact by starting the IPython mainloop.
409 # By default always interact by starting the IPython mainloop.
410 Global.interact = True
410 Global.interact = True
411
411
412 # No GUI integration by default
412 # No GUI integration by default
413 Global.gui = False
413 Global.gui = False
414 # Pylab off by default
414 # Pylab off by default
415 Global.pylab = False
415 Global.pylab = False
416
416
417 # Deprecated versions of gui support that used threading, we support
417 # Deprecated versions of gui support that used threading, we support
418 # them just for bacwards compatibility as an alternate spelling for
418 # them just for bacwards compatibility as an alternate spelling for
419 # '--gui X'
419 # '--gui X'
420 Global.qthread = False
420 Global.qthread = False
421 Global.q4thread = False
421 Global.q4thread = False
422 Global.wthread = False
422 Global.wthread = False
423 Global.gthread = False
423 Global.gthread = False
424
424
425 def load_file_config(self):
425 def load_file_config(self):
426 if hasattr(self.command_line_config.Global, 'quick'):
426 if hasattr(self.command_line_config.Global, 'quick'):
427 if self.command_line_config.Global.quick:
427 if self.command_line_config.Global.quick:
428 self.file_config = Config()
428 self.file_config = Config()
429 return
429 return
430 super(IPythonApp, self).load_file_config()
430 super(IPythonApp, self).load_file_config()
431
431
432 def post_load_file_config(self):
432 def post_load_file_config(self):
433 if hasattr(self.command_line_config.Global, 'extra_extension'):
433 if hasattr(self.command_line_config.Global, 'extra_extension'):
434 if not hasattr(self.file_config.Global, 'extensions'):
434 if not hasattr(self.file_config.Global, 'extensions'):
435 self.file_config.Global.extensions = []
435 self.file_config.Global.extensions = []
436 self.file_config.Global.extensions.append(
436 self.file_config.Global.extensions.append(
437 self.command_line_config.Global.extra_extension)
437 self.command_line_config.Global.extra_extension)
438 del self.command_line_config.Global.extra_extension
438 del self.command_line_config.Global.extra_extension
439
439
440 def pre_construct(self):
440 def pre_construct(self):
441 config = self.master_config
441 config = self.master_config
442
442
443 if hasattr(config.Global, 'classic'):
443 if hasattr(config.Global, 'classic'):
444 if config.Global.classic:
444 if config.Global.classic:
445 config.InteractiveShell.cache_size = 0
445 config.InteractiveShell.cache_size = 0
446 config.InteractiveShell.pprint = 0
446 config.PlainTextFormatter.pprint = 0
447 config.InteractiveShell.prompt_in1 = '>>> '
447 config.InteractiveShell.prompt_in1 = '>>> '
448 config.InteractiveShell.prompt_in2 = '... '
448 config.InteractiveShell.prompt_in2 = '... '
449 config.InteractiveShell.prompt_out = ''
449 config.InteractiveShell.prompt_out = ''
450 config.InteractiveShell.separate_in = \
450 config.InteractiveShell.separate_in = \
451 config.InteractiveShell.separate_out = \
451 config.InteractiveShell.separate_out = \
452 config.InteractiveShell.separate_out2 = ''
452 config.InteractiveShell.separate_out2 = ''
453 config.InteractiveShell.colors = 'NoColor'
453 config.InteractiveShell.colors = 'NoColor'
454 config.InteractiveShell.xmode = 'Plain'
454 config.InteractiveShell.xmode = 'Plain'
455
455
456 if hasattr(config.Global, 'nosep'):
456 if hasattr(config.Global, 'nosep'):
457 if config.Global.nosep:
457 if config.Global.nosep:
458 config.InteractiveShell.separate_in = \
458 config.InteractiveShell.separate_in = \
459 config.InteractiveShell.separate_out = \
459 config.InteractiveShell.separate_out = \
460 config.InteractiveShell.separate_out2 = ''
460 config.InteractiveShell.separate_out2 = ''
461
461
462 # if there is code of files to run from the cmd line, don't interact
462 # if there is code of files to run from the cmd line, don't interact
463 # unless the -i flag (Global.force_interact) is true.
463 # unless the -i flag (Global.force_interact) is true.
464 code_to_run = config.Global.get('code_to_run','')
464 code_to_run = config.Global.get('code_to_run','')
465 file_to_run = False
465 file_to_run = False
466 if self.extra_args and self.extra_args[0]:
466 if self.extra_args and self.extra_args[0]:
467 file_to_run = True
467 file_to_run = True
468 if file_to_run or code_to_run:
468 if file_to_run or code_to_run:
469 if not config.Global.force_interact:
469 if not config.Global.force_interact:
470 config.Global.interact = False
470 config.Global.interact = False
471
471
472 def construct(self):
472 def construct(self):
473 # I am a little hesitant to put these into InteractiveShell itself.
473 # I am a little hesitant to put these into InteractiveShell itself.
474 # But that might be the place for them
474 # But that might be the place for them
475 sys.path.insert(0, '')
475 sys.path.insert(0, '')
476
476
477 # Create an InteractiveShell instance.
477 # Create an InteractiveShell instance.
478 self.shell = TerminalInteractiveShell.instance(config=self.master_config)
478 self.shell = TerminalInteractiveShell.instance(config=self.master_config)
479
479
480 def post_construct(self):
480 def post_construct(self):
481 """Do actions after construct, but before starting the app."""
481 """Do actions after construct, but before starting the app."""
482 config = self.master_config
482 config = self.master_config
483
483
484 # shell.display_banner should always be False for the terminal
484 # shell.display_banner should always be False for the terminal
485 # based app, because we call shell.show_banner() by hand below
485 # based app, because we call shell.show_banner() by hand below
486 # so the banner shows *before* all extension loading stuff.
486 # so the banner shows *before* all extension loading stuff.
487 self.shell.display_banner = False
487 self.shell.display_banner = False
488 if config.Global.display_banner and \
488 if config.Global.display_banner and \
489 config.Global.interact:
489 config.Global.interact:
490 self.shell.show_banner()
490 self.shell.show_banner()
491
491
492 # Make sure there is a space below the banner.
492 # Make sure there is a space below the banner.
493 if self.log_level <= logging.INFO: print
493 if self.log_level <= logging.INFO: print
494
494
495 # Now a variety of things that happen after the banner is printed.
495 # Now a variety of things that happen after the banner is printed.
496 self._enable_gui_pylab()
496 self._enable_gui_pylab()
497 self._load_extensions()
497 self._load_extensions()
498 self._run_exec_lines()
498 self._run_exec_lines()
499 self._run_exec_files()
499 self._run_exec_files()
500 self._run_cmd_line_code()
500 self._run_cmd_line_code()
501
501
502 def _enable_gui_pylab(self):
502 def _enable_gui_pylab(self):
503 """Enable GUI event loop integration, taking pylab into account."""
503 """Enable GUI event loop integration, taking pylab into account."""
504 Global = self.master_config.Global
504 Global = self.master_config.Global
505
505
506 # Select which gui to use
506 # Select which gui to use
507 if Global.gui:
507 if Global.gui:
508 gui = Global.gui
508 gui = Global.gui
509 # The following are deprecated, but there's likely to be a lot of use
509 # The following are deprecated, but there's likely to be a lot of use
510 # of this form out there, so we might as well support it for now. But
510 # of this form out there, so we might as well support it for now. But
511 # the --gui option above takes precedence.
511 # the --gui option above takes precedence.
512 elif Global.wthread:
512 elif Global.wthread:
513 gui = inputhook.GUI_WX
513 gui = inputhook.GUI_WX
514 elif Global.qthread:
514 elif Global.qthread:
515 gui = inputhook.GUI_QT
515 gui = inputhook.GUI_QT
516 elif Global.gthread:
516 elif Global.gthread:
517 gui = inputhook.GUI_GTK
517 gui = inputhook.GUI_GTK
518 else:
518 else:
519 gui = None
519 gui = None
520
520
521 # Using --pylab will also require gui activation, though which toolkit
521 # Using --pylab will also require gui activation, though which toolkit
522 # to use may be chosen automatically based on mpl configuration.
522 # to use may be chosen automatically based on mpl configuration.
523 if Global.pylab:
523 if Global.pylab:
524 activate = self.shell.enable_pylab
524 activate = self.shell.enable_pylab
525 if Global.pylab == 'auto':
525 if Global.pylab == 'auto':
526 gui = None
526 gui = None
527 else:
527 else:
528 gui = Global.pylab
528 gui = Global.pylab
529 else:
529 else:
530 # Enable only GUI integration, no pylab
530 # Enable only GUI integration, no pylab
531 activate = inputhook.enable_gui
531 activate = inputhook.enable_gui
532
532
533 if gui or Global.pylab:
533 if gui or Global.pylab:
534 try:
534 try:
535 self.log.info("Enabling GUI event loop integration, "
535 self.log.info("Enabling GUI event loop integration, "
536 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
536 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
537 activate(gui)
537 activate(gui)
538 except:
538 except:
539 self.log.warn("Error in enabling GUI event loop integration:")
539 self.log.warn("Error in enabling GUI event loop integration:")
540 self.shell.showtraceback()
540 self.shell.showtraceback()
541
541
542 def _load_extensions(self):
542 def _load_extensions(self):
543 """Load all IPython extensions in Global.extensions.
543 """Load all IPython extensions in Global.extensions.
544
544
545 This uses the :meth:`ExtensionManager.load_extensions` to load all
545 This uses the :meth:`ExtensionManager.load_extensions` to load all
546 the extensions listed in ``self.master_config.Global.extensions``.
546 the extensions listed in ``self.master_config.Global.extensions``.
547 """
547 """
548 try:
548 try:
549 if hasattr(self.master_config.Global, 'extensions'):
549 if hasattr(self.master_config.Global, 'extensions'):
550 self.log.debug("Loading IPython extensions...")
550 self.log.debug("Loading IPython extensions...")
551 extensions = self.master_config.Global.extensions
551 extensions = self.master_config.Global.extensions
552 for ext in extensions:
552 for ext in extensions:
553 try:
553 try:
554 self.log.info("Loading IPython extension: %s" % ext)
554 self.log.info("Loading IPython extension: %s" % ext)
555 self.shell.extension_manager.load_extension(ext)
555 self.shell.extension_manager.load_extension(ext)
556 except:
556 except:
557 self.log.warn("Error in loading extension: %s" % ext)
557 self.log.warn("Error in loading extension: %s" % ext)
558 self.shell.showtraceback()
558 self.shell.showtraceback()
559 except:
559 except:
560 self.log.warn("Unknown error in loading extensions:")
560 self.log.warn("Unknown error in loading extensions:")
561 self.shell.showtraceback()
561 self.shell.showtraceback()
562
562
563 def _run_exec_lines(self):
563 def _run_exec_lines(self):
564 """Run lines of code in Global.exec_lines in the user's namespace."""
564 """Run lines of code in Global.exec_lines in the user's namespace."""
565 try:
565 try:
566 if hasattr(self.master_config.Global, 'exec_lines'):
566 if hasattr(self.master_config.Global, 'exec_lines'):
567 self.log.debug("Running code from Global.exec_lines...")
567 self.log.debug("Running code from Global.exec_lines...")
568 exec_lines = self.master_config.Global.exec_lines
568 exec_lines = self.master_config.Global.exec_lines
569 for line in exec_lines:
569 for line in exec_lines:
570 try:
570 try:
571 self.log.info("Running code in user namespace: %s" %
571 self.log.info("Running code in user namespace: %s" %
572 line)
572 line)
573 self.shell.run_cell(line)
573 self.shell.run_cell(line)
574 except:
574 except:
575 self.log.warn("Error in executing line in user "
575 self.log.warn("Error in executing line in user "
576 "namespace: %s" % line)
576 "namespace: %s" % line)
577 self.shell.showtraceback()
577 self.shell.showtraceback()
578 except:
578 except:
579 self.log.warn("Unknown error in handling Global.exec_lines:")
579 self.log.warn("Unknown error in handling Global.exec_lines:")
580 self.shell.showtraceback()
580 self.shell.showtraceback()
581
581
582 def _exec_file(self, fname):
582 def _exec_file(self, fname):
583 full_filename = filefind(fname, [u'.', self.ipython_dir])
583 full_filename = filefind(fname, [u'.', self.ipython_dir])
584 if os.path.isfile(full_filename):
584 if os.path.isfile(full_filename):
585 if full_filename.endswith(u'.py'):
585 if full_filename.endswith(u'.py'):
586 self.log.info("Running file in user namespace: %s" %
586 self.log.info("Running file in user namespace: %s" %
587 full_filename)
587 full_filename)
588 # Ensure that __file__ is always defined to match Python behavior
588 # Ensure that __file__ is always defined to match Python behavior
589 self.shell.user_ns['__file__'] = fname
589 self.shell.user_ns['__file__'] = fname
590 try:
590 try:
591 self.shell.safe_execfile(full_filename, self.shell.user_ns)
591 self.shell.safe_execfile(full_filename, self.shell.user_ns)
592 finally:
592 finally:
593 del self.shell.user_ns['__file__']
593 del self.shell.user_ns['__file__']
594 elif full_filename.endswith('.ipy'):
594 elif full_filename.endswith('.ipy'):
595 self.log.info("Running file in user namespace: %s" %
595 self.log.info("Running file in user namespace: %s" %
596 full_filename)
596 full_filename)
597 self.shell.safe_execfile_ipy(full_filename)
597 self.shell.safe_execfile_ipy(full_filename)
598 else:
598 else:
599 self.log.warn("File does not have a .py or .ipy extension: <%s>"
599 self.log.warn("File does not have a .py or .ipy extension: <%s>"
600 % full_filename)
600 % full_filename)
601 def _run_exec_files(self):
601 def _run_exec_files(self):
602 try:
602 try:
603 if hasattr(self.master_config.Global, 'exec_files'):
603 if hasattr(self.master_config.Global, 'exec_files'):
604 self.log.debug("Running files in Global.exec_files...")
604 self.log.debug("Running files in Global.exec_files...")
605 exec_files = self.master_config.Global.exec_files
605 exec_files = self.master_config.Global.exec_files
606 for fname in exec_files:
606 for fname in exec_files:
607 self._exec_file(fname)
607 self._exec_file(fname)
608 except:
608 except:
609 self.log.warn("Unknown error in handling Global.exec_files:")
609 self.log.warn("Unknown error in handling Global.exec_files:")
610 self.shell.showtraceback()
610 self.shell.showtraceback()
611
611
612 def _run_cmd_line_code(self):
612 def _run_cmd_line_code(self):
613 if hasattr(self.master_config.Global, 'code_to_run'):
613 if hasattr(self.master_config.Global, 'code_to_run'):
614 line = self.master_config.Global.code_to_run
614 line = self.master_config.Global.code_to_run
615 try:
615 try:
616 self.log.info("Running code given at command line (-c): %s" %
616 self.log.info("Running code given at command line (-c): %s" %
617 line)
617 line)
618 self.shell.run_cell(line)
618 self.shell.run_cell(line)
619 except:
619 except:
620 self.log.warn("Error in executing line in user namespace: %s" %
620 self.log.warn("Error in executing line in user namespace: %s" %
621 line)
621 line)
622 self.shell.showtraceback()
622 self.shell.showtraceback()
623 return
623 return
624 # Like Python itself, ignore the second if the first of these is present
624 # Like Python itself, ignore the second if the first of these is present
625 try:
625 try:
626 fname = self.extra_args[0]
626 fname = self.extra_args[0]
627 except:
627 except:
628 pass
628 pass
629 else:
629 else:
630 try:
630 try:
631 self._exec_file(fname)
631 self._exec_file(fname)
632 except:
632 except:
633 self.log.warn("Error in executing file in user namespace: %s" %
633 self.log.warn("Error in executing file in user namespace: %s" %
634 fname)
634 fname)
635 self.shell.showtraceback()
635 self.shell.showtraceback()
636
636
637 def start_app(self):
637 def start_app(self):
638 if self.master_config.Global.interact:
638 if self.master_config.Global.interact:
639 self.log.debug("Starting IPython's mainloop...")
639 self.log.debug("Starting IPython's mainloop...")
640 self.shell.mainloop()
640 self.shell.mainloop()
641 else:
641 else:
642 self.log.debug("IPython not interactive, start_app is no-op...")
642 self.log.debug("IPython not interactive, start_app is no-op...")
643
643
644
644
645 def load_default_config(ipython_dir=None):
645 def load_default_config(ipython_dir=None):
646 """Load the default config file from the default ipython_dir.
646 """Load the default config file from the default ipython_dir.
647
647
648 This is useful for embedded shells.
648 This is useful for embedded shells.
649 """
649 """
650 if ipython_dir is None:
650 if ipython_dir is None:
651 ipython_dir = get_ipython_dir()
651 ipython_dir = get_ipython_dir()
652 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
652 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
653 config = cl.load_config()
653 config = cl.load_config()
654 return config
654 return config
655
655
656
656
657 def launch_new_instance():
657 def launch_new_instance():
658 """Create and run a full blown IPython instance"""
658 """Create and run a full blown IPython instance"""
659 app = IPythonApp()
659 app = IPythonApp()
660 app.start()
660 app.start()
661
661
662
662
663 if __name__ == '__main__':
663 if __name__ == '__main__':
664 launch_new_instance()
664 launch_new_instance()
@@ -1,110 +1,110 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 """This module contains blocking clients for the controller interfaces.
4 """This module contains blocking clients for the controller interfaces.
5
5
6 Unlike the clients in `asyncclient.py`, the clients in this module are fully
6 Unlike the clients in `asyncclient.py`, the clients in this module are fully
7 blocking. This means that methods on the clients return the actual results
7 blocking. This means that methods on the clients return the actual results
8 rather than a deferred to the result. Also, we manage the Twisted reactor
8 rather than a deferred to the result. Also, we manage the Twisted reactor
9 for you. This is done by running the reactor in a thread.
9 for you. This is done by running the reactor in a thread.
10
10
11 The main classes in this module are:
11 The main classes in this module are:
12
12
13 * MultiEngineClient
13 * MultiEngineClient
14 * TaskClient
14 * TaskClient
15 * Task
15 * Task
16 * CompositeError
16 * CompositeError
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2009 The IPython Development Team
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Warnings control
27 # Warnings control
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 import warnings
30 import warnings
31
31
32 # Twisted generates annoying warnings with Python 2.6, as will do other code
32 # Twisted generates annoying warnings with Python 2.6, as will do other code
33 # that imports 'sets' as of today
33 # that imports 'sets' as of today
34 warnings.filterwarnings('ignore', 'the sets module is deprecated',
34 warnings.filterwarnings('ignore', 'the sets module is deprecated',
35 DeprecationWarning )
35 DeprecationWarning )
36
36
37 # This one also comes from Twisted
37 # This one also comes from Twisted
38 warnings.filterwarnings('ignore', 'the sha module is deprecated',
38 warnings.filterwarnings('ignore', 'the sha module is deprecated',
39 DeprecationWarning)
39 DeprecationWarning)
40
40
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42 # Imports
42 # Imports
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44
44
45 import sys
45 import sys
46
46
47 import twisted
47 import twisted
48 from twisted.internet import reactor
48 from twisted.internet import reactor
49 from twisted.python import log
49 from twisted.python import log
50
50
51 from IPython.kernel.clientconnector import ClientConnector, Cluster
51 from IPython.kernel.clientconnector import ClientConnector, Cluster
52 from IPython.kernel.twistedutil import ReactorInThread
52 from IPython.kernel.twistedutil import ReactorInThread
53 from IPython.kernel.twistedutil import blockingCallFromThread
53 from IPython.kernel.twistedutil import blockingCallFromThread
54
54
55 # These enable various things
55 # These enable various things
56 from IPython.kernel import codeutil
56 from IPython.kernel import codeutil
57
57
58 # Other things that the user will need
58 # Other things that the user will need
59 from IPython.kernel.task import MapTask, StringTask
59 from IPython.kernel.task import MapTask, StringTask
60 from IPython.kernel.error import CompositeError
60 from IPython.kernel.error import CompositeError
61
61
62 #-------------------------------------------------------------------------------
62 #-------------------------------------------------------------------------------
63 # Code
63 # Code
64 #-------------------------------------------------------------------------------
64 #-------------------------------------------------------------------------------
65
65
66 # PotentialZombieWarning is deprecated from Twisted 10.0.0 and above and
66 # PotentialZombieWarning is deprecated from Twisted 10.0.0 and above and
67 # using the filter on > 10.0.0 creates a warning itself.
67 # using the filter on > 10.0.0 creates a warning itself.
68 if twisted.version.major < 10:
68 if twisted.version.major < 10:
69 from twisted.internet.error import PotentialZombieWarning
69 from twisted.internet.error import PotentialZombieWarning
70 warnings.simplefilter('ignore', PotentialZombieWarning)
70 warnings.simplefilter('ignore', PotentialZombieWarning)
71
71
72 _client_tub = ClientConnector()
72 _client_tub = ClientConnector()
73
73
74 get_multiengine_client = _client_tub.get_multiengine_client
74 get_multiengine_client = _client_tub.get_multiengine_client
75 get_task_client = _client_tub.get_task_client
75 get_task_client = _client_tub.get_task_client
76 MultiEngineClient = get_multiengine_client
76 MultiEngineClient = get_multiengine_client
77 TaskClient = get_task_client
77 TaskClient = get_task_client
78
78
79 # This isn't great. I should probably set this up in the ReactorInThread
79 # This isn't great. I should probably set this up in the ReactorInThread
80 # class below. But, it does work for now.
80 # class below. But, it does work for now.
81 log.startLogging(sys.stdout, setStdout=0)
81 log.startLogging(sys.stdout, setStdout=0)
82
82
83 def _result_list_printer(obj, p, cycle):
83 def _result_list_printer(obj, p, cycle):
84 if cycle:
84 if cycle:
85 return p.text('ResultList(...)')
85 return p.text('ResultList(...)')
86 return p.text(repr(obj))
86 return p.text(repr(obj))
87
87
88 # ResultList is a list subclass and will use the default pretty printer.
88 # ResultList is a list subclass and will use the default pretty printer.
89 # This overrides that to use the __repr__ of ResultList.
89 # This overrides that to use the __repr__ of ResultList.
90 ip = get_ipython()
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 'IPython.kernel.multiengineclient', 'ResultList', _result_list_printer
92 'IPython.kernel.multiengineclient', 'ResultList', _result_list_printer
93 )
93 )
94
94
95 # Now we start the reactor in a thread
95 # Now we start the reactor in a thread
96 rit = ReactorInThread()
96 rit = ReactorInThread()
97 rit.setDaemon(True)
97 rit.setDaemon(True)
98 rit.start()
98 rit.start()
99
99
100
100
101 __all__ = [
101 __all__ = [
102 'MapTask',
102 'MapTask',
103 'StringTask',
103 'StringTask',
104 'MultiEngineClient',
104 'MultiEngineClient',
105 'TaskClient',
105 'TaskClient',
106 'CompositeError',
106 'CompositeError',
107 'get_task_client',
107 'get_task_client',
108 'get_multiengine_client',
108 'get_multiengine_client',
109 'Cluster'
109 'Cluster'
110 ]
110 ]
@@ -1,208 +1,280 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Pylab (matplotlib) support utilities.
2 """Pylab (matplotlib) support utilities.
3
3
4 Authors
4 Authors
5 -------
5 -------
6
6
7 * Fernando Perez.
7 * Fernando Perez.
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2009 The IPython Development Team
12 # Copyright (C) 2009 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 from cStringIO import StringIO
23
22 from IPython.utils.decorators import flag_calls
24 from IPython.utils.decorators import flag_calls
23
25
24 # If user specifies a GUI, that dictates the backend, otherwise we read the
26 # If user specifies a GUI, that dictates the backend, otherwise we read the
25 # user's mpl default from the mpl rc structure
27 # user's mpl default from the mpl rc structure
26 backends = {'tk': 'TkAgg',
28 backends = {'tk': 'TkAgg',
27 'gtk': 'GTKAgg',
29 'gtk': 'GTKAgg',
28 'wx': 'WXAgg',
30 'wx': 'WXAgg',
29 'qt': 'Qt4Agg', # qt3 not supported
31 'qt': 'Qt4Agg', # qt3 not supported
30 'qt4': 'Qt4Agg',
32 'qt4': 'Qt4Agg',
31 'inline' : 'module://IPython.zmq.pylab.backend_inline'}
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 def find_gui_and_backend(gui=None):
140 def find_gui_and_backend(gui=None):
39 """Given a gui string return the gui and mpl backend.
141 """Given a gui string return the gui and mpl backend.
40
142
41 Parameters
143 Parameters
42 ----------
144 ----------
43 gui : str
145 gui : str
44 Can be one of ('tk','gtk','wx','qt','qt4','inline').
146 Can be one of ('tk','gtk','wx','qt','qt4','inline').
45
147
46 Returns
148 Returns
47 -------
149 -------
48 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
150 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
49 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline').
151 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline').
50 """
152 """
51
153
52 import matplotlib
154 import matplotlib
53
155
54 if gui:
156 if gui:
55 # select backend based on requested gui
157 # select backend based on requested gui
56 backend = backends[gui]
158 backend = backends[gui]
57 else:
159 else:
58 backend = matplotlib.rcParams['backend']
160 backend = matplotlib.rcParams['backend']
59 # In this case, we need to find what the appropriate gui selection call
161 # In this case, we need to find what the appropriate gui selection call
60 # should be for IPython, so we can activate inputhook accordingly
162 # should be for IPython, so we can activate inputhook accordingly
61 g2b = backends # maps gui names to mpl backend names
163 g2b = backends # maps gui names to mpl backend names
62 b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict
164 b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict
63 gui = b2g.get(backend, None)
165 gui = b2g.get(backend, None)
64 return gui, backend
166 return gui, backend
65
167
66
168
67 def activate_matplotlib(backend):
169 def activate_matplotlib(backend):
68 """Activate the given backend and set interactive to True."""
170 """Activate the given backend and set interactive to True."""
69
171
70 import matplotlib
172 import matplotlib
71 if backend.startswith('module://'):
173 if backend.startswith('module://'):
72 # Work around bug in matplotlib: matplotlib.use converts the
174 # Work around bug in matplotlib: matplotlib.use converts the
73 # backend_id to lowercase even if a module name is specified!
175 # backend_id to lowercase even if a module name is specified!
74 matplotlib.rcParams['backend'] = backend
176 matplotlib.rcParams['backend'] = backend
75 else:
177 else:
76 matplotlib.use(backend)
178 matplotlib.use(backend)
77 matplotlib.interactive(True)
179 matplotlib.interactive(True)
78
180
79 # This must be imported last in the matplotlib series, after
181 # This must be imported last in the matplotlib series, after
80 # backend/interactivity choices have been made
182 # backend/interactivity choices have been made
81 import matplotlib.pylab as pylab
183 import matplotlib.pylab as pylab
82
184
83 # XXX For now leave this commented out, but depending on discussions with
185 # XXX For now leave this commented out, but depending on discussions with
84 # mpl-dev, we may be able to allow interactive switching...
186 # mpl-dev, we may be able to allow interactive switching...
85 #import matplotlib.pyplot
187 #import matplotlib.pyplot
86 #matplotlib.pyplot.switch_backend(backend)
188 #matplotlib.pyplot.switch_backend(backend)
87
189
88 pylab.show._needmain = False
190 pylab.show._needmain = False
89 # We need to detect at runtime whether show() is called by the user.
191 # We need to detect at runtime whether show() is called by the user.
90 # For this, we wrap it into a decorator which adds a 'called' flag.
192 # For this, we wrap it into a decorator which adds a 'called' flag.
91 pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
193 pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
92
194
93
195
94 def import_pylab(user_ns, backend, import_all=True, shell=None):
196 def import_pylab(user_ns, backend, import_all=True, shell=None):
95 """Import the standard pylab symbols into user_ns."""
197 """Import the standard pylab symbols into user_ns."""
96
198
97 # Import numpy as np/pyplot as plt are conventions we're trying to
199 # Import numpy as np/pyplot as plt are conventions we're trying to
98 # somewhat standardize on. Making them available to users by default
200 # somewhat standardize on. Making them available to users by default
99 # will greatly help this.
201 # will greatly help this.
100 s = ("import numpy\n"
202 s = ("import numpy\n"
101 "import matplotlib\n"
203 "import matplotlib\n"
102 "from matplotlib import pylab, mlab, pyplot\n"
204 "from matplotlib import pylab, mlab, pyplot\n"
103 "np = numpy\n"
205 "np = numpy\n"
104 "plt = pyplot\n"
206 "plt = pyplot\n"
105 )
207 )
106 exec s in user_ns
208 exec s in user_ns
107
209
108 if shell is not None:
210 if shell is not None:
109 exec s in shell.user_ns_hidden
211 exec s in shell.user_ns_hidden
110 # If using our svg payload backend, register the post-execution
212 # If using our svg payload backend, register the post-execution
111 # function that will pick up the results for display. This can only be
213 # function that will pick up the results for display. This can only be
112 # done with access to the real shell object.
214 # done with access to the real shell object.
113 if backend == backends['inline']:
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 from matplotlib import pyplot
217 from matplotlib import pyplot
116 shell.register_post_execute(flush_svg)
218 shell.register_post_execute(flush_svg)
117 # The typical default figure size is too large for inline use. We
219 # The typical default figure size is too large for inline use. We
118 # might make this a user-configurable parameter later.
220 # might make this a user-configurable parameter later.
119 figsize(6.0, 4.0)
221 figsize(6.0, 4.0)
120 # Add 'figsize' to pyplot and to the user's namespace
222 # Add 'figsize' to pyplot and to the user's namespace
121 user_ns['figsize'] = pyplot.figsize = figsize
223 user_ns['figsize'] = pyplot.figsize = figsize
122 shell.user_ns_hidden['figsize'] = figsize
224 shell.user_ns_hidden['figsize'] = figsize
123 else:
225
124 from IPython.zmq.pylab.backend_inline import pastefig
226 # The old pastefig function has been replaced by display
125 from matplotlib import pyplot
227 # Always add this svg formatter so display works.
126 # Add 'paste' to pyplot and to the user's namespace
228 from IPython.zmq.pylab.backend_inline import figure_to_svg
127 user_ns['pastefig'] = pyplot.pastefig = pastefig
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 if import_all:
242 if import_all:
130 s = ("from matplotlib.pylab import *\n"
243 s = ("from matplotlib.pylab import *\n"
131 "from numpy import *\n")
244 "from numpy import *\n")
132 exec s in user_ns
245 exec s in user_ns
133 if shell is not None:
246 if shell is not None:
134 exec s in shell.user_ns_hidden
247 exec s in shell.user_ns_hidden
135
248
136
249
137 def pylab_activate(user_ns, gui=None, import_all=True):
250 def pylab_activate(user_ns, gui=None, import_all=True):
138 """Activate pylab mode in the user's namespace.
251 """Activate pylab mode in the user's namespace.
139
252
140 Loads and initializes numpy, matplotlib and friends for interactive use.
253 Loads and initializes numpy, matplotlib and friends for interactive use.
141
254
142 Parameters
255 Parameters
143 ----------
256 ----------
144 user_ns : dict
257 user_ns : dict
145 Namespace where the imports will occur.
258 Namespace where the imports will occur.
146
259
147 gui : optional, string
260 gui : optional, string
148 A valid gui name following the conventions of the %gui magic.
261 A valid gui name following the conventions of the %gui magic.
149
262
150 import_all : optional, boolean
263 import_all : optional, boolean
151 If true, an 'import *' is done from numpy and pylab.
264 If true, an 'import *' is done from numpy and pylab.
152
265
153 Returns
266 Returns
154 -------
267 -------
155 The actual gui used (if not given as input, it was obtained from matplotlib
268 The actual gui used (if not given as input, it was obtained from matplotlib
156 itself, and will be needed next to configure IPython's gui integration.
269 itself, and will be needed next to configure IPython's gui integration.
157 """
270 """
158 gui, backend = find_gui_and_backend(gui)
271 gui, backend = find_gui_and_backend(gui)
159 activate_matplotlib(backend)
272 activate_matplotlib(backend)
160 import_pylab(user_ns, backend)
273 import_pylab(user_ns, backend)
161
274
162 print """
275 print """
163 Welcome to pylab, a matplotlib-based Python environment [backend: %s].
276 Welcome to pylab, a matplotlib-based Python environment [backend: %s].
164 For more information, type 'help(pylab)'.""" % backend
277 For more information, type 'help(pylab)'.""" % backend
165
278
166 return gui
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 # encoding: utf-8
1 # encoding: utf-8
2 """Generic functions for extending IPython.
2 """Generic functions for extending IPython.
3
3
4 See http://cheeseshop.python.org/pypi/simplegeneric.
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 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
18 #
9 #
19 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
20 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
21 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
22
13
23 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
24 # Imports
15 # Imports
25 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
26
17
27 from IPython.core.error import TryNext
18 from IPython.core.error import TryNext
28 from IPython.external.simplegeneric import generic
19 from IPython.external.simplegeneric import generic
29
20
30 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
31 # Imports
22 # Imports
32 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
33
24
34
25
35 @generic
26 @generic
36 def inspect_object(obj):
27 def inspect_object(obj):
37 """Called when you do obj?"""
28 """Called when you do obj?"""
38 raise TryNext
29 raise TryNext
39
30
40
31
41 @generic
32 @generic
42 def complete_object(obj, prev_completions):
33 def complete_object(obj, prev_completions):
43 """Custom completer dispatching for python objects.
34 """Custom completer dispatching for python objects.
44
35
45 Parameters
36 Parameters
46 ----------
37 ----------
47 obj : object
38 obj : object
48 The object to complete.
39 The object to complete.
49 prev_completions : list
40 prev_completions : list
50 List of attributes discovered so far.
41 List of attributes discovered so far.
51
42
52 This should return the list of attributes in obj. If you only wish to
43 This should return the list of attributes in obj. If you only wish to
53 add to the attributes already discovered normally, return
44 add to the attributes already discovered normally, return
54 own_attrs + prev_completions.
45 own_attrs + prev_completions.
55 """
46 """
56 raise TryNext
47 raise TryNext
57
48
58
49
@@ -1,398 +1,396 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """A dict subclass that supports attribute style access.
3 """A dict subclass that supports attribute style access.
4
4
5 Authors:
5 Authors:
6
6
7 * Fernando Perez (original)
7 * Fernando Perez (original)
8 * Brian Granger (refactoring to a dict subclass)
8 * Brian Granger (refactoring to a dict subclass)
9 """
9 """
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 The IPython Development Team
12 # Copyright (C) 2008-2009 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 from IPython.utils.data import list2dict2
22 from IPython.utils.data import list2dict2
23
23
24 __all__ = ['Struct']
24 __all__ = ['Struct']
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Code
27 # Code
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30
30
31 class Struct(dict):
31 class Struct(dict):
32 """A dict subclass with attribute style access.
32 """A dict subclass with attribute style access.
33
33
34 This dict subclass has a a few extra features:
34 This dict subclass has a a few extra features:
35
35
36 * Attribute style access.
36 * Attribute style access.
37 * Protection of class members (like keys, items) when using attribute
37 * Protection of class members (like keys, items) when using attribute
38 style access.
38 style access.
39 * The ability to restrict assignment to only existing keys.
39 * The ability to restrict assignment to only existing keys.
40 * Intelligent merging.
40 * Intelligent merging.
41 * Overloaded operators.
41 * Overloaded operators.
42 """
42 """
43 _allownew = True
43 _allownew = True
44 def __init__(self, *args, **kw):
44 def __init__(self, *args, **kw):
45 """Initialize with a dictionary, another Struct, or data.
45 """Initialize with a dictionary, another Struct, or data.
46
46
47 Parameters
47 Parameters
48 ----------
48 ----------
49 args : dict, Struct
49 args : dict, Struct
50 Initialize with one dict or Struct
50 Initialize with one dict or Struct
51 kw : dict
51 kw : dict
52 Initialize with key, value pairs.
52 Initialize with key, value pairs.
53
53
54 Examples
54 Examples
55 --------
55 --------
56
56
57 >>> s = Struct(a=10,b=30)
57 >>> s = Struct(a=10,b=30)
58 >>> s.a
58 >>> s.a
59 10
59 10
60 >>> s.b
60 >>> s.b
61 30
61 30
62 >>> s2 = Struct(s,c=30)
62 >>> s2 = Struct(s,c=30)
63 >>> s2.keys()
63 >>> s2.keys()
64 ['a', 'c', 'b']
64 ['a', 'c', 'b']
65 """
65 """
66 object.__setattr__(self, '_allownew', True)
66 object.__setattr__(self, '_allownew', True)
67 dict.__init__(self, *args, **kw)
67 dict.__init__(self, *args, **kw)
68
68
69 def __setitem__(self, key, value):
69 def __setitem__(self, key, value):
70 """Set an item with check for allownew.
70 """Set an item with check for allownew.
71
71
72 Examples
72 Examples
73 --------
73 --------
74
74
75 >>> s = Struct()
75 >>> s = Struct()
76 >>> s['a'] = 10
76 >>> s['a'] = 10
77 >>> s.allow_new_attr(False)
77 >>> s.allow_new_attr(False)
78 >>> s['a'] = 10
78 >>> s['a'] = 10
79 >>> s['a']
79 >>> s['a']
80 10
80 10
81 >>> try:
81 >>> try:
82 ... s['b'] = 20
82 ... s['b'] = 20
83 ... except KeyError:
83 ... except KeyError:
84 ... print 'this is not allowed'
84 ... print 'this is not allowed'
85 ...
85 ...
86 this is not allowed
86 this is not allowed
87 """
87 """
88 if not self._allownew and not self.has_key(key):
88 if not self._allownew and not self.has_key(key):
89 raise KeyError(
89 raise KeyError(
90 "can't create new attribute %s when allow_new_attr(False)" % key)
90 "can't create new attribute %s when allow_new_attr(False)" % key)
91 dict.__setitem__(self, key, value)
91 dict.__setitem__(self, key, value)
92
92
93 def __setattr__(self, key, value):
93 def __setattr__(self, key, value):
94 """Set an attr with protection of class members.
94 """Set an attr with protection of class members.
95
95
96 This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to
96 This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to
97 :exc:`AttributeError`.
97 :exc:`AttributeError`.
98
98
99 Examples
99 Examples
100 --------
100 --------
101
101
102 >>> s = Struct()
102 >>> s = Struct()
103 >>> s.a = 10
103 >>> s.a = 10
104 >>> s.a
104 >>> s.a
105 10
105 10
106 >>> try:
106 >>> try:
107 ... s.get = 10
107 ... s.get = 10
108 ... except AttributeError:
108 ... except AttributeError:
109 ... print "you can't set a class member"
109 ... print "you can't set a class member"
110 ...
110 ...
111 you can't set a class member
111 you can't set a class member
112 """
112 """
113 # If key is an str it might be a class member or instance var
113 # If key is an str it might be a class member or instance var
114 if isinstance(key, str):
114 if isinstance(key, str):
115 # I can't simply call hasattr here because it calls getattr, which
115 # I can't simply call hasattr here because it calls getattr, which
116 # calls self.__getattr__, which returns True for keys in
116 # calls self.__getattr__, which returns True for keys in
117 # self._data. But I only want keys in the class and in
117 # self._data. But I only want keys in the class and in
118 # self.__dict__
118 # self.__dict__
119 if key in self.__dict__ or hasattr(Struct, key):
119 if key in self.__dict__ or hasattr(Struct, key):
120 raise AttributeError(
120 raise AttributeError(
121 'attr %s is a protected member of class Struct.' % key
121 'attr %s is a protected member of class Struct.' % key
122 )
122 )
123 try:
123 try:
124 self.__setitem__(key, value)
124 self.__setitem__(key, value)
125 except KeyError, e:
125 except KeyError, e:
126 raise AttributeError(e)
126 raise AttributeError(e)
127
127
128 def __getattr__(self, key):
128 def __getattr__(self, key):
129 """Get an attr by calling :meth:`dict.__getitem__`.
129 """Get an attr by calling :meth:`dict.__getitem__`.
130
130
131 Like :meth:`__setattr__`, this method converts :exc:`KeyError` to
131 Like :meth:`__setattr__`, this method converts :exc:`KeyError` to
132 :exc:`AttributeError`.
132 :exc:`AttributeError`.
133
133
134 Examples
134 Examples
135 --------
135 --------
136
136
137 >>> s = Struct(a=10)
137 >>> s = Struct(a=10)
138 >>> s.a
138 >>> s.a
139 10
139 10
140 >>> type(s.get)
140 >>> type(s.get)
141 <type 'builtin_function_or_method'>
141 <type 'builtin_function_or_method'>
142 >>> try:
142 >>> try:
143 ... s.b
143 ... s.b
144 ... except AttributeError:
144 ... except AttributeError:
145 ... print "I don't have that key"
145 ... print "I don't have that key"
146 ...
146 ...
147 I don't have that key
147 I don't have that key
148 """
148 """
149 try:
149 try:
150 result = self[key]
150 result = self[key]
151 except KeyError:
151 except KeyError:
152 raise AttributeError(key)
152 raise AttributeError(key)
153 else:
153 else:
154 return result
154 return result
155
155
156 def __iadd__(self, other):
156 def __iadd__(self, other):
157 """s += s2 is a shorthand for s.merge(s2).
157 """s += s2 is a shorthand for s.merge(s2).
158
158
159 Examples
159 Examples
160 --------
160 --------
161
161
162 >>> s = Struct(a=10,b=30)
162 >>> s = Struct(a=10,b=30)
163 >>> s2 = Struct(a=20,c=40)
163 >>> s2 = Struct(a=20,c=40)
164 >>> s += s2
164 >>> s += s2
165 >>> s
165 >>> s
166 {'a': 10, 'c': 40, 'b': 30}
166 {'a': 10, 'c': 40, 'b': 30}
167 """
167 """
168 self.merge(other)
168 self.merge(other)
169 return self
169 return self
170
170
171 def __add__(self,other):
171 def __add__(self,other):
172 """s + s2 -> New Struct made from s.merge(s2).
172 """s + s2 -> New Struct made from s.merge(s2).
173
173
174 Examples
174 Examples
175 --------
175 --------
176
176
177 >>> s1 = Struct(a=10,b=30)
177 >>> s1 = Struct(a=10,b=30)
178 >>> s2 = Struct(a=20,c=40)
178 >>> s2 = Struct(a=20,c=40)
179 >>> s = s1 + s2
179 >>> s = s1 + s2
180 >>> s
180 >>> s
181 {'a': 10, 'c': 40, 'b': 30}
181 {'a': 10, 'c': 40, 'b': 30}
182 """
182 """
183 sout = self.copy()
183 sout = self.copy()
184 sout.merge(other)
184 sout.merge(other)
185 return sout
185 return sout
186
186
187 def __sub__(self,other):
187 def __sub__(self,other):
188 """s1 - s2 -> remove keys in s2 from s1.
188 """s1 - s2 -> remove keys in s2 from s1.
189
189
190 Examples
190 Examples
191 --------
191 --------
192
192
193 >>> s1 = Struct(a=10,b=30)
193 >>> s1 = Struct(a=10,b=30)
194 >>> s2 = Struct(a=40)
194 >>> s2 = Struct(a=40)
195 >>> s = s1 - s2
195 >>> s = s1 - s2
196 >>> s
196 >>> s
197 {'b': 30}
197 {'b': 30}
198 """
198 """
199 sout = self.copy()
199 sout = self.copy()
200 sout -= other
200 sout -= other
201 return sout
201 return sout
202
202
203 def __isub__(self,other):
203 def __isub__(self,other):
204 """Inplace remove keys from self that are in other.
204 """Inplace remove keys from self that are in other.
205
205
206 Examples
206 Examples
207 --------
207 --------
208
208
209 >>> s1 = Struct(a=10,b=30)
209 >>> s1 = Struct(a=10,b=30)
210 >>> s2 = Struct(a=40)
210 >>> s2 = Struct(a=40)
211 >>> s1 -= s2
211 >>> s1 -= s2
212 >>> s1
212 >>> s1
213 {'b': 30}
213 {'b': 30}
214 """
214 """
215 for k in other.keys():
215 for k in other.keys():
216 if self.has_key(k):
216 if self.has_key(k):
217 del self[k]
217 del self[k]
218 return self
218 return self
219
219
220 def __dict_invert(self, data):
220 def __dict_invert(self, data):
221 """Helper function for merge.
221 """Helper function for merge.
222
222
223 Takes a dictionary whose values are lists and returns a dict with
223 Takes a dictionary whose values are lists and returns a dict with
224 the elements of each list as keys and the original keys as values.
224 the elements of each list as keys and the original keys as values.
225 """
225 """
226 outdict = {}
226 outdict = {}
227 for k,lst in data.items():
227 for k,lst in data.items():
228 if isinstance(lst, str):
228 if isinstance(lst, str):
229 lst = lst.split()
229 lst = lst.split()
230 for entry in lst:
230 for entry in lst:
231 outdict[entry] = k
231 outdict[entry] = k
232 return outdict
232 return outdict
233
233
234 def dict(self):
234 def dict(self):
235 return self
235 return self
236
236
237 def copy(self):
237 def copy(self):
238 """Return a copy as a Struct.
238 """Return a copy as a Struct.
239
239
240 Examples
240 Examples
241 --------
241 --------
242
242
243 >>> s = Struct(a=10,b=30)
243 >>> s = Struct(a=10,b=30)
244 >>> s2 = s.copy()
244 >>> s2 = s.copy()
245 >>> s2
245 >>> s2
246 {'a': 10, 'b': 30}
246 {'a': 10, 'b': 30}
247 >>> type(s2).__name__
247 >>> type(s2).__name__
248 'Struct'
248 'Struct'
249 """
249 """
250 return Struct(dict.copy(self))
250 return Struct(dict.copy(self))
251
251
252 def hasattr(self, key):
252 def hasattr(self, key):
253 """hasattr function available as a method.
253 """hasattr function available as a method.
254
254
255 Implemented like has_key.
255 Implemented like has_key.
256
256
257 Examples
257 Examples
258 --------
258 --------
259
259
260 >>> s = Struct(a=10)
260 >>> s = Struct(a=10)
261 >>> s.hasattr('a')
261 >>> s.hasattr('a')
262 True
262 True
263 >>> s.hasattr('b')
263 >>> s.hasattr('b')
264 False
264 False
265 >>> s.hasattr('get')
265 >>> s.hasattr('get')
266 False
266 False
267 """
267 """
268 return self.has_key(key)
268 return self.has_key(key)
269
269
270 def allow_new_attr(self, allow = True):
270 def allow_new_attr(self, allow = True):
271 """Set whether new attributes can be created in this Struct.
271 """Set whether new attributes can be created in this Struct.
272
272
273 This can be used to catch typos by verifying that the attribute user
273 This can be used to catch typos by verifying that the attribute user
274 tries to change already exists in this Struct.
274 tries to change already exists in this Struct.
275 """
275 """
276 object.__setattr__(self, '_allownew', allow)
276 object.__setattr__(self, '_allownew', allow)
277
277
278 def merge(self, __loc_data__=None, __conflict_solve=None, **kw):
278 def merge(self, __loc_data__=None, __conflict_solve=None, **kw):
279 """Merge two Structs with customizable conflict resolution.
279 """Merge two Structs with customizable conflict resolution.
280
280
281 This is similar to :meth:`update`, but much more flexible. First, a
281 This is similar to :meth:`update`, but much more flexible. First, a
282 dict is made from data+key=value pairs. When merging this dict with
282 dict is made from data+key=value pairs. When merging this dict with
283 the Struct S, the optional dictionary 'conflict' is used to decide
283 the Struct S, the optional dictionary 'conflict' is used to decide
284 what to do.
284 what to do.
285
285
286 If conflict is not given, the default behavior is to preserve any keys
286 If conflict is not given, the default behavior is to preserve any keys
287 with their current value (the opposite of the :meth:`update` method's
287 with their current value (the opposite of the :meth:`update` method's
288 behavior).
288 behavior).
289
289
290 Parameters
290 Parameters
291 ----------
291 ----------
292 __loc_data : dict, Struct
292 __loc_data : dict, Struct
293 The data to merge into self
293 The data to merge into self
294 __conflict_solve : dict
294 __conflict_solve : dict
295 The conflict policy dict. The keys are binary functions used to
295 The conflict policy dict. The keys are binary functions used to
296 resolve the conflict and the values are lists of strings naming
296 resolve the conflict and the values are lists of strings naming
297 the keys the conflict resolution function applies to. Instead of
297 the keys the conflict resolution function applies to. Instead of
298 a list of strings a space separated string can be used, like
298 a list of strings a space separated string can be used, like
299 'a b c'.
299 'a b c'.
300 kw : dict
300 kw : dict
301 Additional key, value pairs to merge in
301 Additional key, value pairs to merge in
302
302
303 Notes
303 Notes
304 -----
304 -----
305
305
306 The `__conflict_solve` dict is a dictionary of binary functions which will be used to
306 The `__conflict_solve` dict is a dictionary of binary functions which will be used to
307 solve key conflicts. Here is an example::
307 solve key conflicts. Here is an example::
308
308
309 __conflict_solve = dict(
309 __conflict_solve = dict(
310 func1=['a','b','c'],
310 func1=['a','b','c'],
311 func2=['d','e']
311 func2=['d','e']
312 )
312 )
313
313
314 In this case, the function :func:`func1` will be used to resolve
314 In this case, the function :func:`func1` will be used to resolve
315 keys 'a', 'b' and 'c' and the function :func:`func2` will be used for
315 keys 'a', 'b' and 'c' and the function :func:`func2` will be used for
316 keys 'd' and 'e'. This could also be written as::
316 keys 'd' and 'e'. This could also be written as::
317
317
318 __conflict_solve = dict(func1='a b c',func2='d e')
318 __conflict_solve = dict(func1='a b c',func2='d e')
319
319
320 These functions will be called for each key they apply to with the
320 These functions will be called for each key they apply to with the
321 form::
321 form::
322
322
323 func1(self['a'], other['a'])
323 func1(self['a'], other['a'])
324
324
325 The return value is used as the final merged value.
325 The return value is used as the final merged value.
326
326
327 As a convenience, merge() provides five (the most commonly needed)
327 As a convenience, merge() provides five (the most commonly needed)
328 pre-defined policies: preserve, update, add, add_flip and add_s. The
328 pre-defined policies: preserve, update, add, add_flip and add_s. The
329 easiest explanation is their implementation::
329 easiest explanation is their implementation::
330
330
331 preserve = lambda old,new: old
331 preserve = lambda old,new: old
332 update = lambda old,new: new
332 update = lambda old,new: new
333 add = lambda old,new: old + new
333 add = lambda old,new: old + new
334 add_flip = lambda old,new: new + old # note change of order!
334 add_flip = lambda old,new: new + old # note change of order!
335 add_s = lambda old,new: old + ' ' + new # only for str!
335 add_s = lambda old,new: old + ' ' + new # only for str!
336
336
337 You can use those four words (as strings) as keys instead
337 You can use those four words (as strings) as keys instead
338 of defining them as functions, and the merge method will substitute
338 of defining them as functions, and the merge method will substitute
339 the appropriate functions for you.
339 the appropriate functions for you.
340
340
341 For more complicated conflict resolution policies, you still need to
341 For more complicated conflict resolution policies, you still need to
342 construct your own functions.
342 construct your own functions.
343
343
344 Examples
344 Examples
345 --------
345 --------
346
346
347 This show the default policy:
347 This show the default policy:
348
348
349 >>> s = Struct(a=10,b=30)
349 >>> s = Struct(a=10,b=30)
350 >>> s2 = Struct(a=20,c=40)
350 >>> s2 = Struct(a=20,c=40)
351 >>> s.merge(s2)
351 >>> s.merge(s2)
352 >>> s
352 >>> s
353 {'a': 10, 'c': 40, 'b': 30}
353 {'a': 10, 'c': 40, 'b': 30}
354
354
355 Now, show how to specify a conflict dict:
355 Now, show how to specify a conflict dict:
356
356
357 >>> s = Struct(a=10,b=30)
357 >>> s = Struct(a=10,b=30)
358 >>> s2 = Struct(a=20,b=40)
358 >>> s2 = Struct(a=20,b=40)
359 >>> conflict = {'update':'a','add':'b'}
359 >>> conflict = {'update':'a','add':'b'}
360 >>> s.merge(s2,conflict)
360 >>> s.merge(s2,conflict)
361 >>> s
361 >>> s
362 {'a': 20, 'b': 70}
362 {'a': 20, 'b': 70}
363 """
363 """
364
364
365 data_dict = dict(__loc_data__,**kw)
365 data_dict = dict(__loc_data__,**kw)
366
366
367 # policies for conflict resolution: two argument functions which return
367 # policies for conflict resolution: two argument functions which return
368 # the value that will go in the new struct
368 # the value that will go in the new struct
369 preserve = lambda old,new: old
369 preserve = lambda old,new: old
370 update = lambda old,new: new
370 update = lambda old,new: new
371 add = lambda old,new: old + new
371 add = lambda old,new: old + new
372 add_flip = lambda old,new: new + old # note change of order!
372 add_flip = lambda old,new: new + old # note change of order!
373 add_s = lambda old,new: old + ' ' + new
373 add_s = lambda old,new: old + ' ' + new
374
374
375 # default policy is to keep current keys when there's a conflict
375 # default policy is to keep current keys when there's a conflict
376 conflict_solve = list2dict2(self.keys(), default = preserve)
376 conflict_solve = list2dict2(self.keys(), default = preserve)
377
377
378 # the conflict_solve dictionary is given by the user 'inverted': we
378 # the conflict_solve dictionary is given by the user 'inverted': we
379 # need a name-function mapping, it comes as a function -> names
379 # need a name-function mapping, it comes as a function -> names
380 # dict. Make a local copy (b/c we'll make changes), replace user
380 # dict. Make a local copy (b/c we'll make changes), replace user
381 # strings for the three builtin policies and invert it.
381 # strings for the three builtin policies and invert it.
382 if __conflict_solve:
382 if __conflict_solve:
383 inv_conflict_solve_user = __conflict_solve.copy()
383 inv_conflict_solve_user = __conflict_solve.copy()
384 for name, func in [('preserve',preserve), ('update',update),
384 for name, func in [('preserve',preserve), ('update',update),
385 ('add',add), ('add_flip',add_flip),
385 ('add',add), ('add_flip',add_flip),
386 ('add_s',add_s)]:
386 ('add_s',add_s)]:
387 if name in inv_conflict_solve_user.keys():
387 if name in inv_conflict_solve_user.keys():
388 inv_conflict_solve_user[func] = inv_conflict_solve_user[name]
388 inv_conflict_solve_user[func] = inv_conflict_solve_user[name]
389 del inv_conflict_solve_user[name]
389 del inv_conflict_solve_user[name]
390 conflict_solve.update(self.__dict_invert(inv_conflict_solve_user))
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 for key in data_dict:
391 for key in data_dict:
394 if key not in self:
392 if key not in self:
395 self[key] = data_dict[key]
393 self[key] = data_dict[key]
396 else:
394 else:
397 self[key] = conflict_solve[key](self[key],data_dict[key])
395 self[key] = conflict_solve[key](self[key],data_dict[key])
398
396
@@ -1,629 +1,632 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """A simple interactive kernel that talks to a frontend over 0MQ.
2 """A simple interactive kernel that talks to a frontend over 0MQ.
3
3
4 Things to do:
4 Things to do:
5
5
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 call set_parent on all the PUB objects with the message about to be executed.
7 call set_parent on all the PUB objects with the message about to be executed.
8 * Implement random port and security key logic.
8 * Implement random port and security key logic.
9 * Implement control messages.
9 * Implement control messages.
10 * Implement event loop and poll version.
10 * Implement event loop and poll version.
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Standard library imports.
18 # Standard library imports.
19 import __builtin__
19 import __builtin__
20 import atexit
20 import atexit
21 import sys
21 import sys
22 import time
22 import time
23 import traceback
23 import traceback
24
24
25 # System library imports.
25 # System library imports.
26 import zmq
26 import zmq
27
27
28 # Local imports.
28 # Local imports.
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.utils import io
30 from IPython.utils import io
31 from IPython.utils.jsonutil import json_clean
31 from IPython.utils.jsonutil import json_clean
32 from IPython.lib import pylabtools
32 from IPython.lib import pylabtools
33 from IPython.utils.traitlets import Instance, Float
33 from IPython.utils.traitlets import Instance, Float
34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
35 start_kernel)
35 start_kernel)
36 from iostream import OutStream
36 from iostream import OutStream
37 from session import Session, Message
37 from session import Session, Message
38 from zmqshell import ZMQInteractiveShell
38 from zmqshell import ZMQInteractiveShell
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Main kernel class
41 # Main kernel class
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 class Kernel(Configurable):
44 class Kernel(Configurable):
45
45
46 #---------------------------------------------------------------------------
46 #---------------------------------------------------------------------------
47 # Kernel interface
47 # Kernel interface
48 #---------------------------------------------------------------------------
48 #---------------------------------------------------------------------------
49
49
50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
51 session = Instance(Session)
51 session = Instance(Session)
52 reply_socket = Instance('zmq.Socket')
52 reply_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
54 req_socket = Instance('zmq.Socket')
54 req_socket = Instance('zmq.Socket')
55
55
56 # Private interface
56 # Private interface
57
57
58 # Time to sleep after flushing the stdout/err buffers in each execute
58 # Time to sleep after flushing the stdout/err buffers in each execute
59 # cycle. While this introduces a hard limit on the minimal latency of the
59 # cycle. While this introduces a hard limit on the minimal latency of the
60 # execute cycle, it helps prevent output synchronization problems for
60 # execute cycle, it helps prevent output synchronization problems for
61 # clients.
61 # clients.
62 # Units are in seconds. The minimum zmq latency on local host is probably
62 # Units are in seconds. The minimum zmq latency on local host is probably
63 # ~150 microseconds, set this to 500us for now. We may need to increase it
63 # ~150 microseconds, set this to 500us for now. We may need to increase it
64 # a little if it's not enough after more interactive testing.
64 # a little if it's not enough after more interactive testing.
65 _execute_sleep = Float(0.0005, config=True)
65 _execute_sleep = Float(0.0005, config=True)
66
66
67 # Frequency of the kernel's event loop.
67 # Frequency of the kernel's event loop.
68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
69 # adapt to milliseconds.
69 # adapt to milliseconds.
70 _poll_interval = Float(0.05, config=True)
70 _poll_interval = Float(0.05, config=True)
71
71
72 # If the shutdown was requested over the network, we leave here the
72 # If the shutdown was requested over the network, we leave here the
73 # necessary reply message so it can be sent by our registered atexit
73 # necessary reply message so it can be sent by our registered atexit
74 # handler. This ensures that the reply is only sent to clients truly at
74 # handler. This ensures that the reply is only sent to clients truly at
75 # the end of our shutdown process (which happens after the underlying
75 # the end of our shutdown process (which happens after the underlying
76 # IPython shell's own shutdown).
76 # IPython shell's own shutdown).
77 _shutdown_message = None
77 _shutdown_message = None
78
78
79 # This is a dict of port number that the kernel is listening on. It is set
79 # This is a dict of port number that the kernel is listening on. It is set
80 # by record_ports and used by connect_request.
80 # by record_ports and used by connect_request.
81 _recorded_ports = None
81 _recorded_ports = None
82
82
83 def __init__(self, **kwargs):
83 def __init__(self, **kwargs):
84 super(Kernel, self).__init__(**kwargs)
84 super(Kernel, self).__init__(**kwargs)
85
85
86 # Before we even start up the shell, register *first* our exit handlers
86 # Before we even start up the shell, register *first* our exit handlers
87 # so they come before the shell's
87 # so they come before the shell's
88 atexit.register(self._at_shutdown)
88 atexit.register(self._at_shutdown)
89
89
90 # Initialize the InteractiveShell subclass
90 # Initialize the InteractiveShell subclass
91 self.shell = ZMQInteractiveShell.instance()
91 self.shell = ZMQInteractiveShell.instance()
92 self.shell.displayhook.session = self.session
92 self.shell.displayhook.session = self.session
93 self.shell.displayhook.pub_socket = self.pub_socket
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 # TMP - hack while developing
97 # TMP - hack while developing
96 self.shell._reply_content = None
98 self.shell._reply_content = None
97
99
98 # Build dict of handlers for message types
100 # Build dict of handlers for message types
99 msg_types = [ 'execute_request', 'complete_request',
101 msg_types = [ 'execute_request', 'complete_request',
100 'object_info_request', 'history_request',
102 'object_info_request', 'history_request',
101 'connect_request', 'shutdown_request']
103 'connect_request', 'shutdown_request']
102 self.handlers = {}
104 self.handlers = {}
103 for msg_type in msg_types:
105 for msg_type in msg_types:
104 self.handlers[msg_type] = getattr(self, msg_type)
106 self.handlers[msg_type] = getattr(self, msg_type)
105
107
106 def do_one_iteration(self):
108 def do_one_iteration(self):
107 """Do one iteration of the kernel's evaluation loop.
109 """Do one iteration of the kernel's evaluation loop.
108 """
110 """
109 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
111 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
110 if msg is None:
112 if msg is None:
111 return
113 return
112
114
113 # This assert will raise in versions of zeromq 2.0.7 and lesser.
115 # This assert will raise in versions of zeromq 2.0.7 and lesser.
114 # We now require 2.0.8 or above, so we can uncomment for safety.
116 # We now require 2.0.8 or above, so we can uncomment for safety.
115 # print(ident,msg, file=sys.__stdout__)
117 # print(ident,msg, file=sys.__stdout__)
116 assert ident is not None, "Missing message part."
118 assert ident is not None, "Missing message part."
117
119
118 # Print some info about this message and leave a '--->' marker, so it's
120 # Print some info about this message and leave a '--->' marker, so it's
119 # easier to trace visually the message chain when debugging. Each
121 # easier to trace visually the message chain when debugging. Each
120 # handler prints its message at the end.
122 # handler prints its message at the end.
121 # Eventually we'll move these from stdout to a logger.
123 # Eventually we'll move these from stdout to a logger.
122 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
124 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
123 io.raw_print(' Content: ', msg['content'],
125 io.raw_print(' Content: ', msg['content'],
124 '\n --->\n ', sep='', end='')
126 '\n --->\n ', sep='', end='')
125
127
126 # Find and call actual handler for message
128 # Find and call actual handler for message
127 handler = self.handlers.get(msg['msg_type'], None)
129 handler = self.handlers.get(msg['msg_type'], None)
128 if handler is None:
130 if handler is None:
129 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
131 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
130 else:
132 else:
131 handler(ident, msg)
133 handler(ident, msg)
132
134
133 # Check whether we should exit, in case the incoming message set the
135 # Check whether we should exit, in case the incoming message set the
134 # exit flag on
136 # exit flag on
135 if self.shell.exit_now:
137 if self.shell.exit_now:
136 io.raw_print('\nExiting IPython kernel...')
138 io.raw_print('\nExiting IPython kernel...')
137 # We do a normal, clean exit, which allows any actions registered
139 # We do a normal, clean exit, which allows any actions registered
138 # via atexit (such as history saving) to take place.
140 # via atexit (such as history saving) to take place.
139 sys.exit(0)
141 sys.exit(0)
140
142
141
143
142 def start(self):
144 def start(self):
143 """ Start the kernel main loop.
145 """ Start the kernel main loop.
144 """
146 """
145 while True:
147 while True:
146 time.sleep(self._poll_interval)
148 time.sleep(self._poll_interval)
147 self.do_one_iteration()
149 self.do_one_iteration()
148
150
149 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
151 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
150 """Record the ports that this kernel is using.
152 """Record the ports that this kernel is using.
151
153
152 The creator of the Kernel instance must call this methods if they
154 The creator of the Kernel instance must call this methods if they
153 want the :meth:`connect_request` method to return the port numbers.
155 want the :meth:`connect_request` method to return the port numbers.
154 """
156 """
155 self._recorded_ports = {
157 self._recorded_ports = {
156 'xrep_port' : xrep_port,
158 'xrep_port' : xrep_port,
157 'pub_port' : pub_port,
159 'pub_port' : pub_port,
158 'req_port' : req_port,
160 'req_port' : req_port,
159 'hb_port' : hb_port
161 'hb_port' : hb_port
160 }
162 }
161
163
162 #---------------------------------------------------------------------------
164 #---------------------------------------------------------------------------
163 # Kernel request handlers
165 # Kernel request handlers
164 #---------------------------------------------------------------------------
166 #---------------------------------------------------------------------------
165
167
166 def _publish_pyin(self, code, parent):
168 def _publish_pyin(self, code, parent):
167 """Publish the code request on the pyin stream."""
169 """Publish the code request on the pyin stream."""
168
170
169 pyin_msg = self.session.send(self.pub_socket, u'pyin',{u'code':code}, parent=parent)
171 pyin_msg = self.session.send(self.pub_socket, u'pyin',{u'code':code}, parent=parent)
170
172
171 def execute_request(self, ident, parent):
173 def execute_request(self, ident, parent):
172
174
173 status_msg = self.session.send(self.pub_socket,
175 status_msg = self.session.send(self.pub_socket,
174 u'status',
176 u'status',
175 {u'execution_state':u'busy'},
177 {u'execution_state':u'busy'},
176 parent=parent
178 parent=parent
177 )
179 )
178
180
179 try:
181 try:
180 content = parent[u'content']
182 content = parent[u'content']
181 code = content[u'code']
183 code = content[u'code']
182 silent = content[u'silent']
184 silent = content[u'silent']
183 except:
185 except:
184 io.raw_print_err("Got bad msg: ")
186 io.raw_print_err("Got bad msg: ")
185 io.raw_print_err(Message(parent))
187 io.raw_print_err(Message(parent))
186 return
188 return
187
189
188 shell = self.shell # we'll need this a lot here
190 shell = self.shell # we'll need this a lot here
189
191
190 # Replace raw_input. Note that is not sufficient to replace
192 # Replace raw_input. Note that is not sufficient to replace
191 # raw_input in the user namespace.
193 # raw_input in the user namespace.
192 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
194 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
193 __builtin__.raw_input = raw_input
195 __builtin__.raw_input = raw_input
194
196
195 # Set the parent message of the display hook and out streams.
197 # Set the parent message of the display hook and out streams.
196 shell.displayhook.set_parent(parent)
198 shell.displayhook.set_parent(parent)
199 shell.display_pub.set_parent(parent)
197 sys.stdout.set_parent(parent)
200 sys.stdout.set_parent(parent)
198 sys.stderr.set_parent(parent)
201 sys.stderr.set_parent(parent)
199
202
200 # Re-broadcast our input for the benefit of listening clients, and
203 # Re-broadcast our input for the benefit of listening clients, and
201 # start computing output
204 # start computing output
202 if not silent:
205 if not silent:
203 self._publish_pyin(code, parent)
206 self._publish_pyin(code, parent)
204
207
205 reply_content = {}
208 reply_content = {}
206 try:
209 try:
207 if silent:
210 if silent:
208 # run_code uses 'exec' mode, so no displayhook will fire, and it
211 # run_code uses 'exec' mode, so no displayhook will fire, and it
209 # doesn't call logging or history manipulations. Print
212 # doesn't call logging or history manipulations. Print
210 # statements in that code will obviously still execute.
213 # statements in that code will obviously still execute.
211 shell.run_code(code)
214 shell.run_code(code)
212 else:
215 else:
213 # FIXME: the shell calls the exception handler itself.
216 # FIXME: the shell calls the exception handler itself.
214 shell._reply_content = None
217 shell._reply_content = None
215 shell.run_cell(code)
218 shell.run_cell(code)
216 except:
219 except:
217 status = u'error'
220 status = u'error'
218 # FIXME: this code right now isn't being used yet by default,
221 # FIXME: this code right now isn't being used yet by default,
219 # because the runlines() call above directly fires off exception
222 # because the runlines() call above directly fires off exception
220 # reporting. This code, therefore, is only active in the scenario
223 # reporting. This code, therefore, is only active in the scenario
221 # where runlines itself has an unhandled exception. We need to
224 # where runlines itself has an unhandled exception. We need to
222 # uniformize this, for all exception construction to come from a
225 # uniformize this, for all exception construction to come from a
223 # single location in the codbase.
226 # single location in the codbase.
224 etype, evalue, tb = sys.exc_info()
227 etype, evalue, tb = sys.exc_info()
225 tb_list = traceback.format_exception(etype, evalue, tb)
228 tb_list = traceback.format_exception(etype, evalue, tb)
226 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
229 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
227 else:
230 else:
228 status = u'ok'
231 status = u'ok'
229
232
230 reply_content[u'status'] = status
233 reply_content[u'status'] = status
231
234
232 # Return the execution counter so clients can display prompts
235 # Return the execution counter so clients can display prompts
233 reply_content['execution_count'] = shell.execution_count -1
236 reply_content['execution_count'] = shell.execution_count -1
234
237
235 # FIXME - fish exception info out of shell, possibly left there by
238 # FIXME - fish exception info out of shell, possibly left there by
236 # runlines. We'll need to clean up this logic later.
239 # runlines. We'll need to clean up this logic later.
237 if shell._reply_content is not None:
240 if shell._reply_content is not None:
238 reply_content.update(shell._reply_content)
241 reply_content.update(shell._reply_content)
239
242
240 # At this point, we can tell whether the main code execution succeeded
243 # At this point, we can tell whether the main code execution succeeded
241 # or not. If it did, we proceed to evaluate user_variables/expressions
244 # or not. If it did, we proceed to evaluate user_variables/expressions
242 if reply_content['status'] == 'ok':
245 if reply_content['status'] == 'ok':
243 reply_content[u'user_variables'] = \
246 reply_content[u'user_variables'] = \
244 shell.user_variables(content[u'user_variables'])
247 shell.user_variables(content[u'user_variables'])
245 reply_content[u'user_expressions'] = \
248 reply_content[u'user_expressions'] = \
246 shell.user_expressions(content[u'user_expressions'])
249 shell.user_expressions(content[u'user_expressions'])
247 else:
250 else:
248 # If there was an error, don't even try to compute variables or
251 # If there was an error, don't even try to compute variables or
249 # expressions
252 # expressions
250 reply_content[u'user_variables'] = {}
253 reply_content[u'user_variables'] = {}
251 reply_content[u'user_expressions'] = {}
254 reply_content[u'user_expressions'] = {}
252
255
253 # Payloads should be retrieved regardless of outcome, so we can both
256 # Payloads should be retrieved regardless of outcome, so we can both
254 # recover partial output (that could have been generated early in a
257 # recover partial output (that could have been generated early in a
255 # block, before an error) and clear the payload system always.
258 # block, before an error) and clear the payload system always.
256 reply_content[u'payload'] = shell.payload_manager.read_payload()
259 reply_content[u'payload'] = shell.payload_manager.read_payload()
257 # Be agressive about clearing the payload because we don't want
260 # Be agressive about clearing the payload because we don't want
258 # it to sit in memory until the next execute_request comes in.
261 # it to sit in memory until the next execute_request comes in.
259 shell.payload_manager.clear_payload()
262 shell.payload_manager.clear_payload()
260
263
261 # Send the reply.
264 # Send the reply.
262 reply_msg = self.session.send(self.reply_socket, u'execute_reply', reply_content, parent, ident=ident)
265 reply_msg = self.session.send(self.reply_socket, u'execute_reply', reply_content, parent, ident=ident)
263 io.raw_print(reply_msg)
266 io.raw_print(reply_msg)
264
267
265 # Flush output before sending the reply.
268 # Flush output before sending the reply.
266 sys.stdout.flush()
269 sys.stdout.flush()
267 sys.stderr.flush()
270 sys.stderr.flush()
268 # FIXME: on rare occasions, the flush doesn't seem to make it to the
271 # FIXME: on rare occasions, the flush doesn't seem to make it to the
269 # clients... This seems to mitigate the problem, but we definitely need
272 # clients... This seems to mitigate the problem, but we definitely need
270 # to better understand what's going on.
273 # to better understand what's going on.
271 if self._execute_sleep:
274 if self._execute_sleep:
272 time.sleep(self._execute_sleep)
275 time.sleep(self._execute_sleep)
273
276
274 if reply_msg['content']['status'] == u'error':
277 if reply_msg['content']['status'] == u'error':
275 self._abort_queue()
278 self._abort_queue()
276
279
277 status_msg = self.session.send(self.pub_socket,
280 status_msg = self.session.send(self.pub_socket,
278 u'status',
281 u'status',
279 {u'execution_state':u'idle'},
282 {u'execution_state':u'idle'},
280 parent=parent
283 parent=parent
281 )
284 )
282
285
283 def complete_request(self, ident, parent):
286 def complete_request(self, ident, parent):
284 txt, matches = self._complete(parent)
287 txt, matches = self._complete(parent)
285 matches = {'matches' : matches,
288 matches = {'matches' : matches,
286 'matched_text' : txt,
289 'matched_text' : txt,
287 'status' : 'ok'}
290 'status' : 'ok'}
288 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
291 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
289 matches, parent, ident)
292 matches, parent, ident)
290 io.raw_print(completion_msg)
293 io.raw_print(completion_msg)
291
294
292 def object_info_request(self, ident, parent):
295 def object_info_request(self, ident, parent):
293 object_info = self.shell.object_inspect(parent['content']['oname'])
296 object_info = self.shell.object_inspect(parent['content']['oname'])
294 # Before we send this object over, we scrub it for JSON usage
297 # Before we send this object over, we scrub it for JSON usage
295 oinfo = json_clean(object_info)
298 oinfo = json_clean(object_info)
296 msg = self.session.send(self.reply_socket, 'object_info_reply',
299 msg = self.session.send(self.reply_socket, 'object_info_reply',
297 oinfo, parent, ident)
300 oinfo, parent, ident)
298 io.raw_print(msg)
301 io.raw_print(msg)
299
302
300 def history_request(self, ident, parent):
303 def history_request(self, ident, parent):
301 output = parent['content']['output']
304 output = parent['content']['output']
302 index = parent['content']['index']
305 index = parent['content']['index']
303 raw = parent['content']['raw']
306 raw = parent['content']['raw']
304 hist = self.shell.get_history(index=index, raw=raw, output=output)
307 hist = self.shell.get_history(index=index, raw=raw, output=output)
305 content = {'history' : hist}
308 content = {'history' : hist}
306 msg = self.session.send(self.reply_socket, 'history_reply',
309 msg = self.session.send(self.reply_socket, 'history_reply',
307 content, parent, ident)
310 content, parent, ident)
308 io.raw_print(msg)
311 io.raw_print(msg)
309
312
310 def connect_request(self, ident, parent):
313 def connect_request(self, ident, parent):
311 if self._recorded_ports is not None:
314 if self._recorded_ports is not None:
312 content = self._recorded_ports.copy()
315 content = self._recorded_ports.copy()
313 else:
316 else:
314 content = {}
317 content = {}
315 msg = self.session.send(self.reply_socket, 'connect_reply',
318 msg = self.session.send(self.reply_socket, 'connect_reply',
316 content, parent, ident)
319 content, parent, ident)
317 io.raw_print(msg)
320 io.raw_print(msg)
318
321
319 def shutdown_request(self, ident, parent):
322 def shutdown_request(self, ident, parent):
320 self.shell.exit_now = True
323 self.shell.exit_now = True
321 self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent)
324 self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent)
322 sys.exit(0)
325 sys.exit(0)
323
326
324 #---------------------------------------------------------------------------
327 #---------------------------------------------------------------------------
325 # Protected interface
328 # Protected interface
326 #---------------------------------------------------------------------------
329 #---------------------------------------------------------------------------
327
330
328 def _abort_queue(self):
331 def _abort_queue(self):
329 while True:
332 while True:
330 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
333 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
331 if msg is None:
334 if msg is None:
332 break
335 break
333 else:
336 else:
334 assert ident is not None, \
337 assert ident is not None, \
335 "Unexpected missing message part."
338 "Unexpected missing message part."
336 io.raw_print("Aborting:\n", Message(msg))
339 io.raw_print("Aborting:\n", Message(msg))
337 msg_type = msg['msg_type']
340 msg_type = msg['msg_type']
338 reply_type = msg_type.split('_')[0] + '_reply'
341 reply_type = msg_type.split('_')[0] + '_reply'
339 reply_msg = self.session.send(self.reply_socket, reply_type,
342 reply_msg = self.session.send(self.reply_socket, reply_type,
340 {'status' : 'aborted'}, msg, ident=ident)
343 {'status' : 'aborted'}, msg, ident=ident)
341 io.raw_print(reply_msg)
344 io.raw_print(reply_msg)
342 # We need to wait a bit for requests to come in. This can probably
345 # We need to wait a bit for requests to come in. This can probably
343 # be set shorter for true asynchronous clients.
346 # be set shorter for true asynchronous clients.
344 time.sleep(0.1)
347 time.sleep(0.1)
345
348
346 def _raw_input(self, prompt, ident, parent):
349 def _raw_input(self, prompt, ident, parent):
347 # Flush output before making the request.
350 # Flush output before making the request.
348 sys.stderr.flush()
351 sys.stderr.flush()
349 sys.stdout.flush()
352 sys.stdout.flush()
350
353
351 # Send the input request.
354 # Send the input request.
352 content = dict(prompt=prompt)
355 content = dict(prompt=prompt)
353 msg = self.session.send(self.req_socket, u'input_request', content, parent)
356 msg = self.session.send(self.req_socket, u'input_request', content, parent)
354
357
355 # Await a response.
358 # Await a response.
356 ident, reply = self.session.recv(self.req_socket, 0)
359 ident, reply = self.session.recv(self.req_socket, 0)
357 try:
360 try:
358 value = reply['content']['value']
361 value = reply['content']['value']
359 except:
362 except:
360 io.raw_print_err("Got bad raw_input reply: ")
363 io.raw_print_err("Got bad raw_input reply: ")
361 io.raw_print_err(Message(parent))
364 io.raw_print_err(Message(parent))
362 value = ''
365 value = ''
363 return value
366 return value
364
367
365 def _complete(self, msg):
368 def _complete(self, msg):
366 c = msg['content']
369 c = msg['content']
367 try:
370 try:
368 cpos = int(c['cursor_pos'])
371 cpos = int(c['cursor_pos'])
369 except:
372 except:
370 # If we don't get something that we can convert to an integer, at
373 # If we don't get something that we can convert to an integer, at
371 # least attempt the completion guessing the cursor is at the end of
374 # least attempt the completion guessing the cursor is at the end of
372 # the text, if there's any, and otherwise of the line
375 # the text, if there's any, and otherwise of the line
373 cpos = len(c['text'])
376 cpos = len(c['text'])
374 if cpos==0:
377 if cpos==0:
375 cpos = len(c['line'])
378 cpos = len(c['line'])
376 return self.shell.complete(c['text'], c['line'], cpos)
379 return self.shell.complete(c['text'], c['line'], cpos)
377
380
378 def _object_info(self, context):
381 def _object_info(self, context):
379 symbol, leftover = self._symbol_from_context(context)
382 symbol, leftover = self._symbol_from_context(context)
380 if symbol is not None and not leftover:
383 if symbol is not None and not leftover:
381 doc = getattr(symbol, '__doc__', '')
384 doc = getattr(symbol, '__doc__', '')
382 else:
385 else:
383 doc = ''
386 doc = ''
384 object_info = dict(docstring = doc)
387 object_info = dict(docstring = doc)
385 return object_info
388 return object_info
386
389
387 def _symbol_from_context(self, context):
390 def _symbol_from_context(self, context):
388 if not context:
391 if not context:
389 return None, context
392 return None, context
390
393
391 base_symbol_string = context[0]
394 base_symbol_string = context[0]
392 symbol = self.shell.user_ns.get(base_symbol_string, None)
395 symbol = self.shell.user_ns.get(base_symbol_string, None)
393 if symbol is None:
396 if symbol is None:
394 symbol = __builtin__.__dict__.get(base_symbol_string, None)
397 symbol = __builtin__.__dict__.get(base_symbol_string, None)
395 if symbol is None:
398 if symbol is None:
396 return None, context
399 return None, context
397
400
398 context = context[1:]
401 context = context[1:]
399 for i, name in enumerate(context):
402 for i, name in enumerate(context):
400 new_symbol = getattr(symbol, name, None)
403 new_symbol = getattr(symbol, name, None)
401 if new_symbol is None:
404 if new_symbol is None:
402 return symbol, context[i:]
405 return symbol, context[i:]
403 else:
406 else:
404 symbol = new_symbol
407 symbol = new_symbol
405
408
406 return symbol, []
409 return symbol, []
407
410
408 def _at_shutdown(self):
411 def _at_shutdown(self):
409 """Actions taken at shutdown by the kernel, called by python's atexit.
412 """Actions taken at shutdown by the kernel, called by python's atexit.
410 """
413 """
411 # io.rprint("Kernel at_shutdown") # dbg
414 # io.rprint("Kernel at_shutdown") # dbg
412 if self._shutdown_message is not None:
415 if self._shutdown_message is not None:
413 self.session.send(self.reply_socket, self._shutdown_message)
416 self.session.send(self.reply_socket, self._shutdown_message)
414 self.session.send(self.pub_socket, self._shutdown_message)
417 self.session.send(self.pub_socket, self._shutdown_message)
415 io.raw_print(self._shutdown_message)
418 io.raw_print(self._shutdown_message)
416 # A very short sleep to give zmq time to flush its message buffers
419 # A very short sleep to give zmq time to flush its message buffers
417 # before Python truly shuts down.
420 # before Python truly shuts down.
418 time.sleep(0.01)
421 time.sleep(0.01)
419
422
420
423
421 class QtKernel(Kernel):
424 class QtKernel(Kernel):
422 """A Kernel subclass with Qt support."""
425 """A Kernel subclass with Qt support."""
423
426
424 def start(self):
427 def start(self):
425 """Start a kernel with QtPy4 event loop integration."""
428 """Start a kernel with QtPy4 event loop integration."""
426
429
427 from PyQt4 import QtCore
430 from PyQt4 import QtCore
428 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
431 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
429
432
430 self.app = get_app_qt4([" "])
433 self.app = get_app_qt4([" "])
431 self.app.setQuitOnLastWindowClosed(False)
434 self.app.setQuitOnLastWindowClosed(False)
432 self.timer = QtCore.QTimer()
435 self.timer = QtCore.QTimer()
433 self.timer.timeout.connect(self.do_one_iteration)
436 self.timer.timeout.connect(self.do_one_iteration)
434 # Units for the timer are in milliseconds
437 # Units for the timer are in milliseconds
435 self.timer.start(1000*self._poll_interval)
438 self.timer.start(1000*self._poll_interval)
436 start_event_loop_qt4(self.app)
439 start_event_loop_qt4(self.app)
437
440
438
441
439 class WxKernel(Kernel):
442 class WxKernel(Kernel):
440 """A Kernel subclass with Wx support."""
443 """A Kernel subclass with Wx support."""
441
444
442 def start(self):
445 def start(self):
443 """Start a kernel with wx event loop support."""
446 """Start a kernel with wx event loop support."""
444
447
445 import wx
448 import wx
446 from IPython.lib.guisupport import start_event_loop_wx
449 from IPython.lib.guisupport import start_event_loop_wx
447
450
448 doi = self.do_one_iteration
451 doi = self.do_one_iteration
449 # Wx uses milliseconds
452 # Wx uses milliseconds
450 poll_interval = int(1000*self._poll_interval)
453 poll_interval = int(1000*self._poll_interval)
451
454
452 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
455 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
453 # We make the Frame hidden when we create it in the main app below.
456 # We make the Frame hidden when we create it in the main app below.
454 class TimerFrame(wx.Frame):
457 class TimerFrame(wx.Frame):
455 def __init__(self, func):
458 def __init__(self, func):
456 wx.Frame.__init__(self, None, -1)
459 wx.Frame.__init__(self, None, -1)
457 self.timer = wx.Timer(self)
460 self.timer = wx.Timer(self)
458 # Units for the timer are in milliseconds
461 # Units for the timer are in milliseconds
459 self.timer.Start(poll_interval)
462 self.timer.Start(poll_interval)
460 self.Bind(wx.EVT_TIMER, self.on_timer)
463 self.Bind(wx.EVT_TIMER, self.on_timer)
461 self.func = func
464 self.func = func
462
465
463 def on_timer(self, event):
466 def on_timer(self, event):
464 self.func()
467 self.func()
465
468
466 # We need a custom wx.App to create our Frame subclass that has the
469 # We need a custom wx.App to create our Frame subclass that has the
467 # wx.Timer to drive the ZMQ event loop.
470 # wx.Timer to drive the ZMQ event loop.
468 class IPWxApp(wx.App):
471 class IPWxApp(wx.App):
469 def OnInit(self):
472 def OnInit(self):
470 self.frame = TimerFrame(doi)
473 self.frame = TimerFrame(doi)
471 self.frame.Show(False)
474 self.frame.Show(False)
472 return True
475 return True
473
476
474 # The redirect=False here makes sure that wx doesn't replace
477 # The redirect=False here makes sure that wx doesn't replace
475 # sys.stdout/stderr with its own classes.
478 # sys.stdout/stderr with its own classes.
476 self.app = IPWxApp(redirect=False)
479 self.app = IPWxApp(redirect=False)
477 start_event_loop_wx(self.app)
480 start_event_loop_wx(self.app)
478
481
479
482
480 class TkKernel(Kernel):
483 class TkKernel(Kernel):
481 """A Kernel subclass with Tk support."""
484 """A Kernel subclass with Tk support."""
482
485
483 def start(self):
486 def start(self):
484 """Start a Tk enabled event loop."""
487 """Start a Tk enabled event loop."""
485
488
486 import Tkinter
489 import Tkinter
487 doi = self.do_one_iteration
490 doi = self.do_one_iteration
488 # Tk uses milliseconds
491 # Tk uses milliseconds
489 poll_interval = int(1000*self._poll_interval)
492 poll_interval = int(1000*self._poll_interval)
490 # For Tkinter, we create a Tk object and call its withdraw method.
493 # For Tkinter, we create a Tk object and call its withdraw method.
491 class Timer(object):
494 class Timer(object):
492 def __init__(self, func):
495 def __init__(self, func):
493 self.app = Tkinter.Tk()
496 self.app = Tkinter.Tk()
494 self.app.withdraw()
497 self.app.withdraw()
495 self.func = func
498 self.func = func
496
499
497 def on_timer(self):
500 def on_timer(self):
498 self.func()
501 self.func()
499 self.app.after(poll_interval, self.on_timer)
502 self.app.after(poll_interval, self.on_timer)
500
503
501 def start(self):
504 def start(self):
502 self.on_timer() # Call it once to get things going.
505 self.on_timer() # Call it once to get things going.
503 self.app.mainloop()
506 self.app.mainloop()
504
507
505 self.timer = Timer(doi)
508 self.timer = Timer(doi)
506 self.timer.start()
509 self.timer.start()
507
510
508
511
509 class GTKKernel(Kernel):
512 class GTKKernel(Kernel):
510 """A Kernel subclass with GTK support."""
513 """A Kernel subclass with GTK support."""
511
514
512 def start(self):
515 def start(self):
513 """Start the kernel, coordinating with the GTK event loop"""
516 """Start the kernel, coordinating with the GTK event loop"""
514 from .gui.gtkembed import GTKEmbed
517 from .gui.gtkembed import GTKEmbed
515
518
516 gtk_kernel = GTKEmbed(self)
519 gtk_kernel = GTKEmbed(self)
517 gtk_kernel.start()
520 gtk_kernel.start()
518
521
519
522
520 #-----------------------------------------------------------------------------
523 #-----------------------------------------------------------------------------
521 # Kernel main and launch functions
524 # Kernel main and launch functions
522 #-----------------------------------------------------------------------------
525 #-----------------------------------------------------------------------------
523
526
524 def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0,
527 def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0,
525 independent=False, pylab=False, colors=None):
528 independent=False, pylab=False, colors=None):
526 """Launches a localhost kernel, binding to the specified ports.
529 """Launches a localhost kernel, binding to the specified ports.
527
530
528 Parameters
531 Parameters
529 ----------
532 ----------
530 ip : str, optional
533 ip : str, optional
531 The ip address the kernel will bind to.
534 The ip address the kernel will bind to.
532
535
533 xrep_port : int, optional
536 xrep_port : int, optional
534 The port to use for XREP channel.
537 The port to use for XREP channel.
535
538
536 pub_port : int, optional
539 pub_port : int, optional
537 The port to use for the SUB channel.
540 The port to use for the SUB channel.
538
541
539 req_port : int, optional
542 req_port : int, optional
540 The port to use for the REQ (raw input) channel.
543 The port to use for the REQ (raw input) channel.
541
544
542 hb_port : int, optional
545 hb_port : int, optional
543 The port to use for the hearbeat REP channel.
546 The port to use for the hearbeat REP channel.
544
547
545 independent : bool, optional (default False)
548 independent : bool, optional (default False)
546 If set, the kernel process is guaranteed to survive if this process
549 If set, the kernel process is guaranteed to survive if this process
547 dies. If not set, an effort is made to ensure that the kernel is killed
550 dies. If not set, an effort is made to ensure that the kernel is killed
548 when this process dies. Note that in this case it is still good practice
551 when this process dies. Note that in this case it is still good practice
549 to kill kernels manually before exiting.
552 to kill kernels manually before exiting.
550
553
551 pylab : bool or string, optional (default False)
554 pylab : bool or string, optional (default False)
552 If not False, the kernel will be launched with pylab enabled. If a
555 If not False, the kernel will be launched with pylab enabled. If a
553 string is passed, matplotlib will use the specified backend. Otherwise,
556 string is passed, matplotlib will use the specified backend. Otherwise,
554 matplotlib's default backend will be used.
557 matplotlib's default backend will be used.
555
558
556 colors : None or string, optional (default None)
559 colors : None or string, optional (default None)
557 If not None, specify the color scheme. One of (NoColor, LightBG, Linux)
560 If not None, specify the color scheme. One of (NoColor, LightBG, Linux)
558
561
559 Returns
562 Returns
560 -------
563 -------
561 A tuple of form:
564 A tuple of form:
562 (kernel_process, xrep_port, pub_port, req_port)
565 (kernel_process, xrep_port, pub_port, req_port)
563 where kernel_process is a Popen object and the ports are integers.
566 where kernel_process is a Popen object and the ports are integers.
564 """
567 """
565 extra_arguments = []
568 extra_arguments = []
566 if pylab:
569 if pylab:
567 extra_arguments.append('--pylab')
570 extra_arguments.append('--pylab')
568 if isinstance(pylab, basestring):
571 if isinstance(pylab, basestring):
569 extra_arguments.append(pylab)
572 extra_arguments.append(pylab)
570 if ip is not None:
573 if ip is not None:
571 extra_arguments.append('--ip')
574 extra_arguments.append('--ip')
572 if isinstance(ip, basestring):
575 if isinstance(ip, basestring):
573 extra_arguments.append(ip)
576 extra_arguments.append(ip)
574 if colors is not None:
577 if colors is not None:
575 extra_arguments.append('--colors')
578 extra_arguments.append('--colors')
576 extra_arguments.append(colors)
579 extra_arguments.append(colors)
577 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
580 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
578 xrep_port, pub_port, req_port, hb_port,
581 xrep_port, pub_port, req_port, hb_port,
579 independent, extra_arguments)
582 independent, extra_arguments)
580
583
581
584
582 def main():
585 def main():
583 """ The IPython kernel main entry point.
586 """ The IPython kernel main entry point.
584 """
587 """
585 parser = make_argument_parser()
588 parser = make_argument_parser()
586 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
589 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
587 const='auto', help = \
590 const='auto', help = \
588 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
591 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
589 given, the GUI backend is matplotlib's, otherwise use one of: \
592 given, the GUI backend is matplotlib's, otherwise use one of: \
590 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
593 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
591 parser.add_argument('--colors',
594 parser.add_argument('--colors',
592 type=str, dest='colors',
595 type=str, dest='colors',
593 help="Set the color scheme (NoColor, Linux, and LightBG).",
596 help="Set the color scheme (NoColor, Linux, and LightBG).",
594 metavar='ZMQInteractiveShell.colors')
597 metavar='ZMQInteractiveShell.colors')
595 namespace = parser.parse_args()
598 namespace = parser.parse_args()
596
599
597 kernel_class = Kernel
600 kernel_class = Kernel
598
601
599 kernel_classes = {
602 kernel_classes = {
600 'qt' : QtKernel,
603 'qt' : QtKernel,
601 'qt4': QtKernel,
604 'qt4': QtKernel,
602 'inline': Kernel,
605 'inline': Kernel,
603 'wx' : WxKernel,
606 'wx' : WxKernel,
604 'tk' : TkKernel,
607 'tk' : TkKernel,
605 'gtk': GTKKernel,
608 'gtk': GTKKernel,
606 }
609 }
607 if namespace.pylab:
610 if namespace.pylab:
608 if namespace.pylab == 'auto':
611 if namespace.pylab == 'auto':
609 gui, backend = pylabtools.find_gui_and_backend()
612 gui, backend = pylabtools.find_gui_and_backend()
610 else:
613 else:
611 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
614 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
612 kernel_class = kernel_classes.get(gui)
615 kernel_class = kernel_classes.get(gui)
613 if kernel_class is None:
616 if kernel_class is None:
614 raise ValueError('GUI is not supported: %r' % gui)
617 raise ValueError('GUI is not supported: %r' % gui)
615 pylabtools.activate_matplotlib(backend)
618 pylabtools.activate_matplotlib(backend)
616 if namespace.colors:
619 if namespace.colors:
617 ZMQInteractiveShell.colors=namespace.colors
620 ZMQInteractiveShell.colors=namespace.colors
618
621
619 kernel = make_kernel(namespace, kernel_class, OutStream)
622 kernel = make_kernel(namespace, kernel_class, OutStream)
620
623
621 if namespace.pylab:
624 if namespace.pylab:
622 pylabtools.import_pylab(kernel.shell.user_ns, backend,
625 pylabtools.import_pylab(kernel.shell.user_ns, backend,
623 shell=kernel.shell)
626 shell=kernel.shell)
624
627
625 start_kernel(namespace, kernel)
628 start_kernel(namespace, kernel)
626
629
627
630
628 if __name__ == '__main__':
631 if __name__ == '__main__':
629 main()
632 main()
@@ -1,119 +1,73 b''
1 """Produce SVG versions of active plots for display by the rich Qt frontend.
1 """Produce SVG versions of active plots for display by the rich Qt frontend.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Imports
4 # Imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 from __future__ import print_function
6 from __future__ import print_function
7
7
8 # Standard library imports
8 # Standard library imports
9 from cStringIO import StringIO
10
9
11 # System library imports.
12 import matplotlib
10 import matplotlib
13 from matplotlib.backends.backend_svg import new_figure_manager
11 from matplotlib.backends.backend_svg import new_figure_manager
14 from matplotlib._pylab_helpers import Gcf
12 from matplotlib._pylab_helpers import Gcf
15
13
16 # Local imports.
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 # Functions
19 # Functions
21 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
22
21
23 def show(close=True):
22 def show(close=False):
24 """Show all figures as SVG payloads sent to the IPython clients.
23 """Show all figures as SVG payloads sent to the IPython clients.
25
24
26 Parameters
25 Parameters
27 ----------
26 ----------
28 close : bool, optional
27 close : bool, optional
29 If true, a ``plt.close('all')`` call is automatically issued after
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 for figure_manager in Gcf.get_all_fig_managers():
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 if close:
34 if close:
35 matplotlib.pyplot.close('all')
35 matplotlib.pyplot.close('all')
36
36
37
37 # This flag will be reset by draw_if_interactive when called
38 # This flag will be reset by draw_if_interactive when called
38 show._draw_called = False
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 def draw_if_interactive():
42 def draw_if_interactive():
103 """
43 """
104 Is called after every pylab drawing command
44 Is called after every pylab drawing command
105 """
45 """
106 # We simply flag we were called and otherwise do nothing. At the end of
46 # We simply flag we were called and otherwise do nothing. At the end of
107 # the code execution, a separate call to show_close() will act upon this.
47 # the code execution, a separate call to show_close() will act upon this.
108 show._draw_called = True
48 show._draw_called = True
109
49
110
50
111 def flush_svg():
51 def flush_svg():
112 """Call show, close all open figures, sending all SVG images.
52 """Call show, close all open figures, sending all SVG images.
113
53
114 This is meant to be called automatically and will call show() if, during
54 This is meant to be called automatically and will call show() if, during
115 prior code execution, there had been any calls to draw_if_interactive.
55 prior code execution, there had been any calls to draw_if_interactive.
116 """
56 """
117 if show._draw_called:
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 show._draw_called = False
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
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
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
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now